登录
This commit is contained in:
@@ -0,0 +1,808 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use support\exception\BusinessException;
|
||||
use support\Db;
|
||||
|
||||
/**
|
||||
* 构建查询工具类
|
||||
* | 方法 | 说明 |
|
||||
* | ------------------------------- | --------------------- |
|
||||
* | `buildQuery($config)` | 构建动态查询(关联加载/字段/过滤/排序) |
|
||||
* | `paginate($q,$per,$page)` | 分页返回 Paginator |
|
||||
* | `getAll($q)` | 不分页直接 `get()` |
|
||||
* | `findByPk($model,$id)` | 根据主键查询单条,找不到抛 404 |
|
||||
* | `findOneBy($model,$where)` | 根据任意条件查询单条,找不到抛 404 |
|
||||
* | `deleteByPk($model,$ids)` | 根据主键删除(可批量),返回删除条数 |
|
||||
* | `deleteBy($model,$where)` | 根据任意条件删除,返回删除条数 |
|
||||
* | `updateByPk($model,$id,$data)` | 根据主键更新,找不到抛 404 |
|
||||
* | `updateBy($model,$where,$data)` | 根据任意条件更新,返回影响行数 |
|
||||
*/
|
||||
|
||||
class CrudUtil
|
||||
{
|
||||
|
||||
/**
|
||||
* 构建查询,支持:
|
||||
* - 本表字段过滤 where
|
||||
* - 关联加载 with
|
||||
* - 关联表字段选择 withFields
|
||||
* - 关联表字段过滤 where with dot-notation
|
||||
* - 排序 order
|
||||
* - 本表字段选择 fields
|
||||
*
|
||||
* $config = [
|
||||
* 'model' => User::class,
|
||||
* 'where' => [
|
||||
* 'status' => 1,
|
||||
* 'name' => ['like','%张%'],
|
||||
* 'roles.name' => '管理员', // 关联表字段过滤
|
||||
* 'posts.created_at'=> ['>','2025-01-01'],
|
||||
* ],
|
||||
* 'order' => ['id'=>'desc'],
|
||||
* 'fields' => ['id','name','email'],
|
||||
* 'with' => ['roles','posts'],
|
||||
* 'withFields' => [
|
||||
* 'roles' => ['id','name'], // 关联表字段选择
|
||||
* 'posts' => ['id','title','user_id'],
|
||||
* ],
|
||||
* 'dataLimit' => [
|
||||
* 'type' => 'personal|same_role|role_tree|relation', // personal:个人数据,same_role:同角色,role_tree:角色树,relation:从属关联数据
|
||||
* 'userId' => 1,
|
||||
* 'roleId' => 2,
|
||||
* 'userField' => 'user_id',
|
||||
* 'roleField' => 'role_id'
|
||||
* ]
|
||||
* ];
|
||||
*/
|
||||
public static function buildQuery(array $config): Builder
|
||||
{
|
||||
/** @var Model $model */
|
||||
$model = new $config['model'];
|
||||
$q = $model->newQuery();
|
||||
|
||||
// eager-load:支持 ['rel','rel2'] 和 ['rel'=>fields[], ...]
|
||||
if (! empty($config['with'])) {
|
||||
foreach ($config['with'] as $rel => $fields) {
|
||||
if (is_int($rel)) {
|
||||
// 普通关联
|
||||
$q->with($fields);
|
||||
} else {
|
||||
// 带字段筛选的关联
|
||||
$q->with([$rel => function ($qr) use ($fields) {
|
||||
$key = $qr->getModel()->getKeyName();
|
||||
if (! in_array($key, $fields, true)) {
|
||||
$fields[] = $key;
|
||||
}
|
||||
$qr->select($fields);
|
||||
}]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 表字段
|
||||
if (!empty($config['fields'])) {
|
||||
$q->select($config['fields']);
|
||||
}
|
||||
|
||||
// where
|
||||
if (!empty($config['where'])) {
|
||||
foreach ($config['where'] as $col => $val) {
|
||||
if (strpos($col, '.') !== false) {
|
||||
// 多层支持
|
||||
$segments = explode('.', $col);
|
||||
$leaf = array_pop($segments);
|
||||
self::applyNestedWhere($q, $segments, $leaf, $val);
|
||||
} else {
|
||||
self::applyWhere($q, $col, $val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// or where
|
||||
if (!empty($config['orWhere'])) {
|
||||
$q->where(function($q) use($config) {
|
||||
foreach ($config['orWhere'] as $cond) {
|
||||
[$col,$op,$val] = $cond;
|
||||
$q->orWhere($col,$op,$val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 排序
|
||||
if (!empty($config['order'])) {
|
||||
foreach ($config['order'] as $col => $dir) {
|
||||
$q->orderBy($col, strtolower($dir) === 'asc' ? 'asc' : 'desc');
|
||||
}
|
||||
}
|
||||
|
||||
// 数据权限过滤
|
||||
if (!empty($config['dataLimit'])) {
|
||||
self::applyDataLimit($q, $config['dataLimit']);
|
||||
}
|
||||
|
||||
return $q;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param int $perPage
|
||||
* @param int $page
|
||||
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
|
||||
*/
|
||||
public static function paginate(Builder $q, int $perPage, int $page)
|
||||
{
|
||||
return $q->paginate($perPage, ['*'], 'page', $page);
|
||||
}
|
||||
|
||||
/**
|
||||
* 非分页查询
|
||||
*
|
||||
* @param Builder $query
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
*/
|
||||
public static function getAll(Builder $q)
|
||||
{
|
||||
return $q->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行复杂查询——仅在显式调用时生效
|
||||
*
|
||||
* @param string $modelClass 模型类
|
||||
* @param callable $callback function(Builder $q) { ... }
|
||||
* @return mixed 由 callback 返回的结果
|
||||
*/
|
||||
public static function executeComplex(string $modelClass, callable $cb)
|
||||
{
|
||||
/** @var Model $model */
|
||||
$model = new $modelClass;
|
||||
return $cb($model->newQuery());
|
||||
}
|
||||
|
||||
/**
|
||||
* 主键单条查询
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param mixed $id
|
||||
* @param array $with
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function findByPk(string $modelClass, $id, array $with = []): Model
|
||||
{
|
||||
$m = $modelClass::with($with)->find($id);
|
||||
if (!$m) {
|
||||
throw new BusinessException("记录 ID={$id} 不存在", 404);
|
||||
}
|
||||
return $m;
|
||||
}
|
||||
|
||||
/**
|
||||
* 任意条件单条查询,支持 dataLimit
|
||||
*
|
||||
* @param Builder $query
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function findOneBy(Builder $q): Model
|
||||
{
|
||||
$model = $q->first();
|
||||
if (!$model) {
|
||||
throw new BusinessException("记录不存在", 404);
|
||||
}
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建,支持 dataLimit
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param array $data
|
||||
* @param array $dataLimit
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function create(
|
||||
string $modelClass,
|
||||
array $data,
|
||||
array $dataLimit = []
|
||||
): Model {
|
||||
// dataLimit 检查/注入
|
||||
if (!empty($dataLimit)) {
|
||||
self::applyDataLimitOnMutate($data, $dataLimit);
|
||||
}
|
||||
return $modelClass::create($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 主键更新,支持 dataLimit
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param mixed $id
|
||||
* @param array $data
|
||||
* @param array $dataLimit
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function updateByPk(
|
||||
string $modelClass,
|
||||
$id,
|
||||
array $data,
|
||||
array $dataLimit = []
|
||||
): Model {
|
||||
/** @var Model $m */
|
||||
$m = $modelClass::find($id);
|
||||
if (!$m) {
|
||||
throw new BusinessException("记录 ID={$id} 不存在", 404);
|
||||
}
|
||||
// dataLimit 校验
|
||||
if (!empty($dataLimit)) {
|
||||
self::applyDataLimitOnMutate($m, $dataLimit, $data);
|
||||
}
|
||||
$m->fill($data)->save();
|
||||
return $m;
|
||||
}
|
||||
|
||||
/**
|
||||
* 非主键条件更新(批量),支持 dataLimit
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param array $data
|
||||
* @return int 受影响行数
|
||||
*/
|
||||
public static function updateBy(Builder $q, array $data): int
|
||||
{
|
||||
return $q->update($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 主键删除(支持批量)
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param array $ids
|
||||
* @return int 删除条数
|
||||
*/
|
||||
public static function deleteByPk(string $modelClass, array $ids): int
|
||||
{
|
||||
return $modelClass::destroy($ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 非主键条件删除,支持 dataLimit
|
||||
*
|
||||
* @param Builder $query
|
||||
* @return int 删除条数
|
||||
*/
|
||||
public static function deleteBy(Builder $q): int
|
||||
{
|
||||
return $q->delete();
|
||||
}
|
||||
|
||||
|
||||
//=================== Internal Methods ===================//
|
||||
|
||||
|
||||
/**
|
||||
* 支持多层的 whereHas:$relations=['roles','permissions'],$leaf='name'
|
||||
*/
|
||||
protected static function applyNestedWhere(Builder $q, array $relations, string $leaf, $val): void
|
||||
{
|
||||
$rel = array_shift($relations);
|
||||
$q->whereHas($rel, function (Builder $qr) use ($relations, $leaf, $val) {
|
||||
if ($relations) {
|
||||
// 还有更深层,继续递归
|
||||
self::applyNestedWhere($qr, $relations, $leaf, $val);
|
||||
} else {
|
||||
// 最后一层,使用普通 applyWhere
|
||||
self::applyWhere($qr, $leaf, $val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 单字段 where 支持:
|
||||
* - 多条件数组 [ [op1,val1], [op2,val2], … ]
|
||||
* - 单条件 ['op', val]
|
||||
* - 直接值
|
||||
*
|
||||
* @param Builder $q
|
||||
* @param string $col
|
||||
* @param mixed $val
|
||||
* @return void
|
||||
*/
|
||||
protected static function applyWhere(Builder $q, string $col, $val): void
|
||||
{
|
||||
// 多条件数组
|
||||
if (is_array($val) && isset($val[0]) && is_array($val[0])) {
|
||||
foreach ($val as $pair) {
|
||||
if (is_array($pair) && count($pair) === 2) {
|
||||
self::applySingleWhere($q, $col, $pair[0], $pair[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 单条件
|
||||
elseif (is_array($val) && count($val) === 2) {
|
||||
self::applySingleWhere($q, $col, $val[0], $val[1]);
|
||||
}
|
||||
// 直接等值
|
||||
else {
|
||||
$q->where($col, $val);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行条件 where
|
||||
*/
|
||||
protected static function applySingleWhere(Builder $q, string $col, string $op, $v): void
|
||||
{
|
||||
switch (strtolower($op)) {
|
||||
case 'like':
|
||||
$q->where($col, 'like', $v);
|
||||
break;
|
||||
case 'in':
|
||||
$q->whereIn($col, (array)$v);
|
||||
break;
|
||||
case 'not in':
|
||||
$q->whereNotIn($col, (array)$v);
|
||||
break;
|
||||
case 'null':
|
||||
$q->whereNull($col);
|
||||
break;
|
||||
case 'not null':
|
||||
$q->whereNotNull($col);
|
||||
break;
|
||||
case 'between':
|
||||
$q->whereBetween($col, (array)$v);
|
||||
break;
|
||||
default:
|
||||
$q->where($col, $op, $v);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ================== Data Limit ==================
|
||||
|
||||
/**
|
||||
* 应用数据权限过滤到查询(buildQuery 场景)
|
||||
*/
|
||||
protected static function applyDataLimit(Builder $q, array $dataLimit): void
|
||||
{
|
||||
$type = $dataLimit['type'] ?? 'personal';
|
||||
$userId = $dataLimit['userId'] ?? 0;
|
||||
$roleId = $dataLimit['roleId'] ?? 0;
|
||||
$userField = $dataLimit['userField'] ?? 'user_id';
|
||||
$roleField = $dataLimit['roleField'] ?? 'role_id';
|
||||
|
||||
self::applyQueryPermission($q, $type, $userId, $roleId, $userField, $roleField);
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用数据权限到"创建/更新"操作
|
||||
*
|
||||
* - $target 可能是 array|Model 对象
|
||||
* - $newData 仅在 updateByPk 场景时传入,用以校验变更归属
|
||||
*/
|
||||
protected static function applyDataLimitOnMutate(&$target, array $dataLimit, array $newData = []): void
|
||||
{
|
||||
$type = $dataLimit['type'] ?? 'personal';
|
||||
$userId = $dataLimit['userId'] ?? 0;
|
||||
$roleId = $dataLimit['roleId'] ?? 0;
|
||||
$userField = $dataLimit['userField'] ?? 'user_id';
|
||||
$roleField = $dataLimit['roleField'] ?? 'role_id';
|
||||
|
||||
self::applyMutationPermission($target, $type, $userId, $roleId, $newData, $userField, $roleField);
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用数据权限过滤到查询
|
||||
*
|
||||
* @param Builder $query 查询构造器
|
||||
* @param string $type 权限类型:superadmin, personal, same_role, role_tree, relation
|
||||
* @param int $currentUserId 当前用户ID
|
||||
* @param int $currentRoleId 当前角色ID
|
||||
* @param string $userField 用户ID字段名
|
||||
* @param string $roleField 角色ID字段名
|
||||
*/
|
||||
public static function applyQueryPermission(
|
||||
Builder $query,
|
||||
string $type,
|
||||
int $currentUserId = 0,
|
||||
int $currentRoleId = 0,
|
||||
string $userField = 'user_id',
|
||||
string $roleField = 'role_id'
|
||||
): void {
|
||||
// 超管不需要过滤
|
||||
if (self::isSuperAdmin($currentUserId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($type) {
|
||||
case 'personal':
|
||||
// 个人权限:只能访问自己的数据
|
||||
$query->where($userField, $currentUserId);
|
||||
break;
|
||||
|
||||
case 'same_role':
|
||||
// 同角色权限:访问同角色的数据
|
||||
$userIds = self::getSameRoleUserIds($currentRoleId);
|
||||
$query->whereIn($userField, $userIds);
|
||||
break;
|
||||
|
||||
case 'role_tree':
|
||||
// 角色树权限:访问自己角色及子角色的数据
|
||||
$userIds = self::getRoleTreeUserIds($currentRoleId);
|
||||
$query->whereIn($userField, $userIds);
|
||||
break;
|
||||
|
||||
case 'relation':
|
||||
// 从属关系权限:访问自己及下属的数据
|
||||
$userIds = self::getRelationUserIds($currentUserId);
|
||||
$query->whereIn($userField, $userIds);
|
||||
break;
|
||||
|
||||
default:
|
||||
// 默认个人权限
|
||||
$query->where($userField, $currentUserId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用数据权限到创建/更新操作
|
||||
*
|
||||
* @param mixed $target 创建时为数组,更新时为Model对象
|
||||
* @param string $type 权限类型
|
||||
* @param int $currentUserId 当前用户ID
|
||||
* @param int $currentRoleId 当前角色ID
|
||||
* @param array $newData 更新时的数据
|
||||
* @param string $userField 用户ID字段名
|
||||
* @param string $roleField 角色ID字段名
|
||||
*/
|
||||
public static function applyMutationPermission(
|
||||
&$target,
|
||||
string $type,
|
||||
int $currentUserId,
|
||||
int $currentRoleId,
|
||||
array $newData = [],
|
||||
string $userField = 'user_id',
|
||||
string $roleField = 'role_id'
|
||||
): void {
|
||||
// 超管不需要检查
|
||||
if (self::isSuperAdmin($currentUserId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($type) {
|
||||
case 'personal':
|
||||
self::handlePersonalPermission($target, $newData, $userField, $currentUserId);
|
||||
break;
|
||||
|
||||
case 'same_role':
|
||||
self::handleSameRolePermission($target, $newData, $userField, $roleField, $currentRoleId);
|
||||
break;
|
||||
|
||||
case 'role_tree':
|
||||
self::handleRoleTreePermission($target, $newData, $userField, $roleField, $currentRoleId);
|
||||
break;
|
||||
|
||||
case 'relation':
|
||||
self::handleRelationPermission($target, $newData, $userField, $currentUserId);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new BusinessException("未定义的数据权限类型: $type", 403);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同角色的用户ID列表
|
||||
*
|
||||
* @param int $roleId 角色ID
|
||||
* @return array 用户ID列表
|
||||
*/
|
||||
public static function getSameRoleUserIds(int $roleId): array
|
||||
{
|
||||
return Db::table('user_roles')
|
||||
->where('role_id', $roleId)
|
||||
->pluck('user_id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取角色树下的所有用户ID列表
|
||||
*
|
||||
* @param int $roleId 当前角色ID
|
||||
* @return array 用户ID列表
|
||||
*/
|
||||
public static function getRoleTreeUserIds(int $roleId): array
|
||||
{
|
||||
// 获取角色树中的所有角色ID
|
||||
$roleIds = self::getRoleTreeIds($roleId);
|
||||
|
||||
// 获取这些角色下的所有用户ID
|
||||
return Db::table('user_roles')
|
||||
->whereIn('role_id', $roleIds)
|
||||
->pluck('user_id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取从属关系下的用户ID列表(包括自己和下属)
|
||||
*
|
||||
* @param int $userId 当前用户ID
|
||||
* @return array 用户ID列表
|
||||
*/
|
||||
public static function getRelationUserIds(int $userId): array
|
||||
{
|
||||
// 获取所有下属用户ID(递归)
|
||||
$subordinateIds = self::getSubordinateIds($userId);
|
||||
|
||||
// 返回自己和所有下属的ID
|
||||
return array_merge([$userId], $subordinateIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取直接下属的用户ID列表
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return array 直接下属用户ID列表
|
||||
*/
|
||||
public static function getDirectSubordinateIds(int $userId): array
|
||||
{
|
||||
return Db::table('user')
|
||||
->where('report_to', $userId)
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归获取所有下属用户ID列表
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return array 所有下属用户ID列表
|
||||
*/
|
||||
private static function getSubordinateIds(int $userId): array
|
||||
{
|
||||
$subordinates = self::getDirectSubordinateIds($userId);
|
||||
$allSubordinates = $subordinates;
|
||||
|
||||
foreach ($subordinates as $subordinateId) {
|
||||
$allSubordinates = array_merge($allSubordinates, self::getSubordinateIds($subordinateId));
|
||||
}
|
||||
|
||||
return $allSubordinates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理个人权限
|
||||
*/
|
||||
private static function handlePersonalPermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
int $currentUserId
|
||||
): void {
|
||||
if (is_array($target)) {
|
||||
// 创建时强制设置用户ID
|
||||
$target[$userField] = $currentUserId;
|
||||
} else {
|
||||
// 更新时校验原始记录
|
||||
if ($target->{$userField} !== $currentUserId) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 禁止变更归属字段
|
||||
if (isset($newData[$userField]) && $newData[$userField] !== $currentUserId) {
|
||||
throw new BusinessException("无权变更归属字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理同角色权限
|
||||
*/
|
||||
private static function handleSameRolePermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
string $roleField,
|
||||
int $currentRoleId
|
||||
): void {
|
||||
// 获取同角色用户ID列表
|
||||
$sameRoleUserIds = self::getSameRoleUserIds($currentRoleId);
|
||||
|
||||
if (is_array($target)) {
|
||||
// 创建时设置归属用户并校验
|
||||
if (isset($target[$userField])) {
|
||||
if (!in_array($target[$userField], $sameRoleUserIds)) {
|
||||
throw new BusinessException("无权为指定用户创建数据", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$userField] = $currentRoleId;
|
||||
}
|
||||
} else {
|
||||
// 更新时校验原始记录
|
||||
if (!in_array($target->{$userField}, $sameRoleUserIds)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 禁止变更归属字段到无权限的用户
|
||||
if (isset($newData[$userField]) && !in_array($newData[$userField], $sameRoleUserIds)) {
|
||||
throw new BusinessException("无权变更归属字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理角色树权限
|
||||
*/
|
||||
private static function handleRoleTreePermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
string $roleField,
|
||||
int $currentRoleId
|
||||
): void {
|
||||
// 获取角色树用户ID列表
|
||||
$roleTreeUserIds = self::getRoleTreeUserIds($currentRoleId);
|
||||
|
||||
if (is_array($target)) {
|
||||
// 创建时校验用户是否在允许范围内
|
||||
if (isset($target[$userField])) {
|
||||
if (!in_array($target[$userField], $roleTreeUserIds)) {
|
||||
throw new BusinessException("无权为指定用户创建数据", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$userField] = $currentRoleId;
|
||||
}
|
||||
} else {
|
||||
// 更新时校验原始记录用户
|
||||
if (!in_array($target->{$userField}, $roleTreeUserIds)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 校验新用户是否在允许范围内
|
||||
if (isset($newData[$userField])) {
|
||||
if (!in_array($newData[$userField], $roleTreeUserIds)) {
|
||||
throw new BusinessException("无权变更用户字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理从属关系权限
|
||||
*/
|
||||
private static function handleRelationPermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
int $currentUserId
|
||||
): void {
|
||||
// 获取从属关系用户ID列表
|
||||
$relationUserIds = self::getRelationUserIds($currentUserId);
|
||||
|
||||
if (is_array($target)) {
|
||||
// 创建时校验用户是否在允许范围内
|
||||
if (isset($target[$userField])) {
|
||||
if (!in_array($target[$userField], $relationUserIds)) {
|
||||
throw new BusinessException("无权为指定用户创建数据", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$userField] = $currentUserId;
|
||||
}
|
||||
} else {
|
||||
// 更新时校验原始记录用户
|
||||
if (!in_array($target->{$userField}, $relationUserIds)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 校验新用户是否在允许范围内
|
||||
if (isset($newData[$userField])) {
|
||||
if (!in_array($newData[$userField], $relationUserIds)) {
|
||||
throw new BusinessException("无权变更用户字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取角色树ID(当前角色及其所有子角色)
|
||||
* 从数据库中动态获取角色树关系
|
||||
*/
|
||||
private static function getRoleTreeIds(int $roleId): array
|
||||
{
|
||||
static $roleTreeCache = [];
|
||||
|
||||
if (isset($roleTreeCache[$roleId])) {
|
||||
return $roleTreeCache[$roleId];
|
||||
}
|
||||
|
||||
// 从数据库中递归获取角色树
|
||||
$ids = [$roleId];
|
||||
$queue = [$roleId];
|
||||
|
||||
while (!empty($queue)) {
|
||||
$current = array_shift($queue);
|
||||
// 查找当前角色的所有子角色
|
||||
$childRoles = Db::table('roles')
|
||||
->where('parent_id', $current)
|
||||
->where('status', 1) // 只获取启用的角色
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
foreach ($childRoles as $childId) {
|
||||
if (!in_array($childId, $ids)) {
|
||||
$ids[] = $childId;
|
||||
$queue[] = $childId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$roleTreeCache[$roleId] = $ids;
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为超管
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return bool 是否为超管
|
||||
*/
|
||||
public static function isSuperAdmin(int $userId): bool
|
||||
{
|
||||
// 检查用户是否关联了超级管理员角色
|
||||
// 设定角色ID为1的是超级管理员角色
|
||||
$superAdminRoleId = 1;
|
||||
|
||||
return Db::table('user_roles')
|
||||
->where('user_id', $userId)
|
||||
->where('role_id', $superAdminRoleId)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户的角色ID
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return int 角色ID
|
||||
*/
|
||||
public static function getUserIdRoleId(int $userId): int
|
||||
{
|
||||
// 从 user_roles 表中获取当前用户的角色ID
|
||||
$roleId = Db::table('user_roles')
|
||||
->where('user_id', $userId)
|
||||
->value('role_id');
|
||||
|
||||
return $roleId ?: 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户的所有角色ID(包括继承的角色)
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return array 角色ID列表
|
||||
*/
|
||||
public static function getUserAllRoleIds(int $userId): array
|
||||
{
|
||||
// 获取用户直接关联的角色
|
||||
$directRoleIds = Db::table('user_roles')
|
||||
->where('user_id', $userId)
|
||||
->pluck('role_id')
|
||||
->toArray();
|
||||
|
||||
// 获取所有继承的角色
|
||||
$allRoleIds = [];
|
||||
foreach ($directRoleIds as $roleId) {
|
||||
$allRoleIds = array_merge($allRoleIds, self::getRoleTreeIds($roleId));
|
||||
}
|
||||
|
||||
// 去重并返回
|
||||
return array_unique($allRoleIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,843 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use support\exception\BusinessException;
|
||||
use support\Db;
|
||||
|
||||
/**
|
||||
* 构建查询工具类
|
||||
* | 方法 | 说明 |
|
||||
* | ------------------------------- | --------------------- |
|
||||
* | `buildQuery($config)` | 构建动态查询(关联加载/字段/过滤/排序) |
|
||||
* | `paginate($q,$per,$page)` | 分页返回 Paginator |
|
||||
* | `getAll($q)` | 不分页直接 `get()` |
|
||||
* | `findByPk($model,$id)` | 根据主键查询单条,找不到抛 404 |
|
||||
* | `findOneBy($model,$where)` | 根据任意条件查询单条,找不到抛 404 |
|
||||
* | `deleteByPk($model,$ids)` | 根据主键删除(可批量),返回删除条数 |
|
||||
* | `deleteBy($model,$where)` | 根据任意条件删除,返回删除条数 |
|
||||
* | `updateByPk($model,$id,$data)` | 根据主键更新,找不到抛 404 |
|
||||
* | `updateBy($model,$where,$data)` | 根据任意条件更新,返回影响行数 |
|
||||
*/
|
||||
|
||||
class CrudUtil_bak
|
||||
{
|
||||
|
||||
/**
|
||||
* 构建查询,支持:
|
||||
* - 本表字段过滤 where
|
||||
* - 关联加载 with
|
||||
* - 关联表字段选择 withFields
|
||||
* - 关联表字段过滤 where with dot-notation
|
||||
* - 排序 order
|
||||
* - 本表字段选择 fields
|
||||
*
|
||||
* $config = [
|
||||
* 'model' => User::class,
|
||||
* 'where' => [
|
||||
* 'status' => 1,
|
||||
* 'name' => ['like','%张%'],
|
||||
* 'roles.name' => '管理员', // 关联表字段过滤
|
||||
* 'posts.created_at'=> ['>','2025-01-01'],
|
||||
* ],
|
||||
* 'order' => ['id'=>'desc'],
|
||||
* 'fields' => ['id','name','email'],
|
||||
* 'with' => ['roles','posts'],
|
||||
* 'withFields' => [
|
||||
* 'roles' => ['id','name'], // 关联表字段选择
|
||||
* 'posts' => ['id','title','user_id'],
|
||||
* ],
|
||||
* ];
|
||||
*/
|
||||
public static function buildQuery(array $config): Builder
|
||||
{
|
||||
/** @var Model $model */
|
||||
$model = new $config['model'];
|
||||
$q = $model->newQuery();
|
||||
|
||||
// eager-load:支持 ['rel','rel2'] 和 ['rel'=>fields[], ...]
|
||||
if (! empty($config['with'])) {
|
||||
foreach ($config['with'] as $rel => $fields) {
|
||||
if (is_int($rel)) {
|
||||
// 普通关联
|
||||
$q->with($fields);
|
||||
} else {
|
||||
// 带字段筛选的关联
|
||||
$q->with([$rel => function ($qr) use ($fields) {
|
||||
$key = $qr->getModel()->getKeyName();
|
||||
if (! in_array($key, $fields, true)) {
|
||||
$fields[] = $key;
|
||||
}
|
||||
$qr->select($fields);
|
||||
}]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 表字段
|
||||
if (!empty($config['fields'])) {
|
||||
$q->select($config['fields']);
|
||||
}
|
||||
|
||||
// where
|
||||
if (!empty($config['where'])) {
|
||||
foreach ($config['where'] as $col => $val) {
|
||||
if (strpos($col, '.') !== false) {
|
||||
// 多层支持
|
||||
$segments = explode('.', $col);
|
||||
$leaf = array_pop($segments);
|
||||
self::applyNestedWhere($q, $segments, $leaf, $val);
|
||||
} else {
|
||||
self::applyWhere($q, $col, $val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// or where
|
||||
if (!empty($config['orWhere'])) {
|
||||
$q->where(function($q) use($config) {
|
||||
foreach ($config['orWhere'] as $cond) {
|
||||
[$col,$op,$val] = $cond;
|
||||
$q->orWhere($col,$op,$val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 排序
|
||||
if (!empty($config['order'])) {
|
||||
foreach ($config['order'] as $col => $dir) {
|
||||
$q->orderBy($col, strtolower($dir) === 'asc' ? 'asc' : 'desc');
|
||||
}
|
||||
}
|
||||
|
||||
// 数据权限过滤
|
||||
if (!empty($config['dataLimit'])) {
|
||||
self::applyDataLimit($q, $config['dataLimit']);
|
||||
}
|
||||
|
||||
return $q;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param int $perPage
|
||||
* @param int $page
|
||||
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
|
||||
*/
|
||||
public static function paginate(Builder $q, int $perPage, int $page)
|
||||
{
|
||||
return $q->paginate($perPage, ['*'], 'page', $page);
|
||||
}
|
||||
|
||||
/**
|
||||
* 非分页查询
|
||||
*
|
||||
* @param Builder $query
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
*/
|
||||
public static function getAll(Builder $q)
|
||||
{
|
||||
return $q->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行复杂查询——仅在显式调用时生效
|
||||
*
|
||||
* @param string $modelClass 模型类
|
||||
* @param callable $callback function(Builder $q) { ... }
|
||||
* @return mixed 由 callback 返回的结果
|
||||
*/
|
||||
public static function executeComplex(string $modelClass, callable $cb)
|
||||
{
|
||||
/** @var Model $model */
|
||||
$model = new $modelClass;
|
||||
return $cb($model->newQuery());
|
||||
}
|
||||
|
||||
/**
|
||||
* 主键单条查询
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param mixed $id
|
||||
* @param array $with
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function findByPk(string $modelClass, $id, array $with = []): Model
|
||||
{
|
||||
$m = $modelClass::with($with)->find($id);
|
||||
if (!$m) {
|
||||
throw new BusinessException("记录 ID={$id} 不存在", 404);
|
||||
}
|
||||
return $m;
|
||||
}
|
||||
|
||||
/**
|
||||
* 任意条件单条查询,支持 dataLimit
|
||||
*
|
||||
* @param Builder $query
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function findOneBy(Builder $q): Model
|
||||
{
|
||||
return $q->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建,支持 dataLimit
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param array $data
|
||||
* @param array $dataLimit
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function create(
|
||||
string $modelClass,
|
||||
array $data,
|
||||
array $dataLimit = []
|
||||
): Model {
|
||||
// dataLimit 检查/注入
|
||||
if (!empty($dataLimit)) {
|
||||
self::applyDataLimitOnMutate($data, $dataLimit);
|
||||
}
|
||||
return $modelClass::create($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 主键更新,支持 dataLimit
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param mixed $id
|
||||
* @param array $data
|
||||
* @param array $dataLimit
|
||||
* @return Model
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public static function updateByPk(
|
||||
string $modelClass,
|
||||
$id,
|
||||
array $data,
|
||||
array $dataLimit = []
|
||||
): Model {
|
||||
/** @var Model $m */
|
||||
$m = $modelClass::find($id);
|
||||
if (!$m) {
|
||||
throw new BusinessException("记录 ID={$id} 不存在", 404);
|
||||
}
|
||||
// dataLimit 校验
|
||||
if (!empty($dataLimit)) {
|
||||
self::applyDataLimitOnMutate($m, $dataLimit, $data);
|
||||
}
|
||||
$m->fill($data)->save();
|
||||
return $m;
|
||||
}
|
||||
|
||||
/**
|
||||
* 非主键条件更新(批量),支持 dataLimit
|
||||
*
|
||||
* @param Builder $query
|
||||
* @param array $data
|
||||
* @return int 受影响行数
|
||||
*/
|
||||
public static function updateBy(Builder $q, array $data): int
|
||||
{
|
||||
return $q->update($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 主键删除(支持批量)
|
||||
*
|
||||
* @param string $modelClass
|
||||
* @param array $ids
|
||||
* @return int 删除条数
|
||||
*/
|
||||
public static function deleteByPk(string $modelClass, array $ids): int
|
||||
{
|
||||
return $modelClass::destroy($ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 非主键条件删除,支持 dataLimit
|
||||
*
|
||||
* @param Builder $query
|
||||
* @return int 删除条数
|
||||
*/
|
||||
public static function deleteBy(Builder $q): int
|
||||
{
|
||||
return $q->delete();
|
||||
}
|
||||
|
||||
|
||||
//=================== Internal Methods ===================//
|
||||
|
||||
|
||||
/**
|
||||
* 支持多层的 whereHas:$relations=['roles','permissions'],$leaf='name'
|
||||
*/
|
||||
protected static function applyNestedWhere(Builder $q, array $relations, string $leaf, $val): void
|
||||
{
|
||||
$rel = array_shift($relations);
|
||||
$q->whereHas($rel, function (Builder $qr) use ($relations, $leaf, $val) {
|
||||
if ($relations) {
|
||||
// 还有更深层,继续递归
|
||||
self::applyNestedWhere($qr, $relations, $leaf, $val);
|
||||
} else {
|
||||
// 最后一层,使用普通 applyWhere
|
||||
self::applyWhere($qr, $leaf, $val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 单字段 where 支持:
|
||||
* - 多条件数组 [ [op1,val1], [op2,val2], … ]
|
||||
* - 单条件 ['op', val]
|
||||
* - 直接值
|
||||
*
|
||||
* @param Builder $q
|
||||
* @param string $col
|
||||
* @param mixed $val
|
||||
* @return void
|
||||
*/
|
||||
protected static function applyWhere(Builder $q, string $col, $val): void
|
||||
{
|
||||
// 多条件数组
|
||||
if (is_array($val) && isset($val[0]) && is_array($val[0])) {
|
||||
foreach ($val as $pair) {
|
||||
if (is_array($pair) && count($pair) === 2) {
|
||||
self::applySingleWhere($q, $col, $pair[0], $pair[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 单条件
|
||||
elseif (is_array($val) && count($val) === 2) {
|
||||
self::applySingleWhere($q, $col, $val[0], $val[1]);
|
||||
}
|
||||
// 直接等值
|
||||
else {
|
||||
$q->where($col, $val);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行条件 where
|
||||
*/
|
||||
protected static function applySingleWhere(Builder $q, string $col, string $op, $v): void
|
||||
{
|
||||
switch (strtolower($op)) {
|
||||
case 'like':
|
||||
$q->where($col, 'like', $v);
|
||||
break;
|
||||
case 'in':
|
||||
$q->whereIn($col, (array)$v);
|
||||
break;
|
||||
case 'not in':
|
||||
$q->whereNotIn($col, (array)$v);
|
||||
break;
|
||||
case 'null':
|
||||
$q->whereNull($col);
|
||||
break;
|
||||
case 'not null':
|
||||
$q->whereNotNull($col);
|
||||
break;
|
||||
case 'between':
|
||||
$q->whereBetween($col, (array)$v);
|
||||
break;
|
||||
default:
|
||||
$q->where($col, $op, $v);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ================== Data Limit ==================
|
||||
|
||||
/**
|
||||
* 应用数据权限过滤到查询
|
||||
*
|
||||
* @param Builder $query 查询构造器
|
||||
* @param string $type 权限类型:superadmin, personal, same_role, role_tree, relation
|
||||
* @param int $currentUserId 当前用户ID
|
||||
* @param int $currentRoleId 当前角色ID
|
||||
* @param string $userField 用户ID字段名
|
||||
* @param string $roleField 角色ID字段名
|
||||
*/
|
||||
public static function applyQueryPermission(
|
||||
Builder $query,
|
||||
string $type,
|
||||
int $currentUserId = 0,
|
||||
int $currentRoleId = 0,
|
||||
string $userField = 'user_id',
|
||||
string $roleField = 'role_id'
|
||||
): void {
|
||||
// 超管不需要过滤
|
||||
if (self::isSuperAdmin($currentUserId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($type) {
|
||||
case 'personal':
|
||||
// 个人权限:只能访问自己的数据
|
||||
$query->where($userField, $currentUserId);
|
||||
break;
|
||||
|
||||
case 'same_role':
|
||||
// 同角色权限:访问同角色的数据
|
||||
$userIds = self::getSameRoleUserIds($currentRoleId);
|
||||
$query->whereIn($userField, $userIds);
|
||||
break;
|
||||
|
||||
case 'role_tree':
|
||||
// 角色树权限:访问自己角色及子角色的数据
|
||||
$userIds = self::getRoleTreeUserIds($currentRoleId);
|
||||
$query->whereIn($userField, $userIds);
|
||||
break;
|
||||
|
||||
case 'relation':
|
||||
// 从属关系权限:访问自己及下属的数据
|
||||
$userIds = self::getRelationUserIds($currentUserId);
|
||||
$query->whereIn($userField, $userIds);
|
||||
break;
|
||||
|
||||
default:
|
||||
// 默认个人权限
|
||||
$query->where($userField, $currentUserId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用数据权限到创建/更新操作
|
||||
*
|
||||
* @param mixed $target 创建时为数组,更新时为Model对象
|
||||
* @param string $type 权限类型
|
||||
* @param int $currentUserId 当前用户ID
|
||||
* @param int $currentRoleId 当前角色ID
|
||||
* @param array $newData 更新时的数据
|
||||
* @param string $userField 用户ID字段名
|
||||
* @param string $roleField 角色ID字段名
|
||||
*/
|
||||
public static function applyMutationPermission(
|
||||
&$target,
|
||||
string $type,
|
||||
int $currentUserId,
|
||||
int $currentRoleId,
|
||||
array $newData = [],
|
||||
string $userField = 'admin_id',
|
||||
string $roleField = 'role_id'
|
||||
): void {
|
||||
// 超管不需要检查
|
||||
if (self::isSuperAdmin($currentUserId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($type) {
|
||||
case 'personal':
|
||||
self::handlePersonalPermission($target, $newData, $userField, $currentUserId);
|
||||
break;
|
||||
|
||||
case 'same_role':
|
||||
self::handleSameRolePermission($target, $newData, $userField, $roleField, $currentRoleId);
|
||||
break;
|
||||
|
||||
case 'role_tree':
|
||||
self::handleRoleTreePermission($target, $newData, $userField, $roleField, $currentRoleId);
|
||||
break;
|
||||
|
||||
case 'relation':
|
||||
self::handleRelationPermission($target, $newData, $userField, $currentUserId);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new BusinessException("未定义的数据权限类型: $type", 403);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同角色的用户ID列表
|
||||
*
|
||||
* @param int $roleId 角色ID
|
||||
* @return array 用户ID列表
|
||||
*/
|
||||
public static function getSameRoleUserIds(int $roleId): array
|
||||
{
|
||||
return Db::table('user_roles')
|
||||
->where('role_id', $roleId)
|
||||
->pluck('user_id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取角色树下的所有用户ID列表
|
||||
*
|
||||
* @param int $roleId 当前角色ID
|
||||
* @return array 用户ID列表
|
||||
*/
|
||||
public static function getRoleTreeUserIds(int $roleId): array
|
||||
{
|
||||
// 获取角色树中的所有角色ID
|
||||
$roleIds = self::getRoleTreeIds($roleId);
|
||||
|
||||
// 获取这些角色下的所有用户ID
|
||||
return Db::table('user_roles')
|
||||
->whereIn('role_id', $roleIds)
|
||||
->pluck('user_id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取从属关系下的用户ID列表(包括自己和下属)
|
||||
*
|
||||
* @param int $userId 当前用户ID
|
||||
* @return array 用户ID列表
|
||||
*/
|
||||
public static function getRelationUserIds(int $userId): array
|
||||
{
|
||||
// 获取所有下属用户ID(递归)
|
||||
$subordinateIds = self::getSubordinateIds($userId);
|
||||
|
||||
// 返回自己和所有下属的ID
|
||||
return array_merge([$userId], $subordinateIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取直接下属的用户ID列表
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return array 直接下属用户ID列表
|
||||
*/
|
||||
public static function getDirectSubordinateIds(int $userId): array
|
||||
{
|
||||
return Db::table('user')
|
||||
->where('report_to', $userId)
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归获取所有下属用户ID列表
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return array 所有下属用户ID列表
|
||||
*/
|
||||
private static function getSubordinateIds(int $userId): array
|
||||
{
|
||||
$subordinates = self::getDirectSubordinateIds($userId);
|
||||
$allSubordinates = $subordinates;
|
||||
|
||||
foreach ($subordinates as $subordinateId) {
|
||||
$allSubordinates = array_merge($allSubordinates, self::getSubordinateIds($subordinateId));
|
||||
}
|
||||
|
||||
return $allSubordinates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理个人权限
|
||||
*/
|
||||
private static function handlePersonalPermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
int $currentUserId
|
||||
): void {
|
||||
if (is_array($target)) {
|
||||
// 创建时强制设置用户ID
|
||||
$target[$userField] = $currentUserId;
|
||||
} else {
|
||||
// 更新时校验原始记录
|
||||
if ($target->{$userField} !== $currentUserId) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 禁止变更归属字段
|
||||
if (isset($newData[$userField]) && $newData[$userField] !== $currentUserId) {
|
||||
throw new BusinessException("无权变更归属字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理同角色权限
|
||||
*/
|
||||
private static function handleSameRolePermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
string $roleField,
|
||||
int $currentRoleId
|
||||
): void {
|
||||
// 获取同角色用户ID列表
|
||||
$sameRoleUserIds = self::getSameRoleUserIds($currentRoleId);
|
||||
|
||||
if (is_array($target)) {
|
||||
// 创建时设置归属用户并校验
|
||||
if (isset($target[$userField])) {
|
||||
if (!in_array($target[$userField], $sameRoleUserIds)) {
|
||||
throw new BusinessException("无权为指定用户创建数据", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$userField] = $currentRoleId;
|
||||
}
|
||||
} else {
|
||||
// 更新时校验原始记录
|
||||
if (!in_array($target->{$userField}, $sameRoleUserIds)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 禁止变更归属字段到无权限的用户
|
||||
if (isset($newData[$userField]) && !in_array($newData[$userField], $sameRoleUserIds)) {
|
||||
throw new BusinessException("无权变更归属字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理角色树权限
|
||||
*/
|
||||
private static function handleRoleTreePermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
string $roleField,
|
||||
int $currentRoleId
|
||||
): void {
|
||||
// 获取角色树用户ID列表
|
||||
$roleTreeUserIds = self::getRoleTreeUserIds($currentRoleId);
|
||||
|
||||
if (is_array($target)) {
|
||||
// 创建时校验用户是否在允许范围内
|
||||
if (isset($target[$userField])) {
|
||||
if (!in_array($target[$userField], $roleTreeUserIds)) {
|
||||
throw new BusinessException("无权为指定用户创建数据", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$userField] = $currentRoleId;
|
||||
}
|
||||
} else {
|
||||
// 更新时校验原始记录用户
|
||||
if (!in_array($target->{$userField}, $roleTreeUserIds)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 校验新用户是否在允许范围内
|
||||
if (isset($newData[$userField])) {
|
||||
if (!in_array($newData[$userField], $roleTreeUserIds)) {
|
||||
throw new BusinessException("无权变更用户字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理从属关系权限
|
||||
*/
|
||||
private static function handleRelationPermission(
|
||||
&$target,
|
||||
array $newData,
|
||||
string $userField,
|
||||
int $currentUserId
|
||||
): void {
|
||||
// 获取从属关系用户ID列表
|
||||
$relationUserIds = self::getRelationUserIds($currentUserId);
|
||||
|
||||
if (is_array($target)) {
|
||||
// 创建时校验用户是否在允许范围内
|
||||
if (isset($target[$userField])) {
|
||||
if (!in_array($target[$userField], $relationUserIds)) {
|
||||
throw new BusinessException("无权为指定用户创建数据", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$userField] = $currentUserId;
|
||||
}
|
||||
} else {
|
||||
// 更新时校验原始记录用户
|
||||
if (!in_array($target->{$userField}, $relationUserIds)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
|
||||
// 校验新用户是否在允许范围内
|
||||
if (isset($newData[$userField])) {
|
||||
if (!in_array($newData[$userField], $relationUserIds)) {
|
||||
throw new BusinessException("无权变更用户字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取角色树ID(当前角色及其所有子角色)
|
||||
* 从数据库中动态获取角色树关系
|
||||
*/
|
||||
private static function getRoleTreeIds(int $roleId): array
|
||||
{
|
||||
static $roleTreeCache = [];
|
||||
|
||||
if (isset($roleTreeCache[$roleId])) {
|
||||
return $roleTreeCache[$roleId];
|
||||
}
|
||||
|
||||
// 从数据库中递归获取角色树
|
||||
$ids = [$roleId];
|
||||
$queue = [$roleId];
|
||||
|
||||
while (!empty($queue)) {
|
||||
$current = array_shift($queue);
|
||||
// 查找当前角色的所有子角色
|
||||
$childRoles = Db::table('roles')
|
||||
->where('parent_id', $current)
|
||||
->where('status', 1) // 只获取启用的角色
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
foreach ($childRoles as $childId) {
|
||||
if (!in_array($childId, $ids)) {
|
||||
$ids[] = $childId;
|
||||
$queue[] = $childId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$roleTreeCache[$roleId] = $ids;
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为超管
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return bool 是否为超管
|
||||
*/
|
||||
public static function isSuperAdmin(int $userId): bool
|
||||
{
|
||||
// 检查用户是否关联了超级管理员角色
|
||||
// 假设角色ID为1的是超级管理员角色
|
||||
$superAdminRoleId = 1;
|
||||
|
||||
return Db::table('user_roles')
|
||||
->where('user_id', $userId)
|
||||
->where('role_id', $superAdminRoleId)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户的角色ID
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return int 角色ID
|
||||
*/
|
||||
public static function getUserIdRoleId(int $userId): int
|
||||
{
|
||||
// 从 user_roles 表中获取当前用户的角色ID
|
||||
$roleId = Db::table('user_roles')
|
||||
->where('user_id', $userId)
|
||||
->value('role_id');
|
||||
|
||||
return $roleId ?: 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户的所有角色ID(包括继承的角色)
|
||||
*
|
||||
* @param int $userId 用户ID
|
||||
* @return array 角色ID列表
|
||||
*/
|
||||
public static function getUserAllRoleIds(int $userId): array
|
||||
{
|
||||
// 获取用户直接关联的角色
|
||||
$directRoleIds = Db::table('user_roles')
|
||||
->where('user_id', $userId)
|
||||
->pluck('role_id')
|
||||
->toArray();
|
||||
|
||||
// 获取所有继承的角色
|
||||
$allRoleIds = [];
|
||||
foreach ($directRoleIds as $roleId) {
|
||||
$allRoleIds = array_merge($allRoleIds, self::getRoleTreeIds($roleId));
|
||||
}
|
||||
|
||||
// 去重并返回
|
||||
return array_unique($allRoleIds);
|
||||
}
|
||||
|
||||
// ================== Data Limit ==================
|
||||
|
||||
/**
|
||||
* 应用数据权限过滤到查询(buildQuery 场景)
|
||||
*/
|
||||
protected static function applyDataLimit(Builder $q, array $dataLimit): void
|
||||
{
|
||||
if (Auth::isSuperAdmin()) {
|
||||
return;
|
||||
}
|
||||
$type = $dataLimit['type'] ?? null;
|
||||
$field = $dataLimit['field'] ?? 'admin_id';
|
||||
|
||||
if ($type === 'personal') {
|
||||
$q->where($field, admin_id());
|
||||
} elseif ($type === 'auth') {
|
||||
$q->whereIn($field, Auth::getScopeAdminIds(true));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用数据权限到“创建/更新”操作
|
||||
*
|
||||
* - $target 可能是 array|Model 对象
|
||||
* - $newData 仅在 updateByPk 场景时传入,用以校验变更归属
|
||||
*/
|
||||
protected static function applyDataLimitOnMutate(&$target, array $dataLimit, array $newData = []): void
|
||||
{
|
||||
if (Auth::isSuperAdmin()) {
|
||||
return;
|
||||
}
|
||||
$type = $dataLimit['type'] ?? null;
|
||||
$field = $dataLimit['field'] ?? 'admin_id';
|
||||
|
||||
// 读取当前归属:create 时 $target 是 array,update 时是 Model
|
||||
$current = is_array($target) ? null : $target->{$field};
|
||||
|
||||
// 1. personal → 只能自己
|
||||
if ($type === 'personal') {
|
||||
// create: 强制设置
|
||||
if (is_array($target)) {
|
||||
$target[$field] = admin_id();
|
||||
}
|
||||
// update: 校验当前归属
|
||||
elseif ($current !== admin_id()) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
// 若要修改归属,也必须和自己一致
|
||||
if (isset($newData[$field]) && $newData[$field] !== admin_id()) {
|
||||
throw new BusinessException("无权变更归属字段", 403);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. auth → 自己及下属
|
||||
if ($type === 'auth') {
|
||||
$scope = Auth::getScopeAdminIds(true);
|
||||
// create: 若前端指定归属,则校验范围;否则默认自己
|
||||
if (is_array($target)) {
|
||||
if (isset($target[$field])) {
|
||||
if (!in_array($target[$field], $scope)) {
|
||||
throw new BusinessException("无权为指定用户操作", 403);
|
||||
}
|
||||
} else {
|
||||
$target[$field] = admin_id();
|
||||
}
|
||||
}
|
||||
// update: 校验当前归属
|
||||
elseif (!in_array($current, $scope)) {
|
||||
throw new BusinessException("无权操作该记录", 403);
|
||||
}
|
||||
// 校验更新中指定的新归属
|
||||
if (isset($newData[$field]) && !in_array($newData[$field], $scope)) {
|
||||
throw new BusinessException("无权变更归属字段", 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use support\Cache;
|
||||
use Webman\Exception\BusinessException;
|
||||
|
||||
class Feishu
|
||||
{
|
||||
|
||||
protected $appId = '';
|
||||
protected $appSecret = '';
|
||||
protected $baseUri = '';
|
||||
protected $client = null;
|
||||
protected $options = [];
|
||||
protected $error = '';
|
||||
protected $abbr = 'hesu';
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
public function __construct(string $appId = '', string $appSecret = '', string $abbr = 'hesu')
|
||||
{
|
||||
|
||||
if ($abbr === 'mbaf') {
|
||||
$this->baseUri = 'https://open.larksuite.com/open-apis/';
|
||||
} else {
|
||||
$this->baseUri = 'https://open.feishu.cn/open-apis/';
|
||||
}
|
||||
|
||||
$this->appId = $appId;
|
||||
$this->appSecret = $appSecret;
|
||||
$this->abbr = $abbr;
|
||||
|
||||
$this->client = new Client([
|
||||
'base_uri' => $this->baseUri,
|
||||
'verify' => false, // 禁用SSL验证
|
||||
]);
|
||||
|
||||
$this->options = [
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json; charset=utf-8'
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常
|
||||
*/
|
||||
public function error()
|
||||
{
|
||||
return $this->error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求
|
||||
*/
|
||||
public function requestResult($url = "", $method = "POST")
|
||||
{
|
||||
try {
|
||||
$res = $this->client->request($method, $this->baseUri.$url, $this->options);
|
||||
if ($res->getBody()) {
|
||||
$result = json_decode($res->getBody(), true);
|
||||
// var_dump($result);
|
||||
if ($result["code"] === 0) {
|
||||
return $result;
|
||||
} else {
|
||||
$this->error = $result["msg"];
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
$this->error = "result error";
|
||||
return false;
|
||||
}
|
||||
} catch (RequestException $e) {
|
||||
if ($e->hasResponse()) {
|
||||
var_dump('2 :'.$e->getResponse()->getBody());
|
||||
throw new BusinessException($e->getResponse()->getBody());
|
||||
} else {
|
||||
var_dump('3 :'.$e->getMessage());
|
||||
throw new BusinessException($e->getMessage());
|
||||
}
|
||||
} catch (\Throwable $th) {
|
||||
var_dump('4 :'.$th->getFile()."|".$th->getLine()."|".$th->getMessage());
|
||||
$this->error = $th->getFile()."|".$th->getLine()."|".$th->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权
|
||||
*/
|
||||
public function authorize($certificate,$mobile, $url = 'authen/v1/authorize')
|
||||
{
|
||||
$arr = [
|
||||
'app_id' => $certificate['app_id'],
|
||||
'redirect_uri' => $certificate['r_url'],
|
||||
'scope' => $certificate['scope'],
|
||||
'state' => $certificate['state']
|
||||
];
|
||||
$queryData = http_build_query($arr);
|
||||
return $this->baseUri.$url.'?'.$queryData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自建应用获取 tenant_access_token
|
||||
*/
|
||||
public function tenantAccessToken()
|
||||
{
|
||||
$tenantAccessToken = Cache::get($this->abbr.'-tenantAccessToken');
|
||||
if (!$tenantAccessToken) {
|
||||
$this->options["json"] = [
|
||||
"app_id" => $this->appId,
|
||||
"app_secret" => $this->appSecret
|
||||
];
|
||||
$rst = $this->requestResult('auth/v3/tenant_access_token/internal', 'POST');
|
||||
if ($rst) {
|
||||
$tenantAccessToken = $rst['tenant_access_token'];
|
||||
Cache::set($this->abbr.'-tenantAccessToken', $tenantAccessToken, $rst['expire']);
|
||||
} else {
|
||||
throw new BusinessException('tenant_access_token 获取失败');
|
||||
}
|
||||
}
|
||||
return $tenantAccessToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过手机号或邮箱获取用户 ID
|
||||
*/
|
||||
public function getUserIdByPhoneOrEmail($phone = '', $userIdType = 'open_id')
|
||||
{
|
||||
$this->options["headers"] = [
|
||||
"Authorization" => "Bearer " . $this->tenantAccessToken(),
|
||||
"Content-Type" => "application/json; charset=utf-8"
|
||||
];
|
||||
$this->options["json"] = [
|
||||
"emails" => [],
|
||||
"mobiles" => [$phone],
|
||||
"include_resigned" => false
|
||||
];
|
||||
$rst = $this->requestResult('contact/v3/users/batch_get_id?user_id_type='.$userIdType, 'POST');
|
||||
return $rst;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*/
|
||||
public function sendMessages($receiveId = '', $content = '', $msgType = 'text', $receiveIdtype = 'open_id')
|
||||
{
|
||||
$this->options["headers"] = [
|
||||
"Authorization" => "Bearer " . $this->tenantAccessToken(),
|
||||
"Content-Type" => "application/json; charset=utf-8"
|
||||
];
|
||||
$this->options["json"] = [
|
||||
"receive_id" => $receiveId,
|
||||
"msg_type" => $msgType,
|
||||
"content" => $content
|
||||
];
|
||||
$rst = $this->requestResult('im/v1/messages?receive_id_type='.$receiveIdtype, 'POST');
|
||||
return $rst;
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑消息
|
||||
*/
|
||||
public function updateSendMessages($messageId = '', $content = '', $msgType = 'text')
|
||||
{
|
||||
$this->options["headers"] = [
|
||||
"Authorization" => "Bearer " . $this->tenantAccessToken(),
|
||||
"Content-Type" => "application/json; charset=utf-8"
|
||||
];
|
||||
$this->options["json"] = [
|
||||
"msg_type" => $msgType,
|
||||
"content" => $content
|
||||
];
|
||||
$rst = $this->requestResult('im/v1/messages/'.$messageId, 'PUT');
|
||||
return $rst;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户 user_access_token
|
||||
*/
|
||||
public function userAccessToken($code = "", $redirect_uri = "")
|
||||
{
|
||||
$this->options["headers"] = [
|
||||
"Content-Type" => "application/json; charset=utf-8"
|
||||
];
|
||||
$this->options["json"] = [
|
||||
"grant_type" => "authorization_code",
|
||||
"client_id" => $this->appId,
|
||||
"client_secret" => $this->appSecret,
|
||||
"code" => $code,
|
||||
"redirect_uri" => $redirect_uri
|
||||
];
|
||||
return $this->requestResult('authen/v2/oauth/token');
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户信息
|
||||
*/
|
||||
public function userInfo($userAccessToken = "")
|
||||
{
|
||||
$this->options["headers"] = [
|
||||
"Authorization" => "Bearer " . $userAccessToken,
|
||||
"Content-Type" => "application/json; charset=utf-8"
|
||||
];
|
||||
return $this->requestResult('authen/v1/user_info', "GET");
|
||||
}
|
||||
|
||||
// public function user_access_token($code = "")
|
||||
// {
|
||||
// $url = "";
|
||||
// $this->options["headers"] = [
|
||||
// "Authorization" => "Bearer ".$this->tenantAccessToken(),
|
||||
// "Content-Type" => "application/json; charset=utf-8"
|
||||
// ];
|
||||
// $this->options["json"] = [
|
||||
// "grant_type" => "authorization_code",
|
||||
// "code" => $code
|
||||
// ];
|
||||
// $this->options["form_params"] = [
|
||||
// "app_id" => $this->app_id,
|
||||
// "app_secret" => $this->app_secret
|
||||
// ];
|
||||
// return $this->requestResult($url);
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use Webman\Exception\BusinessException;
|
||||
|
||||
class FeishuMessage
|
||||
{
|
||||
|
||||
protected $app_id = 'cli_a6183b882cb8500d';
|
||||
protected $app_secret = 'VqYib48u4EtDIa6nG9qH3f0fYCA1bCvs';
|
||||
protected $state = 'hesu';
|
||||
protected $class = null;
|
||||
|
||||
public function __construct($options = [])
|
||||
{
|
||||
if (isset($options['app_id']) && $options['app_id']) {
|
||||
$this->app_id = $options['app_id'];
|
||||
}
|
||||
if (isset($options['app_secret']) && $options['app_secret']) {
|
||||
$this->app_secret = $options['app_secret'];
|
||||
}
|
||||
if (isset($options['state']) && $options['state']) {
|
||||
$this->state = $options['state'];
|
||||
}
|
||||
$this->class = new Feishu($this->app_id, $this->app_secret, $this->state);
|
||||
}
|
||||
|
||||
/**
|
||||
* 飞书消息模板
|
||||
* @param string $scene
|
||||
* @param array $options
|
||||
*/
|
||||
public function messageTemplates(string $scene = 'group-send', array $options = [])
|
||||
{
|
||||
try {
|
||||
$template = match ($scene) {
|
||||
'inquiry-group-send' => $this->groupNewTemplates(
|
||||
$options['quality'],
|
||||
$options['order_no'],
|
||||
$options['channel'],
|
||||
$options['country'],
|
||||
$options['enter_user'],
|
||||
$options['r_time']
|
||||
),
|
||||
'inquiry-group-update' => $this->groupUpdateTemplates(
|
||||
$options['quality'],
|
||||
$options['order_no'],
|
||||
$options['channel'],
|
||||
$options['country'],
|
||||
$options['enter_user'],
|
||||
$options['r_time'],
|
||||
$options['t_time']
|
||||
),
|
||||
'inquiry-person-allocation' => $this->personAllocationTemplates(
|
||||
$options['quality'],
|
||||
$options['order_no'],
|
||||
$options['channel'],
|
||||
$options['country'],
|
||||
$options['enter_user'],
|
||||
$options['r_time'],
|
||||
$options['t_time']
|
||||
),
|
||||
'crm-person-follow-up' => $this->personFollowUpTemplates(
|
||||
$options['contacts'],
|
||||
$options['follow_next'],
|
||||
$options['follow_last']
|
||||
)
|
||||
};
|
||||
} catch (\UnhandledMatchError $e) {
|
||||
throw new BusinessException($e->getMessage());
|
||||
}
|
||||
return $template;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送飞书消息
|
||||
* @param array $options
|
||||
*/
|
||||
public function messageSend(string $scene = 'group-send', array $options = [])
|
||||
{
|
||||
$template = $this->messageTemplates($scene, $options);
|
||||
$result = $this->class->sendMessages($options['receive_id'], $template, $options['msg_type'], $options['receive_id_type']);
|
||||
if (!isset($result['code']) || $result['code'] !== 0) {
|
||||
throw new BusinessException('发送飞书消息失败');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 线索消息发送
|
||||
*/
|
||||
public function groupNewTemplates($quality = '💛 银牌商机', $order_no = 'SN2025072365640', $channel = '谷歌', $country = '白俄罗斯', $enter_user = '木子李', $r_time = '2025-07-24 09:41:23')
|
||||
{
|
||||
$content = '{
|
||||
"schema": "2.0",
|
||||
"config": {
|
||||
"update_multi": true,
|
||||
"style": {
|
||||
"text_size": {
|
||||
"normal_v2": {
|
||||
"default": "normal",
|
||||
"pc": "normal",
|
||||
"mobile": "heading"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"body": {
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "16px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"padding": "0px 20px 20px 20px",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "column_set",
|
||||
"horizontal_align": "left",
|
||||
"columns": [
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "weighted",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": " **'.$quality.'**\n- **编号:** '.$order_no.'\n- **渠道:** '.$channel.'\n- **国家:** '.$country.'\n- **发布人:** '.$enter_user.'\n- **发布时间:** '.$r_time.'",
|
||||
"text_align": "left",
|
||||
"text_size": "normal_v2",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
}
|
||||
],
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"weight": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "form",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "column_set",
|
||||
"flex_mode": "stretch",
|
||||
"horizontal_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"columns": [
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "auto",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "button",
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "立即跟踪"
|
||||
},
|
||||
"type": "primary_filled",
|
||||
"width": "fill",
|
||||
"size": "medium",
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "list-check-bold_outlined"
|
||||
},
|
||||
"confirm": {
|
||||
"title": {
|
||||
"tag": "plain_text",
|
||||
"content": "确认跟踪?"
|
||||
},
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "客户线索:'.$order_no.'"
|
||||
}
|
||||
},
|
||||
"behaviors": [
|
||||
{
|
||||
"type": "callback",
|
||||
"value": "'.$order_no.'"
|
||||
}
|
||||
],
|
||||
"form_action_type": "submit",
|
||||
"name": "Button_m7d0zqa2",
|
||||
"element_id": "track"
|
||||
}
|
||||
],
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top"
|
||||
},
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "auto",
|
||||
"elements": [],
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top"
|
||||
},
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "auto",
|
||||
"elements": [],
|
||||
"padding": "0px 0px 0px 0px",
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
}
|
||||
],
|
||||
"margin": "4px 0px 0px 0px"
|
||||
}
|
||||
],
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "12px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"padding": "0px 0px 0px 0px",
|
||||
"margin": "0px 0px 0px 0px",
|
||||
"name": "Form_m7d0zqa1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"header": {
|
||||
"title": {
|
||||
"tag": "plain_text",
|
||||
"content": "新的【公海】客户线索"
|
||||
},
|
||||
"subtitle": {
|
||||
"tag": "plain_text",
|
||||
"content": ""
|
||||
},
|
||||
"template": "default",
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "ai-common_colorful"
|
||||
},
|
||||
"padding": "12px 12px 12px 20px"
|
||||
}
|
||||
}';
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 线索消息更新
|
||||
*/
|
||||
public function groupUpdateTemplates($quality = '💛 银牌商机', $order_no = 'SN2025072365640', $channel = '谷歌', $country = '白俄罗斯', $enter_user = '木子李', $r_time = '2025-07-24 09:41:23', $t_time = '2025-07-24 14:41:23')
|
||||
{
|
||||
$content = '{
|
||||
"schema": "2.0",
|
||||
"config": {
|
||||
"update_multi": true,
|
||||
"style": {
|
||||
"text_size": {
|
||||
"normal_v2": {
|
||||
"default": "normal",
|
||||
"pc": "normal",
|
||||
"mobile": "heading"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"body": {
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "16px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"padding": "0px 20px 20px 20px",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "column_set",
|
||||
"horizontal_align": "left",
|
||||
"columns": [
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "weighted",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": " **'.$quality.'**\n- **编号:** '.$order_no.'\n- **渠道:** '.$channel.'\n- **国家:** '.$country.'\n- **发布人:** '.$enter_user.'\n- **发布时间:** '.$r_time.'",
|
||||
"text_align": "left",
|
||||
"text_size": "normal_v2",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
}
|
||||
],
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"weight": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "跟踪时间:'.$t_time.'",
|
||||
"text_size": "notation",
|
||||
"text_align": "left",
|
||||
"text_color": "green"
|
||||
},
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "chat-done_outlined",
|
||||
"color": "green"
|
||||
},
|
||||
"element_id": "track_time"
|
||||
}
|
||||
]
|
||||
},
|
||||
"header": {
|
||||
"title": {
|
||||
"tag": "plain_text",
|
||||
"content": "【公海】客户线索"
|
||||
},
|
||||
"subtitle": {
|
||||
"tag": "plain_text",
|
||||
"content": ""
|
||||
},
|
||||
"text_tag_list": [
|
||||
{
|
||||
"tag": "text_tag",
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "已跟踪"
|
||||
},
|
||||
"color": "orange"
|
||||
}
|
||||
],
|
||||
"template": "green",
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "ai-common_colorful"
|
||||
},
|
||||
"padding": "12px 12px 12px 20px"
|
||||
}
|
||||
}';
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 线索分配消息
|
||||
*/
|
||||
public function personAllocationTemplates($quality = '💛 银牌商机', $order_no = 'SN2025072365640', $channel = '谷歌', $country = '白俄罗斯', $enter_user = '木子李', $r_time = '2025-07-24 09:41:23', $t_time = '2025-07-24 14:41:23')
|
||||
{
|
||||
$content = '{
|
||||
"schema": "2.0",
|
||||
"config": {
|
||||
"update_multi": true,
|
||||
"style": {
|
||||
"text_size": {
|
||||
"normal_v2": {
|
||||
"default": "normal",
|
||||
"pc": "normal",
|
||||
"mobile": "heading"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"body": {
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "16px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"padding": "0px 20px 20px 20px",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "column_set",
|
||||
"horizontal_align": "left",
|
||||
"columns": [
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "weighted",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": " **'.$quality.'**\n- **编号:** '.$order_no.'\n- **渠道:** '.$channel.'\n- **国家:** '.$country.'\n- **录单人:** '.$enter_user.'\n- **录入时间:** '.$r_time.'",
|
||||
"text_align": "left",
|
||||
"text_size": "normal_v2",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
}
|
||||
],
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"weight": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "分配时间:'.$t_time.'",
|
||||
"text_size": "notation",
|
||||
"text_align": "left",
|
||||
"text_color": "green"
|
||||
},
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "chat-done_outlined",
|
||||
"color": "green"
|
||||
},
|
||||
"element_id": "allocation_time"
|
||||
}
|
||||
]
|
||||
},
|
||||
"header": {
|
||||
"title": {
|
||||
"tag": "plain_text",
|
||||
"content": "新的客户线索"
|
||||
},
|
||||
"subtitle": {
|
||||
"tag": "plain_text",
|
||||
"content": ""
|
||||
},
|
||||
"text_tag_list": [
|
||||
{
|
||||
"tag": "text_tag",
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "指定"
|
||||
},
|
||||
"color": "yellow"
|
||||
}
|
||||
],
|
||||
"template": "blue",
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "todo_colorful"
|
||||
},
|
||||
"padding": "12px 12px 12px 20px"
|
||||
}
|
||||
}';
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 跟进提醒消息
|
||||
*/
|
||||
public function personFollowUpTemplates($contacts = '木子李', $follow_next = '2025-07-24 14:41:23', $follow_last = '2025-07-24 14:41:23')
|
||||
{
|
||||
$content = '{
|
||||
"schema": "2.0",
|
||||
"config": {
|
||||
"update_multi": true,
|
||||
"style": {
|
||||
"text_size": {
|
||||
"normal_v2": {
|
||||
"default": "normal",
|
||||
"pc": "normal",
|
||||
"mobile": "heading"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"body": {
|
||||
"direction": "vertical",
|
||||
"horizontal_spacing": "8px",
|
||||
"vertical_spacing": "16px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"padding": "0px 20px 20px 20px",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "column_set",
|
||||
"horizontal_align": "left",
|
||||
"columns": [
|
||||
{
|
||||
"tag": "column",
|
||||
"width": "weighted",
|
||||
"elements": [
|
||||
{
|
||||
"tag": "markdown",
|
||||
"content": "- **客户名称:** '.$contacts.'\n- **跟进时间:** '.$follow_next.'",
|
||||
"text_align": "left",
|
||||
"text_size": "normal_v2",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
}
|
||||
],
|
||||
"vertical_spacing": "8px",
|
||||
"horizontal_align": "left",
|
||||
"vertical_align": "top",
|
||||
"weight": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "hr",
|
||||
"margin": "0px 0px 0px 0px"
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"text": {
|
||||
"tag": "plain_text",
|
||||
"content": "最近跟进:'.$follow_last.'",
|
||||
"text_size": "notation",
|
||||
"text_align": "left",
|
||||
"text_color": "grey"
|
||||
},
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "chat_outlined",
|
||||
"color": "grey"
|
||||
},
|
||||
"element_id": "track_time"
|
||||
}
|
||||
]
|
||||
},
|
||||
"header": {
|
||||
"title": {
|
||||
"tag": "plain_text",
|
||||
"content": "跟进提醒"
|
||||
},
|
||||
"subtitle": {
|
||||
"tag": "plain_text",
|
||||
"content": ""
|
||||
},
|
||||
"template": "green",
|
||||
"icon": {
|
||||
"tag": "standard_icon",
|
||||
"token": "calendar_colorful"
|
||||
},
|
||||
"padding": "12px 12px 12px 20px"
|
||||
}
|
||||
}';
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use Firebase\JWT\JWT as FirebaseJWT;
|
||||
use Firebase\JWT\Key;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class Jwt
|
||||
{
|
||||
protected $secretKey;
|
||||
protected $algorithm;
|
||||
protected $issuer;
|
||||
protected $expiration;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->secretKey = config('jwt.jwt_secret_key');
|
||||
$this->algorithm = config('jwt.jwt_algorithm');
|
||||
$this->issuer = config('jwt.jwt_issuer');
|
||||
$this->expiration = config('jwt.jwt_expiration');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 JWT 令牌
|
||||
*
|
||||
* @param array $payload
|
||||
* @return string
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function generateToken(array $payload): string
|
||||
{
|
||||
$defaultPayload = [
|
||||
// // —— 注册 Claim ——
|
||||
'iss' => $this->issuer, // 签发者
|
||||
// 'sub' => 'user_1001', // 面向的用户
|
||||
// 'aud' => 'api.gateway.example.com', // 接收方
|
||||
// 'iat' => time(), // 签发时间
|
||||
// 'nbf' => time(), // 生效时间
|
||||
// 'exp' => time() + $this->expiration, // 1 小时后过期
|
||||
'jti' => bin2hex(random_bytes(16)), // 唯一 ID
|
||||
// // —— 自定义 Claim ——
|
||||
// 'uid' => 1001, // 业务用户 ID
|
||||
// 'roles' => ['admin', 'editor'], // 用户角色
|
||||
// 'meta' => ['region' => 'CN', 'tier' => 5], // 任意自定义数据
|
||||
];
|
||||
|
||||
$payload = array_merge($defaultPayload, $payload);
|
||||
|
||||
try {
|
||||
return FirebaseJWT::encode($payload, $this->secretKey, $this->algorithm);
|
||||
} catch (\Exception $e) {
|
||||
throw new BusinessException("令牌生成失败:" . $e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 JWT 令牌
|
||||
*
|
||||
* @param string $token
|
||||
* @return object
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function verifyToken(string $token)
|
||||
{
|
||||
try {
|
||||
return FirebaseJWT::decode($token, new Key($this->secretKey, $this->algorithm));
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
throw new BusinessException('令牌已过期', 401);
|
||||
} catch (\Firebase\JWT\SignatureInvalidException $e) {
|
||||
throw new BusinessException('无效的令牌签名', 401);
|
||||
} catch (\Firebase\JWT\BeforeValidException $e) {
|
||||
throw new BusinessException('令牌尚未生效', 401);
|
||||
} catch (\Exception $e) {
|
||||
throw new BusinessException('令牌验证失败:' . $e->getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function describe()
|
||||
{
|
||||
/* payload
|
||||
1. 注册 Claim 详解
|
||||
|
||||
Claim 名称 含义 类型 建议取值
|
||||
iss Issuer,发行者,标识该 JWT 的签发主体 string or URI 你的服务域名或项目标识,比如 https://api.example.com
|
||||
sub Subject,主题,标识该 JWT 所面向的用户 string or int 用户在你系统里的唯一 ID
|
||||
aud Audience,受众,标识该 JWT 的接收方 string or array 接收该令牌的服务标识,比如 ["service-a","service-b"]
|
||||
exp Expiration Time,过期时间,Unix 时间戳,到达此时间后不可用 int time() + 3600(1 小时后过期)
|
||||
nbf Not Before,生效时间,Unix 时间戳,表示在此时间之前不可用 int time() 或者 time() + 60(1 分钟后生效)
|
||||
iat Issued At,签发时间,Unix 时间戳 int time()
|
||||
jti JWT ID,JWT 的唯一标识符,用于去重或一次性令牌 string uniqid('', true) 或者 UUID
|
||||
|
||||
注意:exp、nbf、iat 必须是整数(秒级时间戳),否则库会抛类型异常或验证失败。
|
||||
|
||||
2. 自定义 Claim
|
||||
|
||||
除了上面这些“注册”字段,你可以任意添加,比如:
|
||||
|
||||
php
|
||||
$payload['uid'] = 123; // 业务用户 ID
|
||||
$payload['roles'] = ['admin','user']; // 权限数组
|
||||
$payload['feature'] = 'beta'; // 标记某个功能开关
|
||||
|
||||
这些字段在你的应用程序里可以自由取用。
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
// app/service/ResourceService.php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use support\Db;
|
||||
|
||||
class MigrationResources
|
||||
{
|
||||
/**
|
||||
* 获取完整的资源树结构(不区分系统)
|
||||
*
|
||||
* @param array $conditions 筛选条件
|
||||
* @return array
|
||||
*/
|
||||
public function getFullResourceTree($table = 'resources', array $conditions = []): array
|
||||
{
|
||||
// 查询所有资源数据
|
||||
$query = Db::table($table)->where($conditions);
|
||||
|
||||
// 按排序字段排序
|
||||
$resources = $query->orderBy('sort')->orderBy('id')->get();
|
||||
// var_dump($resources->count());
|
||||
// 转换为数组
|
||||
$resourceList = [];
|
||||
foreach ($resources as $resource) {
|
||||
$resourceList[] = (array) $resource;
|
||||
}
|
||||
|
||||
// 构建树状结构
|
||||
return $this->buildTree($resourceList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建树状结构
|
||||
*
|
||||
* @param array $resources 资源列表
|
||||
* @param int $parentId 父级ID
|
||||
* @return array
|
||||
*/
|
||||
private function buildTree(array $resources, int $parentId = 0): array
|
||||
{
|
||||
$tree = [];
|
||||
|
||||
foreach ($resources as $resource) {
|
||||
if ($resource['parent_id'] == $parentId) {
|
||||
// 递归获取子节点
|
||||
$children = $this->buildTree($resources, $resource['id']);
|
||||
|
||||
// 如果有子节点,则添加到children字段
|
||||
if (!empty($children)) {
|
||||
$resource['children'] = $children;
|
||||
}
|
||||
|
||||
$tree[] = $resource;
|
||||
}
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用引用方式构建树(性能优化版)
|
||||
*
|
||||
* @param array $conditions 筛选条件
|
||||
* @return array
|
||||
*/
|
||||
public function getFullResourceTreeOptimized($table = 'resources', array $conditions = []): array
|
||||
{
|
||||
// 查询所有资源数据
|
||||
$query = Db::table($table)->where($conditions);
|
||||
|
||||
// 按排序字段排序
|
||||
$resources = $query->orderBy('sort')->orderBy('id')->get();
|
||||
|
||||
// 构建ID映射和引用关系
|
||||
$resourceMap = [];
|
||||
$tree = [];
|
||||
|
||||
// 初始化所有节点
|
||||
foreach ($resources as $resource) {
|
||||
$resourceArray = (array) $resource;
|
||||
$resourceMap[$resourceArray['id']] = $resourceArray;
|
||||
}
|
||||
|
||||
// 构建父子关系
|
||||
foreach ($resourceMap as $id => &$node) {
|
||||
if ($node['parent_id'] == 0) {
|
||||
// 根节点
|
||||
$tree[] = &$node;
|
||||
} else {
|
||||
// 子节点
|
||||
if (isset($resourceMap[$node['parent_id']])) {
|
||||
if (!isset($resourceMap[$node['parent_id']]['children'])) {
|
||||
$resourceMap[$node['parent_id']]['children'] = [];
|
||||
}
|
||||
$resourceMap[$node['parent_id']]['children'][] = &$node;
|
||||
} else {
|
||||
// 父节点不存在,作为根节点处理
|
||||
$tree[] = &$node;
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($node);
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扁平化的资源列表
|
||||
*
|
||||
* @param array $conditions 筛选条件
|
||||
* @return array
|
||||
*/
|
||||
public function getResourceList($table = 'resources', array $conditions = []): array
|
||||
{
|
||||
$query = Db::table($table)->where($conditions);
|
||||
|
||||
// 按排序字段排序
|
||||
$resources = $query->orderBy('sort')->orderBy('id')->get();
|
||||
|
||||
// 转换为数组
|
||||
$resourceList = [];
|
||||
foreach ($resources as $resource) {
|
||||
$resourceList[] = (array) $resource;
|
||||
}
|
||||
|
||||
return $resourceList;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 递归插入资源树
|
||||
*/
|
||||
private function insertResourceTree($table, $tree, $parentId, $keys = [])
|
||||
{
|
||||
$keys = ['system_id','name','desc','type','code','parent_id','url','icon','open_type','link',
|
||||
'is_hide','is_hide_tab','no_auth','is_home','instance','keep_alive','sort','status'];
|
||||
foreach ($tree as $item) {
|
||||
// 保存子节点
|
||||
$children = $item['children'] ?? [];
|
||||
|
||||
// 过滤字段
|
||||
$filteredItem = [];
|
||||
foreach ($item as $k => $v) {
|
||||
if (in_array($k, $keys)) {
|
||||
$filteredItem[$k] = $v;
|
||||
}
|
||||
}
|
||||
|
||||
// 设置parent_id
|
||||
$filteredItem['parent_id'] = $parentId;
|
||||
|
||||
// 插入并获取新ID
|
||||
$newId = Db::table($table)->insertGetId($filteredItem);
|
||||
echo "插入节点: {$filteredItem['name']}, 新ID: $newId\n";
|
||||
|
||||
// 递归处理子节点
|
||||
if (!empty($children)) {
|
||||
$this->insertResourceTree($table, $children, $newId, $keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function do(string $from = 'resources_20250916_bak', string $to = 'resources_yuanshi', array $where = [])
|
||||
{
|
||||
try {
|
||||
// 开启事务
|
||||
Db::beginTransaction();
|
||||
|
||||
// 查询迁移资源的树状结果集
|
||||
$list = $this->getFullResourceTreeOptimized($from, $where);
|
||||
|
||||
// 入库字段
|
||||
$keys = ['system_id','name','desc','type','code','parent_id','url','icon','open_type','link',
|
||||
'is_hide','is_hide_tab','no_auth','is_home','instance','keep_alive','sort','status'];
|
||||
|
||||
// 使用递归处理树结构
|
||||
$this->insertResourceTree($to, $list, 0, $keys);
|
||||
|
||||
// 提交事务
|
||||
Db::commit();
|
||||
|
||||
echo "数据插入成功";
|
||||
|
||||
} catch (\Exception $e) {
|
||||
// 回滚事务
|
||||
Db::rollBack();
|
||||
|
||||
echo "数据插入失败: " . $e->getMessage() . " 在文件 " . $e->getFile() . " 第 " . $e->getLine() . " 行";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
class OauthClients
|
||||
{
|
||||
|
||||
/**
|
||||
* 生成 OAuth2 client 凭证
|
||||
*
|
||||
* @param int $idBytes 用于生成 client_id 的随机字节长度(最终 hex 长度 = $idBytes * 2)
|
||||
* @param int $secretBytes 用于生成 client_secret 的随机字节长度(最终 hex 长度 = $secretBytes * 2)
|
||||
* @return array ['client_id' => string, 'client_secret' => string]
|
||||
*/
|
||||
public function generateClientCredentials(int $idBytes = 16, int $secretBytes = 32): array
|
||||
{
|
||||
// 生成随机字节,并转为十六进制字符串
|
||||
$clientId = bin2hex(random_bytes($idBytes));
|
||||
$clientSecret = bin2hex(random_bytes($secretBytes));
|
||||
|
||||
return [
|
||||
'client_id' => $clientId,
|
||||
'client_secret' => $clientSecret,
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use support\Log;
|
||||
use support\Redis;
|
||||
|
||||
class RedisUidRotator
|
||||
{
|
||||
private string $key;
|
||||
private string $setKey;
|
||||
private string $lockKey;
|
||||
private int $expireSeconds;
|
||||
|
||||
public function __construct(string $rotatorName, int $expireSeconds = 604800)
|
||||
{
|
||||
$this->key = "uid_rotator:{$rotatorName}:index";
|
||||
$this->setKey = "uid_rotator:{$rotatorName}:uids";
|
||||
$this->lockKey = "uid_rotator:{$rotatorName}:lock";
|
||||
$this->expireSeconds = $expireSeconds;
|
||||
}
|
||||
|
||||
public function setUids(array $uids, bool $resetIndex = true): bool
|
||||
{
|
||||
// 删除旧数据
|
||||
Redis::del($this->setKey);
|
||||
|
||||
if (!empty($uids)) {
|
||||
// 添加新UID集合
|
||||
foreach ($uids as $uid) {
|
||||
Redis::sAdd($this->setKey, $uid);
|
||||
}
|
||||
|
||||
// 重置索引
|
||||
if ($resetIndex) {
|
||||
Redis::set($this->key, 0);
|
||||
}
|
||||
}
|
||||
|
||||
$this->touchExpire();
|
||||
return true;
|
||||
}
|
||||
|
||||
public function next(): ?int
|
||||
{
|
||||
$lockAcquired = false;
|
||||
try {
|
||||
// 获取锁(改用原生命令)
|
||||
$lockAcquired = $this->acquireLock(5);
|
||||
if (!$lockAcquired) {
|
||||
throw new \RuntimeException("获取锁失败");
|
||||
}
|
||||
|
||||
// 获取当前索引
|
||||
$currentIndex = (int)Redis::get($this->key);
|
||||
|
||||
// 获取所有UID
|
||||
$uids = Redis::sMembers($this->setKey);
|
||||
if (empty($uids)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 计算位置
|
||||
$uid = $uids[$currentIndex % count($uids)];
|
||||
$nextIndex = $currentIndex + 1;
|
||||
|
||||
// 更新索引
|
||||
Redis::set($this->key, $nextIndex);
|
||||
$this->touchExpire();
|
||||
|
||||
return is_numeric($uid) ? (int)$uid : $uid;
|
||||
} catch (\Throwable $e) {
|
||||
Log::info("UID分配错误: " . $e->getMessage());
|
||||
return null;
|
||||
} finally {
|
||||
if ($lockAcquired) {
|
||||
Redis::del($this->lockKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function acquireLock(int $timeout = 5): bool
|
||||
{
|
||||
$start = time();
|
||||
$lockTimeout = $timeout + 1; // 锁过期时间比等待时间长
|
||||
|
||||
while (time() - $start < $timeout) {
|
||||
// 使用SETNX实现锁(分两步)
|
||||
if (Redis::setNx($this->lockKey, 1)) {
|
||||
// 设置过期时间
|
||||
Redis::expire($this->lockKey, $lockTimeout);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查锁是否已过期但未被删除(处理死锁)
|
||||
if (Redis::ttl($this->lockKey) < 0) {
|
||||
Redis::del($this->lockKey);
|
||||
}
|
||||
|
||||
usleep(100000); // 100ms重试间隔
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function touchExpire(): void
|
||||
{
|
||||
Redis::expire($this->key, $this->expireSeconds);
|
||||
Redis::expire($this->setKey, $this->expireSeconds);
|
||||
}
|
||||
|
||||
public function getPosition(): int
|
||||
{
|
||||
return (int)Redis::get($this->key);
|
||||
}
|
||||
|
||||
public function resetIndex(int $position = 0): bool
|
||||
{
|
||||
return (bool)Redis::set($this->key, max(0, $position));
|
||||
}
|
||||
|
||||
public function getUids(): array
|
||||
{
|
||||
return Redis::sMembers($this->setKey) ?: [];
|
||||
}
|
||||
|
||||
public function addUids($uids): int
|
||||
{
|
||||
$added = 0;
|
||||
$uids = is_array($uids) ? $uids : [$uids];
|
||||
|
||||
foreach ($uids as $uid) {
|
||||
$added += Redis::sAdd($this->setKey, $uid);
|
||||
}
|
||||
|
||||
$this->touchExpire();
|
||||
return $added;
|
||||
}
|
||||
|
||||
public function removeUids($uids): int
|
||||
{
|
||||
$removed = 0;
|
||||
$uids = is_array($uids) ? $uids : [$uids];
|
||||
|
||||
foreach ($uids as $uid) {
|
||||
$removed += Redis::sRem($this->setKey, $uid);
|
||||
}
|
||||
|
||||
return $removed;
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return (int)Redis::sCard($this->setKey);
|
||||
}
|
||||
|
||||
public function destroy(): void
|
||||
{
|
||||
Redis::del([$this->key, $this->setKey, $this->lockKey]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use support\Db;
|
||||
|
||||
class TableInspector
|
||||
{
|
||||
/**
|
||||
* 获取某个表的所有字段信息
|
||||
*/
|
||||
public static function getColumns(string $table, ?string $database = null): array
|
||||
{
|
||||
$database = $database ?: Db::connection()->getDatabaseName();
|
||||
|
||||
$columns = Db::select("
|
||||
SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE,
|
||||
COLUMN_DEFAULT, COLUMN_COMMENT, EXTRA
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
|
||||
ORDER BY ORDINAL_POSITION
|
||||
", [$database, $table]);
|
||||
|
||||
return array_map(function ($col) {
|
||||
return [
|
||||
'name' => $col->COLUMN_NAME,
|
||||
'type' => $col->DATA_TYPE,
|
||||
'column_type' => $col->COLUMN_TYPE,
|
||||
'nullable' => $col->IS_NULLABLE === 'YES',
|
||||
'default' => $col->COLUMN_DEFAULT,
|
||||
'comment' => $col->COLUMN_COMMENT,
|
||||
'extra' => $col->EXTRA,
|
||||
];
|
||||
}, $columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字段名列表
|
||||
*/
|
||||
public static function getColumnNames(string $table, ?string $database = null): array
|
||||
{
|
||||
return array_column(self::getColumns($table, $database), 'name');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字段注释 map:字段名 => 注释
|
||||
*/
|
||||
public static function getColumnComments(string $table, ?string $database = null): array
|
||||
{
|
||||
$columns = self::getColumns($table, $database);
|
||||
$map = [];
|
||||
foreach ($columns as $col) {
|
||||
$map[$col['name']] = $col['comment'];
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
class Tree
|
||||
{
|
||||
// /**
|
||||
// * 递归构建树形结构
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param int $parentId 父级ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @param int $level 当前层级
|
||||
// * @return array
|
||||
// */
|
||||
// public static function build(array $data, int $parentId = 0, string $pidField = 'parent_id', string $idField = 'id', int $level = 0): array
|
||||
// {
|
||||
// $tree = [];
|
||||
|
||||
// foreach ($data as $item) {
|
||||
// if ($item[$pidField] == $parentId) {
|
||||
// $item['level'] = $level;
|
||||
// $children = static::build($data, $item[$idField], $pidField, $idField, $level + 1);
|
||||
|
||||
// if (!empty($children)) {
|
||||
// $item['children'] = $children;
|
||||
// }
|
||||
|
||||
// $tree[] = $item;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $tree;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 使用引用方式构建树形结构(性能更好)
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @return array
|
||||
// */
|
||||
// public static function buildWithReference(array $data, string $pidField = 'parent_id', string $idField = 'id'): array
|
||||
// {
|
||||
// $items = [];
|
||||
// $tree = [];
|
||||
|
||||
// // 建立以id为索引的数组
|
||||
// foreach ($data as $item) {
|
||||
// $item['level'] = 0;
|
||||
// $items[$item[$idField]] = $item;
|
||||
// }
|
||||
|
||||
// // 构建树形结构
|
||||
// foreach ($items as $id => $item) {
|
||||
// if ($item[$pidField] == 0) {
|
||||
// $tree[] = &$items[$id];
|
||||
// } else {
|
||||
// if (isset($items[$item[$pidField]])) {
|
||||
// $items[$id]['level'] = $items[$item[$pidField]]['level'] + 1;
|
||||
|
||||
// if (!isset($items[$item[$pidField]]['children'])) {
|
||||
// $items[$item[$pidField]]['children'] = [];
|
||||
// }
|
||||
|
||||
// $items[$item[$pidField]]['children'][] = &$items[$id];
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $tree;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 将树形结构扁平化为列表(带层级前缀)
|
||||
// *
|
||||
// * @param array $tree 树形结构数据
|
||||
// * @param string $prefix 前缀字符
|
||||
// * @param string $field 显示字段名
|
||||
// * @param int $level 层级
|
||||
// * @return array
|
||||
// */
|
||||
// public static function flattenWithPrefix(array $tree, string $prefix = '--', string $field = 'name', int $level = 0): array
|
||||
// {
|
||||
// $result = [];
|
||||
|
||||
// foreach ($tree as $item) {
|
||||
// $item[$field . '_with_prefix'] = str_repeat($prefix, $item['level']) . $item[$field];
|
||||
// $result[] = $item;
|
||||
|
||||
// if (isset($item['children']) && !empty($item['children'])) {
|
||||
// $children = static::flattenWithPrefix($item['children'], $prefix, $field, $item['level'] + 1);
|
||||
// $result = array_merge($result, $children);
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $result;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 根据父ID查找所有子节点(包括子孙节点)
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param int $parentId 父级ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @return array
|
||||
// */
|
||||
// public static function findChildren(array $data, int $parentId, string $pidField = 'parent_id', string $idField = 'id'): array
|
||||
// {
|
||||
// $children = [];
|
||||
|
||||
// foreach ($data as $item) {
|
||||
// if ($item[$pidField] == $parentId) {
|
||||
// $children[] = $item;
|
||||
// $grandChildren = static::findChildren($data, $item[$idField], $pidField, $idField);
|
||||
// $children = array_merge($children, $grandChildren);
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $children;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 获取指定节点的所有父级节点
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param int $id 当前节点ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @return array
|
||||
// */
|
||||
// public static function getParents(array $data, int $id, string $pidField = 'parent_id', string $idField = 'id'): array
|
||||
// {
|
||||
// $parents = [];
|
||||
|
||||
// foreach ($data as $item) {
|
||||
// if ($item[$idField] == $id) {
|
||||
// if ($item[$pidField] != 0) {
|
||||
// $parents[] = $item;
|
||||
// $parentParents = static::getParents($data, $item[$pidField], $pidField, $idField);
|
||||
// $parents = array_merge($parents, $parentParents);
|
||||
// }
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $parents;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 获取指定节点的子孙节点ID列表
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param int $parentId 父级ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @return array
|
||||
// */
|
||||
// public static function getChildrenIds(array $data, int $parentId, string $pidField = 'parent_id', string $idField = 'id'): array
|
||||
// {
|
||||
// $ids = [];
|
||||
// $children = static::findChildren($data, $parentId, $pidField, $idField);
|
||||
|
||||
// foreach ($children as $child) {
|
||||
// $ids[] = $child[$idField];
|
||||
// }
|
||||
|
||||
// return $ids;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 检查是否有子节点
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param int $parentId 父级ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @return bool
|
||||
// */
|
||||
// public static function hasChildren(array $data, int $parentId, string $pidField = 'parent_id'): bool
|
||||
// {
|
||||
// foreach ($data as $item) {
|
||||
// if ($item[$pidField] == $parentId) {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return false;
|
||||
// }
|
||||
|
||||
|
||||
// /**
|
||||
// * 构建带有权限列表的资源树(权限不显示在树结构中)
|
||||
// *
|
||||
// * @param array $data 资源数据列表
|
||||
// * @param int $parentId 父级ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @param string $typeField 类型字段名
|
||||
// * @param string $permissionType 权限类型标识
|
||||
// * @param int $level 当前层级
|
||||
// * @return array
|
||||
// */
|
||||
// public static function buildWithAuthList(
|
||||
// array $data,
|
||||
// int $parentId = 0,
|
||||
// string $pidField = 'parent_id',
|
||||
// string $idField = 'id',
|
||||
// string $typeField = 'type',
|
||||
// string $permissionType = 'permission',
|
||||
// int $level = 0
|
||||
// ): array {
|
||||
// $tree = [];
|
||||
|
||||
// foreach ($data as $item) {
|
||||
// // 只处理指定父级的非权限节点
|
||||
// if ($item[$pidField] == $parentId && $item[$typeField] != $permissionType) {
|
||||
// $item['level'] = $level;
|
||||
|
||||
// // 递归处理子节点(非权限类型)
|
||||
// $children = static::buildWithAuthList($data, $item[$idField], $pidField, $idField, $typeField, $permissionType, $level + 1);
|
||||
|
||||
// if (!empty($children)) {
|
||||
// $item['children'] = $children;
|
||||
// }
|
||||
|
||||
// // 收集当前节点下的所有权限
|
||||
// $item['auth_list'] = static::collectDirectPermissions($data, $item[$idField], $pidField, $typeField, $permissionType);
|
||||
|
||||
// $tree[] = $item;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $tree;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 收集指定节点下的直接权限项(只收集直接子节点中的权限)
|
||||
// *
|
||||
// * @param array $data 数据列表
|
||||
// * @param int $parentId 父级ID
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $typeField 类型字段名
|
||||
// * @param string $permissionType 权限类型标识
|
||||
// * @return array
|
||||
// */
|
||||
// public static function collectDirectPermissions1(
|
||||
// array $data,
|
||||
// int $parentId,
|
||||
// string $pidField = 'parent_id',
|
||||
// string $typeField = 'type',
|
||||
// string $permissionType = 'permission'
|
||||
// ): array {
|
||||
// $permissions = [];
|
||||
|
||||
// foreach ($data as $item) {
|
||||
// // 收集直接子节点中的权限类型
|
||||
// if ($item[$pidField] == $parentId && $item[$typeField] == $permissionType) {
|
||||
// $permissions[] = $item;
|
||||
// }
|
||||
// }
|
||||
|
||||
// return $permissions;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 使用引用方式构建带有权限列表的资源树(权限不显示在树结构中)
|
||||
// *
|
||||
// * @param array $data 资源数据列表
|
||||
// * @param string $pidField 父级字段名
|
||||
// * @param string $idField ID字段名
|
||||
// * @param string $typeField 类型字段名
|
||||
// * @param string $permissionType 权限类型标识
|
||||
// * @return array
|
||||
// */
|
||||
// public static function buildWithAuthListAndReference(
|
||||
// array $data,
|
||||
// string $pidField = 'parent_id',
|
||||
// string $idField = 'id',
|
||||
// string $typeField = 'type',
|
||||
// string $permissionType = 'permission'
|
||||
// ): array {
|
||||
// $items = [];
|
||||
// $tree = [];
|
||||
|
||||
// // 建立以id为索引的数组(只包含非权限节点)
|
||||
// foreach ($data as $item) {
|
||||
// if ($item[$typeField] != $permissionType) {
|
||||
// $item['level'] = 0;
|
||||
// $items[$item[$idField]] = $item;
|
||||
// }
|
||||
// }
|
||||
|
||||
// // 构建树形结构
|
||||
// foreach ($items as $id => $item) {
|
||||
// if ($item[$pidField] == 0) {
|
||||
// $tree[] = &$items[$id];
|
||||
// } else {
|
||||
// if (isset($items[$item[$pidField]])) {
|
||||
// $items[$id]['level'] = $items[$item[$pidField]]['level'] + 1;
|
||||
|
||||
// if (!isset($items[$item[$pidField]]['children'])) {
|
||||
// $items[$item[$pidField]]['children'] = [];
|
||||
// }
|
||||
|
||||
// $items[$item[$pidField]]['children'][] = &$items[$id];
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // 为每个节点添加权限列表
|
||||
// foreach ($items as &$item) {
|
||||
// $item['auth_list'] = static::collectDirectPermissions($data, $item[$idField], $pidField, $typeField, $permissionType);
|
||||
// }
|
||||
|
||||
// return $tree;
|
||||
// }
|
||||
|
||||
|
||||
|
||||
// 8.13 add
|
||||
/**
|
||||
* 构建前端需要的菜单树结构
|
||||
*
|
||||
* @param array $data 服务端菜单数据
|
||||
* @param int $parentId 父级ID
|
||||
* @return array
|
||||
*/
|
||||
public static function buildMenuTree(array $data, int $parentId = 0): array
|
||||
{
|
||||
$tree = [];
|
||||
|
||||
foreach ($data as $item) {
|
||||
// 只处理非权限类型的节点
|
||||
if ($item['parent_id'] == $parentId && $item['type'] != 'permission') {
|
||||
// 转换数据结构以匹配前端需要的格式
|
||||
$menuItem = [
|
||||
'id' => $item['id'],
|
||||
'path' => $item['url'] ?? '',
|
||||
'name' => $item['name'],
|
||||
'component' => $item['url'] ?? '',
|
||||
'meta' => [
|
||||
'title' => $item['name'],
|
||||
'icon' => $item['icon'] ?? '',
|
||||
'isHide' => !empty($item['is_hide']),
|
||||
'isHideTab' => !empty($item['is_hide_tab']),
|
||||
'keepAlive' => !empty($item['keep_alive']),
|
||||
]
|
||||
];
|
||||
|
||||
// 收集当前节点下的所有权限
|
||||
$permissions = static::collectDirectPermissions($data, $item['id']);
|
||||
if (!empty($permissions)) {
|
||||
$authList = [];
|
||||
foreach ($permissions as $permission) {
|
||||
$authList[] = [
|
||||
'id' => $permission['id'],
|
||||
'title' => $permission['name'] ?? '',
|
||||
'authMark' => $permission['code'] ?? '',
|
||||
'selected' => isset($permission['selected']) && $permission['selected'] ? true : false
|
||||
];
|
||||
}
|
||||
$menuItem['meta']['authList'] = $authList;
|
||||
}
|
||||
|
||||
// 将服务端额外字段放入meta中
|
||||
$extraFields = static::getExtraFields($item);
|
||||
if (!empty($extraFields)) {
|
||||
$menuItem['meta'] = array_merge($menuItem['meta'], $extraFields);
|
||||
}
|
||||
|
||||
// 递归处理子菜单
|
||||
$children = static::buildMenuTree($data, $item['id']);
|
||||
if (!empty($children)) {
|
||||
$menuItem['children'] = $children;
|
||||
}
|
||||
|
||||
$tree[] = $menuItem;
|
||||
}
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用引用方式构建前端需要的菜单树结构(性能更好)
|
||||
*
|
||||
* @param array $data 服务端菜单数据
|
||||
* @return array
|
||||
*/
|
||||
public static function buildMenuTreeWithReference(array $data): array
|
||||
{
|
||||
$items = [];
|
||||
$tree = [];
|
||||
|
||||
// 过滤出菜单类型的节点并转换数据结构
|
||||
$menuData = array_filter($data, function($item) {
|
||||
return ($item['type'] ?? '') != 'permission';
|
||||
});
|
||||
|
||||
// 建立以id为索引的数组并转换数据结构
|
||||
foreach ($menuData as $item) {
|
||||
$items[$item['id']] = [
|
||||
'id' => $item['id'],
|
||||
'path' => $item['url'] ?? '',
|
||||
'name' => $item['name'],
|
||||
'component' => $item['url'] ?? '',
|
||||
'meta' => [
|
||||
'title' => $item['name'],
|
||||
'icon' => $item['icon'] ?? '',
|
||||
'isHide' => !empty($item['is_hide']),
|
||||
'isHideTab' => !empty($item['is_hide_tab']),
|
||||
'keepAlive' => !empty($item['keep_alive']),
|
||||
]
|
||||
];
|
||||
|
||||
// 将服务端额外字段放入meta中
|
||||
$extraFields = static::getExtraFields($item);
|
||||
if (!empty($extraFields)) {
|
||||
$items[$item['id']]['meta'] = array_merge($items[$item['id']]['meta'], $extraFields);
|
||||
}
|
||||
}
|
||||
|
||||
// 构建树形结构
|
||||
foreach ($menuData as $item) {
|
||||
if ($item['parent_id'] == 0) {
|
||||
$tree[] = &$items[$item['id']];
|
||||
} else {
|
||||
if (isset($items[$item['parent_id']])) {
|
||||
if (!isset($items[$item['parent_id']]['children'])) {
|
||||
$items[$item['parent_id']]['children'] = [];
|
||||
}
|
||||
$items[$item['parent_id']]['children'][] = &$items[$item['id']];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 为每个节点添加权限列表
|
||||
foreach ($items as &$item) {
|
||||
$parentId = $item['id'];
|
||||
$permissions = static::collectDirectPermissions($data, $parentId);
|
||||
if (!empty($permissions)) {
|
||||
$authList = [];
|
||||
foreach ($permissions as $permission) {
|
||||
$authList[] = [
|
||||
'id' => $permission['id'],
|
||||
'title' => $permission['name'] ?? '',
|
||||
'authMark' => $permission['code'] ?? ''
|
||||
];
|
||||
}
|
||||
$item['meta']['authList'] = $authList;
|
||||
}
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集指定节点下的直接权限项(只收集直接子节点中的权限)
|
||||
*
|
||||
* @param array $data 数据列表
|
||||
* @param int $parentId 父级ID
|
||||
* @return array
|
||||
*/
|
||||
public static function collectDirectPermissions(array $data, int $parentId): array
|
||||
{
|
||||
$permissions = [];
|
||||
|
||||
foreach ($data as $item) {
|
||||
// 收集直接子节点中的权限类型
|
||||
if ($item['parent_id'] == $parentId && ($item['type'] ?? '') == 'permission') {
|
||||
$permissions[] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取需要放入meta的额外字段
|
||||
*
|
||||
* @param array $item 菜单项
|
||||
* @return array
|
||||
*/
|
||||
public static function getExtraFields(array $item): array
|
||||
{
|
||||
$extraFields = [];
|
||||
$standardFields = [
|
||||
'id', 'name', 'url', 'icon', 'is_hide', 'is_hide_tab', 'keep_alive', 'level'
|
||||
];
|
||||
|
||||
foreach ($item as $key => $value) {
|
||||
// 如果不是标准字段且不是auth_list,则放入extraFields
|
||||
if (!in_array($key, $standardFields) && $key !== 'auth_list') {
|
||||
// 转换下划线命名到驼峰命名
|
||||
$camelKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
|
||||
$extraFields[$camelKey] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $extraFields;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
// UID旋转器(依次循环获取)
|
||||
class UidRotator
|
||||
{
|
||||
private static $uids = [];
|
||||
private static $index = 0;
|
||||
private static $initialized = false;
|
||||
|
||||
/**
|
||||
* 初始化或重置分配器
|
||||
*
|
||||
* @param array $uids UID数组
|
||||
* @param int $startIndex 起始索引位置
|
||||
*/
|
||||
public static function initialize(array $uids = [], int $startIndex = 0)
|
||||
{
|
||||
if (!empty($uids)) {
|
||||
self::$uids = $uids;
|
||||
}
|
||||
|
||||
self::$index = $startIndex % max(1, count(self::$uids));
|
||||
self::$initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态设置新的UID数组
|
||||
*
|
||||
* @param array $newUids 新的UID数组
|
||||
* @param bool $resetIndex 是否重置索引
|
||||
*/
|
||||
public static function setUids(array $newUids, bool $resetIndex = true)
|
||||
{
|
||||
self::$uids = $newUids;
|
||||
if ($resetIndex) {
|
||||
self::$index = 0;
|
||||
} else {
|
||||
// 确保索引不越界
|
||||
self::$index = min(self::$index, max(0, count(self::$uids) - 1));
|
||||
}
|
||||
|
||||
self::$initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加新的UID到数组
|
||||
*
|
||||
* @param int|array $newUids 单个UID或UID数组
|
||||
*/
|
||||
public static function addUids($newUids)
|
||||
{
|
||||
if (!self::$initialized) {
|
||||
self::initialize();
|
||||
}
|
||||
|
||||
if (is_array($newUids)) {
|
||||
self::$uids = array_merge(self::$uids, $newUids);
|
||||
} else {
|
||||
self::$uids[] = $newUids;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一个分配的UID
|
||||
*
|
||||
* @return int|null 返回UID,没有可用UID时返回null
|
||||
*/
|
||||
public static function next()
|
||||
{
|
||||
if (!self::$initialized) {
|
||||
self::initialize();
|
||||
}
|
||||
|
||||
if (empty(self::$uids)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$uid = self::$uids[self::$index];
|
||||
|
||||
// 移动到下一个位置(循环)
|
||||
self::$index = (self::$index + 1) % count(self::$uids);
|
||||
|
||||
return $uid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前指针位置
|
||||
*/
|
||||
public static function getPosition(): int
|
||||
{
|
||||
return self::$index;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前指针位置
|
||||
*
|
||||
* @param int $position 新的位置索引
|
||||
*/
|
||||
public static function setPosition(int $position)
|
||||
{
|
||||
if (!self::$initialized) {
|
||||
self::initialize();
|
||||
}
|
||||
|
||||
if (!empty(self::$uids)) {
|
||||
self::$index = $position % count(self::$uids);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前UID数组
|
||||
*/
|
||||
public static function getUids(): array
|
||||
{
|
||||
return self::$uids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置指针到起始位置
|
||||
*/
|
||||
public static function reset()
|
||||
{
|
||||
self::$index = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 随机打乱当前UID数组
|
||||
*/
|
||||
public static function shuffle()
|
||||
{
|
||||
shuffle(self::$uids);
|
||||
self::$index = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// // 使用方法:
|
||||
|
||||
// // 初始化分配器
|
||||
// UidRotator::initialize([64, 63, 83, 93]);
|
||||
|
||||
// echo UidRotator::next(); // 64
|
||||
// echo UidRotator::next(); // 63
|
||||
|
||||
// // 动态添加新UID
|
||||
// UidRotator::addUids(108);
|
||||
// UidRotator::addUids([118, 131]);
|
||||
|
||||
// echo UidRotator::next(); // 83
|
||||
|
||||
// // 设置新数组并重置索引
|
||||
// UidRotator::setUids([150, 143, 156]);
|
||||
|
||||
// echo UidRotator::next(); // 150
|
||||
// echo UidRotator::next(); // 143
|
||||
|
||||
// // 设置新数组但保持当前索引位置
|
||||
// UidRotator::setUids([157, 158, 159, 160], false);
|
||||
// echo UidRotator::next(); // 159 (因为之前索引是2)
|
||||
|
||||
|
||||
// // 从特定位置开始
|
||||
// UidRotator::initialize([64, 63, 83, 93], 2);
|
||||
// echo UidRotator::next(); // 83
|
||||
|
||||
// // 获取当前状态
|
||||
// $currentPosition = UidRotator::getPosition();
|
||||
// $allUids = UidRotator::getUids();
|
||||
|
||||
// // 设置新位置
|
||||
// UidRotator::setPosition(1);
|
||||
// echo UidRotator::next(); // 63
|
||||
|
||||
// // 随机打乱数组
|
||||
// UidRotator::shuffle();
|
||||
// print_r(UidRotator::getUids()); // 随机顺序的数组
|
||||
@@ -0,0 +1,360 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils;
|
||||
|
||||
use app\common\model\UserRoles;
|
||||
use GatewayWorker\Lib\Gateway;
|
||||
use app\common\utils\WsResponse;
|
||||
use app\common\service\MessageNotificationsService;
|
||||
use support\Redis;
|
||||
|
||||
class WsEvents
|
||||
{
|
||||
|
||||
private $registerAddress = '127.0.0.1:1236';
|
||||
protected $clientId;
|
||||
protected $eventData;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
Gateway::$registerAddress = $this->registerAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听消息接收
|
||||
*/
|
||||
public function message($client_id, $message)
|
||||
{
|
||||
$this->clientId = $client_id;
|
||||
|
||||
$payload = json_decode($message, true);
|
||||
$event = $payload['event'];
|
||||
$this->eventData = $payload['data'] ?? [];
|
||||
$traceId = $payload['trace_id'] ?? null;
|
||||
|
||||
$method = $this->eventToMethod($event);
|
||||
|
||||
if (method_exists($this, $method)) {
|
||||
try {
|
||||
$this->$method($traceId);
|
||||
} catch (\Throwable $th) {
|
||||
Gateway::sendToClient($client_id, WsResponse::error(
|
||||
$event,
|
||||
500,
|
||||
$th->getMessage(),
|
||||
$traceId
|
||||
));
|
||||
}
|
||||
} else {
|
||||
Gateway::sendToClient($client_id, WsResponse::error(
|
||||
$event,
|
||||
404,
|
||||
"Event handler not found: $method",
|
||||
$traceId
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
protected function eventToMethod(string $event): string
|
||||
{
|
||||
$parts = explode('.', $event);
|
||||
$method = array_shift($parts);
|
||||
foreach ($parts as $part) {
|
||||
$method .= ucfirst($part);
|
||||
}
|
||||
return $method;
|
||||
}
|
||||
|
||||
|
||||
// ================= 系统事件 =================
|
||||
/**
|
||||
* 认证
|
||||
*/
|
||||
public function auth($client_id, $payload)
|
||||
{
|
||||
try {
|
||||
// 检查来源
|
||||
if (!isset($payload['server']['HTTP_ORIGIN'])) {
|
||||
flg('[x] [TOKEN认证] 未定义HTTP_ORIGIN', false);
|
||||
Gateway::sendToClient($client_id, WsResponse::error(
|
||||
'system.auth',
|
||||
1001,
|
||||
'[x] [TOKEN认证] 未定义HTTP_ORIGIN'
|
||||
));
|
||||
Gateway::closeClient($client_id);
|
||||
return;
|
||||
}
|
||||
|
||||
// 连接是否满足条件
|
||||
if (getenv('ENVIRONMENT') === 'master' && $payload['server']['HTTP_ORIGIN'] === getenv('MAIN_DOMAIN')) {
|
||||
flg('[x] [TOKEN认证] HTTP_ORIGIN不满足条件', false);
|
||||
Gateway::sendToClient($client_id, WsResponse::error(
|
||||
'system.auth',
|
||||
1001,
|
||||
'[x] [TOKEN认证] HTTP_ORIGIN不满足条件'
|
||||
));
|
||||
Gateway::closeClient($client_id);
|
||||
return;
|
||||
}
|
||||
|
||||
// 签名检查
|
||||
if (!isset($payload['get']['token'])) {
|
||||
flg('[x] [TOKEN认证] 未携带TOKEN参数', false);
|
||||
Gateway::sendToClient($client_id, WsResponse::error(
|
||||
'system.auth',
|
||||
1001,
|
||||
'[x] [TOKEN认证] 未携带TOKEN参数'
|
||||
));
|
||||
Gateway::closeClient($client_id);
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析TOKEN
|
||||
$user = (new Jwt())->verifyToken($payload['get']['token']);
|
||||
|
||||
// 绑定用户ID
|
||||
Gateway::bindUid($client_id, $user->uid);
|
||||
|
||||
// 绑定SESSION
|
||||
$_SESSION['uid'] = $user->uid;
|
||||
// $_SESSION['name'] = $user->uname;
|
||||
|
||||
// 响应
|
||||
Gateway::sendToClient($client_id, WsResponse::success(
|
||||
'system.auth',
|
||||
['uid' => $user->uid]
|
||||
));
|
||||
} catch (\Throwable $th) {
|
||||
flg('[x] [TOKEN认证] TOKEN认证失败:'.$th->getMessage(), false);
|
||||
Gateway::sendToClient($client_id, WsResponse::error(
|
||||
'system.auth',
|
||||
1001,
|
||||
'[x] [TOKEN认证] TOKEN认证失败:'.$th->getMessage()
|
||||
));
|
||||
Gateway::closeClient($client_id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public function logout(string $client_id)
|
||||
{
|
||||
// var_dump('====== ====== ====== start ====== ====== ======');
|
||||
// var_dump('关闭客户端ID:'.$client_id);
|
||||
// if ($_SESSION !== null) {
|
||||
// var_dump($_SESSION);
|
||||
// }
|
||||
// var_dump('====== ====== ====== end ====== ====== ======');
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统心跳
|
||||
*
|
||||
* @param string|null $traceId
|
||||
*/
|
||||
public function systemPing(?string $traceId)
|
||||
{
|
||||
Gateway::sendToClient($this->clientId, WsResponse::success(
|
||||
'system.pong',
|
||||
['time' => time()],
|
||||
$traceId
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
public function systemConnect(?string $traceId)
|
||||
{
|
||||
// 响应
|
||||
Gateway::sendToClient($this->clientId, WsResponse::success(
|
||||
'system.connect.receive',
|
||||
['time' => time()],
|
||||
$traceId
|
||||
));
|
||||
|
||||
// 获取审批待办数量
|
||||
$num = (new \app\common\utils\approval\service\ApprovalFlowService())->getInitTodoCount($_SESSION['uid']);
|
||||
$this->todoCounts($_SESSION['uid'], $num);
|
||||
|
||||
// 绑定检查
|
||||
$initData = $this->initCheck($_SESSION['uid']);
|
||||
Gateway::sendToClient($this->clientId, WsResponse::success(
|
||||
'system.init.check',
|
||||
$initData,
|
||||
$traceId
|
||||
));
|
||||
}
|
||||
|
||||
// ================= 消息通知事件 =================
|
||||
/**
|
||||
* 管理端主动推送通知
|
||||
*/
|
||||
public function notifyPush(?string $traceId)
|
||||
{
|
||||
$title = $this->eventData['title'] ?? null;
|
||||
$content = $this->eventData['content'] ?? null;
|
||||
$toUids = $this->eventData['to_uids'] ?? [];
|
||||
|
||||
if (!$title || !$content) {
|
||||
Gateway::sendToClient($this->clientId, WsResponse::error(
|
||||
'notify.push.result',
|
||||
400,
|
||||
'标题和内容不能为空',
|
||||
$traceId
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
// 写消息
|
||||
$msgService = new MessageNotificationsService();
|
||||
$msgId = $msgService->createMessage([
|
||||
'sender_id' => $this->eventData['sender_id'] ?? 0,
|
||||
'sender_type' => $this->eventData['sender_type'] ?? 'system',
|
||||
'title' => $title,
|
||||
'content' => $content,
|
||||
'scene' => $this->eventData['scene'] ?? 0,
|
||||
'recipient' => $this->eventData['to_uids'] ? implode(',', $this->eventData['to_uids']) : '',
|
||||
'push_method' => isset($this->eventData['push_method']) ? $this->eventData['push_method'] : 0
|
||||
]);
|
||||
|
||||
// 写用户状态
|
||||
$uids = !empty($toUids) ? $toUids : $msgService->getAllUserIds();
|
||||
$msgService->addUserStatus($msgId, $uids);
|
||||
|
||||
$payload = WsResponse::success('notify.receive', [
|
||||
'msg_id' => $msgId,
|
||||
'title' => $title,
|
||||
'content' => $content,
|
||||
'created_at' => time()
|
||||
], $traceId);
|
||||
|
||||
if (!empty($toUids)) {
|
||||
// 推送给指定用户
|
||||
foreach ($toUids as $uid) {
|
||||
Gateway::sendToUid($uid, $payload);
|
||||
}
|
||||
} else {
|
||||
// 推送给全体在线用户
|
||||
Gateway::sendToAll($payload);
|
||||
}
|
||||
|
||||
// 回复发送者确认
|
||||
Gateway::sendToClient($this->clientId, WsResponse::success(
|
||||
'notify.push.result',
|
||||
['msg_id' => $msgId],
|
||||
$traceId,
|
||||
'消息发送成功'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端标记通知已读
|
||||
*/
|
||||
public function notifyRead(?string $traceId)
|
||||
{
|
||||
$msgIds = $this->eventData['msg_ids'];
|
||||
if (!is_array($msgIds) && $msgIds !== 'all') {
|
||||
Gateway::sendToClient($this->clientId, WsResponse::error(
|
||||
'notify.read.result',
|
||||
400,
|
||||
'消息ID不能为空',
|
||||
$traceId
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新消息为已读
|
||||
$msgService = new MessageNotificationsService();
|
||||
$msgService->markAsRead($msgIds, Gateway::getUidByClientId($this->clientId));
|
||||
|
||||
Gateway::sendToClient($this->clientId, WsResponse::success(
|
||||
'notify.read.result',
|
||||
['msg_ids' => $msgIds],
|
||||
$traceId
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
approval.todo.counts 审批待办数量
|
||||
|
||||
*/
|
||||
|
||||
// ================= 主动推送 =================
|
||||
|
||||
public function pushWebsocket(string $event, int|string $uid, array $data)
|
||||
{
|
||||
return match (gettype($uid)) {
|
||||
'integer' => Gateway::sendToUid($uid, WsResponse::success($event, $data)),
|
||||
'string' => Gateway::sendToClient($uid, WsResponse::success($event, $data)),
|
||||
default => throw new \InvalidArgumentException('UID must be integer or string'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// ================= 业务处理 =================
|
||||
|
||||
/**
|
||||
* 初始化检查
|
||||
*/
|
||||
public function initCheck(int $userId)
|
||||
{
|
||||
$data = [
|
||||
// 'is_report_to' => false,
|
||||
// 'is_office_clerk' => false,
|
||||
'is_sign' => false
|
||||
];
|
||||
|
||||
$user = \app\common\model\User::find($userId);
|
||||
// if ($user->report_to > 0) {
|
||||
// $data['is_report_to'] = true;
|
||||
// }
|
||||
|
||||
if ($user->sign_img !== null && $user->sign_img !== '') {
|
||||
$data['is_sign'] = true;
|
||||
}
|
||||
|
||||
// $ug = \app\common\model\UserGroupMembers::with(['group' => function($query) {
|
||||
// $query->where('scenario_code', 'stock_orders');
|
||||
// }])->where('user_id', $userId)->first();
|
||||
// if ($ug !== null) {
|
||||
// $data['is_office_clerk'] = true;
|
||||
// }
|
||||
|
||||
if ($data['is_sign']) {
|
||||
Redis::hSet('user:check:sign'.$userId, 'status', 1);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
// 审批待办数量
|
||||
public function todoCounts(int $userId, int $num = 0)
|
||||
{
|
||||
$ly = [
|
||||
1 => 186,
|
||||
3 => 224,
|
||||
];
|
||||
|
||||
if ($num === 0) {
|
||||
$num = (new \app\common\utils\approval\service\ApprovalFlowService())->getInitTodoCount($userId);
|
||||
}
|
||||
|
||||
$systemIds = \app\common\model\UserSystems::where('user_id', $userId)->pluck('system_id')->toArray();
|
||||
if (count($systemIds) > 0) {
|
||||
foreach ($systemIds as $systemId) {
|
||||
if (isset($ly[$systemId])) {
|
||||
$chain = \app\common\service\MenuBadgeService::buildBadgeChain(menuId: $ly[$systemId], leafCount: $num);
|
||||
$this->pushWebsocket('approval.todo.counts', $userId, $chain);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
namespace app\common\utils;
|
||||
|
||||
class WsResponse
|
||||
{
|
||||
/**
|
||||
* 成功返回
|
||||
*
|
||||
* @param string $event 事件名称
|
||||
* @param array $data 返回数据
|
||||
* @param string|null $traceId 请求追踪ID,可选,默认 null
|
||||
* @param int $code 错误码
|
||||
* @param string $message 错误信息
|
||||
* @return string JSON
|
||||
*/
|
||||
public static function success(string $event, array $data = [], ?string $traceId = null, string $message = 'ok', int $code = 0): string
|
||||
{
|
||||
return json_encode([
|
||||
'event' => $event,
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
'trace_id' => $traceId, // 如果没有传就是 null
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误返回
|
||||
*
|
||||
* @param string $event 事件名称
|
||||
* @param int $code 错误码
|
||||
* @param string $message 错误信息
|
||||
* @param string|null $traceId 请求追踪ID,可选,默认 null
|
||||
* @param array $data 附加数据(可选)
|
||||
* @return string JSON
|
||||
*/
|
||||
public static function error(string $event, int $code, string $message, ?string $traceId = null, array $data = []): string
|
||||
{
|
||||
return json_encode([
|
||||
'event' => $event,
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
'trace_id' => $traceId, // 如果没有传就是 null
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,857 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\crawl\service;
|
||||
|
||||
use app\common\model\UsedcarCrawlResultsImages;
|
||||
use app\common\service\UploadService;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use QL\QueryList;
|
||||
use support\Redis;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
use Throwable;
|
||||
|
||||
class UsedCarCrawl
|
||||
{
|
||||
// 默认请求头
|
||||
private const DEFAULT_HEADERS = [
|
||||
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||
'Accept-Language' => 'zh-CN,zh;q=0.9',
|
||||
'Referer' => 'https://www.dongchedi.com/',
|
||||
];
|
||||
|
||||
// Redis队列键名
|
||||
private const REDIS_QUEUE_KEY = 'usedcar:urls';
|
||||
|
||||
// 能源类型常量
|
||||
public const ENERGY_TYPE_RENEWABLE = 'RE';
|
||||
public const ENERGY_TYPE_CONVENTIONAL = 'CE';
|
||||
public const ENERGY_TYPE_UNKNOWN = 'UNKNOWN';
|
||||
|
||||
/**
|
||||
* 插入队列url
|
||||
*
|
||||
* @param string $url URL地址
|
||||
* @param string $scene 场景:usedcar(二手信息) config(配置信息)
|
||||
* @param int $id 记录ID
|
||||
* @return int
|
||||
*/
|
||||
public function pushUrl(string $url = '', string $scene = 'usedcar', int $id = 0): int
|
||||
{
|
||||
$data = [
|
||||
'scene' => $scene,
|
||||
'url' => $url,
|
||||
'id' => $id,
|
||||
];
|
||||
|
||||
return Redis::lpush(
|
||||
self::REDIS_QUEUE_KEY,
|
||||
json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取队列url
|
||||
*
|
||||
* @return array|null
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function popUrl(): ?array
|
||||
{
|
||||
$data = Redis::rPop(self::REDIS_QUEUE_KEY);
|
||||
if (!$data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$task = json_decode($data, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE || !is_array($task)) {
|
||||
throw new BusinessException('任务数据解析失败:' . json_last_error_msg());
|
||||
}
|
||||
|
||||
// 基本字段校验
|
||||
if (empty($task['url']) || empty($task['scene'])) {
|
||||
throw new BusinessException('队列任务数据缺少必要字段:url 或 scene');
|
||||
}
|
||||
|
||||
return $task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行抓取任务
|
||||
*
|
||||
* @return bool
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function execute(): bool
|
||||
{
|
||||
try {
|
||||
$task = $this->popUrl();
|
||||
|
||||
if (!$task) {
|
||||
// 队列为空,任务结束
|
||||
return false;
|
||||
}
|
||||
|
||||
$url = (string)$task['url'];
|
||||
$scene = (string)$task['scene'];
|
||||
$id = (int)($task['id'] ?? 0);
|
||||
|
||||
$html = $this->fetchHtml($url);
|
||||
if ($html === '') {
|
||||
throw new BusinessException("页面内容为空: {$url}");
|
||||
}
|
||||
|
||||
switch ($scene) {
|
||||
case 'usedcar':
|
||||
$info = $this->parseUsedCarDetail($html, $url);
|
||||
$insertId = $this->saveUsedCarBasicInfo($info);
|
||||
|
||||
// 下载图片 + 上传 + 入库(图片失败不影响主记录)
|
||||
$imagesArray = json_decode($info['images'] ?? '[]', true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$imagesArray = [];
|
||||
}
|
||||
$saveDir = public_path('uploads/usedcar/' . $insertId);
|
||||
$this->uploadAndRemove($imagesArray, $saveDir, $info['used_car_id'], $insertId);
|
||||
|
||||
// 继续派发配置页任务
|
||||
if (!empty($info['car_id_url'])) {
|
||||
$this->pushUrl($info['car_id_url'], 'config', $insertId);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'config':
|
||||
if ($id <= 0) {
|
||||
throw new BusinessException("配置任务缺少主记录ID");
|
||||
}
|
||||
|
||||
$data = $this->parseConfigDetail($html);
|
||||
$this->saveUsedCarConfigInfo($data, $id);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new BusinessException("未知的任务场景: " . $scene);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (GuzzleException $e) {
|
||||
throw new BusinessException("网络请求失败: " . $e->getMessage());
|
||||
} catch (BusinessException $e) {
|
||||
// 业务异常原样抛出,方便上层知道是逻辑问题
|
||||
throw $e;
|
||||
} catch (Throwable $th) {
|
||||
// 兜底异常,避免 worker 直接挂掉
|
||||
throw new BusinessException(
|
||||
"执行任务出错: " . $th->getMessage()
|
||||
. ' | 行号: ' . $th->getLine()
|
||||
. ' | 文件: ' . $th->getFile()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取网页HTML内容
|
||||
*
|
||||
* @param string $url
|
||||
* @return string
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function fetchHtml(string $url): string
|
||||
{
|
||||
$client = new Client();
|
||||
$response = $client->request('GET', $url, [
|
||||
'headers' => self::DEFAULT_HEADERS,
|
||||
'timeout' => 10,
|
||||
]);
|
||||
|
||||
return (string)$response->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析二手车详情页信息
|
||||
*
|
||||
* @param string $html
|
||||
* @param string $url
|
||||
* @return array
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function parseUsedCarDetail(string $html = '', string $url = ''): array
|
||||
{
|
||||
try {
|
||||
$ql = QueryList::html($html);
|
||||
} catch (Throwable $e) {
|
||||
throw new BusinessException('解析 HTML 失败(详情页): ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$title = trim($ql->find('h1')->text());
|
||||
$price = trim($ql->find('.head-info_price-wrap__Y4bxi > p')->text());
|
||||
$pageText = $ql->find('body')->text();
|
||||
$jsonText = $ql->find('#__NEXT_DATA__')->text();
|
||||
|
||||
if ($jsonText === '') {
|
||||
throw new BusinessException('详情页未找到 __NEXT_DATA__ JSON');
|
||||
}
|
||||
|
||||
$jsonArray = $this->decodeJson($jsonText, '详情页 __NEXT_DATA__');
|
||||
|
||||
// 车辆相册
|
||||
$images = $jsonArray['props']['pageProps']['skuDetail']['head_images'] ?? [];
|
||||
|
||||
// 车辆ID / 年份
|
||||
$carInfo = $jsonArray['props']['pageProps']['skuDetail']['car_info'] ?? [];
|
||||
$carId = $carInfo['car_id'] ?? 0;
|
||||
$year = (int)($carInfo['year'] ?? 0);
|
||||
|
||||
// 车辆ID URL
|
||||
$carIdUrl = $carId ? ('https://www.dongchedi.com/auto/params-carIds-' . $carId) : '';
|
||||
|
||||
// 能源类型(两个字段择一)
|
||||
$overview = $jsonArray['props']['pageProps']['skuDetail']['car_config_overview'] ?? [];
|
||||
$fuelForm = $overview['power']['fuel_form'] ?? '';
|
||||
$newFuelForm = $overview['new_energy_power']['fuel_form'] ?? '';
|
||||
$resultFuelForm = $fuelForm === '' ? $newFuelForm : $fuelForm;
|
||||
|
||||
// 使用里程
|
||||
$importantText = $jsonArray['props']['pageProps']['skuDetail']['important_text'] ?? '';
|
||||
$importantTextArray = $importantText ? explode(' | ', $importantText) : [];
|
||||
$usageMileage = '';
|
||||
if (isset($importantTextArray[1])) {
|
||||
$usageMileage = str_replace('万公里', '', $importantTextArray[1]);
|
||||
}
|
||||
|
||||
// 车辆名称 品牌、车系、车型
|
||||
$brandName = $carInfo['brand_name'] ?? '';
|
||||
$seriesName = $carInfo['series_name'] ?? '';
|
||||
$carName = $carInfo['car_name'] ?? '';
|
||||
|
||||
// 商家信息
|
||||
$shopInfo = $jsonArray['props']['pageProps']['skuDetail']['shop_info'] ?? [];
|
||||
$formatShopInfo = [
|
||||
'shop_id' => $shopInfo['shop_id'] ?? 0,
|
||||
'shop_name' => $shopInfo['shop_short_name'] ?? '',
|
||||
'shop_address' => $shopInfo['shop_address'] ?? '',
|
||||
];
|
||||
|
||||
// 简介参数
|
||||
$otherParams = $jsonArray['props']['pageProps']['skuDetail']['other_params'] ?? [];
|
||||
$displacement = $this->getParamValue($otherParams, '排量');
|
||||
$gearbox = $this->getParamValue($otherParams, '变速箱');
|
||||
|
||||
$formatCarInfo = [
|
||||
'displacement' => $displacement,
|
||||
'gearbox' => $gearbox,
|
||||
];
|
||||
|
||||
// 提取新车指导价 / 比新车省金额
|
||||
$newPrice = $this->extractPatternValue($pageText, '/新车指导价[::]\s*([^\r\n万]*万)/u');
|
||||
$priceDifference = $this->extractPatternValue($pageText, '/比新车省[::]\s*([^\r\n万]*万)/u');
|
||||
|
||||
// 提取车况介绍
|
||||
$conditionDesc = '';
|
||||
if ($pageText && preg_match('/车况介绍\s*(.*?)\s*推荐理由/su', $pageText, $m)) {
|
||||
$conditionDesc = trim($m[1]);
|
||||
}
|
||||
|
||||
return [
|
||||
'used_car_id' => $this->extractIdFromUrl($url),
|
||||
'car_id' => $carId,
|
||||
'url' => $url,
|
||||
'title' => $title,
|
||||
'price' => str_replace('万', '', $this->decodePrice($price)),
|
||||
'new_price' => str_replace('万', '', $newPrice),
|
||||
'price_difference' => str_replace('万', '', $priceDifference),
|
||||
'condition_desc' => $conditionDesc,
|
||||
'images' => json_encode($images, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'car_id_url' => $carIdUrl,
|
||||
'used_detail' => $jsonText,
|
||||
'format_shop_info' => json_encode($formatShopInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'fuel_form' => $resultFuelForm,
|
||||
'classify_energy' => $this->detectEnergyType($resultFuelForm),
|
||||
'usage_mileage' => $usageMileage,
|
||||
'brand_name' => $brandName,
|
||||
'series_name' => $seriesName,
|
||||
'car_name' => $carName,
|
||||
'year' => $year,
|
||||
'format_car_info' => json_encode($formatCarInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析配置详情页信息
|
||||
*
|
||||
* @param string $html
|
||||
* @return array
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function parseConfigDetail(string $html = ''): array
|
||||
{
|
||||
try {
|
||||
$ql = QueryList::html($html);
|
||||
} catch (Throwable $e) {
|
||||
throw new BusinessException('解析 HTML 失败(配置页): ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$jsonText = $ql->find('#__NEXT_DATA__')->text();
|
||||
if ($jsonText === '') {
|
||||
throw new BusinessException('配置页未找到 __NEXT_DATA__ JSON');
|
||||
}
|
||||
|
||||
$raw = $this->decodeJson($jsonText, '配置页 __NEXT_DATA__');
|
||||
|
||||
$properties = $raw['props']['pageProps']['rawData']['properties'] ?? [];
|
||||
$carInfo = $raw['props']['pageProps']['rawData']['car_info'][0] ?? [];
|
||||
|
||||
$valuesMap = $this->buildValuesMap($carInfo);
|
||||
$groups = $this->buildCarSpecGroups($properties, $valuesMap);
|
||||
|
||||
return [
|
||||
'format_car_info' => [
|
||||
'market_time' => $this->getFieldValue($groups, 'market_time'), // 上市时间
|
||||
'driver_form' => $this->getFieldValue($groups, 'driver_form'), // 驱动形式
|
||||
'seat_count' => $this->getFieldValue($groups, 'seat_count'), // 座位数
|
||||
'engine_description' => $this->getFieldValue($groups, 'engine_description'), // 发动机
|
||||
'engine_max_power_horsepower' => $this->getFieldValue($groups, 'engine_max_power_horsepower'), // 发动机最大功率
|
||||
'electric_description' => $this->getFieldValue($groups, 'electric_description'), // 电动机
|
||||
'battery_capacity' => $this->getFieldValue($groups, 'battery_capacity'), // 电池容量
|
||||
'battery_type' => $this->getFieldValue($groups, 'battery_type'), // 电池类型
|
||||
'recharge_mileage' => $this->getFieldValue($groups, 'recharge_mileage'), // 续航里程
|
||||
],
|
||||
'groups' => $groups,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从车辆配置中获取能源类型
|
||||
*
|
||||
* @param array $data JSON数据
|
||||
* @return string|null 能源类型
|
||||
*/
|
||||
public function getFuelFormByConfig(array $data): ?string
|
||||
{
|
||||
if (empty($data[0]['items']) || !is_array($data[0]['items'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($data[0]['items'] as $item) {
|
||||
if (isset($item['key']) && $item['key'] === 'fuel_form') {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从数据中根据字段key获取值
|
||||
*
|
||||
* @param mixed $data 数据
|
||||
* @param string $field 字段名
|
||||
* @return string|null
|
||||
*/
|
||||
public function getFieldValue($data, string $field): ?string
|
||||
{
|
||||
if (is_string($data)) {
|
||||
$data = json_decode($data, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_array($data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($data as $group) {
|
||||
if (isset($group['items']) && is_array($group['items'])) {
|
||||
foreach ($group['items'] as $item) {
|
||||
if (($item['key'] ?? null) === $field) {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
|
||||
if (!empty($item['children']) && is_array($item['children'])) {
|
||||
foreach ($item['children'] as $child) {
|
||||
if (($child['key'] ?? null) === $field) {
|
||||
return $child['value'] ?? null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从参数列表中获取指定名称的值
|
||||
*/
|
||||
public function getParamValue(array $params, string $name): ?string
|
||||
{
|
||||
foreach ($params as $item) {
|
||||
if (($item['name'] ?? null) === $name) {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断车辆能源类型
|
||||
*/
|
||||
public function detectEnergyType(string $text): string
|
||||
{
|
||||
if (function_exists('mb_internal_encoding')) {
|
||||
mb_internal_encoding('UTF-8');
|
||||
}
|
||||
|
||||
// 明确定义的新能源关键字
|
||||
$newEnergyKeywords = [
|
||||
'纯电', '纯电动', '电动车', 'BEV',
|
||||
'插电混动', '插电式混合', '插电式', '插电', 'PHEV',
|
||||
'增程式', '增程', 'REEV',
|
||||
'氢能', '氢燃料', '燃料电池', 'FCEV',
|
||||
'太阳能',
|
||||
];
|
||||
|
||||
// 传统能源关键字
|
||||
$traditionalKeywords = [
|
||||
'汽油',
|
||||
'柴油',
|
||||
'天然气', 'LNG', 'CNG',
|
||||
];
|
||||
|
||||
// 普通混动关键字(归为传统能源)
|
||||
$hybridKeywords = [
|
||||
'油电混合', '油电混动', '油电',
|
||||
'混动',
|
||||
'双擎',
|
||||
'HEV',
|
||||
];
|
||||
|
||||
$contains = function (string $haystack, string $needle): bool {
|
||||
if ($needle === '') {
|
||||
return false;
|
||||
}
|
||||
if (function_exists('mb_stripos')) {
|
||||
return mb_stripos($haystack, $needle) !== false;
|
||||
}
|
||||
return stripos($haystack, $needle) !== false;
|
||||
};
|
||||
|
||||
foreach ($newEnergyKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return self::ENERGY_TYPE_RENEWABLE;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($hybridKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return self::ENERGY_TYPE_CONVENTIONAL;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($traditionalKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return self::ENERGY_TYPE_CONVENTIONAL;
|
||||
}
|
||||
}
|
||||
|
||||
return self::ENERGY_TYPE_UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存二手车基本信息到数据库
|
||||
*
|
||||
* @param array $data 数据
|
||||
* @return int 插入记录ID
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function saveUsedCarBasicInfo(array $data): int
|
||||
{
|
||||
try {
|
||||
$time = time();
|
||||
$data['created_at'] = $data['created_at'] ?? $time;
|
||||
$data['updated_at'] = $time;
|
||||
|
||||
return (int)Db::table('usedcar_crawl_results')->insertGetId($data);
|
||||
} catch (Throwable $e) {
|
||||
throw new BusinessException('保存二手车基础信息失败:' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新配置信息到数据库
|
||||
*
|
||||
* @param array $data 配置数据
|
||||
* @param int $id 记录ID
|
||||
* @return bool|int
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function saveUsedCarConfigInfo(array $data, int $id)
|
||||
{
|
||||
try {
|
||||
$record = Db::table('usedcar_crawl_results')->find($id);
|
||||
|
||||
if (!$record) {
|
||||
// 找不到记录就算了,不抛致命错误,视业务情况也可以抛异常
|
||||
return false;
|
||||
}
|
||||
|
||||
$groups = $data['groups'] ?? [];
|
||||
$oldFormat = [];
|
||||
|
||||
if (!empty($record->format_car_info)) {
|
||||
$decoded = json_decode($record->format_car_info, true);
|
||||
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
|
||||
$oldFormat = $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
$formatCarInfo = array_merge(
|
||||
$oldFormat,
|
||||
$data['format_car_info'] ?? []
|
||||
);
|
||||
|
||||
return Db::table('usedcar_crawl_results')
|
||||
->where('id', $id)
|
||||
->update([
|
||||
'format_car_info' => json_encode($formatCarInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'config_detail' => json_encode($groups, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
throw new BusinessException('保存车辆配置信息失败:' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建值映射表
|
||||
*/
|
||||
public function buildValuesMap(array $carInfo): array
|
||||
{
|
||||
$valuesMap = [];
|
||||
|
||||
// 顶层字段
|
||||
foreach ($carInfo as $k => $v) {
|
||||
if ($k === 'info' || is_array($v)) {
|
||||
continue;
|
||||
}
|
||||
$valuesMap[$k] = ['value' => $v];
|
||||
}
|
||||
|
||||
// info中的配置项
|
||||
if (!empty($carInfo['info']) && is_array($carInfo['info'])) {
|
||||
foreach ($carInfo['info'] as $k => $v) {
|
||||
if (is_array($v) && array_key_exists('value', $v)) {
|
||||
$valuesMap[$k] = $v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $valuesMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建车辆规格分组
|
||||
*/
|
||||
public function buildCarSpecGroups(array $properties, array $valuesMap): array
|
||||
{
|
||||
$groups = [];
|
||||
$currentKey = null;
|
||||
|
||||
foreach ($properties as $item) {
|
||||
$type = (int)($item['type'] ?? 1);
|
||||
$key = $item['key'] ?? '';
|
||||
$text = $item['text'] ?? '';
|
||||
$subList = $item['sub_list'] ?? null;
|
||||
|
||||
// 分类字段:type = 0 / 2
|
||||
if (in_array($type, [0, 2], true)) {
|
||||
$currentKey = $key ?: ($text ?: ('group_' . count($groups)));
|
||||
|
||||
if (!isset($groups[$currentKey])) {
|
||||
$groups[$currentKey] = [
|
||||
'group_key' => $currentKey,
|
||||
'group_text' => $text,
|
||||
'group_type' => $type,
|
||||
'items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 普通字段:挂到最近的分类下
|
||||
if ($currentKey === null) {
|
||||
$currentKey = '_default';
|
||||
$groups[$currentKey] = [
|
||||
'group_key' => '_default',
|
||||
'group_text' => '其他',
|
||||
'group_type' => -1,
|
||||
'items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$value = '';
|
||||
if ($key && isset($valuesMap[$key])) {
|
||||
$value = trim((string)($valuesMap[$key]['value'] ?? ''));
|
||||
}
|
||||
|
||||
$node = [
|
||||
'key' => $key,
|
||||
'text' => $text,
|
||||
'value' => $value,
|
||||
];
|
||||
|
||||
if (is_array($subList) && !empty($subList)) {
|
||||
$children = [];
|
||||
foreach ($subList as $sub) {
|
||||
$subKey = $sub['key'] ?? '';
|
||||
$subText = $sub['text'] ?? '';
|
||||
$subValue = '';
|
||||
|
||||
if ($subKey && isset($valuesMap[$subKey])) {
|
||||
$subValue = trim((string)($valuesMap[$subKey]['value'] ?? ''));
|
||||
}
|
||||
|
||||
$children[] = [
|
||||
'key' => $subKey,
|
||||
'text' => $subText,
|
||||
'value' => $subValue,
|
||||
];
|
||||
}
|
||||
|
||||
$node['children'] = $children;
|
||||
}
|
||||
|
||||
$groups[$currentKey]['items'][] = $node;
|
||||
}
|
||||
|
||||
return array_values($groups);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码懂车帝价格
|
||||
*/
|
||||
protected function decodePrice(string $str): string
|
||||
{
|
||||
$map = [
|
||||
"\u{E53D}" => '1',
|
||||
"\u{E3F0}" => '2',
|
||||
"\u{E422}" => '3',
|
||||
"\u{E42C}" => '4',
|
||||
"\u{E49C}" => '5',
|
||||
"\u{E42B}" => '6',
|
||||
"\u{E4FE}" => '7',
|
||||
"\u{E548}" => '8',
|
||||
"\u{E4C8}" => '9',
|
||||
"\u{E453}" => '0',
|
||||
"\u{E45F}" => '万',
|
||||
];
|
||||
|
||||
return strtr($str, $map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从URL中提取ID
|
||||
*/
|
||||
protected function extractIdFromUrl(string $url)
|
||||
{
|
||||
if (preg_match('/\/(\d+)$/', $url, $matches)) {
|
||||
return (int)$matches[1];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取符合正则表达式的值(只保留数字和小数点)
|
||||
*/
|
||||
protected function extractPatternValue(string $text, string $pattern): string
|
||||
{
|
||||
$value = '';
|
||||
if ($text && preg_match($pattern, $text, $m)) {
|
||||
$value = trim(preg_replace('/[^0-9.]/', '', $m[1]));
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载单张图片
|
||||
*/
|
||||
public function downloadImage(string $url, string $saveDir, ?string $filename = null, array $headers = []): ?string
|
||||
{
|
||||
if (!is_dir($saveDir)) {
|
||||
if (!@mkdir($saveDir, 0777, true) && !is_dir($saveDir)) {
|
||||
// echo "[Image] 创建目录失败:{$saveDir}\n";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ($filename === null) {
|
||||
$path = parse_url($url, PHP_URL_PATH);
|
||||
$ext = pathinfo($path ?? '', PATHINFO_EXTENSION);
|
||||
|
||||
if ($ext === '') {
|
||||
$ext = 'jpg';
|
||||
}
|
||||
|
||||
$filename = md5($url) . '.' . $ext;
|
||||
}
|
||||
|
||||
$savePath = rtrim($saveDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
|
||||
|
||||
$defaultHeaders = [
|
||||
'User-Agent: ' . self::DEFAULT_HEADERS['User-Agent'],
|
||||
'Accept: image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
'Referer: ' . self::DEFAULT_HEADERS['Referer'],
|
||||
];
|
||||
|
||||
foreach ($headers as $h) {
|
||||
$defaultHeaders[] = $h;
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_CONNECTTIMEOUT => 5,
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_HTTPHEADER => $defaultHeaders,
|
||||
]);
|
||||
|
||||
$data = curl_exec($ch);
|
||||
$errNo = curl_errno($ch);
|
||||
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($errNo !== 0 || $code !== 200 || $data === false || $data === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$bytes = @file_put_contents($savePath, $data);
|
||||
if ($bytes === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $savePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量下载相册
|
||||
*
|
||||
* @param array $urls 图片URL数组
|
||||
* @param string $saveDir 保存目录
|
||||
* @return array [原始URL => 保存路径或null]
|
||||
*/
|
||||
public function downloadImageAlbum(array $urls, string $saveDir): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($urls as $url) {
|
||||
$url = trim((string)$url);
|
||||
if ($url === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (strpos($url, '//') === 0) {
|
||||
$url = 'https:' . $url;
|
||||
}
|
||||
|
||||
try {
|
||||
$path = $this->downloadImage($url, $saveDir);
|
||||
} catch (Throwable $e) {
|
||||
$path = null;
|
||||
}
|
||||
|
||||
$result[$url] = $path;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载 -> 上传 -> 删除本地
|
||||
*
|
||||
* @param array $images 原始相册URL列表
|
||||
* @param string $path 本地保存目录
|
||||
* @param int $usedCarId 懂车帝 used_car_id
|
||||
* @param int $id 本地 crawl 记录id
|
||||
* @return bool
|
||||
*/
|
||||
public function uploadAndRemove(array $images, string $path, $usedCarId, $id): bool
|
||||
{
|
||||
if (empty($images)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 下载图片
|
||||
$filePatch = $this->downloadImageAlbum($images, $path);
|
||||
if (empty($filePatch)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$uploadService = new UploadService();
|
||||
|
||||
foreach ($filePatch as $url => $filePath) {
|
||||
if ($filePath === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
// 上传云端
|
||||
$param = [
|
||||
'path' => $filePath,
|
||||
'scene' => 'usedcar_crawl',
|
||||
'category' => 'usedcar',
|
||||
];
|
||||
|
||||
$result = $uploadService->uploadLocalFile($param);
|
||||
if (empty($result['file_name'])) {
|
||||
// 上传失败则跳过,但不抛异常影响主流程
|
||||
continue;
|
||||
}
|
||||
|
||||
// 保存图片信息
|
||||
UsedcarCrawlResultsImages::create([
|
||||
'uc_id' => $id,
|
||||
'used_car_id' => $usedCarId,
|
||||
'original_name'=> $result['original_name'] ?? '',
|
||||
'file_path' => $result['file_name'],
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
// 单张图失败不影响其他
|
||||
// 可以按需写日志
|
||||
} finally {
|
||||
// 删除本地文件
|
||||
if (is_file($filePath)) {
|
||||
@unlink($filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除目录
|
||||
rmdir($path);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全解 JSON
|
||||
*
|
||||
* @param string $json
|
||||
* @param string $context
|
||||
* @return array
|
||||
* @throws BusinessException
|
||||
*/
|
||||
protected function decodeJson(string $json, string $context = 'JSON'): array
|
||||
{
|
||||
$data = json_decode($json, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
|
||||
throw new BusinessException($context . ' 解析失败:' . json_last_error_msg());
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,681 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\crawl\service;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use QL\QueryList;
|
||||
use support\Redis;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class UsedCarCrawl_bak
|
||||
{
|
||||
|
||||
/**
|
||||
* 插入队列url
|
||||
*
|
||||
* $scene 二手信息 usedcar 配置信息 config
|
||||
*/
|
||||
public function iUrl(string $url = '', string $scene = 'usedcar', int $id = 0)
|
||||
{
|
||||
return Redis::lpush('usedcar:urls', json_encode([
|
||||
'scene' => $scene,
|
||||
'url' => $url,
|
||||
'id' => $id
|
||||
], JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取队列url
|
||||
*
|
||||
* $scene 二手信息 usedcar 配置信息 config
|
||||
*/
|
||||
public function rUrl()
|
||||
{
|
||||
return json_decode(Redis::rPop('usedcar:urls'), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行抓取
|
||||
*/
|
||||
public function doData()
|
||||
{
|
||||
try {
|
||||
$raw = $this->rUrl();
|
||||
|
||||
if (!$raw) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$html = $this->getHtml($raw['url']);
|
||||
|
||||
switch ($raw['scene']) {
|
||||
case 'usedcar':
|
||||
$info = $this->getUsedDetail($html, $raw['url']);
|
||||
$id = $this->saveUsedcarBasicToDb($info);
|
||||
$this->iUrl($info['car_id_url'], 'config', $id);
|
||||
break;
|
||||
|
||||
case 'config':
|
||||
$data = $this->getConfigDetail($html);
|
||||
$this->saveUsedcarConfigToDb($data, $raw['id']);
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (\Throwable $th) {
|
||||
throw new BusinessException($th->getMessage().'|'.$th->getLine().'|'.$th->getFile());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取html
|
||||
*/
|
||||
public function getHtml($url)
|
||||
{
|
||||
$client = new Client();
|
||||
$res = $client->request('GET', $url, [
|
||||
'headers' => [
|
||||
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
|
||||
. 'AppleWebKit/537.36 (KHTML, like Gecko) '
|
||||
. 'Chrome/120.0.0.0 Safari/537.36',
|
||||
'Accept-Language' => 'zh-CN,zh;q=0.9',
|
||||
'Referer' => 'https://www.dongchedi.com/'
|
||||
]
|
||||
]);
|
||||
return (string)$res->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取二手信息
|
||||
*/
|
||||
public function getUsedDetail(string $html = '', string $url = '')
|
||||
{
|
||||
$ql = QueryList::html($html);
|
||||
|
||||
$title = $ql->find('h1')->text();
|
||||
$price = $ql->find('.head-info_price-wrap__Y4bxi > p')->text();
|
||||
$pageText = $ql->find('body')->text();
|
||||
$jsonText = $ql->find('#__NEXT_DATA__')->text();
|
||||
|
||||
// 新车指导价
|
||||
$newPrice = '';
|
||||
if ($pageText) {
|
||||
if (preg_match('/新车指导价[::]\s*([^\r\n万]*万)/u', $pageText, $m)) {
|
||||
$newPrice = trim(preg_replace('/[^0-9.]/', '', $m[1]));
|
||||
}
|
||||
}
|
||||
|
||||
// 比新车省
|
||||
$priceDifference = '';
|
||||
if ($pageText) {
|
||||
if (preg_match('/比新车省[::]\s*([^\r\n万]*万)/u', $pageText, $m)) {
|
||||
$priceDifference = trim(preg_replace('/[^0-9.]/', '', $m[1]));
|
||||
}
|
||||
}
|
||||
|
||||
// 车况介绍
|
||||
$conditionDesc = '';
|
||||
if ($pageText) {
|
||||
if (preg_match('/车况介绍\s*(.*?)\s*推荐理由/su', $pageText, $m)) {
|
||||
$conditionDesc = trim($m[1]);
|
||||
}
|
||||
}
|
||||
|
||||
$jsonArray = json_decode($jsonText, true);
|
||||
|
||||
// 车辆相册
|
||||
$images = $jsonArray['props']['pageProps']['skuDetail']['head_images'] ?? [];
|
||||
|
||||
// 车辆ID
|
||||
$carId = $jsonArray['props']['pageProps']['skuDetail']['car_info']['car_id'] ?? 0;
|
||||
|
||||
// 车辆年份
|
||||
$year = $jsonArray['props']['pageProps']['skuDetail']['car_info']['year'] ?? 0;
|
||||
|
||||
// 车辆ID URL
|
||||
$carIdUrl = $carId ? ('https://www.dongchedi.com/auto/params-carIds-' . $carId) : '';
|
||||
|
||||
// 能源类型
|
||||
$fuelForm = $jsonArray['props']['pageProps']['skuDetail']['car_config_overview']['power']['fuel_form'] ?? '';
|
||||
$newFuelForm = $jsonArray['props']['pageProps']['skuDetail']['car_config_overview']['new_energy_power']['fuel_form'] ?? '';
|
||||
$resultFuelForm = $fuelForm === '' ? $newFuelForm : $fuelForm;
|
||||
|
||||
// 使用里程
|
||||
$importantText = $jsonArray['props']['pageProps']['skuDetail']['important_text'] ?? '';
|
||||
$importantTextArray = explode(' | ', $importantText);
|
||||
$usageMileage = str_replace('万公里', '', isset($importantTextArray[1]) ? $importantTextArray[1] : '');
|
||||
|
||||
// 车辆名称 品牌、车系、车型
|
||||
$brandName = $jsonArray['props']['pageProps']['skuDetail']['car_info']['brand_name'] ?? '';
|
||||
$seriesName = $jsonArray['props']['pageProps']['skuDetail']['car_info']['series_name'] ?? '';
|
||||
$carName = $jsonArray['props']['pageProps']['skuDetail']['car_info']['car_name'] ?? '';
|
||||
|
||||
// 商家信息
|
||||
$shopInfo = $jsonArray['props']['pageProps']['skuDetail']['shop_info'] ?? [];
|
||||
$formatShopInfo = [
|
||||
'shop_id' => $shopInfo['shop_id'] ?? 0,
|
||||
'shop_name' => $shopInfo['shop_short_name'] ?? '',
|
||||
'shop_address' => $shopInfo['shop_address'] ?? ''
|
||||
];
|
||||
|
||||
// 简介参数
|
||||
$otherParams = $jsonArray['props']['pageProps']['skuDetail']['other_params'] ?? [];
|
||||
// 排量
|
||||
$displacement = $this->getOtherParamValue($otherParams, '排量');
|
||||
// 变速箱
|
||||
$gearbox = $this->getOtherParamValue($otherParams, '变速箱');
|
||||
// 格式化车辆信息
|
||||
$formatCarInfo = [
|
||||
'displacement' => $displacement,
|
||||
'gearbox' => $gearbox
|
||||
];
|
||||
|
||||
// 整理车辆信息
|
||||
$info['used_car_id'] = $this->getLastIdFromUrl($url);
|
||||
$info['car_id'] = $carId;
|
||||
$info['url'] = $url;
|
||||
$info['title'] = $title;
|
||||
$info['price'] = str_replace('万', '', $this->decodeDongchediPrice($price));
|
||||
$info['new_price'] = str_replace('万', '', $newPrice);
|
||||
$info['price_difference'] = str_replace('万', '', $priceDifference);
|
||||
$info['condition_desc'] = $conditionDesc;
|
||||
$info['images'] = json_encode($images);
|
||||
$info['car_id_url'] = $carIdUrl;
|
||||
$info['used_detail'] = $jsonText;
|
||||
$info['format_shop_info'] = json_encode($formatShopInfo);
|
||||
$info['fuel_form'] = $resultFuelForm;
|
||||
$info['classify_energy'] = $this->detectEnergyType($resultFuelForm);
|
||||
$info['usage_mileage'] = $usageMileage;
|
||||
$info['brand_name'] = $brandName;
|
||||
$info['series_name'] = $seriesName;
|
||||
$info['car_name'] = $carName;
|
||||
$info['year'] = $year;
|
||||
$info['format_car_info'] = json_encode($formatCarInfo);
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取配置信息
|
||||
*/
|
||||
public function getConfigDetail(string $html = '')
|
||||
{
|
||||
$ql = QueryList::html($html);
|
||||
|
||||
$jsonText = $ql->find('#__NEXT_DATA__')->text();
|
||||
|
||||
$raw = json_decode($jsonText, true);
|
||||
$properties = $raw['props']['pageProps']['rawData']['properties'] ?? [];
|
||||
$carInfo = $raw['props']['pageProps']['rawData']['car_info'][0] ?? [];
|
||||
|
||||
$valuesMap = $this->buildValuesMapFromCarInfo($carInfo);
|
||||
$groups = $this->buildCarSpecGroups($properties, $valuesMap);
|
||||
|
||||
$data['format_car_info'] = [
|
||||
'market_time' => $this->getFieldValue($groups, 'market_time'), // 上市时间
|
||||
'driver_form' => $this->getFieldValue($groups, 'driver_form'), // 驱动形式
|
||||
'seat_count' => $this->getFieldValue($groups, 'seat_count'), // 座位数
|
||||
'engine_description' => $this->getFieldValue($groups, 'engine_description'), // 发动机
|
||||
'engine_max_power_horsepower' => $this->getFieldValue($groups, 'engine_max_power_horsepower'), // 发动机最大功率
|
||||
'electric_description' => $this->getFieldValue($groups, 'electric_description'), //电动机
|
||||
'battery_capacity' => $this->getFieldValue($groups, 'battery_capacity'), //电池容量
|
||||
'battery_type' => $this->getFieldValue($groups, 'battery_type'), // 电池类型
|
||||
'recharge_mileage' => $this->getFieldValue($groups, 'recharge_mileage') // 续航里程
|
||||
];
|
||||
$data['groups'] = $groups;
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从车辆配置 JSON 数据中获取能源类型
|
||||
*
|
||||
* @param array $data JSON 数据
|
||||
* @return string|null 能源类型,如 '油电混合'、'纯电动'、
|
||||
*/
|
||||
public function getFuelFormByConfigInfo(array $data)
|
||||
{
|
||||
$fuelForm = null;
|
||||
foreach ($data[0]['items'] as $item) {
|
||||
if ($item['key'] === 'fuel_form') {
|
||||
$fuelForm = $item['value'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $fuelForm;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从车辆配置 JSON 数据中根据字段 key 获取对应的 value
|
||||
*
|
||||
* @param string|array $data JSON 字符串 或 已解析的数组
|
||||
* @param string $field 要查找的字段 key(如 'fuel_form')
|
||||
* @return string|null 找到则返回 value,否则返回 null
|
||||
*/
|
||||
public function getFieldValue($data, string $field)
|
||||
{
|
||||
// 如果传入的是 JSON 字符串,先解码
|
||||
if (is_string($data)) {
|
||||
$data = json_decode($data, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return null; // JSON 格式错误
|
||||
}
|
||||
}
|
||||
|
||||
// 遍历第一层(假设结构是 [ { "items": [...] } ])
|
||||
foreach ($data as $group) {
|
||||
if (isset($group['items']) && is_array($group['items'])) {
|
||||
foreach ($group['items'] as $item) {
|
||||
if (isset($item['key']) && $item['key'] === $field) {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null; // 未找到
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 other_params 数组中根据 name 获取对应的 value
|
||||
*
|
||||
* @param array $otherParams 格式为 [ ['name' => 'xxx', 'value' => 'yyy'], ... ]
|
||||
* @param string $name 要查找的字段名称(如 '上牌地')
|
||||
* @return string|null 找到则返回 value,否则返回 null
|
||||
*/
|
||||
public function getOtherParamValue(array $otherParams, string $name): ?string
|
||||
{
|
||||
foreach ($otherParams as $item) {
|
||||
if (isset($item['name']) && $item['name'] === $name) {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据给定字符串判断车辆能源类型
|
||||
*
|
||||
* 返回:
|
||||
* - RE 新能源(纯电、插电混动、增程、氢燃料等)
|
||||
* - CE 传统能源(汽油、柴油、天然气、非插电混动等)
|
||||
* - UNKNOWN 无法判断
|
||||
*
|
||||
* @param string $text 例如:'2022款 某某牌 2.0L 油电混合 双擎'
|
||||
* @return string
|
||||
*/
|
||||
public function detectEnergyType(string $text): string
|
||||
{
|
||||
if (function_exists('mb_internal_encoding')) {
|
||||
mb_internal_encoding('UTF-8');
|
||||
}
|
||||
|
||||
// 明确定义的新能源关键字(纯电 / 插电 / 增程 / 氢 / 太阳能 等)
|
||||
$newEnergyKeywords = [
|
||||
// 纯电
|
||||
'纯电', '纯电动', '电动车', 'BEV',
|
||||
// 插电式混合
|
||||
'插电混动', '插电式混合', '插电式', '插电', 'PHEV',
|
||||
// 增程式
|
||||
'增程式', '增程', 'REEV',
|
||||
// 氢能 / 燃料电池
|
||||
'氢能', '氢燃料', '燃料电池', 'FCEV',
|
||||
// 其它
|
||||
'太阳能',
|
||||
];
|
||||
|
||||
// 传统能源关键字(包括燃油/燃气)
|
||||
$traditionalKeywords = [
|
||||
'汽油',
|
||||
'柴油',
|
||||
'天然气', 'LNG', 'CNG',
|
||||
];
|
||||
|
||||
// 普通混动关键字(按你的要求,统一归为传统能源)
|
||||
$hybridKeywords = [
|
||||
'油电混合', '油电混动', '油电',
|
||||
'混动', // 不带“插电”的混动
|
||||
'双擎', // 丰田常见表达
|
||||
'HEV',
|
||||
];
|
||||
|
||||
// 辅助:不区分大小写的包含判断,优先 mb_stripos
|
||||
$contains = function (string $haystack, string $needle): bool {
|
||||
if ($needle === '') {
|
||||
return false;
|
||||
}
|
||||
if (function_exists('mb_stripos')) {
|
||||
return mb_stripos($haystack, $needle) !== false;
|
||||
}
|
||||
return stripos($haystack, $needle) !== false;
|
||||
};
|
||||
|
||||
// 1. 先判断“明确新能源”关键词(插电、增程、氢、纯电等)
|
||||
foreach ($newEnergyKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return 'RE';
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 再判断“普通油电混动”——按照你的业务,一律归为传统能源
|
||||
foreach ($hybridKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return 'CE';
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 再判断传统能源(纯燃油/气)
|
||||
foreach ($traditionalKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return 'CE';
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 都没匹配上
|
||||
return 'UNKNOWN';
|
||||
}
|
||||
|
||||
/**
|
||||
* 二手信息入库
|
||||
*/
|
||||
public function saveUsedcarBasicToDb(array $data = [])
|
||||
{
|
||||
$data['created_at'] = time();
|
||||
$data['updated_at'] = time();
|
||||
return Db::table('usedcar_crawl_results')->insertGetId($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新信息入库
|
||||
*/
|
||||
public function saveUsedcarConfigToDb(array $data = [], int $id = 0)
|
||||
{
|
||||
$info = Db::table('usedcar_crawl_results')->find($id);
|
||||
|
||||
if (!$info) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$groups = $data['groups'];
|
||||
$formatCarInfo = array_merge($data['format_car_info'], json_decode($info->format_car_info, true));
|
||||
|
||||
return Db::table('usedcar_crawl_results')
|
||||
->where('id', $id)
|
||||
->update([
|
||||
'format_car_info' => json_encode($formatCarInfo, JSON_UNESCAPED_UNICODE),
|
||||
'config_detail' => json_encode($groups, JSON_UNESCAPED_UNICODE),
|
||||
'updated_at' => time()
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 car_info 扁平成一个 [key => ['value' => xxx]] 的 map
|
||||
*
|
||||
* @param array $carInfo rawData['car_info'][0]
|
||||
* @return array
|
||||
*/
|
||||
public function buildValuesMapFromCarInfo(array $carInfo): array
|
||||
{
|
||||
$valuesMap = [];
|
||||
|
||||
// 1) car_info 顶层的一些字段(official_price、series_name 等)
|
||||
foreach ($carInfo as $k => $v) {
|
||||
if ($k === 'info' || is_array($v)) {
|
||||
continue;
|
||||
}
|
||||
$valuesMap[$k] = ['value' => $v];
|
||||
}
|
||||
|
||||
// 2) info 里的配置项
|
||||
if (!empty($carInfo['info']) && is_array($carInfo['info'])) {
|
||||
foreach ($carInfo['info'] as $k => $v) {
|
||||
if (is_array($v) && array_key_exists('value', $v)) {
|
||||
$valuesMap[$k] = $v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $valuesMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 type 重新分组:
|
||||
* - type=0,2 为分组(左侧分类)
|
||||
* - 其它 type 都视为该分组下的字段
|
||||
*
|
||||
* @param array $properties rawData['properties']
|
||||
* @param array $valuesMap 来自 buildValuesMapFromCarInfo()
|
||||
* @return array
|
||||
*/
|
||||
public function buildCarSpecGroups(array $properties, array $valuesMap): array
|
||||
{
|
||||
$groups = [];
|
||||
$currentKey = null; // 当前分组 key
|
||||
|
||||
foreach ($properties as $item) {
|
||||
$type = (int)($item['type'] ?? 1);
|
||||
$key = $item['key'] ?? '';
|
||||
$text = $item['text'] ?? '';
|
||||
$subList = $item['sub_list'] ?? null;
|
||||
|
||||
// ---------- 1) 分类字段:type = 0 / 2 ----------
|
||||
if (in_array($type, [0, 2], true)) {
|
||||
$currentKey = $key ?: ($text ?: ('group_' . count($groups)));
|
||||
|
||||
if (!isset($groups[$currentKey])) {
|
||||
$groups[$currentKey] = [
|
||||
'group_key' => $currentKey,
|
||||
'group_text' => $text,
|
||||
'group_type' => $type,
|
||||
'items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// ---------- 2) 普通字段:挂到最近的分类下 ----------
|
||||
if ($currentKey === null) {
|
||||
// 如果一开始就没有遇到分类,给一个默认分组
|
||||
$currentKey = '_default';
|
||||
$groups[$currentKey] = [
|
||||
'group_key' => '_default',
|
||||
'group_text' => '其他',
|
||||
'group_type' => -1,
|
||||
'items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
// 取 value
|
||||
$value = '';
|
||||
if ($key && isset($valuesMap[$key])) {
|
||||
$value = trim((string)($valuesMap[$key]['value'] ?? ''));
|
||||
}
|
||||
|
||||
$node = [
|
||||
'key' => $key,
|
||||
'text' => $text,
|
||||
'value' => $value,
|
||||
];
|
||||
|
||||
// ---------- 3) sub_list 子项(有就当成 children) ----------
|
||||
if (is_array($subList) && !empty($subList)) {
|
||||
$children = [];
|
||||
foreach ($subList as $sub) {
|
||||
$subKey = $sub['key'] ?? '';
|
||||
$subText = $sub['text'] ?? '';
|
||||
$subValue = '';
|
||||
|
||||
if ($subKey && isset($valuesMap[$subKey])) {
|
||||
$subValue = trim((string)($valuesMap[$subKey]['value'] ?? ''));
|
||||
}
|
||||
|
||||
$children[] = [
|
||||
'key' => $subKey,
|
||||
'text' => $subText,
|
||||
'value' => $subValue,
|
||||
];
|
||||
}
|
||||
|
||||
$node['children'] = $children;
|
||||
}
|
||||
|
||||
$groups[$currentKey]['items'][] = $node;
|
||||
}
|
||||
|
||||
// 你可以按需返回关联数组或索引数组,这里转成索引数组方便前端遍历
|
||||
return array_values($groups);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义价格
|
||||
*/
|
||||
protected function decodeDongchediPrice(string $str): string
|
||||
{
|
||||
// 映射表:PUA 字符 => 数字 / 万
|
||||
$map = [
|
||||
"\u{E53D}" => '1',
|
||||
"\u{E3F0}" => '2',
|
||||
"\u{E422}" => '3',
|
||||
"\u{E42C}" => '4',
|
||||
"\u{E49C}" => '5',
|
||||
"\u{E42B}" => '6',
|
||||
"\u{E4FE}" => '7',
|
||||
"\u{E548}" => '8',
|
||||
"\u{E4C8}" => '9',
|
||||
"\u{E453}" => '0',
|
||||
"\u{E45F}" => '万',
|
||||
];
|
||||
|
||||
return strtr($str, $map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取URL最后ID
|
||||
*/
|
||||
protected function getLastIdFromUrl($url)
|
||||
{
|
||||
// 方法1:使用正则表达式提取最后的数字ID
|
||||
if (preg_match('/\/(\d+)$/', $url, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载单张图片
|
||||
*
|
||||
* @param string $url 图片完整 URL
|
||||
* @param string $saveDir 保存目录(如 /www/usedcar_images/2025-11-20)
|
||||
* @param string|null $filename 指定文件名(可选,不含路径),为空则自动生成
|
||||
* @param array $headers 额外 HTTP 头(可选)
|
||||
*
|
||||
* @return string|null 成功返回保存路径,失败返回 null
|
||||
*/
|
||||
protected function downloadImage(string $url, string $saveDir, ?string $filename = null, array $headers = []): ?string
|
||||
{
|
||||
// 1. 目录检查 & 创建
|
||||
if (!is_dir($saveDir)) {
|
||||
if (!mkdir($saveDir, 0777, true) && !is_dir($saveDir)) {
|
||||
echo "[Image] 创建目录失败:{$saveDir}\n";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 自动生成文件名(基于 URL md5 + 原扩展名)
|
||||
if ($filename === null) {
|
||||
$path = parse_url($url, PHP_URL_PATH); // /xxx/xxx.jpg
|
||||
$ext = pathinfo($path, PATHINFO_EXTENSION); // jpg 或 webp 之类
|
||||
|
||||
if ($ext === '') {
|
||||
$ext = 'jpg'; // 没有扩展名时兜底
|
||||
}
|
||||
|
||||
$filename = md5($url) . '.' . $ext;
|
||||
}
|
||||
|
||||
$savePath = rtrim($saveDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
|
||||
|
||||
// 3. 组装 HTTP 头
|
||||
$defaultHeaders = [
|
||||
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
|
||||
. 'AppleWebKit/537.36 (KHTML, like Gecko) '
|
||||
. 'Chrome/120.0.0.0 Safari/537.36',
|
||||
'Accept: image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
'Referer: https://www.dongchedi.com/', // 很多图床需要 Referer
|
||||
];
|
||||
|
||||
foreach ($headers as $h) {
|
||||
$defaultHeaders[] = $h;
|
||||
}
|
||||
|
||||
// 4. 使用 cURL 下载
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_CONNECTTIMEOUT => 5,
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_HTTPHEADER => $defaultHeaders,
|
||||
]);
|
||||
|
||||
$data = curl_exec($ch);
|
||||
$errNo = curl_errno($ch);
|
||||
$errMsg = curl_error($ch);
|
||||
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($errNo !== 0) {
|
||||
echo "[Image] 下载失败(cURL):{$url} | {$errNo} {$errMsg}\n";
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($code !== 200 || $data === false || $data === '') {
|
||||
echo "[Image] 下载失败(HTTP {$code}):{$url}\n";
|
||||
return null;
|
||||
}
|
||||
|
||||
// 5. 写入本地文件
|
||||
$bytes = file_put_contents($savePath, $data);
|
||||
if ($bytes === false) {
|
||||
echo "[Image] 保存失败:{$savePath}\n";
|
||||
return null;
|
||||
}
|
||||
|
||||
echo "[Image] 下载成功:{$url} => {$savePath}\n";
|
||||
|
||||
return $savePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量下载相册
|
||||
*
|
||||
* @param array $urls 图片 URL 数组
|
||||
* @param string $saveDir 保存目录
|
||||
*
|
||||
* @return array [原始 URL => 保存路径或 null]
|
||||
*/
|
||||
protected function downloadImageAlbum(array $urls, string $saveDir): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($urls as $url) {
|
||||
$url = trim($url);
|
||||
if ($url === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 如果存在 // 开头的相对协议,补全
|
||||
if (strpos($url, '//') === 0) {
|
||||
$url = 'https:' . $url;
|
||||
}
|
||||
|
||||
$path = $this->downloadImage($url, $saveDir);
|
||||
$result[$url] = $path;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\crawl\service;
|
||||
|
||||
use app\common\model\UsedcarCrawlResultsImages;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use QL\QueryList;
|
||||
use support\Redis;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
use Throwable;
|
||||
|
||||
class UsedCarCrawl_bak2
|
||||
{
|
||||
// 默认请求头
|
||||
private const DEFAULT_HEADERS = [
|
||||
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||
'Accept-Language' => 'zh-CN,zh;q=0.9',
|
||||
'Referer' => 'https://www.dongchedi.com/'
|
||||
];
|
||||
|
||||
// Redis队列键名
|
||||
private const REDIS_QUEUE_KEY = 'usedcar:urls';
|
||||
|
||||
// 能源类型常量
|
||||
public const ENERGY_TYPE_RENEWABLE = 'RE';
|
||||
public const ENERGY_TYPE_CONVENTIONAL = 'CE';
|
||||
public const ENERGY_TYPE_UNKNOWN = 'UNKNOWN';
|
||||
|
||||
/**
|
||||
* 插入队列url
|
||||
*
|
||||
* @param string $url URL地址
|
||||
* @param string $scene 场景:usedcar(二手信息) config(配置信息)
|
||||
* @param int $id 记录ID
|
||||
* @return int
|
||||
*/
|
||||
public function pushUrl(string $url = '', string $scene = 'usedcar', int $id = 0): int
|
||||
{
|
||||
$data = [
|
||||
'scene' => $scene,
|
||||
'url' => $url,
|
||||
'id' => $id
|
||||
];
|
||||
|
||||
return Redis::lpush(self::REDIS_QUEUE_KEY, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取队列url
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function popUrl(): ?array
|
||||
{
|
||||
$data = Redis::rPop(self::REDIS_QUEUE_KEY);
|
||||
if (!$data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return json_decode($data, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行抓取任务
|
||||
*
|
||||
* @return bool
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function execute(): bool
|
||||
{
|
||||
try {
|
||||
$task = $this->popUrl();
|
||||
|
||||
if (!$task) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$html = $this->fetchHtml($task['url']);
|
||||
|
||||
switch ($task['scene']) {
|
||||
case 'usedcar':
|
||||
$info = $this->parseUsedCarDetail($html, $task['url']);
|
||||
$id = $this->saveUsedCarBasicInfo($info);
|
||||
$this->uploadAndRemove(json_decode($info['images'], true), public_path('uploads/usedcar/' . $id), $info['used_car_id'], $id);
|
||||
$this->pushUrl($info['car_id_url'], 'config', $id);
|
||||
break;
|
||||
|
||||
case 'config':
|
||||
$data = $this->parseConfigDetail($html);
|
||||
$this->saveUsedCarConfigInfo($data, $task['id']);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new BusinessException("未知的任务场景: " . $task['scene']);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (GuzzleException $e) {
|
||||
throw new BusinessException("网络请求失败: " . $e->getMessage());
|
||||
} catch (Throwable $th) {
|
||||
throw new BusinessException("执行任务出错: " . $th->getMessage() . ' | 行号: ' . $th->getLine() . ' | 文件: ' . $th->getFile());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取网页HTML内容
|
||||
*
|
||||
* @param string $url
|
||||
* @return string
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function fetchHtml(string $url): string
|
||||
{
|
||||
$client = new Client();
|
||||
$response = $client->request('GET', $url, [
|
||||
'headers' => self::DEFAULT_HEADERS
|
||||
]);
|
||||
return (string)$response->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析二手车详情页信息
|
||||
*
|
||||
* @param string $html
|
||||
* @param string $url
|
||||
* @return array
|
||||
*/
|
||||
public function parseUsedCarDetail(string $html = '', string $url = ''): array
|
||||
{
|
||||
$ql = QueryList::html($html);
|
||||
|
||||
$title = $ql->find('h1')->text();
|
||||
$price = $ql->find('.head-info_price-wrap__Y4bxi > p')->text();
|
||||
$pageText = $ql->find('body')->text();
|
||||
$jsonText = $ql->find('#__NEXT_DATA__')->text();
|
||||
|
||||
// 解析JSON数据
|
||||
$jsonArray = json_decode($jsonText, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new BusinessException("JSON解析失败: " . json_last_error_msg());
|
||||
}
|
||||
|
||||
// 车辆相册
|
||||
$images = $jsonArray['props']['pageProps']['skuDetail']['head_images'] ?? [];
|
||||
|
||||
// 车辆ID
|
||||
$carId = $jsonArray['props']['pageProps']['skuDetail']['car_info']['car_id'] ?? 0;
|
||||
|
||||
// 车辆年份
|
||||
$year = $jsonArray['props']['pageProps']['skuDetail']['car_info']['year'] ?? 0;
|
||||
|
||||
// 车辆ID URL
|
||||
$carIdUrl = $carId ? ('https://www.dongchedi.com/auto/params-carIds-' . $carId) : '';
|
||||
|
||||
// 能源类型
|
||||
$fuelForm = $jsonArray['props']['pageProps']['skuDetail']['car_config_overview']['power']['fuel_form'] ?? '';
|
||||
$newFuelForm = $jsonArray['props']['pageProps']['skuDetail']['car_config_overview']['new_energy_power']['fuel_form'] ?? '';
|
||||
$resultFuelForm = $fuelForm === '' ? $newFuelForm : $fuelForm;
|
||||
|
||||
// 使用里程
|
||||
$importantText = $jsonArray['props']['pageProps']['skuDetail']['important_text'] ?? '';
|
||||
$importantTextArray = explode(' | ', $importantText);
|
||||
$usageMileage = str_replace('万公里', '', isset($importantTextArray[1]) ? $importantTextArray[1] : '');
|
||||
|
||||
// 车辆名称 品牌、车系、车型
|
||||
$brandName = $jsonArray['props']['pageProps']['skuDetail']['car_info']['brand_name'] ?? '';
|
||||
$seriesName = $jsonArray['props']['pageProps']['skuDetail']['car_info']['series_name'] ?? '';
|
||||
$carName = $jsonArray['props']['pageProps']['skuDetail']['car_info']['car_name'] ?? '';
|
||||
|
||||
// 商家信息
|
||||
$shopInfo = $jsonArray['props']['pageProps']['skuDetail']['shop_info'] ?? [];
|
||||
$formatShopInfo = [
|
||||
'shop_id' => $shopInfo['shop_id'] ?? 0,
|
||||
'shop_name' => $shopInfo['shop_short_name'] ?? '',
|
||||
'shop_address' => $shopInfo['shop_address'] ?? ''
|
||||
];
|
||||
|
||||
// 简介参数
|
||||
$otherParams = $jsonArray['props']['pageProps']['skuDetail']['other_params'] ?? [];
|
||||
// 排量
|
||||
$displacement = $this->getParamValue($otherParams, '排量');
|
||||
// 变速箱
|
||||
$gearbox = $this->getParamValue($otherParams, '变速箱');
|
||||
// 格式化车辆信息
|
||||
$formatCarInfo = [
|
||||
'displacement' => $displacement,
|
||||
'gearbox' => $gearbox
|
||||
];
|
||||
|
||||
// 提取新车指导价
|
||||
$newPrice = $this->extractPatternValue($pageText, '/新车指导价[::]\s*([^\r\n万]*万)/u');
|
||||
|
||||
// 提取比新车省金额
|
||||
$priceDifference = $this->extractPatternValue($pageText, '/比新车省[::]\s*([^\r\n万]*万)/u');
|
||||
|
||||
// 提取车况介绍
|
||||
$conditionDesc = '';
|
||||
if ($pageText) {
|
||||
if (preg_match('/车况介绍\s*(.*?)\s*推荐理由/su', $pageText, $m)) {
|
||||
$conditionDesc = trim($m[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// 整理车辆信息
|
||||
return [
|
||||
'used_car_id' => $this->extractIdFromUrl($url),
|
||||
'car_id' => $carId,
|
||||
'url' => $url,
|
||||
'title' => $title,
|
||||
'price' => str_replace('万', '', $this->decodePrice($price)),
|
||||
'new_price' => str_replace('万', '', $newPrice),
|
||||
'price_difference' => str_replace('万', '', $priceDifference),
|
||||
'condition_desc' => $conditionDesc,
|
||||
'images' => json_encode($images, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'car_id_url' => $carIdUrl,
|
||||
'used_detail' => $jsonText,
|
||||
'format_shop_info' => json_encode($formatShopInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'fuel_form' => $resultFuelForm,
|
||||
'classify_energy' => $this->detectEnergyType($resultFuelForm),
|
||||
'usage_mileage' => $usageMileage,
|
||||
'brand_name' => $brandName,
|
||||
'series_name' => $seriesName,
|
||||
'car_name' => $carName,
|
||||
'year' => $year,
|
||||
'format_car_info' => json_encode($formatCarInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析配置详情页信息
|
||||
*
|
||||
* @param string $html
|
||||
* @return array
|
||||
*/
|
||||
public function parseConfigDetail(string $html = ''): array
|
||||
{
|
||||
$ql = QueryList::html($html);
|
||||
$jsonText = $ql->find('#__NEXT_DATA__')->text();
|
||||
|
||||
$raw = json_decode($jsonText, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new BusinessException("配置页面JSON解析失败: " . json_last_error_msg());
|
||||
}
|
||||
|
||||
$properties = $raw['props']['pageProps']['rawData']['properties'] ?? [];
|
||||
$carInfo = $raw['props']['pageProps']['rawData']['car_info'][0] ?? [];
|
||||
|
||||
$valuesMap = $this->buildValuesMap($carInfo);
|
||||
$groups = $this->buildCarSpecGroups($properties, $valuesMap);
|
||||
|
||||
return [
|
||||
'format_car_info' => [
|
||||
'market_time' => $this->getFieldValue($groups, 'market_time'), // 上市时间
|
||||
'driver_form' => $this->getFieldValue($groups, 'driver_form'), // 驱动形式
|
||||
'seat_count' => $this->getFieldValue($groups, 'seat_count'), // 座位数
|
||||
'engine_description' => $this->getFieldValue($groups, 'engine_description'), // 发动机
|
||||
'engine_max_power_horsepower' => $this->getFieldValue($groups, 'engine_max_power_horsepower'), // 发动机最大功率
|
||||
'electric_description' => $this->getFieldValue($groups, 'electric_description'), //电动机
|
||||
'battery_capacity' => $this->getFieldValue($groups, 'battery_capacity'), //电池容量
|
||||
'battery_type' => $this->getFieldValue($groups, 'battery_type'), // 电池类型
|
||||
'recharge_mileage' => $this->getFieldValue($groups, 'recharge_mileage') // 续航里程
|
||||
],
|
||||
'groups' => $groups
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从车辆配置中获取能源类型
|
||||
*
|
||||
* @param array $data JSON数据
|
||||
* @return string|null 能源类型
|
||||
*/
|
||||
public function getFuelFormByConfig(array $data): ?string
|
||||
{
|
||||
if (empty($data[0]['items'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($data[0]['items'] as $item) {
|
||||
if (isset($item['key']) && $item['key'] === 'fuel_form') {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从数据中根据字段key获取值
|
||||
*
|
||||
* @param mixed $data 数据
|
||||
* @param string $field 字段名
|
||||
* @return string|null
|
||||
*/
|
||||
public function getFieldValue($data, string $field): ?string
|
||||
{
|
||||
// 如果传入的是 JSON 字符串,先解码
|
||||
if (is_string($data)) {
|
||||
$data = json_decode($data, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果不是数组,直接返回null
|
||||
if (!is_array($data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 遍历寻找对应字段
|
||||
foreach ($data as $group) {
|
||||
if (isset($group['items']) && is_array($group['items'])) {
|
||||
foreach ($group['items'] as $item) {
|
||||
if (isset($item['key']) && $item['key'] === $field) {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
|
||||
// 检查子元素
|
||||
if (isset($item['children']) && is_array($item['children'])) {
|
||||
foreach ($item['children'] as $child) {
|
||||
if (isset($child['key']) && $child['key'] === $field) {
|
||||
return $child['value'] ?? null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从参数列表中获取指定名称的值
|
||||
*
|
||||
* @param array $params 参数列表
|
||||
* @param string $name 名称
|
||||
* @return string|null
|
||||
*/
|
||||
public function getParamValue(array $params, string $name): ?string
|
||||
{
|
||||
foreach ($params as $item) {
|
||||
if (isset($item['name']) && $item['name'] === $name) {
|
||||
return $item['value'] ?? null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断车辆能源类型
|
||||
*
|
||||
* @param string $text 描述文本
|
||||
* @return string 能源类型标识
|
||||
*/
|
||||
public function detectEnergyType(string $text): string
|
||||
{
|
||||
if (function_exists('mb_internal_encoding')) {
|
||||
mb_internal_encoding('UTF-8');
|
||||
}
|
||||
|
||||
// 明确定义的新能源关键字
|
||||
$newEnergyKeywords = [
|
||||
// 纯电
|
||||
'纯电', '纯电动', '电动车', 'BEV',
|
||||
// 插电式混合
|
||||
'插电混动', '插电式混合', '插电式', '插电', 'PHEV',
|
||||
// 增程式
|
||||
'增程式', '增程', 'REEV',
|
||||
// 氢能 / 燃料电池
|
||||
'氢能', '氢燃料', '燃料电池', 'FCEV',
|
||||
// 其它
|
||||
'太阳能',
|
||||
];
|
||||
|
||||
// 传统能源关键字
|
||||
$traditionalKeywords = [
|
||||
'汽油',
|
||||
'柴油',
|
||||
'天然气', 'LNG', 'CNG',
|
||||
];
|
||||
|
||||
// 普通混动关键字(归为传统能源)
|
||||
$hybridKeywords = [
|
||||
'油电混合', '油电混动', '油电',
|
||||
'混动', // 不带"插电"的混动
|
||||
'双擎', // 丰田常见表达
|
||||
'HEV',
|
||||
];
|
||||
|
||||
// 辅助函数:不区分大小写的包含判断
|
||||
$contains = function (string $haystack, string $needle): bool {
|
||||
if ($needle === '') {
|
||||
return false;
|
||||
}
|
||||
if (function_exists('mb_stripos')) {
|
||||
return mb_stripos($haystack, $needle) !== false;
|
||||
}
|
||||
return stripos($haystack, $needle) !== false;
|
||||
};
|
||||
|
||||
// 1. 先判断"明确新能源"关键词
|
||||
foreach ($newEnergyKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return self::ENERGY_TYPE_RENEWABLE;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 再判断"普通油电混动"
|
||||
foreach ($hybridKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return self::ENERGY_TYPE_CONVENTIONAL;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 再判断传统能源
|
||||
foreach ($traditionalKeywords as $kw) {
|
||||
if ($contains($text, $kw)) {
|
||||
return self::ENERGY_TYPE_CONVENTIONAL;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 都没匹配上
|
||||
return self::ENERGY_TYPE_UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存二手车基本信息到数据库
|
||||
*
|
||||
* @param array $data 数据
|
||||
* @return int 插入记录ID
|
||||
*/
|
||||
public function saveUsedCarBasicInfo(array $data): int
|
||||
{
|
||||
$data['created_at'] = time();
|
||||
$data['updated_at'] = time();
|
||||
return Db::table('usedcar_crawl_results')->insertGetId($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新配置信息到数据库
|
||||
*
|
||||
* @param array $data 配置数据
|
||||
* @param int $id 记录ID
|
||||
* @return bool|int
|
||||
*/
|
||||
public function saveUsedCarConfigInfo(array $data, int $id)
|
||||
{
|
||||
$record = Db::table('usedcar_crawl_results')->find($id);
|
||||
|
||||
if (!$record) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$groups = $data['groups'];
|
||||
$formatCarInfo = array_merge(
|
||||
$data['format_car_info'],
|
||||
json_decode($record->format_car_info, true)
|
||||
);
|
||||
|
||||
return Db::table('usedcar_crawl_results')
|
||||
->where('id', $id)
|
||||
->update([
|
||||
'format_car_info' => json_encode($formatCarInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'config_detail' => json_encode($groups, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'updated_at' => time()
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建值映射表
|
||||
*
|
||||
* @param array $carInfo 车辆信息
|
||||
* @return array
|
||||
*/
|
||||
public function buildValuesMap(array $carInfo): array
|
||||
{
|
||||
$valuesMap = [];
|
||||
|
||||
// 处理顶层字段
|
||||
foreach ($carInfo as $k => $v) {
|
||||
if ($k === 'info' || is_array($v)) {
|
||||
continue;
|
||||
}
|
||||
$valuesMap[$k] = ['value' => $v];
|
||||
}
|
||||
|
||||
// 处理info中的配置项
|
||||
if (!empty($carInfo['info']) && is_array($carInfo['info'])) {
|
||||
foreach ($carInfo['info'] as $k => $v) {
|
||||
if (is_array($v) && array_key_exists('value', $v)) {
|
||||
$valuesMap[$k] = $v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $valuesMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建车辆规格分组
|
||||
*
|
||||
* @param array $properties 属性列表
|
||||
* @param array $valuesMap 值映射表
|
||||
* @return array
|
||||
*/
|
||||
public function buildCarSpecGroups(array $properties, array $valuesMap): array
|
||||
{
|
||||
$groups = [];
|
||||
$currentKey = null;
|
||||
|
||||
foreach ($properties as $item) {
|
||||
$type = (int)($item['type'] ?? 1);
|
||||
$key = $item['key'] ?? '';
|
||||
$text = $item['text'] ?? '';
|
||||
$subList = $item['sub_list'] ?? null;
|
||||
|
||||
// 分类字段:type = 0 / 2
|
||||
if (in_array($type, [0, 2], true)) {
|
||||
$currentKey = $key ?: ($text ?: ('group_' . count($groups)));
|
||||
|
||||
if (!isset($groups[$currentKey])) {
|
||||
$groups[$currentKey] = [
|
||||
'group_key' => $currentKey,
|
||||
'group_text' => $text,
|
||||
'group_type' => $type,
|
||||
'items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 普通字段:挂到最近的分类下
|
||||
if ($currentKey === null) {
|
||||
// 如果一开始就没有遇到分类,给一个默认分组
|
||||
$currentKey = '_default';
|
||||
$groups[$currentKey] = [
|
||||
'group_key' => '_default',
|
||||
'group_text' => '其他',
|
||||
'group_type' => -1,
|
||||
'items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
// 取 value
|
||||
$value = '';
|
||||
if ($key && isset($valuesMap[$key])) {
|
||||
$value = trim((string)($valuesMap[$key]['value'] ?? ''));
|
||||
}
|
||||
|
||||
$node = [
|
||||
'key' => $key,
|
||||
'text' => $text,
|
||||
'value' => $value,
|
||||
];
|
||||
|
||||
// 处理子项
|
||||
if (is_array($subList) && !empty($subList)) {
|
||||
$children = [];
|
||||
foreach ($subList as $sub) {
|
||||
$subKey = $sub['key'] ?? '';
|
||||
$subText = $sub['text'] ?? '';
|
||||
$subValue = '';
|
||||
|
||||
if ($subKey && isset($valuesMap[$subKey])) {
|
||||
$subValue = trim((string)($valuesMap[$subKey]['value'] ?? ''));
|
||||
}
|
||||
|
||||
$children[] = [
|
||||
'key' => $subKey,
|
||||
'text' => $subText,
|
||||
'value' => $subValue,
|
||||
];
|
||||
}
|
||||
|
||||
$node['children'] = $children;
|
||||
}
|
||||
|
||||
$groups[$currentKey]['items'][] = $node;
|
||||
}
|
||||
|
||||
// 转成索引数组方便前端遍历
|
||||
return array_values($groups);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码懂车帝价格
|
||||
*
|
||||
* @param string $str 加密字符串
|
||||
* @return string 解码后的字符串
|
||||
*/
|
||||
protected function decodePrice(string $str): string
|
||||
{
|
||||
// 映射表:PUA 字符 => 数字 / 万
|
||||
$map = [
|
||||
"\u{E53D}" => '1',
|
||||
"\u{E3F0}" => '2',
|
||||
"\u{E422}" => '3',
|
||||
"\u{E42C}" => '4',
|
||||
"\u{E49C}" => '5',
|
||||
"\u{E42B}" => '6',
|
||||
"\u{E4FE}" => '7',
|
||||
"\u{E548}" => '8',
|
||||
"\u{E4C8}" => '9',
|
||||
"\u{E453}" => '0',
|
||||
"\u{E45F}" => '万',
|
||||
];
|
||||
|
||||
return strtr($str, $map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从URL中提取ID
|
||||
*
|
||||
* @param string $url URL
|
||||
* @return int|false
|
||||
*/
|
||||
protected function extractIdFromUrl(string $url)
|
||||
{
|
||||
if (preg_match('/\/(\d+)$/', $url, $matches)) {
|
||||
return (int)$matches[1];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取符合正则表达式的值
|
||||
*
|
||||
* @param string $text 文本
|
||||
* @param string $pattern 正则表达式
|
||||
* @return string
|
||||
*/
|
||||
protected function extractPatternValue(string $text, string $pattern): string
|
||||
{
|
||||
$value = '';
|
||||
if ($text) {
|
||||
if (preg_match($pattern, $text, $m)) {
|
||||
$value = trim(preg_replace('/[^0-9.]/', '', $m[1]));
|
||||
}
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载单张图片
|
||||
*
|
||||
* @param string $url 图片完整URL
|
||||
* @param string $saveDir 保存目录
|
||||
* @param string|null $filename 指定文件名
|
||||
* @param array $headers 额外HTTP头
|
||||
* @return string|null 成功返回保存路径,失败返回null
|
||||
*/
|
||||
public function downloadImage(string $url, string $saveDir, ?string $filename = null, array $headers = []): ?string
|
||||
{
|
||||
// 目录检查 & 创建
|
||||
if (!is_dir($saveDir)) {
|
||||
if (!mkdir($saveDir, 0777, true) && !is_dir($saveDir)) {
|
||||
echo "[Image] 创建目录失败:{$saveDir}\n";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 自动生成文件名
|
||||
if ($filename === null) {
|
||||
$path = parse_url($url, PHP_URL_PATH);
|
||||
$ext = pathinfo($path, PATHINFO_EXTENSION);
|
||||
|
||||
if ($ext === '') {
|
||||
$ext = 'jpg';
|
||||
}
|
||||
|
||||
$filename = md5($url) . '.' . $ext;
|
||||
}
|
||||
|
||||
$savePath = rtrim($saveDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
|
||||
|
||||
// 组装HTTP头
|
||||
$defaultHeaders = [
|
||||
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||
'Accept: image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
'Referer: https://www.dongchedi.com/',
|
||||
];
|
||||
|
||||
foreach ($headers as $h) {
|
||||
$defaultHeaders[] = $h;
|
||||
}
|
||||
|
||||
// 使用cURL下载
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_CONNECTTIMEOUT => 5,
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_HTTPHEADER => $defaultHeaders,
|
||||
]);
|
||||
|
||||
$data = curl_exec($ch);
|
||||
$errNo = curl_errno($ch);
|
||||
$errMsg = curl_error($ch);
|
||||
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($errNo !== 0) {
|
||||
// echo "[Image] 下载失败(cURL):{$url} | {$errNo} {$errMsg}\n";
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($code !== 200 || $data === false || $data === '') {
|
||||
// echo "[Image] 下载失败(HTTP {$code}):{$url}\n";
|
||||
return null;
|
||||
}
|
||||
|
||||
// 写入本地文件
|
||||
$bytes = file_put_contents($savePath, $data);
|
||||
if ($bytes === false) {
|
||||
// echo "[Image] 保存失败:{$savePath}\n";
|
||||
return null;
|
||||
}
|
||||
|
||||
// echo "[Image] 下载成功:{$url} => {$savePath}\n";
|
||||
|
||||
return $savePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量下载相册
|
||||
*
|
||||
* @param array $urls 图片URL数组
|
||||
* @param string $saveDir 保存目录
|
||||
* @return array [原始URL => 保存路径或null]
|
||||
*/
|
||||
public function downloadImageAlbum(array $urls, string $saveDir): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($urls as $url) {
|
||||
$url = trim($url);
|
||||
if ($url === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 补全协议
|
||||
if (strpos($url, '//') === 0) {
|
||||
$url = 'https:' . $url;
|
||||
}
|
||||
|
||||
$path = $this->downloadImage($url, $saveDir);
|
||||
$result[$url] = $path;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
public function uploadAndRemove($images, $path, $usedCarId, $id)
|
||||
{
|
||||
// 下载图片
|
||||
$filePatch = $this->downloadImageAlbum($images, $path);
|
||||
|
||||
// 检查图片
|
||||
if (empty($filePatch)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 上传图片
|
||||
foreach ($filePatch as $url => $path) {
|
||||
if ($path === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 上传云端
|
||||
$param = [
|
||||
'path' => $path,
|
||||
'scene' => 'usedcar_crawl',
|
||||
'category' => 'usedcar'
|
||||
];
|
||||
$up = new \app\common\service\UploadService();
|
||||
$result = $up->uploadLocalFile($param);
|
||||
|
||||
// 保存图片信息
|
||||
UsedcarCrawlResultsImages::create([
|
||||
'uc_id' => $id,
|
||||
'used_car_id' => $usedCarId,
|
||||
'original_name' => $result['original_name'],
|
||||
'file_path' => $result['file_name'],
|
||||
]);
|
||||
|
||||
// 删除本地文件
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\email;
|
||||
|
||||
use app\common\model\Country;
|
||||
use app\common\model\CrmCustomer;
|
||||
use support\Db;
|
||||
use support\Log;
|
||||
use support\exception\BusinessException;
|
||||
use app\common\model\EmailParsedResult;
|
||||
use app\common\model\InquiryChannel;
|
||||
use app\common\model\InquiryLog;
|
||||
use app\common\model\User;
|
||||
|
||||
class Emails
|
||||
{
|
||||
|
||||
private $mailbox = '{imap.feishu.cn:993/imap/ssl}INBOX';
|
||||
private $username = 'info@borderlesscar.com';
|
||||
private $password = 'ErkhUA629aocm7Bc';
|
||||
private $limit = 5;
|
||||
private $per_page = 20;
|
||||
private $batch_size = 10;
|
||||
|
||||
|
||||
public function __construct($options = [])
|
||||
{
|
||||
if ($options) {
|
||||
$this->mailbox = $options['mailbox'];
|
||||
$this->username = $options['username'];
|
||||
$this->password = $options['password'];
|
||||
$this->limit = $options['limit'];
|
||||
$this->per_page = $options['per_page'];
|
||||
$this->batch_size = $options['batch_size'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将任意字符串清洗为有效 UTF-8,移除或替换无效字节
|
||||
*/
|
||||
protected function sanitizeUtf8(string $text): string
|
||||
{
|
||||
return iconv('UTF-8', 'UTF-8//IGNORE', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录错误到日志
|
||||
*/
|
||||
protected function logError(string $msg): void
|
||||
{
|
||||
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n";
|
||||
file_put_contents(
|
||||
runtime_path('logs/email_errors.log'),
|
||||
$line,
|
||||
FILE_APPEND | LOCK_EX
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按编码解码并保留 "\r\n"
|
||||
*/
|
||||
protected function getMailBody($inbox, int $id, bool $isUid = false): string
|
||||
{
|
||||
$flags = $isUid ? FT_UID : 0;
|
||||
$structure = imap_fetchstructure($inbox, $id, $flags);
|
||||
|
||||
if (!empty($structure->parts)) {
|
||||
// HTML 部分
|
||||
foreach ($structure->parts as $i => $part) {
|
||||
if (isset($part->subtype) && strtolower($part->subtype) === 'html') {
|
||||
$data = imap_fetchbody($inbox, $id, (string)($i+1), $flags);
|
||||
return $this->decodeBody($data, $part->encoding);
|
||||
}
|
||||
}
|
||||
// 文本部分
|
||||
foreach ($structure->parts as $i => $part) {
|
||||
if (isset($part->subtype) && strtolower($part->subtype) === 'plain') {
|
||||
$data = imap_fetchbody($inbox, $id, (string)($i+1), $flags);
|
||||
return $this->decodeBody($data, $part->encoding);
|
||||
}
|
||||
}
|
||||
// 原始 body
|
||||
return imap_body($inbox, $id, $flags);
|
||||
}
|
||||
|
||||
return imap_body($inbox, $id, $flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按编码解码
|
||||
*/
|
||||
protected function decodeBody(string $body, int $encoding): string
|
||||
{
|
||||
switch ($encoding) {
|
||||
case 3: return imap_base64($body);
|
||||
case 4: return imap_qprint($body);
|
||||
default: return $body;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 HTML,找不到 <h2>Preview</h2> 则返回 null,
|
||||
* 否则提取所有 <span>Key:</span> Value 为小写蛇形 key=>value 数组
|
||||
*/
|
||||
protected function parseHtml(string $html): ?array
|
||||
{
|
||||
$doc = new \DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$doc->loadHTML('<?xml encoding="utf-8"?>' . $html);
|
||||
libxml_clear_errors();
|
||||
|
||||
$xpath = new \DOMXPath($doc);
|
||||
|
||||
// 类型检查
|
||||
if ($xpath->query("//h2[text()='Preview']")->length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nodes = $xpath->query("//div[span]");
|
||||
$data = [];
|
||||
|
||||
/** @var \DOMElement $node */
|
||||
foreach ($nodes as $node) {
|
||||
$span = $xpath->query("span", $node)->item(0);
|
||||
if (! $span) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 原始键名
|
||||
$key = trim(str_replace(':', '', $span->textContent));
|
||||
// 转成小写蛇形
|
||||
$col = strtolower(str_replace(' ', '_', $key));
|
||||
|
||||
// 获取值
|
||||
$a = $xpath->query(".//a", $node)->item(0);
|
||||
if ($a && $a->hasAttribute('href')) {
|
||||
$value = trim($a->getAttribute('href'));
|
||||
} else {
|
||||
$clone = $node->cloneNode(true);
|
||||
$spanClone = $xpath->query(".//span", $clone)->item(0);
|
||||
if ($spanClone) {
|
||||
$spanClone->parentNode->removeChild($spanClone);
|
||||
}
|
||||
$value = trim($clone->textContent);
|
||||
}
|
||||
|
||||
$data[$col] = $value;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取邮件uid
|
||||
*/
|
||||
public function uids()
|
||||
{
|
||||
try {
|
||||
$retryTimes = 3;
|
||||
$retryDelay = 10;
|
||||
$inbox = false;
|
||||
$attempt = 0;
|
||||
|
||||
$maxUid = Db::table('email_uids')->max('uid');
|
||||
|
||||
while ($attempt < $retryTimes) {
|
||||
$attempt++;
|
||||
flg("尝试第 {$attempt} 次连接 IMAP...", false);
|
||||
|
||||
$inbox = @imap_open($this->mailbox, $this->username, $this->password);
|
||||
|
||||
if ($inbox) {
|
||||
break;
|
||||
}
|
||||
|
||||
$error = imap_last_error();
|
||||
flg("<comment>第 {$attempt} 次失败:{$error}</comment>");
|
||||
|
||||
// 若出现 too many login failures 立即暂停一段时间
|
||||
if (stripos($error, 'Too many login failures') !== false) {
|
||||
flg("<error>检测到登录失败次数过多,暂停 60 秒避免封禁</error>");
|
||||
sleep(60);
|
||||
} else {
|
||||
sleep($retryDelay);
|
||||
}
|
||||
}
|
||||
|
||||
if (!$inbox) {
|
||||
flg("<error>最终仍然连接失败:" . imap_last_error() . "</error>");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 拉取 UID 并入库
|
||||
flg("开始拉取 UID 并入库 …", false);
|
||||
$uids = imap_search($inbox, 'ALL', SE_UID) ?: [];
|
||||
|
||||
$uids = array_filter($uids, function($uid) use ($maxUid) {
|
||||
return $uid > $maxUid;
|
||||
});
|
||||
|
||||
sort($uids);
|
||||
$now = time();
|
||||
$count = 0;
|
||||
|
||||
foreach ($uids as $uid) {
|
||||
try {
|
||||
Db::table('email_uids')->insert([
|
||||
'uid' => $uid,
|
||||
'fetched_at' => $now,
|
||||
'email' => $this->username
|
||||
]);
|
||||
$count++;
|
||||
flg("UID:".$uid." 已写入数据库", false);
|
||||
} catch (\Throwable $e) {
|
||||
flg("<comment>{$e->getMessage()}</comment>");
|
||||
}
|
||||
}
|
||||
|
||||
imap_close($inbox);
|
||||
flg("✔ 获取到新询盘邮件 {$count} 条 ...", false);
|
||||
return true;
|
||||
} catch (\Throwable $th) {
|
||||
flg(dpr($th));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取邮件详情
|
||||
*/
|
||||
public function details()
|
||||
{
|
||||
try {
|
||||
$inbox = @imap_open($this->mailbox, $this->username, $this->password);
|
||||
if (!$inbox) {
|
||||
flg("<error>IMAP 连接失败:". imap_last_error() ."</error>");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 依次拉取详情并写入 emails 表
|
||||
flg("依次拉取详情并写入 emails 表 …", false);
|
||||
while (true) {
|
||||
$pending = Db::table('email_uids')
|
||||
->where('status', 0)
|
||||
->orderBy('uid', 'desc')
|
||||
->limit(2)
|
||||
->get();
|
||||
|
||||
if (count($pending) === 0) {
|
||||
flg("邮件UID的详情,已拉取完毕。", false);
|
||||
break;
|
||||
}
|
||||
|
||||
flg("处理下一批 " . count($pending) . " 条 …", false);
|
||||
|
||||
foreach ($pending as $row) {
|
||||
$uid = $row->uid;
|
||||
|
||||
// 包裹整行处理在 try/catch 中,任何异常都不会中断循环
|
||||
try {
|
||||
flg("---- 开始处理 UID={$uid} ----", false);
|
||||
|
||||
// 1. fetch overview
|
||||
$ov = @imap_fetch_overview($inbox, $uid, FT_UID)[0] ?? null;
|
||||
if (!$ov) {
|
||||
$err = imap_last_error() ?: '未知错误';
|
||||
flg("UID={$uid} overview 失败:{$err}");
|
||||
continue;
|
||||
}
|
||||
$subject = mb_convert_encoding($ov->subject ?? '', 'UTF-8', 'GBK,UTF-8');
|
||||
$from = $ov->from ?? '';
|
||||
$date = $ov->date ?? '';
|
||||
|
||||
flg("UID={$uid} overview 成功,subject={$subject}", false);
|
||||
|
||||
// 2. fetch body
|
||||
$body = $this->getMailBody($inbox, $uid, true);
|
||||
flg("UID={$uid} body 长度:" . strlen($body), false);
|
||||
|
||||
// 3. sanitize & insert
|
||||
$body = $this->sanitizeUtf8($body);
|
||||
$now = time();
|
||||
|
||||
try {
|
||||
Db::table('emails')->insert([
|
||||
'uid' => $uid,
|
||||
'subject' => $subject,
|
||||
'from' => $from,
|
||||
'date' => $date,
|
||||
'body' => $body,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
flg("UID={$uid} 写入 emails 成功", false);
|
||||
} catch (\Throwable $e) {
|
||||
flg("UID={$uid} 写入失败:{$e->getMessage()}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 4. 标记已处理
|
||||
try {
|
||||
Db::table('email_uids')
|
||||
->where('uid', $uid)
|
||||
->update([
|
||||
'status' => 1,
|
||||
'processed_at' => $now,
|
||||
]);
|
||||
flg("UID={$uid} 标记为已处理", false);
|
||||
} catch (\Throwable $e) {
|
||||
flg("UID={$uid} 标记状态失败:{$e->getMessage()}", false);
|
||||
// 即使更新 status 失败,也继续下一条
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// 捕获任何非预期错误
|
||||
flg("UID={$uid} 处理异常:{$e->getMessage()}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 批次结束后稍作休眠,防止服务器过载
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
imap_close($inbox);
|
||||
flg("✔ 新邮件详情拉取完成 ...", false);
|
||||
return true;
|
||||
} catch (\Throwable $th) {
|
||||
flg(dpr($th));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮件清洗处理
|
||||
*/
|
||||
public function process()
|
||||
{
|
||||
try {
|
||||
$page = 0;
|
||||
|
||||
// 明确定义 parsed_contacts 表里要插入的所有列(顺序无所谓,但要全部包含)
|
||||
$fields = [
|
||||
'email_id',
|
||||
'date',
|
||||
'email',
|
||||
'name',
|
||||
'tel',
|
||||
'company',
|
||||
'country',
|
||||
'form_url',
|
||||
'message',
|
||||
'ip',
|
||||
'iplocation',
|
||||
'ilang',
|
||||
'mailto',
|
||||
'navigator_language',
|
||||
'navigator_platform',
|
||||
'screen_width',
|
||||
'screen_height',
|
||||
'ucountry',
|
||||
];
|
||||
|
||||
$maxEmailId = Db::table('email_parsed_result')->max('email_id');
|
||||
|
||||
while (true) {
|
||||
$rows = Db::table('emails')
|
||||
->where('status', 0)
|
||||
->where('id', '>', $maxEmailId)
|
||||
->orderBy('id', 'asc')
|
||||
->limit($this->batch_size)
|
||||
->offset($page * $this->batch_size)
|
||||
->get();
|
||||
|
||||
if ($rows->isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
$toInsert = [];
|
||||
foreach ($rows as $row) {
|
||||
$parsed = $this->parseHtml($row->body);
|
||||
if ($parsed === null) {
|
||||
flg(" ↳ [{$row->id}] skip: not a contact-form HTML", false);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 严格按 $fields 顺序填充每条记录,缺失的字段补 null
|
||||
$record = [];
|
||||
foreach ($fields as $col) {
|
||||
if ($col === 'email_id') {
|
||||
$record[$col] = $row->id;
|
||||
} else {
|
||||
$record[$col] = $parsed[$col] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
$toInsert[] = $record;
|
||||
}
|
||||
|
||||
if (!empty($toInsert)) {
|
||||
Db::table('email_parsed_result')->insert($toInsert);
|
||||
|
||||
$emailId = array_column($toInsert, 'email_id');
|
||||
Db::table('emails')->whereIn('id', $emailId)->update(['status' => 1]);
|
||||
|
||||
flg("Inserted batch #" . ($page + 1) . ", count: " . count($toInsert), false);
|
||||
}
|
||||
|
||||
$page++;
|
||||
}
|
||||
|
||||
flg("✔ 邮件清洗完毕,等待分配 ...", false);
|
||||
return true;
|
||||
} catch (\Throwable $th) {
|
||||
flg(dpr($th));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function fenpai()
|
||||
{
|
||||
try {
|
||||
// 配置参数
|
||||
$batchSize = 100; // 每批处理量
|
||||
$delaySeconds = 2; // 每封邮件间隔秒数
|
||||
$throttleAfter = 50; // 每发送多少封后增加休息
|
||||
$throttleSeconds = 5; // 批量休息秒数
|
||||
|
||||
// 固定录单人
|
||||
$enterUserId = 75;
|
||||
$enterUser = User::where('id', $enterUserId)->first();
|
||||
|
||||
// 固定渠道
|
||||
$channel = 12;
|
||||
$channelInfo = InquiryChannel::where('id', $channel)->first();
|
||||
|
||||
// 从库实时获取
|
||||
$users = \app\common\model\User::where('corp_id', 3)->where('status', 1)->orderBy('id')->pluck('id')->toArray();
|
||||
|
||||
// 移除不参与分配人员
|
||||
$users = array_values(array_diff($users, [190]));
|
||||
|
||||
// 初始化 UID 轮询器
|
||||
$uidRotator = new \app\common\utils\RedisUidRotator('email_parsed_result_20250804');
|
||||
$uidRotator->setUids($users, false);
|
||||
|
||||
EmailParsedResult::where('status', 0)
|
||||
->chunkById($batchSize, function ($records) use ($delaySeconds, $throttleAfter, $throttleSeconds, $enterUser, $channelInfo, $uidRotator) {
|
||||
$count = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
try {
|
||||
// 获取国家信息
|
||||
$countryName = $record->iplocation ? removeParentheses($record->iplocation) : '未知';
|
||||
$countryInfo = Country::where('cn_addr', $countryName)->first();
|
||||
|
||||
// 获取下一个分配的UID
|
||||
$assignedUid = $uidRotator->next();
|
||||
|
||||
// 获取分配的用户信息
|
||||
$recipientInfo = User::where('id', $assignedUid)->where('status', 1)->first();
|
||||
if (!$recipientInfo) {
|
||||
flg("用户ID=" . $assignedUid . " 已离职 跳过自动分配,需要手动移除 UID");
|
||||
|
||||
$assignedUid = $uidRotator->next();
|
||||
$recipientInfo = User::where('id', $assignedUid)->where('status', 1)->first();
|
||||
}
|
||||
|
||||
// 生成录单
|
||||
$log = [
|
||||
'order_no' => orderNum(),
|
||||
'enter_user_id' => $enterUser->id,
|
||||
'recipient' => $assignedUid,
|
||||
'quality' => 2,
|
||||
'channel' => $channelInfo->id,
|
||||
'email' => $record->email,
|
||||
'tel' => $record->tel,
|
||||
'whatsapp' => '',
|
||||
'country' => $countryInfo->id,
|
||||
'contacts' => $record->name,
|
||||
'content' => $record->message,
|
||||
'r_time' => time(),
|
||||
't_time' => time(),
|
||||
'status' => 2,
|
||||
'sync_crm' => 1
|
||||
];
|
||||
$inquiryLogResult = InquiryLog::create($log);
|
||||
if (!$inquiryLogResult) {
|
||||
throw new BusinessException('录单失败~');
|
||||
}
|
||||
|
||||
// 同步客户
|
||||
$crmCustomer = new CrmCustomer();
|
||||
$crmCustomer->sn = $inquiryLogResult->order_no;
|
||||
$crmCustomer->corp_id = $recipientInfo->corp_id;
|
||||
$crmCustomer->user_id = $assignedUid;
|
||||
$crmCustomer->type = 1;
|
||||
$crmCustomer->channel_id = $inquiryLogResult->channel;
|
||||
$crmCustomer->country_id = $inquiryLogResult->country;
|
||||
$crmCustomer->magnitude = $inquiryLogResult->quality;
|
||||
$crmCustomer->email = $inquiryLogResult->email;
|
||||
$crmCustomer->phone = $inquiryLogResult->tel;
|
||||
$crmCustomer->WhatsApp = $inquiryLogResult->whatsapp;
|
||||
$crmCustomer->contacts = $inquiryLogResult->contacts;
|
||||
$crmCustomer->desc_collect = $inquiryLogResult->content;
|
||||
$crmCustomer->enter_user_id = $inquiryLogResult->enter_user_id;
|
||||
if (!$crmCustomer->save()) {
|
||||
throw new BusinessException('同步失败~');
|
||||
}
|
||||
|
||||
// 邮件模板
|
||||
// $data = [
|
||||
// 'order_no' => $inquiryLogResult->order_no,
|
||||
// 'enter_user_id' => $enterUser->name,
|
||||
// 'recipient' => $recipientInfo->name,
|
||||
// 'quality' => (new \app\inquiry\service\InquiryLogService())->qualityName($inquiryLogResult->quality),
|
||||
// 'channel' => $channelInfo->name,
|
||||
// 'email' => $inquiryLogResult->email && $inquiryLogResult->email != '' ? $inquiryLogResult->email : ' - ',
|
||||
// 'tel' => $inquiryLogResult->tel && $inquiryLogResult->tel != '' ? $inquiryLogResult->tel : ' - ',
|
||||
// 'whatsapp' => $inquiryLogResult->whatsapp && $inquiryLogResult->whatsapp != '' ? $inquiryLogResult->whatsapp : ' - ',
|
||||
// 'country' => $countryName,
|
||||
// 'contacts' => $inquiryLogResult->contacts && $inquiryLogResult->contacts != '' ? $inquiryLogResult->contacts : ' - ',
|
||||
// 'content' => $inquiryLogResult->content && $inquiryLogResult->content != '' ? $inquiryLogResult->content : ' - ',
|
||||
// 'r_time' => $inquiryLogResult->r_time ? date('Y-m-d H:i:s', $inquiryLogResult->r_time) : ' - ',
|
||||
// 't_time' => $inquiryLogResult->t_time ? date('Y-m-d H:i:s', $inquiryLogResult->t_time) : ' - '
|
||||
// ];
|
||||
// \app\common\utils\email\MailSend::send($recipientInfo->email, '【XYH】新的客户线索', replaceTpl($data));
|
||||
|
||||
// 9.2 修改消息发送
|
||||
$data = [
|
||||
'id' => $inquiryLogResult->id
|
||||
];
|
||||
\Webman\RedisQueue\Redis::send('inquiry-to-crm-new', $data);
|
||||
|
||||
// 更新状态
|
||||
$record->update(['status' => 1]);
|
||||
flg('====== 编号:'.$inquiryLogResult->order_no.' 分配给:'.$recipientInfo->name.' email:'.$recipientInfo->email, false);
|
||||
|
||||
// 每封邮件后延迟
|
||||
if ($delaySeconds > 0) {
|
||||
sleep($delaySeconds);
|
||||
}
|
||||
|
||||
// 每发送一定数量后额外休息
|
||||
if (++$count % $throttleAfter === 0) {
|
||||
sleep($throttleSeconds);
|
||||
flg("已发送 {$count} 封邮件,休息 {$throttleSeconds} 秒", false);
|
||||
}
|
||||
|
||||
} catch (\Exception $e) {
|
||||
flg("邮件发送失败 ID:{$record->id} - " . $e->getMessage());
|
||||
// 更新状态
|
||||
$record->update(['status' => 3]);
|
||||
// 失败后也加入延迟,避免快速连续失败
|
||||
sleep($delaySeconds);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (\Throwable $th) {
|
||||
flg(dpr($th));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\email;
|
||||
|
||||
use app\common\model\InquiryLog;
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
use PHPMailer\PHPMailer\Exception;
|
||||
use support\Db;
|
||||
use support\Log;
|
||||
|
||||
class MailSend
|
||||
{
|
||||
/**
|
||||
* 发送邮件
|
||||
*
|
||||
* @param string|array $to 收件人邮箱(单个字符串或多个数组)
|
||||
* @param string $subject 邮件主题
|
||||
* @param string $body 邮件内容(HTML)
|
||||
* @param array $attachments 附件路径数组 [['path' => '/path/file', 'name' => '文件名']]
|
||||
* @return bool
|
||||
*/
|
||||
public static function send($to, $subject, $body, $attachments = [])
|
||||
{
|
||||
$mail = new PHPMailer(true);
|
||||
|
||||
try {
|
||||
// 服务器配置
|
||||
$mail->isSMTP();
|
||||
$mail->Host = config('imap.smtp_xyh.host'); // SMTP服务器
|
||||
$mail->SMTPAuth = true;
|
||||
$mail->Username = config('imap.smtp_xyh.username'); // 邮箱账号
|
||||
$mail->Password = config('imap.smtp_xyh.password'); // 邮箱密码/授权码
|
||||
$mail->SMTPSecure = config('imap.smtp_xyh.encryption'); // 加密方式 tls/ssl
|
||||
$mail->Port = config('imap.smtp_xyh.port'); // 端口
|
||||
|
||||
// 发件人
|
||||
$mail->setFrom(config('imap.smtp_xyh.from_address'), config('imap.smtp_xyh.from_name'));
|
||||
|
||||
// 收件人(支持单个或多个)
|
||||
if (is_string($to)) {
|
||||
$mail->addAddress($to);
|
||||
} elseif (is_array($to)) {
|
||||
foreach ($to as $email) {
|
||||
$mail->addAddress($email);
|
||||
}
|
||||
}
|
||||
|
||||
// 附件
|
||||
foreach ($attachments as $file) {
|
||||
$mail->addAttachment($file['path'], $file['name'] ?? '');
|
||||
}
|
||||
|
||||
// 内容
|
||||
$mail->isHTML(true);
|
||||
$mail->CharSet = 'UTF-8';
|
||||
$mail->Encoding = 'base64';
|
||||
$mail->Subject = mb_encode_mimeheader($subject, 'UTF-8', 'B', "\r\n");
|
||||
$mail->Body = $body;
|
||||
// $mail->AltBody = strip_tags($body); // 纯文本备用
|
||||
// $mail->AltBody = $altbody;
|
||||
|
||||
$mail->send();
|
||||
return true;
|
||||
} catch (Exception $e) {
|
||||
Log::error("邮件发送失败: " . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
namespace app\common\utils\excel;
|
||||
|
||||
use support\Db;
|
||||
|
||||
/**
|
||||
* ExcelImportTrait
|
||||
*
|
||||
* 把“读取 Sheet → 映射字段 → 规范化数据 → 打时间戳 → 批量入库”
|
||||
* 这条通用导入链路抽成 Trait,便于在多个 Service 里复用。
|
||||
*
|
||||
* 依赖:
|
||||
* - ExcelReader:提供 readSheet / readSheetFromUrl / remap / toDecimal / toBool / toDate
|
||||
* - 你的 OssService:通过 generatePrivateUrl($objectKey) 生成 OSS 私有签名 URL
|
||||
*/
|
||||
trait ExcelImportTrait
|
||||
{
|
||||
/**
|
||||
* 读取某个 Sheet 的“行数组”
|
||||
* - $file 可为本地路径或 URL(由 $isUrl 控制)
|
||||
* - headerRow:表头所在行(Excel 行号,从 1 开始)
|
||||
* - startRow:数据起始行(不传则为 headerRow+1)
|
||||
*/
|
||||
protected function readSheetRows(string $file, string $sheet, bool $isUrl, int $headerRow = 1, ?int $startRow = null): array
|
||||
{
|
||||
$ret = $isUrl
|
||||
? ExcelReader::readSheetFromUrl($file, $sheet, $headerRow, $startRow)
|
||||
: ExcelReader::readSheet($file, $sheet, $headerRow, $startRow);
|
||||
return $ret['rows'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某个 Sheet(传入 OSS 对象键),内部会用你的 OssService 生成签名 URL 再读取
|
||||
*/
|
||||
protected function readSheetRowsFromOssKey(string $objectKey, string $sheet, int $headerRow = 1, ?int $startRow = null): array
|
||||
{
|
||||
$signedUrl = $this->ossSignedUrl($objectKey);
|
||||
$ret = ExcelReader::readSheetFromUrl($signedUrl, $sheet, $headerRow, $startRow);
|
||||
return $ret['rows'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用你的 OssService 生成私有签名 URL
|
||||
* - 兼容你的现有写法:(new \app\common\service\OssService)->generatePrivateUrl($objectKey)
|
||||
*/
|
||||
protected function ossSignedUrl(string $objectKey): string
|
||||
{
|
||||
return (new \app\common\service\OssService())->generatePrivateUrl($objectKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一行做字段映射 + 基础类型规范化(decimal/bool/date)
|
||||
* - $headerMap:表头映射(源列名 => 目标字段名)
|
||||
* - $decimalFields/$boolFields/$dateFields:需要做类型规范化的目标字段名列表
|
||||
*/
|
||||
protected function mapAndNormalizeRow(
|
||||
array $row,
|
||||
array $headerMap,
|
||||
array $decimalFields = [],
|
||||
array $boolFields = [],
|
||||
array $dateFields = []
|
||||
): array {
|
||||
$rec = ExcelReader::remap($row, $headerMap);
|
||||
|
||||
foreach ($decimalFields as $f) {
|
||||
if (array_key_exists($f, $rec)) {
|
||||
$rec[$f] = ExcelReader::toDecimal($rec[$f]); // 建议已升级为“去货币符号/千分位/括号负数”的版本
|
||||
}
|
||||
}
|
||||
foreach ($boolFields as $f) {
|
||||
if (array_key_exists($f, $rec)) {
|
||||
$rec[$f] = ExcelReader::toBool($rec[$f]);
|
||||
}
|
||||
}
|
||||
foreach ($dateFields as $f) {
|
||||
if (array_key_exists($f, $rec)) {
|
||||
$rec[$f] = ExcelReader::toDate($rec[$f]);
|
||||
}
|
||||
}
|
||||
return $rec;
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于 VIN 的跳过规则:VIN 为空、或是“合计/总计”行
|
||||
* - $vinAliases:VIN 列的候选表头(如 ['车架号','VIN NO'])
|
||||
*/
|
||||
protected function shouldSkipByVinAliases(array $row, array $vinAliases = ['车架号', 'VIN NO']): bool
|
||||
{
|
||||
$vin = $this->pickFirstNonEmpty($row, $vinAliases);
|
||||
if ($vin === null) return true;
|
||||
return (bool)preg_match('/^(合计|总计)/u', $vin);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在多个候选键里取第一个非空字符串
|
||||
*/
|
||||
protected function pickFirstNonEmpty(array $row, array $keys): ?string
|
||||
{
|
||||
foreach ($keys as $k) {
|
||||
if (isset($row[$k])) {
|
||||
$v = trim((string)$row[$k]);
|
||||
if ($v !== '') return $v;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一补齐 created_at / updated_at 时间戳(int(11))
|
||||
*/
|
||||
protected function stamp(array &$rec): void
|
||||
{
|
||||
$now = time();
|
||||
$rec['created_at'] = $now;
|
||||
$rec['updated_at'] = $now;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量入库
|
||||
* - 返回 ['inserted'=>N, 'error'=>null|string]
|
||||
* - 发生异常时不抛出,返回 error 字符串,便于上层统一处理
|
||||
*/
|
||||
protected function batchInsert(string $table, array $rows): array
|
||||
{
|
||||
if (!$rows) return ['inserted' => 0, 'error' => null];
|
||||
try {
|
||||
Db::table($table)->insert($rows);
|
||||
return ['inserted' => count($rows), 'error' => null];
|
||||
} catch (\Throwable $e) {
|
||||
return ['inserted' => 0, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
<?php
|
||||
namespace app\common\utils\excel;
|
||||
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||||
|
||||
class ExcelReader
|
||||
{
|
||||
/**
|
||||
* (可选)环境自检:避免因缺少扩展导致读取失败
|
||||
* - simplexml_load_string 存在性(ext-simplexml)
|
||||
* - ext-zip
|
||||
*/
|
||||
public static function assertRequirements(): void
|
||||
{
|
||||
if (!function_exists('simplexml_load_string')) {
|
||||
throw new \RuntimeException('缺少 PHP 扩展:ext-simplexml。请安装/启用后再试。');
|
||||
}
|
||||
if (!extension_loaded('zip')) {
|
||||
throw new \RuntimeException('缺少 PHP 扩展:ext-zip。请安装/启用后再试。');
|
||||
}
|
||||
// 可按需继续检查 ext-mbstring/ext-dom 等
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定 sheet,按某一行作为表头
|
||||
* 返回:['headers'=>[], 'rows'=>[]]
|
||||
* - $headerRow:从 1 开始计数(Excel 行号)
|
||||
* - $startRow:数据起始行(默认 headerRow+1)
|
||||
* - 注意:$filePath 必须是“本地文件路径”;若为 URL,请改用 readSheetFromUrl()
|
||||
*/
|
||||
public static function readSheet(string $filePath, string $sheetName, int $headerRow = 1, ?int $startRow = null): array
|
||||
{
|
||||
self::assertRequirements();
|
||||
|
||||
if (!is_file($filePath)) {
|
||||
throw new \RuntimeException("File not found: {$filePath}");
|
||||
}
|
||||
|
||||
$reader = IOFactory::createReaderForFile($filePath);
|
||||
$reader->setReadDataOnly(true);
|
||||
$spreadsheet = $reader->load($filePath);
|
||||
|
||||
$sheet = $spreadsheet->getSheetByName($sheetName);
|
||||
if (!$sheet) {
|
||||
$names = implode(' / ', $spreadsheet->getSheetNames());
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
throw new \RuntimeException("Sheet '{$sheetName}' not found. Available: {$names}");
|
||||
}
|
||||
|
||||
$highestRow = $sheet->getHighestDataRow();
|
||||
$highestCol = $sheet->getHighestDataColumn();
|
||||
$highestColIndex = Coordinate::columnIndexFromString($highestCol);
|
||||
|
||||
// 读取表头(去除可能的 UTF-8 BOM)
|
||||
$headers = [];
|
||||
for ($col = 1; $col <= $highestColIndex; $col++) {
|
||||
$coord = Coordinate::stringFromColumnIndex($col) . $headerRow;
|
||||
$cell = $sheet->getCell($coord);
|
||||
$raw = $cell ? $cell->getCalculatedValue() : null;
|
||||
$text = is_null($raw) ? '' : trim((string)$raw);
|
||||
// 去掉 BOM
|
||||
if ($col === 1) {
|
||||
$text = preg_replace('/^\xEF\xBB\xBF/u', '', $text);
|
||||
}
|
||||
$headers[$col] = $text === '' ? "COL_{$col}" : $text;
|
||||
}
|
||||
|
||||
// 读取数据
|
||||
$rows = [];
|
||||
$firstDataRow = $startRow ?? ($headerRow + 1);
|
||||
for ($row = $firstDataRow; $row <= $highestRow; $row++) {
|
||||
$record = [];
|
||||
$isEmpty = true;
|
||||
|
||||
for ($col = 1; $col <= $highestColIndex; $col++) {
|
||||
$coord = Coordinate::stringFromColumnIndex($col) . $row;
|
||||
$cell = $sheet->getCell($coord);
|
||||
$value = $cell ? $cell->getCalculatedValue() : null;
|
||||
|
||||
// 日期单元格转换(使用 PhpSpreadsheet 的日期检测)
|
||||
if ($cell && \PhpOffice\PhpSpreadsheet\Shared\Date::isDateTime($cell) && is_numeric($value)) {
|
||||
$dt = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value);
|
||||
$value = $dt ? $dt->format('Y-m-d') : $value;
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$value = trim($value);
|
||||
}
|
||||
if ($value !== null && $value !== '') {
|
||||
$isEmpty = false;
|
||||
}
|
||||
$record[$headers[$col]] = $value;
|
||||
}
|
||||
|
||||
if (!$isEmpty) {
|
||||
$rows[] = $record;
|
||||
}
|
||||
}
|
||||
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
return ['headers' => array_values($headers), 'rows' => $rows];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 URL 读取指定 sheet(内部先下载到临时文件)
|
||||
*/
|
||||
public static function readSheetFromUrl(string $url, string $sheetName, int $headerRow = 1, ?int $startRow = null): array
|
||||
{
|
||||
$tmp = self::downloadToTemp($url);
|
||||
try {
|
||||
return self::readSheet($tmp, $sheetName, $headerRow, $startRow);
|
||||
} finally {
|
||||
@unlink($tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按映射表将“源表头”=>“目标字段名”(snake_case)
|
||||
* $map 形如:['车架号' => 'vin', '实际采购价' => 'actual_purchase_price', ...]
|
||||
*/
|
||||
public static function remap(array $row, array $map): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($map as $from => $to) {
|
||||
$out[$to] = $row[$from] ?? null;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** 将一批行做 remap */
|
||||
public static function remapRows(array $rows, array $map): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($rows as $row) {
|
||||
$out[] = self::remap($row, $map);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将“金额字符串”解析成 float(适配多币种/多地区写法)
|
||||
* - 支持:¥ ¥ $ € £ …、AED/Dirham:dh / dhs / aed、阿语 د.إ
|
||||
* - 支持:中文/全角标点、阿拉伯小数/千分位、细空格、撇号千分位
|
||||
* - 支持:括号负数 (xxx) 与显式负号
|
||||
* - 返回 null 表示无法解析
|
||||
*/
|
||||
public static function toDecimal($v): ?float
|
||||
{
|
||||
if ($v === null || $v === '') return null;
|
||||
if (is_numeric($v)) return (float)$v;
|
||||
|
||||
$s = trim((string)$v);
|
||||
|
||||
// 1) 统一常见 unicode 标点(全角/阿拉伯)与空格
|
||||
$s = strtr($s, [
|
||||
',' => ',', '.' => '.',
|
||||
'٫' => '.', '٬' => ',',
|
||||
"\xC2\xA0" => ' ', // NBSP
|
||||
"\xE2\x80\xAF" => ' ', // NNBSP(窄不换行空格)
|
||||
]);
|
||||
|
||||
// 2) 括号负数,如 (dh1,234.56)
|
||||
$negative = false;
|
||||
if (preg_match('/^\s*\((.*)\)\s*$/u', $s, $m)) {
|
||||
$negative = true;
|
||||
$s = $m[1];
|
||||
}
|
||||
|
||||
// 3) 去币种/符号:AED/Dirham(dh/dhs/aed/د.إ)& 其它常见符号/字母
|
||||
$s = preg_replace('/\b(dhs?|aed)\b/i', '', $s); // dh / dhs / aed
|
||||
$s = str_replace(['د.إ', 'د', 'إ'], '', $s); // 常见阿语形式简化处理
|
||||
$s = preg_replace('/[A-Za-z¥¥$€£₽₺₩₹﷼]+/u', '', $s); // 其它字母/货币符号
|
||||
|
||||
// 4) 只保留 数字/点/逗号/减号/空格/撇号,然后去掉空格与撇号(千分位)
|
||||
$s = preg_replace('/[^\d\.,\-\s\']+/u', '', $s);
|
||||
$s = str_replace([' ', "'"], '', $s);
|
||||
|
||||
// 5) 统一小数分隔符(判断最后出现的分隔符)
|
||||
$lastComma = strrpos($s, ',');
|
||||
$lastDot = strrpos($s, '.');
|
||||
|
||||
if ($lastComma !== false && $lastDot !== false) {
|
||||
// 同时存在,最后出现者视为小数点
|
||||
if ($lastComma > $lastDot) {
|
||||
// 欧式 1.234,56
|
||||
$s = str_replace('.', '', $s); // 去千分点
|
||||
$s = substr_replace($s, '.', $lastComma, 1); // 最后一个逗号改为小数点
|
||||
$s = str_replace(',', '', $s); // 其余逗号清空
|
||||
} else {
|
||||
// 美式 1,234.56
|
||||
$s = str_replace(',', '', $s);
|
||||
}
|
||||
} elseif ($lastComma !== false) {
|
||||
// 只有逗号
|
||||
$digitsAfter = strlen($s) - $lastComma - 1;
|
||||
if (substr_count($s, ',') > 1) {
|
||||
// 多个逗号基本都是千分位
|
||||
$s = str_replace(',', '', $s);
|
||||
} else {
|
||||
// 一个逗号:若逗号后 1~2 位,视为小数点,否则千分位
|
||||
$s = ($digitsAfter >= 1 && $digitsAfter <= 2)
|
||||
? str_replace(',', '.', $s)
|
||||
: str_replace(',', '', $s);
|
||||
}
|
||||
} elseif ($lastDot !== false && substr_count($s, '.') > 1) {
|
||||
// 多个点:保留最后一个为小数点,其他去掉(当作千分位)
|
||||
$digitsAfter = strlen($s) - $lastDot - 1;
|
||||
if ($digitsAfter >= 1 && $digitsAfter <= 2) {
|
||||
$s = preg_replace('/\.(?=.*\.)/', '', $s); // 移除除最后一个外的点
|
||||
} else {
|
||||
$s = str_replace('.', '', $s);
|
||||
}
|
||||
}
|
||||
|
||||
// 6) 处理显式负号
|
||||
if (strpos($s, '-') !== false) {
|
||||
$negative = true;
|
||||
$s = str_replace('-', '', $s);
|
||||
}
|
||||
|
||||
// 7) 最终校验并转 float
|
||||
if ($s === '' || !preg_match('/^\d+(\.\d+)?$/', $s)) {
|
||||
return null; // 无法解析
|
||||
}
|
||||
|
||||
$num = (float)$s;
|
||||
return $negative ? -$num : $num;
|
||||
}
|
||||
|
||||
/** 规范化布尔:'是/否'、'Y/N'、'1/0'、'true/false' */
|
||||
public static function toBool($v): ?int
|
||||
{
|
||||
if ($v === null || $v === '') return null;
|
||||
$s = mb_strtolower(trim((string)$v));
|
||||
if (in_array($s, ['是','y','yes','true','1','√','✅'], true)) return 1;
|
||||
if (in_array($s, ['否','n','no','false','0','×','❌'], true)) return 0;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 规范化日期(readSheet 已对 Excel 日期做过处理,这里再兜底) */
|
||||
public static function toDate($v): ?string
|
||||
{
|
||||
if ($v === null || $v === '') return null;
|
||||
if (is_numeric($v)) {
|
||||
// Excel 序列号兜底
|
||||
$ts = ExcelDate::excelToTimestamp($v);
|
||||
return $ts ? date('Y-m-d', $ts) : null;
|
||||
}
|
||||
// 简单清洗
|
||||
$s = trim((string)$v);
|
||||
// 常见格式直接返回(如 2025-11-04 / 2025/11/04)
|
||||
if (preg_match('/^\d{4}[-\/]\d{1,2}[-\/]\d{1,2}$/', $s)) {
|
||||
return str_replace('/', '-', $s);
|
||||
}
|
||||
return $s; // 留给上层决定是否再严格校验
|
||||
}
|
||||
|
||||
/**
|
||||
* 把远程 URL 流式下载到临时文件;返回临时路径
|
||||
*/
|
||||
protected static function downloadToTemp(string $url, ?string $ext = null): string
|
||||
{
|
||||
$ext = $ext ? ('.' . ltrim($ext, '.')) : '';
|
||||
$tmp = sys_get_temp_dir() . '/excel_' . uniqid() . $ext;
|
||||
$fp = fopen($tmp, 'w');
|
||||
if (!$fp) {
|
||||
throw new \RuntimeException("Cannot open temp file: {$tmp}");
|
||||
}
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_FILE => $fp,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_TIMEOUT => 300,
|
||||
CURLOPT_CONNECTTIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => true,
|
||||
CURLOPT_SSL_VERIFYHOST => 2,
|
||||
CURLOPT_USERAGENT => 'Webman-ExcelReader/1.0',
|
||||
]);
|
||||
$ok = curl_exec($ch);
|
||||
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$err = curl_error($ch);
|
||||
curl_close($ch);
|
||||
fclose($fp);
|
||||
if ($ok === false || $http >= 400) {
|
||||
@unlink($tmp);
|
||||
throw new \RuntimeException("Download failed: HTTP {$http} {$err}");
|
||||
}
|
||||
return $tmp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
// app/controller/PdfController.php
|
||||
namespace app\controller;
|
||||
|
||||
use support\Request;
|
||||
use support\Response;
|
||||
use support\View;
|
||||
use app\common\utils\pdf\service\MpdfDriver;
|
||||
use app\common\utils\pdf\service\PdfHelper;
|
||||
|
||||
class PdfController
|
||||
{
|
||||
// ① 从“现有 HTML 文件 + 外链CSS”生成并在线预览
|
||||
public function previewFromFile(Request $request): Response
|
||||
{
|
||||
// 你的模板路径(示例)
|
||||
$tpl = base_path('resource/templates/stock-order.html');
|
||||
// 可选:把 {{变量}} 替换
|
||||
$html = PdfHelper::loadTemplate($tpl, [
|
||||
'title' => '备货单',
|
||||
'order_no' => 'SO' . date('YmdHis'),
|
||||
'customer' => 'Magic Bridge Auto FZE',
|
||||
]);
|
||||
|
||||
$driver = new MpdfDriver();
|
||||
$pdf = $driver->htmlToPdf($html, [
|
||||
// 若 HTML 里用到相对资源(img/css),给个基准目录
|
||||
'asset_base' => public_path('assets/pdf'),
|
||||
// 也可以单独传 CSS 文件(推荐把 CSS 放在 public/assets/pdf)
|
||||
'css_files' => [
|
||||
public_path('assets/pdf/stock-order.css'),
|
||||
],
|
||||
'header_html' => '<div style="text-align:right;color:#888;font-size:10px">Company • Stock Order</div>',
|
||||
'footer_html' => '<div style="text-align:center;color:#888;font-size:10px">{PAGENO} / {nbpg}</div>',
|
||||
'watermark_text' => '', // 'DRAFT'
|
||||
]);
|
||||
|
||||
return new Response(200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'inline; filename="stock-order.pdf"',
|
||||
], $pdf);
|
||||
}
|
||||
|
||||
// ② 直接下载
|
||||
public function download(Request $request): Response
|
||||
{
|
||||
$html = '<h1>发票</h1><p>客户:永生花</p>';
|
||||
$pdf = (new MpdfDriver())->htmlToPdf($html);
|
||||
return new Response(200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'attachment; filename="invoice.pdf"',
|
||||
], $pdf);
|
||||
}
|
||||
|
||||
// ③ 保存到本地(或上传 OSS 前先落盘)
|
||||
public function save(Request $request): Response
|
||||
{
|
||||
$tpl = base_path('resource/templates/invoice.html');
|
||||
$html = PdfHelper::loadTemplate($tpl, [
|
||||
'invoice_no' => 'INV' . date('YmdHis'),
|
||||
'amount' => '12345.67',
|
||||
]);
|
||||
|
||||
$pdf = (new MpdfDriver())->htmlToPdf($html, [
|
||||
'css_files' => [ public_path('assets/pdf/invoice.css') ],
|
||||
'asset_base'=> public_path('assets/pdf'),
|
||||
]);
|
||||
|
||||
$dir = runtime_path('pdf');
|
||||
if (!is_dir($dir)) mkdir($dir, 0777, true);
|
||||
$path = $dir . '/invoice-' . date('YmdHis') . '.pdf';
|
||||
file_put_contents($path, $pdf);
|
||||
|
||||
return json(['path' => $path]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
// app/service/pdf/MpdfDriver.php
|
||||
namespace app\common\utils\pdf\service;
|
||||
|
||||
use Mpdf\Mpdf;
|
||||
use Mpdf\Config\ConfigVariables;
|
||||
use Mpdf\Config\FontVariables;
|
||||
use Mpdf\HTMLParserMode;
|
||||
|
||||
class MpdfDriver
|
||||
{
|
||||
|
||||
public function htmlToPdf(string $html, array $options = []): string
|
||||
{
|
||||
$opts = array_merge([
|
||||
'format' => 'A4',
|
||||
'orientation' => 'L',
|
||||
'margin_top' => 12,
|
||||
'margin_bottom' => 12,
|
||||
'margin_left' => 10,
|
||||
'margin_right' => 10,
|
||||
'tempDir' => runtime_path('mpdf'),
|
||||
'header_html' => '',
|
||||
'footer_html' => '',
|
||||
'watermark_text'=> '',
|
||||
'css_files' => [],
|
||||
'default_font' => 'notosanssc',
|
||||
'font_dirs' => [public_path('fonts')],
|
||||
'font_data' => [
|
||||
'notosanssc' => ['R'=>'NotoSansSC-Regular.ttf','B'=>'NotoSansSC-Bold.ttf'],
|
||||
],
|
||||
'asset_base' => '',
|
||||
'enable_html5_parser' => true,
|
||||
], $options);
|
||||
|
||||
$defaultConfig = (new ConfigVariables())->getDefaults();
|
||||
$defaultFontConfig = (new FontVariables())->getDefaults();
|
||||
|
||||
$fontDirs = array_merge($defaultConfig['fontDir'], $opts['font_dirs']);
|
||||
$fontData = array_merge($defaultFontConfig['fontdata'], $opts['font_data']);
|
||||
|
||||
$mpdf = new Mpdf([
|
||||
'format' => $opts['format'],
|
||||
'orientation' => $opts['orientation'],
|
||||
'margin_left' => $opts['margin_left'],
|
||||
'margin_right' => $opts['margin_right'],
|
||||
'margin_top' => $opts['margin_top'],
|
||||
'margin_bottom' => $opts['margin_bottom'],
|
||||
'tempDir' => $opts['tempDir'],
|
||||
'fontDir' => $fontDirs,
|
||||
'fontdata' => $fontData,
|
||||
'default_font' => $opts['default_font'],
|
||||
'enable_html5_parser' => $opts['enable_html5_parser'],
|
||||
]);
|
||||
|
||||
if ($opts['header_html']) $mpdf->SetHTMLHeader($opts['header_html']);
|
||||
if ($opts['footer_html']) $mpdf->SetHTMLFooter($opts['footer_html']);
|
||||
|
||||
if (!empty($opts['watermark_text'])) {
|
||||
$mpdf->SetWatermarkText($opts['watermark_text']);
|
||||
$mpdf->showWatermarkText = true;
|
||||
$mpdf->watermarkTextAlpha = 0.08;
|
||||
}
|
||||
|
||||
// 资源绝对化(如果你有相对路径的图片等)
|
||||
$html = PdfHelper::absolutizeAssetUrls($html, $opts['asset_base']);
|
||||
|
||||
// === 关键改动:把 <style>…</style> 抽出来,作为 HEADER_CSS 写入 ===
|
||||
[$inlineCss, $cleanHtml] = $this->extractCssAndCleanHtml($html);
|
||||
|
||||
// 先写外部 css_files
|
||||
if (!empty($opts['css_files'])) {
|
||||
foreach ($opts['css_files'] as $cssFile) {
|
||||
if (is_file($cssFile)) {
|
||||
$mpdf->WriteHTML(file_get_contents($cssFile), HTMLParserMode::HEADER_CSS);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 再写内联 <style> 的 CSS
|
||||
if ($inlineCss !== '') {
|
||||
$mpdf->WriteHTML($inlineCss, HTMLParserMode::HEADER_CSS);
|
||||
}
|
||||
|
||||
// 最后写 HTML 正文(已剔除 <style>,避免任何情况下把 CSS 当文字打印)
|
||||
$mpdf->WriteHTML($cleanHtml, HTMLParserMode::HTML_BODY);
|
||||
|
||||
return $mpdf->Output('', \Mpdf\Output\Destination::STRING_RETURN);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把所有 <style>...</style> 的内容拼成一段 CSS,并把这些 <style> 标签从 HTML 中移除
|
||||
* @return array{0:string,1:string} [css, htmlWithoutStyle]
|
||||
*/
|
||||
private function extractCssAndCleanHtml(string $html): array
|
||||
{
|
||||
$cssParts = [];
|
||||
// 抓取所有 <style ...>...</style>,DOTALL 支持跨行
|
||||
if (preg_match_all('/<style\b[^>]*>(.*?)<\/style>/is', $html, $m)) {
|
||||
foreach ($m[1] as $block) {
|
||||
// 去掉 HTML 注释,以防注释把 CSS 包起来
|
||||
$block = preg_replace('/<!--|-->/', '', $block);
|
||||
$cssParts[] = trim($block);
|
||||
}
|
||||
// 从 HTML 删除所有 <style> 块
|
||||
$html = preg_replace('/<style\b[^>]*>.*?<\/style>/is', '', $html);
|
||||
}
|
||||
$css = implode("\n\n", $cssParts);
|
||||
|
||||
// 额外保险:把 <head> 也清理掉,防止某些解析器把 head 里残余文本当正文
|
||||
$html = preg_replace('/<head\b[^>]*>.*?<\/head>/is', '', $html);
|
||||
|
||||
// 确保剩余 HTML 有 <body>,没有就包一层
|
||||
if (!preg_match('/<body\b/i', $html)) {
|
||||
$html = '<body>' . $html . '</body>';
|
||||
}
|
||||
return [$css, $html];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
// app/service/pdf/PdfHelper.php
|
||||
namespace app\common\utils\pdf\service;
|
||||
|
||||
class PdfHelper
|
||||
{
|
||||
/** 从文件加载 HTML(支持占位符 {{key}} 简单替换) */
|
||||
public static function loadTemplate(string $file, array $vars = []): string
|
||||
{
|
||||
if (!is_file($file)) {
|
||||
throw new \RuntimeException("Template not found: {$file}");
|
||||
}
|
||||
$html = file_get_contents($file);
|
||||
if ($vars) {
|
||||
$search = [];
|
||||
$replace = [];
|
||||
foreach ($vars as $k => $v) {
|
||||
$search[] = '{{' . $k . '}}';
|
||||
$replace[] = htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
$html = str_replace($search, $replace, $html);
|
||||
}
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 HTML 里的相对资源路径(img/link/script href/src)改成绝对路径
|
||||
* 仅处理以 ./ ../ 或非 http(s) 的相对量;base 传 public/assets/pdf 等目录
|
||||
*/
|
||||
public static function absolutizeAssetUrls(string $html, string $baseDir): string
|
||||
{
|
||||
$baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR);
|
||||
// img src
|
||||
$html = preg_replace_callback('#(<img[^>]+src=["\'])([^"\']+)(["\'])#i', function($m) use ($baseDir){
|
||||
$u = $m[2];
|
||||
if (preg_match('#^https?://#i', $u) || strpos($u, 'data:') === 0) return $m[0];
|
||||
$abs = realpath($baseDir . DIRECTORY_SEPARATOR . ltrim($u, '/')) ?: ($baseDir . '/' . ltrim($u, '/'));
|
||||
return $m[1] . $abs . $m[3];
|
||||
}, $html);
|
||||
|
||||
// link href(如果你在 HTML 里写了 <link>,通常建议走 css_files 方式,这里也兼容)
|
||||
$html = preg_replace_callback('#(<link[^>]+href=["\'])([^"\']+)(["\'])#i', function($m) use ($baseDir){
|
||||
$u = $m[2];
|
||||
if (preg_match('#^https?://#i', $u)) return $m[0];
|
||||
$abs = realpath($baseDir . DIRECTORY_SEPARATOR . ltrim($u, '/')) ?: ($baseDir . '/' . ltrim($u, '/'));
|
||||
return $m[1] . $abs . $m[3];
|
||||
}, $html);
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 渲染一个原生 PHP 模板为字符串
|
||||
* @param string $file 模板路径(如 resource/templates/stock-order.php)
|
||||
* @param array $vars 将在模板中以变量名存在(如 $data)
|
||||
* @return string 完整 HTML
|
||||
*/
|
||||
public static function render(string $file, array $vars = []): string
|
||||
{
|
||||
if (!is_file($file)) {
|
||||
throw new \RuntimeException("Template not found: {$file}");
|
||||
}
|
||||
// 将键名导出为同名变量,例如 'data' => [...] 变为 $data
|
||||
extract($vars, EXTR_OVERWRITE);
|
||||
|
||||
// 开启缓冲,将 include 的输出抓取为字符串
|
||||
ob_start();
|
||||
ob_implicit_flush(false);
|
||||
try {
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
include $file;
|
||||
} catch (\Throwable $e) {
|
||||
// 清理缓冲并抛出更清晰的异常
|
||||
ob_end_clean();
|
||||
throw $e;
|
||||
}
|
||||
return ob_get_clean();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
namespace app\common\utils\pdf\service;
|
||||
|
||||
final class PdfStorage
|
||||
{
|
||||
/**
|
||||
* @param string $pdfBin PDF 二进制
|
||||
* @param string|null $dir 保存目录,默认 runtime/pdf
|
||||
* @param string|null $name 文件名(不含目录),默认:stock-order-YYYYmmdd-His-uniqid.pdf
|
||||
* @return string 绝对路径
|
||||
*/
|
||||
public static function saveBinary(string $pdfBin, ?string $dir = null, ?string $name = null): string
|
||||
{
|
||||
$dir = $dir ?: runtime_path('pdf');
|
||||
if (!is_dir($dir)) {
|
||||
if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
|
||||
throw new \RuntimeException("Failed to create dir: {$dir}");
|
||||
}
|
||||
}
|
||||
|
||||
// 生成安全文件名
|
||||
$name = $name ?: ('stock-order-' . date('Ymd-His') . '-' . substr(uniqid('', true), -6) . '.pdf');
|
||||
$name = preg_replace('/[^a-zA-Z0-9_\-.]/', '_', $name); // 简易净化
|
||||
$path = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
|
||||
|
||||
// 先写入临时文件,再原子重命名,避免并发/写入中被读取
|
||||
$tmp = $path . '.part';
|
||||
if (file_put_contents($tmp, $pdfBin, LOCK_EX) === false) {
|
||||
throw new \RuntimeException("Failed to write temp file: {$tmp}");
|
||||
}
|
||||
if (!@rename($tmp, $path)) {
|
||||
@unlink($tmp);
|
||||
throw new \RuntimeException("Failed to move temp to: {$path}");
|
||||
}
|
||||
@chmod($path, 0664);
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>合塑实业-汽车事业部-备货单(客户下定)</title>
|
||||
<style>
|
||||
/* 横版:A4 297mm,左右各 12mm => 可用宽度 273mm */
|
||||
@page { margin: 12mm; }
|
||||
|
||||
body {
|
||||
font-family: 'notosanssc', 'DejaVu Sans', Arial, sans-serif;
|
||||
font-size: 10pt;
|
||||
line-height: 1.3;
|
||||
color: #000;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.container {
|
||||
width: 273mm; /* 横向版心 */
|
||||
margin: 0 auto;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 10pt;
|
||||
padding-bottom: 6pt;
|
||||
}
|
||||
.title {
|
||||
font-size: 14pt;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6pt;
|
||||
}
|
||||
.sub-title {
|
||||
font-size: 9pt;
|
||||
color: #000;
|
||||
margin: 0 6pt;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 10pt;
|
||||
font-size: 9pt;
|
||||
table-layout: fixed; /* 横向固定布局,配合 colgroup 更稳 */
|
||||
}
|
||||
th, td {
|
||||
border: 0.5pt solid #000;
|
||||
padding: 6pt 6pt;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
word-break: break-all;
|
||||
}
|
||||
th {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
/* 跨页友好 */
|
||||
thead { display: table-header-group; }
|
||||
tfoot { display: table-row-group; }
|
||||
tr, img { page-break-inside: avoid; }
|
||||
|
||||
/* 信息类表格左对齐 */
|
||||
.info-table td,
|
||||
.logistics-table td { text-align: left; }
|
||||
|
||||
.info-label { font-weight: bold; color: #000; }
|
||||
.info-value { color: #000; }
|
||||
|
||||
.summary-row {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.payment-title {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nowrap { white-space: nowrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<!-- 头部 -->
|
||||
<div class="header">
|
||||
<h1 class="title">合塑实业-汽车事业部-备货单(客户下定)</h1>
|
||||
<div>
|
||||
<span class="sub-title">备货单号: <?php echo htmlspecialchars($data['order_no'] ?? 'N/A'); ?></span>
|
||||
<span class="sub-title">业务员: <?php echo htmlspecialchars($data['salesperson_snapshot'] ?? ' - '); ?></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 基本信息 -->
|
||||
<table class="info-table">
|
||||
<colgroup>
|
||||
<col style="width:18%">
|
||||
<col style="width:15%">
|
||||
<col style="width:14%">
|
||||
<col style="width:14%">
|
||||
<col style="width:19%">
|
||||
<col style="width:20%">
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="info-label">阿里订单号/PI号:</span> <span class="info-value"><?php echo htmlspecialchars($data['pi_no'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['biz_date'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">清关目的国:</span> <span class="info-value"><?php echo htmlspecialchars($data['clearance_country_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户来源:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_source_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户名称:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户所在国:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_country_snapshot'] ?? ' - '); ?></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 产品列表 -->
|
||||
<table class="product-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>编号</th>
|
||||
<th>车型</th>
|
||||
<th>数量/台</th>
|
||||
<th>颜色/外</th>
|
||||
<th>颜色/内</th>
|
||||
<th>收款价</th>
|
||||
<th>总价</th>
|
||||
<th>官方指导价/二手挂牌价</th>
|
||||
<th>优惠</th>
|
||||
<th>利润</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (($data['veh_list'] ?? []) as $vehicle): ?>
|
||||
<tr>
|
||||
<td rowspan="3">
|
||||
<?php echo htmlspecialchars($vehicle['index'] ?? ' - '); ?>
|
||||
</td>
|
||||
<td rowspan="3">
|
||||
<?php echo htmlspecialchars($vehicle['model_snapshot'] ?? ' - '); ?>
|
||||
<?php if ($vehicle['mileage'] > 0): ?>
|
||||
<span class="nowrap">(<?php echo htmlspecialchars($vehicle['mileage']).'km'; ?>)</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td rowspan="3">
|
||||
<?php echo htmlspecialchars($vehicle['num'] ?? ' - '); ?>
|
||||
</td>
|
||||
<td><?php echo htmlspecialchars($vehicle['color_exterior_snapshot'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['color_interior_snapshot'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['unit_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['total_price']['currency_info'] ?? ' - '); ?></td>
|
||||
|
||||
<?php if ($vehicle['mileage'] > 0): ?>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['listing_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['reduction_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<?php else: ?>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['official_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['discount_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<?php endif; ?>
|
||||
|
||||
<td><?php echo htmlspecialchars($vehicle['profit']['currency_info'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
<tr style="background-color: #f0f0f0; font-weight: bold;">
|
||||
<th>改装费</th>
|
||||
<th>FOB运费</th>
|
||||
<th>车价</th>
|
||||
<th>海运费</th>
|
||||
<th>佣金</th>
|
||||
<th>挂账</th>
|
||||
<th>港杂</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><?php echo htmlspecialchars($vehicle['retrofit_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['fob_transport_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['car_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['ocean_freight']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['commission']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['retention_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['port_misc_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="1" style="text-align:left;">
|
||||
<span class="info-label">备注:</span>
|
||||
</td>
|
||||
<td colspan="9" style="text-align:left;">
|
||||
<span class="info-value"><?php echo $vehicle['remark']; ?></span>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="summary-row">
|
||||
<td colspan="5" style="text-align:left;">
|
||||
<span class="info-label">合同汇率:</span> <span class="info-value"><?php echo htmlspecialchars($data['contract_exchange_rate'] ?? ' - '); ?></span>
|
||||
</td>
|
||||
<td colspan="5" style="text-align:left;">
|
||||
<span class="info-label">合计到岸价:</span> <span class="info-value"><?php echo htmlspecialchars($data['cif_total']['currency_info'] ?? ' - '); ?></span>
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
|
||||
<!-- 物流信息 -->
|
||||
<table class="logistics-table">
|
||||
<colgroup>
|
||||
<col style="width:16%">
|
||||
<col style="width:18%">
|
||||
<col style="width:12%">
|
||||
<col style="width:18%">
|
||||
<col style="width:22%">
|
||||
<col style="width:14%">
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="info-label">清关人:</span> <span class="info-value"><?php echo htmlspecialchars($data['declarant_name'] ?? ' - '); ?></span></td>
|
||||
|
||||
<?php if ($data['is_final'] == 1): ?>
|
||||
<td><span class="info-label">全款收齐日:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['collect_all_date'] ?? ' - '); ?></span></td>
|
||||
<?php else: ?>
|
||||
<td><span class="info-label">预计发运日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['eta_ship_date'] ?? ' - '); ?></span></td>
|
||||
<?php endif; ?>
|
||||
|
||||
<td><span class="info-label">出运方式:</span> <span class="info-value"><?php echo htmlspecialchars($data['shipping_method_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">国内收货港:</span> <span class="info-value"><?php echo htmlspecialchars($data['domestic_port_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">贸易条款/清关目的港:</span> <span class="info-value"><?php echo htmlspecialchars($data['trade_term_snapshot'] ?? ' - '); ?>/<?php echo htmlspecialchars($data['clearance_port_snapshot'] ?? ' - '); ?></span></td>
|
||||
|
||||
<?php if ($data['is_final'] == 1): ?>
|
||||
<td><span class="info-label">提车日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['pick_up_date'] ?? ' - '); ?></span></td>
|
||||
<?php else: ?>
|
||||
<td><span class="info-label">最迟到港时间:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['latest_arrival_date'] ?? ' - '); ?></span></td>
|
||||
<?php endif; ?>
|
||||
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 计划收款信息 -->
|
||||
<table class="payment-table">
|
||||
<colgroup>
|
||||
<col style="width:12%">
|
||||
<col style="width:10%">
|
||||
<col style="width:14%">
|
||||
<col style="width:12%">
|
||||
<col style="width:12%">
|
||||
<col style="width:20%">
|
||||
<col style="width:10%">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:24mm" rowspan="<?php echo htmlspecialchars($data['acc_index']); ?>">计划收款信息</th>
|
||||
<th>序号</th>
|
||||
<th>汇款国</th>
|
||||
<th>日期</th>
|
||||
<th>币种</th>
|
||||
<th>账户</th>
|
||||
<th>汇款人</th>
|
||||
<th>金额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (($data['account_list'] ?? []) as $account): ?>
|
||||
<tr>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['index'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($account['remit_country_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['remit_date'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['currency_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['account_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td style="text-align:left;"><?php echo htmlspecialchars($account['remitter_name'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['amount'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- PDF 底部签名区 -->
|
||||
<div style="margin-top: 6mm; font-size: 12px;">
|
||||
<!-- 左侧:业务员签字 / 备发货负责人签字 -->
|
||||
<div style="width: 50%; float: left; text-align: left;">
|
||||
<!-- 行距通过 margin-bottom 控制;行内元素通过固定行高和 vertical-align: middle 垂直居中 -->
|
||||
<div style="height: 14mm; line-height: 14mm; margin-bottom: 5mm;">
|
||||
<span>业务员签字:</span>
|
||||
<?php if (!empty($data['sign_img_url'])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_img_url']); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div style="height: 14mm; line-height: 14mm;">
|
||||
<span>备发货负责人签字:</span>
|
||||
<?php if (!empty($data['sign_imgs'][1])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_imgs'][1]); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:组长签字 / 日期 -->
|
||||
<div style="width: 50%; float: right; text-align: left;">
|
||||
<div style="height: 14mm; line-height: 14mm; margin-bottom: 5mm;">
|
||||
<span>组长签字:</span>
|
||||
<?php if (!empty($data['sign_imgs'][0])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_imgs'][0]); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div style="height: 14mm; line-height: 14mm;">
|
||||
<span>日期:</span>
|
||||
<?php
|
||||
$_dt = $data['signed_date'] ?? ($data['created_at'] ?? '');
|
||||
if (is_numeric($_dt)) {
|
||||
echo htmlspecialchars(date('Y-m-d', (int)$_dt));
|
||||
} elseif (!empty($_dt)) {
|
||||
$t = strtotime($_dt);
|
||||
echo $t ? htmlspecialchars(date('Y-m-d', $t)) : ' - ';
|
||||
} else {
|
||||
echo ' - ';
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="clear: both;"></div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,326 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>合塑实业-汽车事业部-备货单(客户下定)</title>
|
||||
<style>
|
||||
/* 横版:A4 297mm,左右各 12mm => 可用宽度 273mm */
|
||||
@page { margin: 12mm; }
|
||||
|
||||
body {
|
||||
font-family: 'notosanssc', 'DejaVu Sans', Arial, sans-serif;
|
||||
font-size: 10pt;
|
||||
line-height: 1.3;
|
||||
color: #000;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.container {
|
||||
width: 273mm; /* 横向版心 */
|
||||
margin: 0 auto;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 10pt;
|
||||
padding-bottom: 6pt;
|
||||
}
|
||||
.title {
|
||||
font-size: 14pt;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6pt;
|
||||
}
|
||||
.sub-title {
|
||||
font-size: 9pt;
|
||||
color: #000;
|
||||
margin: 0 6pt;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 10pt;
|
||||
font-size: 9pt;
|
||||
table-layout: fixed; /* 横向固定布局,配合 colgroup 更稳 */
|
||||
}
|
||||
th, td {
|
||||
border: 0.5pt solid #000;
|
||||
padding: 6pt 6pt;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
word-break: break-all;
|
||||
}
|
||||
th {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
/* 跨页友好 */
|
||||
thead { display: table-header-group; }
|
||||
tfoot { display: table-row-group; }
|
||||
tr, img { page-break-inside: avoid; }
|
||||
|
||||
/* 信息类表格左对齐 */
|
||||
.info-table td,
|
||||
.logistics-table td { text-align: left; }
|
||||
|
||||
.info-label { font-weight: bold; color: #000; }
|
||||
.info-value { color: #000; }
|
||||
|
||||
.summary-row {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.payment-title {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nowrap { white-space: nowrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<!-- 头部 -->
|
||||
<div class="header">
|
||||
<h1 class="title">合塑实业-汽车事业部-备货单(客户下定)</h1>
|
||||
<div>
|
||||
<span class="sub-title">备货单号: <?php echo htmlspecialchars($data['order_no'] ?? 'N/A'); ?></span>
|
||||
<span class="sub-title">业务员: <?php echo htmlspecialchars($data['salesperson_snapshot'] ?? ' - '); ?></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 基本信息 -->
|
||||
<table class="info-table">
|
||||
<colgroup>
|
||||
<col style="width:18%">
|
||||
<col style="width:15%">
|
||||
<col style="width:14%">
|
||||
<col style="width:14%">
|
||||
<col style="width:19%">
|
||||
<col style="width:20%">
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="info-label">阿里订单号/PI号:</span> <span class="info-value"><?php echo htmlspecialchars($data['pi_no'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['biz_date'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">清关目的国:</span> <span class="info-value"><?php echo htmlspecialchars($data['clearance_country_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户来源:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_source_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户名称:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户所在国:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_country_snapshot'] ?? ' - '); ?></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 产品列表 -->
|
||||
<table class="product-table">
|
||||
<colgroup>
|
||||
<col style="width:6%">
|
||||
<col style="width:34%">
|
||||
<col style="width:6%">
|
||||
<col style="width:6%">
|
||||
<col style="width:6%">
|
||||
<col style="width:14%">
|
||||
<col style="width:8%">
|
||||
<col style="width:8%">
|
||||
<col style="width:6%">
|
||||
<col style="width:6%">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>编号</th>
|
||||
<th>车型</th>
|
||||
<th>数量/台</th>
|
||||
<th>颜色/外</th>
|
||||
<th>内饰</th>
|
||||
<th>改装</th>
|
||||
<th class="nowrap">官方指导价/二手挂牌价</th>
|
||||
<th class="nowrap">优惠</th>
|
||||
<th class="nowrap">单价</th>
|
||||
<th class="nowrap">总价</th>
|
||||
<th class="nowrap">报关价</th>
|
||||
<th class="nowrap">利润</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (($data['veh_list'] ?? []) as $vehicle): ?>
|
||||
<tr>
|
||||
<td><?php echo htmlspecialchars($vehicle['index'] ?? ' - '); ?></td>
|
||||
<td>
|
||||
<?php echo htmlspecialchars($vehicle['model_snapshot'] ?? ' - '); ?>
|
||||
<?php if ($vehicle['mileage'] > 0): ?>
|
||||
<span class="nowrap">(<?php echo htmlspecialchars($vehicle['mileage']).'km'; ?>)</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?php echo htmlspecialchars($vehicle['num'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['color_exterior_snapshot'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['color_interior_snapshot'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($vehicle['modify'] ?? ' - '); ?></td>
|
||||
|
||||
<?php if ($vehicle['mileage'] > 0): ?>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['listing_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['reduction_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<?php else: ?>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['official_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['discount_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<?php endif; ?>
|
||||
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['unit_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['total_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['clearance_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['profit']['currency_info'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="12" style="text-align:left;">
|
||||
<span class="info-label">备注:</span> <span class="info-value"><?php echo $vehicle['remark']; ?></span>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<tr class="summary-row">
|
||||
<td colspan="6" style="text-align:left;">
|
||||
<span class="info-label">合同汇率:</span> <span class="info-value"><?php echo htmlspecialchars($data['contract_exchange_rate'] ?? ' - '); ?></span>
|
||||
</td>
|
||||
<td colspan="6" style="text-align:left;">
|
||||
<span class="info-label">合计到岸价:</span> <span class="info-value"><?php echo htmlspecialchars($data['cif_total_amount']['currency_info'] ?? ' - '); ?></span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 物流信息 -->
|
||||
<table class="logistics-table">
|
||||
<colgroup>
|
||||
<col style="width:16%">
|
||||
<col style="width:18%">
|
||||
<col style="width:12%">
|
||||
<col style="width:18%">
|
||||
<col style="width:22%">
|
||||
<col style="width:14%">
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="info-label">清关人:</span> <span class="info-value"><?php echo htmlspecialchars($data['declarant_name'] ?? ' - '); ?></span></td>
|
||||
|
||||
<?php if ($data['is_final'] == 1): ?>
|
||||
<td><span class="info-label">全款收齐日:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['collect_all_date'] ?? ' - '); ?></span></td>
|
||||
<?php else: ?>
|
||||
<td><span class="info-label">预计发运日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['eta_ship_date'] ?? ' - '); ?></span></td>
|
||||
<?php endif; ?>
|
||||
|
||||
<td><span class="info-label">出运方式:</span> <span class="info-value"><?php echo htmlspecialchars($data['shipping_method_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">国内收货港:</span> <span class="info-value"><?php echo htmlspecialchars($data['domestic_port_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">贸易条款/清关目的港:</span> <span class="info-value"><?php echo htmlspecialchars($data['trade_term_snapshot'] ?? ' - '); ?>/<?php echo htmlspecialchars($data['clearance_port_snapshot'] ?? ' - '); ?></span></td>
|
||||
|
||||
<?php if ($data['is_final'] == 1): ?>
|
||||
<td><span class="info-label">提车日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['pick_up_date'] ?? ' - '); ?></span></td>
|
||||
<?php else: ?>
|
||||
<td><span class="info-label">最迟到港时间:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['latest_arrival_date'] ?? ' - '); ?></span></td>
|
||||
<?php endif; ?>
|
||||
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 计划收款信息 -->
|
||||
<table class="payment-table">
|
||||
<colgroup>
|
||||
<col style="width:12%">
|
||||
<col style="width:10%">
|
||||
<col style="width:14%">
|
||||
<col style="width:12%">
|
||||
<col style="width:12%">
|
||||
<col style="width:20%">
|
||||
<col style="width:10%">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:24mm" rowspan="<?php echo htmlspecialchars($data['acc_index']); ?>">计划收款信息</th>
|
||||
<th>序号</th>
|
||||
<th>汇款国</th>
|
||||
<th>日期</th>
|
||||
<th>币种</th>
|
||||
<th>账户</th>
|
||||
<th>汇款人</th>
|
||||
<th>金额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (($data['account_list'] ?? []) as $account): ?>
|
||||
<tr>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['index'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($account['remit_country_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['remit_date'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['currency_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['account_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td style="text-align:left;"><?php echo htmlspecialchars($account['remitter_name'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['amount'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- PDF 底部签名区 -->
|
||||
<div style="margin-top: 6mm; font-size: 12px;">
|
||||
<!-- 左侧:业务员签字 / 备发货负责人签字 -->
|
||||
<div style="width: 50%; float: left; text-align: left;">
|
||||
<!-- 行距通过 margin-bottom 控制;行内元素通过固定行高和 vertical-align: middle 垂直居中 -->
|
||||
<div style="height: 14mm; line-height: 14mm; margin-bottom: 5mm;">
|
||||
<span>业务员签字:</span>
|
||||
<?php if (!empty($data['sign_img_url'])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_img_url']); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div style="height: 14mm; line-height: 14mm;">
|
||||
<span>备发货负责人签字:</span>
|
||||
<?php if (!empty($data['sign_imgs'][1])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_imgs'][1]); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:组长签字 / 日期 -->
|
||||
<div style="width: 50%; float: right; text-align: left;">
|
||||
<div style="height: 14mm; line-height: 14mm; margin-bottom: 5mm;">
|
||||
<span>组长签字:</span>
|
||||
<?php if (!empty($data['sign_imgs'][0])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_imgs'][0]); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div style="height: 14mm; line-height: 14mm;">
|
||||
<span>日期:</span>
|
||||
<?php
|
||||
$_dt = $data['signed_date'] ?? ($data['created_at'] ?? '');
|
||||
if (is_numeric($_dt)) {
|
||||
echo htmlspecialchars(date('Y-m-d', (int)$_dt));
|
||||
} elseif (!empty($_dt)) {
|
||||
$t = strtotime($_dt);
|
||||
echo $t ? htmlspecialchars(date('Y-m-d', $t)) : ' - ';
|
||||
} else {
|
||||
echo ' - ';
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="clear: both;"></div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,379 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>合塑实业-汽车事业部-备货单(客户下定)</title>
|
||||
<style>
|
||||
/* 横版:A4 297mm,左右各 12mm => 可用宽度 273mm */
|
||||
@page { margin: 12mm; }
|
||||
|
||||
body {
|
||||
font-family: 'notosanssc', 'DejaVu Sans', Arial, sans-serif;
|
||||
font-size: 10pt;
|
||||
line-height: 1.3;
|
||||
color: #000;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.container {
|
||||
width: 273mm; /* 横向版心 */
|
||||
margin: 0 auto;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 10pt;
|
||||
padding-bottom: 6pt;
|
||||
}
|
||||
.title {
|
||||
font-size: 14pt;
|
||||
font-weight: bold;
|
||||
margin-bottom: 6pt;
|
||||
}
|
||||
.sub-title {
|
||||
font-size: 9pt;
|
||||
color: #000;
|
||||
margin: 0 6pt;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 10pt;
|
||||
font-size: 9pt;
|
||||
table-layout: fixed; /* 横向固定布局,配合 colgroup 更稳 */
|
||||
}
|
||||
th, td {
|
||||
border: 0.5pt solid #000;
|
||||
padding: 6pt 6pt;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
word-break: break-all;
|
||||
}
|
||||
th {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
/* 跨页友好 */
|
||||
thead { display: table-header-group; }
|
||||
tfoot { display: table-row-group; }
|
||||
tr, img { page-break-inside: avoid; }
|
||||
|
||||
/* 信息类表格左对齐 */
|
||||
.info-table td,
|
||||
.logistics-table td { text-align: left; }
|
||||
|
||||
.info-label { font-weight: bold; color: #000; }
|
||||
.info-value { color: #000; }
|
||||
|
||||
.summary-row {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.payment-title {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nowrap { white-space: nowrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<!-- 头部 -->
|
||||
<div class="header">
|
||||
<h1 class="title">合塑实业-汽车事业部-备货单<?php if ($data['is_final'] == 0) { echo '(客户下定)'; } else { echo '(终版)'; } ?></h1>
|
||||
<div>
|
||||
<span class="sub-title">备货单号: <?php echo htmlspecialchars($data['order_no'] ?? 'N/A'); ?></span>
|
||||
<span class="sub-title">业务员: <?php echo htmlspecialchars($data['salesperson_snapshot'] ?? ' - '); ?></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 基本信息 -->
|
||||
<table class="info-table">
|
||||
<colgroup>
|
||||
<col style="width:18%">
|
||||
<col style="width:15%">
|
||||
<col style="width:14%">
|
||||
<col style="width:14%">
|
||||
<col style="width:19%">
|
||||
<col style="width:20%">
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="info-label">阿里订单号/PI号:</span> <span class="info-value"><?php echo htmlspecialchars($data['pi_no'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['biz_date'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">清关目的国:</span> <span class="info-value"><?php echo htmlspecialchars($data['clearance_country_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户来源:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_source_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户名称:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">客户所在国:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_country_snapshot'] ?? ' - '); ?></span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 产品列表 -->
|
||||
<table class="product-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>编号</th>
|
||||
<th>车型</th>
|
||||
<th>数量</th>
|
||||
<th>颜色</th>
|
||||
<th colspan="8">费用明细</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<?php foreach (($data['veh_list'] ?? []) as $vehicle): ?>
|
||||
<!-- ===== 每辆车分组:4行费用 + 1行备注 ===== -->
|
||||
<!-- 行1:左侧4列用 rowspan,右侧为“费用明细(1)”标题 -->
|
||||
<tr>
|
||||
<!-- 编号 跨5行(含备注行) -->
|
||||
<td rowspan="5">
|
||||
<?php echo htmlspecialchars($vehicle['index'] ?? ' - '); ?>
|
||||
</td>
|
||||
|
||||
<!-- 车型 跨4行(不含备注行) -->
|
||||
<td rowspan="4">
|
||||
<?php echo htmlspecialchars($vehicle['model_snapshot'] ?? ' - '); ?><br/><br/>
|
||||
<?php if (!empty($vehicle['mileage']) && $vehicle['mileage'] > 0): ?>
|
||||
<span class="nowrap">里程:<?php echo htmlspecialchars($vehicle['mileage']); ?>km</span>
|
||||
<?php endif; ?><br/>
|
||||
<?php if ($vehicle['vin']): ?>
|
||||
<span class="nowrap">VIN:<?php echo htmlspecialchars($vehicle['vin']); ?></span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
|
||||
<!-- 数量 跨4行 -->
|
||||
<td rowspan="4">
|
||||
<?php echo htmlspecialchars($vehicle['num'] ?? ' - '); ?>
|
||||
</td>
|
||||
|
||||
<!-- 颜色 跨4行:把外/内合并展示 -->
|
||||
<td rowspan="4" style="text-align:left;">
|
||||
外饰:<?php echo htmlspecialchars($vehicle['color_exterior_snapshot'] ?? ' - '); ?><br><br>
|
||||
内饰:<?php echo htmlspecialchars($vehicle['color_interior_snapshot'] ?? ' - '); ?>
|
||||
</td>
|
||||
|
||||
<!-- 费用明细(第1组)标题 -->
|
||||
<th>手续费</th>
|
||||
<th>改装费</th>
|
||||
<th>配件费</th>
|
||||
<th>收款价</th>
|
||||
<th>总价</th>
|
||||
<th>官方指导价/二手挂牌价</th>
|
||||
<th>优惠</th>
|
||||
<th>利润</th>
|
||||
</tr>
|
||||
|
||||
<!-- 行2:费用明细(第1组)数据 -->
|
||||
<tr>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['handling_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['retrofit_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['accessory_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['unit_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['total_price']['currency_info'] ?? ' - '); ?></td>
|
||||
|
||||
<?php if (!empty($vehicle['mileage']) && $vehicle['mileage'] > 0): ?>
|
||||
<!-- 二手:挂牌价 + 优惠(减价) -->
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['listing_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['reduction_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<?php else: ?>
|
||||
<!-- 新车:官方指导价 + 优惠 -->
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['official_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['discount_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<?php endif; ?>
|
||||
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['profit']['currency_info'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
|
||||
<!-- 行3:费用明细(第2组)标题 -->
|
||||
<tr>
|
||||
<th>加价</th>
|
||||
<th>报关价</th>
|
||||
<th>FOB运费</th>
|
||||
<th>车价</th>
|
||||
<th>海运费</th>
|
||||
<th>佣金</th>
|
||||
<th>挂账</th>
|
||||
<th>港杂</th>
|
||||
</tr>
|
||||
|
||||
<!-- 行4:费用明细(第2组)数据 -->
|
||||
<tr>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['increase_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['clearance_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['fob_transport_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['car_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['ocean_freight']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['commission']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['retention_price']['currency_info'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($vehicle['port_misc_fee']['currency_info'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
|
||||
<!-- 行5:备注(因为“编号”已跨到本行,所以这里合并剩余10列) -->
|
||||
<tr>
|
||||
<td colspan="1"><strong>备注</strong></td>
|
||||
<td colspan="10" style="text-align:left;">
|
||||
<span class="info-value">
|
||||
<?php echo nl2br($vehicle['remark'] ?? ''); ?>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<!-- ===== 分组结束 ===== -->
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
|
||||
<tfoot>
|
||||
<tr class="summary-row">
|
||||
<!-- 注意:tfoot 没有跨行单元格,总列=11,所以采用 4 + 7 -->
|
||||
<td colspan="4" style="text-align:left;">
|
||||
<span class="info-label">合同汇率:</span>
|
||||
<span class="info-value"><?php echo htmlspecialchars($data['contract_exchange_rate'] ?? ' - '); ?></span>
|
||||
</td>
|
||||
<td colspan="8" style="text-align:left;">
|
||||
<span class="info-label">合计到岸价:</span>
|
||||
<span class="info-value"><?php echo htmlspecialchars($data['cif_total']['currency_info'] ?? ' - '); ?></span>
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
|
||||
<!-- 物流信息 -->
|
||||
<table class="logistics-table">
|
||||
<colgroup>
|
||||
<col style="width:16%">
|
||||
<col style="width:18%">
|
||||
<col style="width:12%">
|
||||
<col style="width:18%">
|
||||
<col style="width:22%">
|
||||
<col style="width:14%">
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="info-label">清关人:</span> <span class="info-value"><?php echo htmlspecialchars($data['declarant_name'] ?? ' - '); ?></span></td>
|
||||
|
||||
<?php if ($data['is_final'] == 1): ?>
|
||||
<td><span class="info-label">全款收齐日:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['collect_all_date'] ?? ' - '); ?></span></td>
|
||||
<?php else: ?>
|
||||
<td><span class="info-label">预计发运日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['eta_ship_date'] ?? ' - '); ?></span></td>
|
||||
<?php endif; ?>
|
||||
|
||||
<td><span class="info-label">出运方式:</span> <span class="info-value"><?php echo htmlspecialchars($data['shipping_method_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">国内收货港:</span> <span class="info-value"><?php echo htmlspecialchars($data['domestic_port_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">贸易条款:</span> <span class="info-value"><?php echo htmlspecialchars($data['trade_term_snapshot'] ?? ' - '); ?></span></td>
|
||||
<td><span class="info-label">清关目的港:</span> <span class="info-value"><?php echo htmlspecialchars($data['clearance_port_snapshot'] ?? ' - '); ?></span></td>
|
||||
|
||||
<?php if ($data['is_final'] == 1): ?>
|
||||
<td><span class="info-label">提车日期:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['pick_up_date'] ?? ' - '); ?></span></td>
|
||||
<?php else: ?>
|
||||
<td><span class="info-label">最迟到港时间:</span> <span class="info-value nowrap"><?php echo htmlspecialchars($data['latest_arrival_date'] ?? ' - '); ?></span></td>
|
||||
<?php endif; ?>
|
||||
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 计划收款信息 -->
|
||||
<table class="payment-table">
|
||||
<colgroup>
|
||||
<col style="width:12%">
|
||||
<col style="width:10%">
|
||||
<col style="width:14%">
|
||||
<col style="width:12%">
|
||||
<col style="width:12%">
|
||||
<col style="width:20%">
|
||||
<col style="width:10%">
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:24mm" rowspan="<?php echo htmlspecialchars($data['acc_index']); ?>">计划收款信息</th>
|
||||
<th>序号</th>
|
||||
<th>汇款国</th>
|
||||
<th>日期</th>
|
||||
<th>币种</th>
|
||||
<th>账户</th>
|
||||
<th>汇款人</th>
|
||||
<th>金额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (($data['account_list'] ?? []) as $account): ?>
|
||||
<tr>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['index'] ?? ' - '); ?></td>
|
||||
<td><?php echo htmlspecialchars($account['remit_country_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['remit_date'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['currency_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['account_name_snapshot'] ?? ' - '); ?></td>
|
||||
<td style="text-align:left;"><?php echo htmlspecialchars($account['remitter_name'] ?? ' - '); ?></td>
|
||||
<td class="nowrap"><?php echo htmlspecialchars($account['amount'] ?? ' - '); ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- PDF 底部签名区 -->
|
||||
<div style="margin-top: 6mm; font-size: 12px;">
|
||||
<!-- 左侧:业务员签字 / 备发货负责人签字 -->
|
||||
<div style="width: 50%; float: left; text-align: left;">
|
||||
<!-- 行距通过 margin-bottom 控制;行内元素通过固定行高和 vertical-align: middle 垂直居中 -->
|
||||
<div style="height: 14mm; line-height: 14mm; margin-bottom: 5mm;">
|
||||
<span>业务员签字:</span>
|
||||
<?php if (!empty($data['sign_img_url'])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_img_url']); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div style="height: 14mm; line-height: 14mm;">
|
||||
<span>备发货负责人签字:</span>
|
||||
<?php if (!empty($data['sign_imgs'][1])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_imgs'][1]); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:组长签字 / 日期 -->
|
||||
<div style="width: 50%; float: right; text-align: left;">
|
||||
<div style="height: 14mm; line-height: 14mm; margin-bottom: 5mm;">
|
||||
<span>组长签字:</span>
|
||||
<?php if (!empty($data['sign_imgs'][0])): ?>
|
||||
<img src="<?php echo htmlspecialchars($data['sign_imgs'][0]); ?>" style="height: 12mm; vertical-align: middle;">
|
||||
<?php else: ?>
|
||||
<span style="display:inline-block; width:21mm; height:12mm; vertical-align: middle; border-bottom:0.2mm solid #000;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div style="height: 14mm; line-height: 14mm;">
|
||||
<span>日期:</span>
|
||||
<?php
|
||||
$_dt = $data['signed_date'] ?? ($data['created_at'] ?? '');
|
||||
if (is_numeric($_dt)) {
|
||||
echo htmlspecialchars(date('Y-m-d', (int)$_dt));
|
||||
} elseif (!empty($_dt)) {
|
||||
$t = strtotime($_dt);
|
||||
echo $t ? htmlspecialchars(date('Y-m-d', $t)) : ' - ';
|
||||
} else {
|
||||
echo ' - ';
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="clear: both;"></div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\scaffold;
|
||||
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
use app\common\utils\TableInspector;
|
||||
|
||||
class Generate
|
||||
{
|
||||
|
||||
// 配置项
|
||||
protected $options = [];
|
||||
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
if (empty($options)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
public function doGenerate()
|
||||
{
|
||||
$fs = new Filesystem();
|
||||
|
||||
$templateDir = __DIR__ . '/templates/';
|
||||
|
||||
$resultStr = '';
|
||||
|
||||
if (!empty($this->options['controller'])) {
|
||||
$controllerPath = __DIR__ . "/../../../{$this->options['controller']['module']}/controller/".$this->rName($this->options['controller']['name'])."Controller.php";
|
||||
$fs->mkdir(__DIR__ . "/../../../{$this->options['controller']['module']}/controller");
|
||||
$this->deleteFileIfExists($controllerPath);
|
||||
$ControllerStub = $this->generateFile($templateDir, 'ControllerStub.stub', $controllerPath, 'controller');
|
||||
$resultStr .= $ControllerStub;
|
||||
}
|
||||
|
||||
if (!empty($this->options['service'])) {
|
||||
$servicePath = __DIR__ . "/../../../{$this->options['service']['module']}/service/".$this->rName($this->options['service']['name'])."Service.php";
|
||||
$fs->mkdir(__DIR__ . "/../../../{$this->options['service']['module']}/service");
|
||||
$this->deleteFileIfExists($servicePath);
|
||||
$ServiceStub = $this->generateFile($templateDir, 'ServiceStub.stub', $servicePath, 'service');
|
||||
$resultStr .= $ServiceStub;
|
||||
}
|
||||
|
||||
if (!empty($this->options['logic'])) {
|
||||
$logicPath = __DIR__ . "/../../../{$this->options['logic']['module']}/logic/".$this->rName($this->options['logic']['name'])."Logic.php";
|
||||
$fs->mkdir(__DIR__ . "/../../../{$this->options['logic']['module']}/logic");
|
||||
$this->deleteFileIfExists($logicPath);
|
||||
$LogicStub = $this->generateFile($templateDir, 'LogicStub.stub', $logicPath, 'logic');
|
||||
$resultStr .= $LogicStub;
|
||||
}
|
||||
|
||||
if (!empty($this->options['model'])) {
|
||||
$modelPath = __DIR__ . "/../../../{$this->options['model']['module']}/model/".$this->rName($this->options['model']['name']).".php";
|
||||
$fs->mkdir(__DIR__ . "/../../../{$this->options['model']['module']}/model");
|
||||
$this->deleteFileIfExists($modelPath);
|
||||
$ModelStub = $this->generateFile($templateDir, 'ModelStub.stub', $modelPath, 'model');
|
||||
$resultStr .= $ModelStub;
|
||||
}
|
||||
|
||||
if (!empty($this->options['validate'])) {
|
||||
$validatePath = __DIR__ . "/../../../{$this->options['validate']['module']}/validate/".$this->rName($this->options['validate']['name'])."Validate.php";
|
||||
$fs->mkdir(__DIR__ . "/../../../{$this->options['validate']['module']}/validate");
|
||||
$this->deleteFileIfExists($validatePath);
|
||||
$ValidatorStub = $this->generateFile($templateDir, 'ValidateStub.stub', $validatePath, 'validate');
|
||||
$resultStr .= $ValidatorStub;
|
||||
}
|
||||
|
||||
return $resultStr ? $resultStr . "<info>文件生成成功!</info> <br/>" : '未生成任何文件';
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据模板生成文件
|
||||
*
|
||||
* @param string $templateDir 模板目录
|
||||
* @param string $templateFile 模板文件名
|
||||
* @param string $outputPath 输出文件路径
|
||||
*/
|
||||
protected function generateFile($templateDir, $templateFile, $outputPath, $fileType)
|
||||
{
|
||||
$templatePath = $templateDir . $templateFile;
|
||||
|
||||
if (!file_exists($templatePath)) {
|
||||
echo "<error>模板文件 {$templateFile} 不存在!</error> \n";
|
||||
return;
|
||||
}
|
||||
|
||||
$content = file_get_contents($templatePath);
|
||||
|
||||
switch ($fileType) {
|
||||
case 'controller':
|
||||
$content = str_replace('{{controllerModule}}', $this->options['controller']['module'], $content);
|
||||
$content = str_replace('{{serviceModule}}', $this->options['service']['module'], $content);
|
||||
$content = str_replace('{{serviceName}}', $this->rName($this->options['service']['name']), $content);
|
||||
$content = str_replace('{{controllerName}}', $this->rName($this->options['controller']['name']), $content);
|
||||
break;
|
||||
case 'service':
|
||||
$content = str_replace('{{serviceModule}}', $this->options['service']['module'], $content);
|
||||
$content = str_replace('{{validateModule}}', $this->options['validate']['module'], $content);
|
||||
$content = str_replace('{{validateName}}', $this->rName($this->options['validate']['name']), $content);
|
||||
$content = str_replace('{{modelModule}}', $this->options['model']['module'], $content);
|
||||
$content = str_replace('{{modelName}}', $this->rName($this->options['model']['name']), $content);
|
||||
$content = str_replace('{{serviceName}}', $this->rName($this->options['service']['name']), $content);
|
||||
break;
|
||||
case 'logic':
|
||||
$content = str_replace('{{logicModule}}', $this->options['logic']['module'], $content);
|
||||
$content = str_replace('{{modelModule}}', $this->options['model']['module'], $content);
|
||||
$content = str_replace('{{modelName}}', $this->rName($this->options['model']['name']), $content);
|
||||
$content = str_replace('{{logicName}}', $this->rName($this->options['logic']['name']), $content);
|
||||
break;
|
||||
case 'model':
|
||||
$content = str_replace('{{modelModule}}', $this->options['model']['module'], $content);
|
||||
$content = str_replace('{{modelName}}', $this->rName($this->options['model']['name']), $content);
|
||||
$content = str_replace('{{table}}', $this->options['table'], $content);
|
||||
$content = str_replace('{{fillable}}', $this->fillableFields(), $content);
|
||||
break;
|
||||
case 'validate':
|
||||
$content = str_replace('{{validateModule}}', $this->options['validate']['module'], $content);
|
||||
$content = str_replace('{{validateName}}', $this->rName($this->options['validate']['name']), $content);
|
||||
break;
|
||||
}
|
||||
|
||||
file_put_contents($outputPath, $content);
|
||||
|
||||
return "生成文件: <info>{$outputPath}</info> <br/>";
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置字段
|
||||
*
|
||||
* @param array $fields 字段数组
|
||||
*/
|
||||
public function fillableFields()
|
||||
{
|
||||
$tableName = $this->options['table'];
|
||||
$fields = TableInspector::getColumnNames($tableName);
|
||||
$str = '';
|
||||
foreach ($fields as $key => $val) {
|
||||
if ($key < (count($fields)-1)) {
|
||||
$str .= "'{$val}', ";
|
||||
} else {
|
||||
$str .= "'{$val}'";
|
||||
}
|
||||
}
|
||||
$fields = trim($str, '"');
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果文件存在,删除它
|
||||
*
|
||||
* @param string $path 文件路径
|
||||
*/
|
||||
protected function deleteFileIfExists($path)
|
||||
{
|
||||
if (file_exists($path)) {
|
||||
// "文件: <comment>{$path}</comment> 已存在,核对后手动删除。\n";
|
||||
// return;
|
||||
|
||||
unlink($path);
|
||||
echo "删除已存在文件: <comment>{$path}</comment> \n";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置名称
|
||||
*/
|
||||
public function rName($name = '')
|
||||
{
|
||||
return ucfirst(camelize($name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下划线转驼峰
|
||||
* 思路:
|
||||
* step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
|
||||
* step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
|
||||
*/
|
||||
function camelize($uncamelized_words, $separator='_') {
|
||||
$uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
|
||||
return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名转下划线命名
|
||||
* 思路:
|
||||
* 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
|
||||
*/
|
||||
function uncamelize($camelCaps, $separator='_') {
|
||||
return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
namespace app\{{controllerModule}}\controller;
|
||||
|
||||
use app\common\controller\BaseController;
|
||||
use app\common\traits\crud\CrudControllerTrait;
|
||||
use app\{{serviceModule}}\service\{{serviceName}}Service;
|
||||
|
||||
class {{controllerName}}Controller extends BaseController
|
||||
{
|
||||
use CrudControllerTrait;
|
||||
|
||||
protected $service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->service = new {{serviceName}}Service();
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表页数据格式化
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
// protected function indexFormat($data)
|
||||
// {
|
||||
// if (isset($data['created_at']))
|
||||
// $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
|
||||
// if (isset($data['updated_at']))
|
||||
// $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
|
||||
// return $data;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>客户信息 - {{order_no}}</title>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 20px;
|
||||
color: #343a40;
|
||||
}
|
||||
|
||||
.email-container {
|
||||
max-width: 800px;
|
||||
width: 100%;
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
|
||||
border-top: 5px solid #4361ee;
|
||||
}
|
||||
|
||||
.email-header {
|
||||
background: linear-gradient(120deg, #4361ee, #3a0ca3);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
text-align: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 15px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.8rem;
|
||||
margin-bottom: 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.1rem;
|
||||
opacity: 0.9;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.sn-badge {
|
||||
background: #ff9e00;
|
||||
color: white;
|
||||
padding: 6px 15px;
|
||||
border-radius: 20px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
display: inline-block;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.email-body {
|
||||
padding: 40px;
|
||||
}
|
||||
|
||||
.info-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 25px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.info-card {
|
||||
background: #f8f9fa;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
transition: all 0.3s ease;
|
||||
border-left: 4px solid #4361ee;
|
||||
}
|
||||
|
||||
.info-card:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1rem;
|
||||
color: #6c757d;
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.card-title i {
|
||||
margin-right: 10px;
|
||||
color: #4361ee;
|
||||
}
|
||||
|
||||
.card-value {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 600;
|
||||
color: #212529;
|
||||
}
|
||||
|
||||
.status-container {
|
||||
background: #e7f5ff;
|
||||
border-radius: 10px;
|
||||
padding: 25px;
|
||||
margin: 30px 0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border: 1px dashed #4dabf7;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
padding: 8px 20px;
|
||||
border-radius: 30px;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.status-badge.copper {
|
||||
background: #cd7f32;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.status-badge.pending {
|
||||
background: #ffd8a8;
|
||||
color: #e67700;
|
||||
}
|
||||
|
||||
.details-section {
|
||||
background: #f8f9fa;
|
||||
border-radius: 10px;
|
||||
padding: 25px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1.3rem;
|
||||
margin-bottom: 20px;
|
||||
color: #212529;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border-bottom: 2px solid #dee2e6;
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.section-title i {
|
||||
margin-right: 10px;
|
||||
color: #4361ee;
|
||||
}
|
||||
|
||||
.details-content {
|
||||
line-height: 1.8;
|
||||
color: #495057;
|
||||
}
|
||||
|
||||
.email-footer {
|
||||
background: #f1f3f5;
|
||||
padding: 25px;
|
||||
text-align: center;
|
||||
color: #868e96;
|
||||
font-size: 0.9rem;
|
||||
border-top: 1px solid #dee2e6;
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 20px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.footer-links a {
|
||||
color: #495057;
|
||||
text-decoration: none;
|
||||
transition: color 0.3s;
|
||||
}
|
||||
|
||||
.footer-links a:hover {
|
||||
color: #4361ee;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.info-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.email-header {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.email-body {
|
||||
padding: 25px;
|
||||
}
|
||||
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.status-container {
|
||||
flex-direction: column;
|
||||
}
|
||||
.status-item {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.left{
|
||||
width: 100%;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.right{
|
||||
width: 100%;
|
||||
}
|
||||
.copper{
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="email-container">
|
||||
<div class="email-header">
|
||||
<div class="header-content">
|
||||
<div class="logo">
|
||||
<i class="fas fa-user-tie"></i>
|
||||
</div>
|
||||
<h1>客户信息详情</h1>
|
||||
<!--<p class="subtitle">此邮件包含客户详细信息及业务状态,请及时处理</p>-->
|
||||
<div class="sn-badge">编号: {{order_no}}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="email-body">
|
||||
<div class="info-grid">
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-user"></i> 客户名称
|
||||
</div>
|
||||
<div class="card-value">{{contacts}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-phone"></i> 电话
|
||||
</div>
|
||||
<div class="card-value">{{tel}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-globe"></i> 国家/地区
|
||||
</div>
|
||||
<div class="card-value">{{country}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-chart-line"></i> 渠道
|
||||
</div>
|
||||
<div class="card-value">{{channel}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-envelope"></i> 邮箱
|
||||
</div>
|
||||
<div class="card-value">{{email}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fab fa-whatsapp"></i> WhatsApp
|
||||
</div>
|
||||
<div class="card-value">{{whatsapp}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-user-plus"></i> 发布人
|
||||
</div>
|
||||
<div class="card-value">{{enter_user_id}}</div>
|
||||
</div>
|
||||
|
||||
<div class="info-card">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-user-check"></i> 跟踪人
|
||||
</div>
|
||||
<div class="card-value">{{recipient}}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="status-container">
|
||||
<div class="left">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-history"></i> 录单时间
|
||||
</div>
|
||||
<div class="card-value">{{r_time}}</div>
|
||||
</div>
|
||||
|
||||
<div class="right">
|
||||
<div class="card-title">
|
||||
<i class="fas fa-medal"></i> 商机等级
|
||||
</div>
|
||||
<div class="status-badge copper">{{quality}}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="details-section">
|
||||
<h3 class="section-title">
|
||||
<i class="fas fa-file-alt"></i> 详情内容
|
||||
</h3>
|
||||
<div class="details-content">
|
||||
{{content}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="email-footer">
|
||||
<p>© 2025 客户关系管理系统 | 企业客户管理平台</p>
|
||||
<div class="footer-links">
|
||||
<a href="https://www.hnxinyouhe.com"><i class="fas fa-globe"></i> 公司官网</a>
|
||||
<a href="https://www.hnxinyouhe.com"><i class="fas fa-headset"></i> 支持中心</a>
|
||||
<a href="https://www.hnxinyouhe.com"><i class="fas fa-lock"></i> 隐私政策</a>
|
||||
</div>
|
||||
<p style="margin-top: 15px;">此邮件为系统自动生成,请勿直接回复</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 添加简单的交互效果
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const infoCards = document.querySelectorAll('.info-card');
|
||||
|
||||
infoCards.forEach(card => {
|
||||
card.addEventListener('click', function() {
|
||||
this.classList.toggle('active');
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace app\{{logicModule}}\logic;
|
||||
|
||||
use app\common\traits\crud\CrudLogicTrait;
|
||||
use app\{{modelModule}}\model\{{modelName}};
|
||||
|
||||
class {{logicName}}Logic
|
||||
{
|
||||
use CrudLogicTrait;
|
||||
|
||||
/**
|
||||
* 指定当前要操作的模型
|
||||
*/
|
||||
protected string $modelClass = {{modelName}}::class;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace app\{{modelModule}}\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
class {{modelName}} extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = '{{table}}';
|
||||
|
||||
/**
|
||||
* The primary key associated with the table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = true;
|
||||
|
||||
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
/**
|
||||
* 允许自动填充模型字段
|
||||
*/
|
||||
protected $fillable = [{{fillable}}];
|
||||
|
||||
/**
|
||||
* 不允许自动填充模型字段
|
||||
*/
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace app\{{serviceModule}}\service;
|
||||
|
||||
use app\{{validateModule}}\validate\{{validateName}}Validate;
|
||||
use app\common\traits\crud\CrudServiceTrait;
|
||||
use app\{{modelModule}}\model\{{modelName}};
|
||||
|
||||
class {{serviceName}}Service
|
||||
{
|
||||
|
||||
use CrudServiceTrait;
|
||||
|
||||
/**
|
||||
* 指定当前要操作的模型
|
||||
*/
|
||||
protected string $modelClass = {{modelName}}::class;
|
||||
|
||||
/**
|
||||
* 验证器
|
||||
*/
|
||||
protected $validator = {{validateName}}Validate::class;
|
||||
|
||||
/**
|
||||
* 获取验证器
|
||||
*/
|
||||
public function getValidator()
|
||||
{
|
||||
return new $this->validator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace app\{{validateModule}}\validate;
|
||||
|
||||
use think\Validate;
|
||||
|
||||
class {{validateName}}Validate extends Validate
|
||||
{
|
||||
// 规则
|
||||
protected $rule = [
|
||||
|
||||
];
|
||||
|
||||
// 提示
|
||||
protected $message = [
|
||||
|
||||
];
|
||||
|
||||
// 场景
|
||||
protected $scene = [
|
||||
'store' => [
|
||||
|
||||
],
|
||||
|
||||
'update' => [
|
||||
|
||||
]
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>邮箱提醒</title>
|
||||
<style type="text/css">
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333333;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.email-container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
.header {
|
||||
padding: 20px;
|
||||
background-color: #0056b3;
|
||||
color: white;
|
||||
text-align: center;
|
||||
}
|
||||
.content {
|
||||
padding: 20px;
|
||||
}
|
||||
.button {
|
||||
display: inline-block;
|
||||
padding: 10px 20px;
|
||||
background-color: #0056b3;
|
||||
color: white !important;
|
||||
text-decoration: none;
|
||||
border-radius: 4px;
|
||||
font-weight: bold;
|
||||
margin: 10px 0;
|
||||
}
|
||||
.footer {
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #777777;
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
@media only screen and (max-width: 480px) {
|
||||
.email-container {
|
||||
width: 100%;
|
||||
}
|
||||
.button {
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!--[if mso]>
|
||||
<style type="text/css">
|
||||
.button {
|
||||
background-color: #0056b3 !important;
|
||||
color: white !important;
|
||||
}
|
||||
</style>
|
||||
<![endif]-->
|
||||
|
||||
<table class="email-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">
|
||||
<tr>
|
||||
<td class="header">
|
||||
<h1>付款单提醒</h1>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="content">
|
||||
<p>您好,</p>
|
||||
<p>您有新的付款单待处理。请及时查看:</p>
|
||||
|
||||
<ul>
|
||||
<li>付款单编号:{{code}}</li>
|
||||
<li>付款主体:{{payment_entity}}</li>
|
||||
<li>问题描述:{{content}}</li>
|
||||
{{reply}}
|
||||
</ul>
|
||||
|
||||
<p>请点击下方按钮立即查看详情:</p>
|
||||
|
||||
<div style="text-align: center;">
|
||||
<a href="https://x.hnxinyouhe.com" class="button" style="color: white; text-decoration: none;">立即查看</a>
|
||||
</div>
|
||||
|
||||
<!--<p>如果您未请求此操作,请忽略此邮件或联系我们的客服团队。</p>-->
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="footer">
|
||||
<p>© 2025 河南新友合科技有限公司. 保留所有权利。</p>
|
||||
<p>这是系统自动发送的邮件,请勿直接回复。</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>邮箱提醒</title>
|
||||
<style type="text/css">
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333333;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.email-container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
.header {
|
||||
padding: 20px;
|
||||
background-color: #0056b3;
|
||||
color: white;
|
||||
text-align: center;
|
||||
}
|
||||
.content {
|
||||
padding: 20px;
|
||||
}
|
||||
.button {
|
||||
display: inline-block;
|
||||
padding: 10px 20px;
|
||||
background-color: #0056b3;
|
||||
color: white !important;
|
||||
text-decoration: none;
|
||||
border-radius: 4px;
|
||||
font-weight: bold;
|
||||
margin: 10px 0;
|
||||
}
|
||||
.footer {
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #777777;
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
@media only screen and (max-width: 480px) {
|
||||
.email-container {
|
||||
width: 100%;
|
||||
}
|
||||
.button {
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!--[if mso]>
|
||||
<style type="text/css">
|
||||
.button {
|
||||
background-color: #0056b3 !important;
|
||||
color: white !important;
|
||||
}
|
||||
</style>
|
||||
<![endif]-->
|
||||
|
||||
<table class="email-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">
|
||||
<tr>
|
||||
<td class="header">
|
||||
<h1>工单提醒</h1>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="content">
|
||||
<p>你好,</p>
|
||||
<p>你有新的工单待处理。请及时查看:</p>
|
||||
|
||||
<ul>
|
||||
<li>工单编号:{{code}}</li>
|
||||
<li>工单分类:{{category}}</li>
|
||||
<li>问题描述:{{content}}</li>
|
||||
{{reply}}
|
||||
</ul>
|
||||
|
||||
<p>请点击下方按钮立即查看详情:</p>
|
||||
|
||||
<div style="text-align: center;">
|
||||
<a href="https://x.hnxinyouhe.com" class="button" style="color: white; text-decoration: none;">立即查看</a>
|
||||
</div>
|
||||
|
||||
<!--<p>如果您未请求此操作,请忽略此邮件或联系我们的客服团队。</p>-->
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="footer">
|
||||
<p>© 2025 河南新友合科技有限公司. 保留所有权利。</p>
|
||||
<p>这是系统自动发送的邮件,请勿直接回复。</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// 定义所有需要多语言支持的实体
|
||||
'entities' => [
|
||||
'ticket_categorie' => [
|
||||
'translation_model' => \app\ticket\model\CategorieTranslation::class,
|
||||
'foreign_key' => 'categorie_id',
|
||||
],
|
||||
'sys_currency' => [
|
||||
'translation_model' => app\common\model\SysCurrencyTranslation::class,
|
||||
'foreign_key' => 'currency_id',
|
||||
],
|
||||
'sys_dict' => [
|
||||
'translation_model' => app\common\model\SysDictTranslation::class,
|
||||
'foreign_key' => 'dict_id',
|
||||
],
|
||||
'sys_dict_item' => [
|
||||
'translation_model' => app\common\model\SysDictItemTranslation::class,
|
||||
'foreign_key' => 'dict_item_id',
|
||||
],
|
||||
'sys_port_translation' => [
|
||||
'translation_model' => app\common\model\SysPortTranslation::class,
|
||||
'foreign_key' => 'port_id',
|
||||
],
|
||||
'veh_color_translation' => [
|
||||
'translation_model' => app\common\model\VehColorTranslation::class,
|
||||
'foreign_key' => 'color_id',
|
||||
],
|
||||
],
|
||||
|
||||
// 默认支持的目标语种列表
|
||||
'locales' => ['zh','en','ru','ar'],
|
||||
];
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
namespace app\common\utils\translation\jobs;
|
||||
|
||||
use support\Log;
|
||||
use app\common\utils\translation\service\TranslatorClient;
|
||||
|
||||
class TranslationJob
|
||||
{
|
||||
protected $config = [];
|
||||
protected array $payload;
|
||||
|
||||
public function __construct(array $payload)
|
||||
{
|
||||
$this->config = getConfig('/common/utils/translation/config/trans.php');
|
||||
// $this->config = getConfig('/queue/translation/config/trans.php');
|
||||
$this->payload = $payload;
|
||||
}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$cfgAll = $this->config['entities'];
|
||||
$pt = $this->payload;
|
||||
$type = $pt['entityType'];
|
||||
$id = $pt['entityId'];
|
||||
$locale = $pt['locale'];
|
||||
$sourceLocale = $pt['sourceLocale'];
|
||||
$sourceFields = $pt['sourceFields'];
|
||||
$clientFields = $pt['clientFields'];
|
||||
|
||||
if (! isset($cfgAll[$type])) {
|
||||
Log::warning("TranslationJob: 未配置实体 {$type}");
|
||||
return;
|
||||
}
|
||||
|
||||
$cfg = $cfgAll[$type];
|
||||
$modelClass = $cfg['translation_model'];
|
||||
$foreignKey = $cfg['foreign_key'];
|
||||
|
||||
// 决定采用前端提供、源语种还是第三方翻译
|
||||
if (! empty($clientFields)) {
|
||||
$fields = $clientFields;
|
||||
} elseif ($locale === $sourceLocale) {
|
||||
$fields = $sourceFields;
|
||||
} else {
|
||||
$translator = new TranslatorClient();
|
||||
$fields = [];
|
||||
foreach ($sourceFields as $key => $text) {
|
||||
$fields[$key] = $translator->translate($text, $sourceLocale, $locale);
|
||||
}
|
||||
}
|
||||
|
||||
// 写库
|
||||
try {
|
||||
$modelClass::updateOrCreate(
|
||||
[
|
||||
$foreignKey => $id,
|
||||
'locale' => $locale,
|
||||
],
|
||||
array_merge($fields, ['locale' => $locale])
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error("TranslationJob 保存失败: {$type}#{$id} locale={$locale}: ".$e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\utils\translation\queue;
|
||||
|
||||
use support\Log;
|
||||
use Webman\RedisQueue\Consumer;
|
||||
use app\common\utils\translation\jobs\TranslationJob;
|
||||
|
||||
class Translation implements Consumer
|
||||
{
|
||||
// 要消费的队列名
|
||||
public $queue = 'transTask';
|
||||
|
||||
// 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
|
||||
public $connection = 'default';
|
||||
|
||||
// 消费
|
||||
public function consume($data)
|
||||
{
|
||||
try {
|
||||
// 无需反序列化
|
||||
// var_export($data); // 输出 ['to' => 'tom@gmail.com', 'content' => 'hello']
|
||||
|
||||
$job = new TranslationJob($data);
|
||||
$job->handle();
|
||||
} catch (\Throwable $e) {
|
||||
Log::error("TranslationService 异步任务异常: ".$e->getMessage());
|
||||
}
|
||||
}
|
||||
// 消费失败回调
|
||||
/*
|
||||
$package = [
|
||||
'id' => 1357277951, // 消息ID
|
||||
'time' => 1709170510, // 消息时间
|
||||
'delay' => 0, // 延迟时间
|
||||
'attempts' => 2, // 消费次数
|
||||
'queue' => 'send-mail', // 队列名
|
||||
'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
|
||||
'max_attempts' => 5, // 最大重试次数
|
||||
'error' => '错误信息' // 错误信息
|
||||
]
|
||||
*/
|
||||
public function onConsumeFailure(\Throwable $e, $package)
|
||||
{
|
||||
echo "consume failure\n";
|
||||
echo $e->getMessage() . "\n";
|
||||
// 无需反序列化
|
||||
var_export($package);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
namespace app\common\utils\translation\service;
|
||||
|
||||
// use Webman\RedisQueue\Client;
|
||||
use Webman\RedisQueue\Redis;
|
||||
|
||||
class TranslationService
|
||||
{
|
||||
|
||||
// 配置
|
||||
protected $config = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->config = getConfig('/common/utils/translation/config/trans.php');
|
||||
// $this->config = getConfig('/queue/translation/config/trans.php');
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步排队所有语种的翻译任务
|
||||
*
|
||||
* @param string $entityType 实体名,如 'vehicle'
|
||||
* @param int $entityId 主表 ID
|
||||
* @param string $sourceLocale 源语种,如 'zh'
|
||||
* @param array $sourceFields 源语种字段 ['name'=>…,'condition_desc'=>…]
|
||||
* @param array $clientFields 前端已传翻译 ['en'=>[...], …]
|
||||
* @param array $intactFields 不需要翻译的字段
|
||||
*/
|
||||
public function queueTranslations(string $entityType, int $entityId, string $sourceLocale, array $sourceFields, array $clientFields = [], array $intactFields = []): void
|
||||
{
|
||||
foreach ($this->config['locales'] as $locale) {
|
||||
$payload = [
|
||||
'entityType' => $entityType,
|
||||
'entityId' => $entityId,
|
||||
'locale' => $locale,
|
||||
'sourceLocale' => $sourceLocale,
|
||||
'sourceFields' => $sourceFields,
|
||||
'clientFields' => $clientFields[$locale] ?? [],
|
||||
];
|
||||
Redis::send('transTask', $payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
namespace app\common\utils\translation\service;
|
||||
|
||||
use app\queue\utils\XunfeiFanyi;
|
||||
use support\Log;
|
||||
|
||||
class TranslatorClient
|
||||
{
|
||||
|
||||
// protected string $endpoint;
|
||||
// protected string $apiKey;
|
||||
|
||||
// public function __construct()
|
||||
// {
|
||||
// $this->endpoint = env('TRANSLATION_API_URL');
|
||||
// $this->apiKey = env('TRANSLATION_API_KEY');
|
||||
// }
|
||||
|
||||
/**
|
||||
* 翻译文本
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public function translate(string $text, string $from = 'cn', string $to = 'ru'): string
|
||||
{
|
||||
try {
|
||||
$xunfei = new XunfeiFanyi();
|
||||
$rst_dst = $xunfei->fanyi($text, $from, $to);
|
||||
if ($rst_dst) {
|
||||
return $rst_dst["trans_result"]["dst"];
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error("TranslatorClient 错误: ".$e->getMessage());
|
||||
throw new \RuntimeException('翻译服务调用失败');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user