Merge branch 'develop'

This commit is contained in:
mzl
2025-09-24 19:12:13 +08:00
parent 04208b3b5c
commit b897771541
31 changed files with 5899 additions and 895 deletions
@@ -112,8 +112,9 @@ class ApprovalRecordsController extends BaseController
'instance_id' => $record['instance_id'], 'instance_id' => $record['instance_id'],
'biz_id' => $record['instance']['biz_id'], 'biz_id' => $record['instance']['biz_id'],
'biz_desc' => '备货单号【'.$record['instance']['bizInfo']['order_no'].'】', 'biz_desc' => '业务单号【'.$record['instance']['bizInfo']['order_no'].'】',
'biz_type' => $record['instance']['flow_type'], 'biz_type' => $record['instance']['flow_type'],
'flow_type' => $record['instance']['flow_type'],
'initiator_name' => $record['instance']['initiator']['name'], 'initiator_name' => $record['instance']['initiator']['name'],
'initiator_avatar' => $record['instance']['initiator']['avatar'], 'initiator_avatar' => $record['instance']['initiator']['avatar'],
@@ -139,4 +140,63 @@ class ApprovalRecordsController extends BaseController
} }
return $data; return $data;
} }
public function businessOrder(Request $request)
{
try {
$raw = $this->service->serviceBusinessOrder($request, $request->all());
$data = $this->transformData($raw, method_exists($this, 'borderFormat')
? [$this, 'borderFormat']
: null);
return $this->success($data);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
public function transferApproval(Request $request)
{
try {
$raw = $this->service->transferApproval($request, $request->all());
$data = $this->transformData($raw, method_exists($this, 'transferFormat')
? [$this, 'transferFormat']
: null);
return $this->success($data);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
public function approvalTimeline(Request $request)
{
try {
$raw = $this->service->serviceApprovalTimeline($request, $request->all());
$data = $this->transformData($raw, method_exists($this, 'timelineFormat')
? [$this, 'timelineFormat']
: null);
return $this->success($data);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
protected function timelineFormat($data)
{
$result = [];
foreach ($data as $record) {
$result[] = [
'id' => $record['id'],
'name' => $record['approver']['name'],
'comment' => $record['comment'] ?? '无',
'time' => $record['updated_at'],
'status_desc' => SysDictItem::where('item_value', $record['status'])->where('status', 1)->value('item_label'),
];
}
return $result;
}
} }
@@ -0,0 +1,33 @@
<?php
namespace app\common\controller;
use app\common\controller\BaseController;
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\PurchaseOrderItemsService;
class PurchaseOrderItemsController extends BaseController
{
use CrudControllerTrait;
protected $service;
public function __construct()
{
$this->service = new PurchaseOrderItemsService();
}
/**
* 列表页数据格式化
*
* @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,137 @@
<?php
namespace app\common\controller;
use app\common\controller\BaseController;
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\PurchaseOrdersService;
use support\Request;
class PurchaseOrdersController extends BaseController
{
use CrudControllerTrait;
protected $service;
public function __construct()
{
$this->service = new PurchaseOrdersService();
}
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
protected function indexFormat($data)
{
if (isset($data['records']) && count($data['records']) > 0) {
foreach ($data['records'] as &$record) {
$contractFile = $record['contract_file'] ? explode(',', $record['contract_file']) : [];
$contractFileUrl = [];
if (count($contractFile) > 0) {
foreach ($contractFile as $file) {
$contractFileUrl[] = (new \app\common\service\OssService)->generatePrivateUrl($file);
}
}
$result = [
'id' => $record['id'],
'order_no' => $record['order_no'],
'pi_no' => $record['pi_no'],
'buyer_id' => $record['buyer_id'],
'buyer_name' => $record['buyer_name'],
'contract_file' => $contractFile,
'contract_file_url' => $contractFileUrl,
'status' => $record['status'],
'status_text' => array_flip(\app\common\service\SysDictService::pluckKeyValueByCode('purchase_status'))[$record['status']],
'remark' => $record['remark'],
'created_at' => date('Y-m-d H:i:s', $record['created_at']),
'updated_at' => date('Y-m-d H:i:s', $record['updated_at']),
];
$record = $result;
}
unset($record);
}
return $data;
}
/**
* 详情页数据格式化
*
* @param array $data
* @return array
*/
protected function showFormat($data)
{
$contractFile = $data['contract_file'] ? explode(',', $data['contract_file']) : [];
$contractFileUrl = [];
if (count($contractFile) > 0) {
foreach ($contractFile as $file) {
$contractFileUrl[] = (new \app\common\service\OssService)->generatePrivateUrl($file);
}
}
$result = [
'id' => $data['id'],
'order_no' => $data['order_no'],
'pi_no' => $data['pi_no'],
'buyer_id' => $data['buyer_id'],
'buyer_name' => $data['buyer_name'],
'contract_file' => $contractFile,
'contract_file_url' => $contractFileUrl,
'status' => $data['status'],
'remark' => $data['remark']
];
$temps = [];
if (isset($data['items']) && count($data['items']) > 0) {
foreach ($data['items'] as $record) {
if (!in_array($record['stockOrder']['id'], array_keys($temps))) {
$temps[$record['stockOrder']['id']] = [
'id' => $record['stockOrder']['id'],
'order_no' => $record['stockOrder']['order_no'],
'salesperson_snapshot' => $record['stockOrder']['salesperson_snapshot'],
'biz_date' => date('Y-m-d', $record['stockOrder']['biz_date'])
];
}
$temps[$record['stockOrder']['id']]['stock_order_items'][] =[
'id' => $record['stockOrderItems']['id'],
'model_snapshot' => $record['stockOrderItems']['model_snapshot'],
'unique_id' => $record['stockOrderItems']['unique_id'],
];
}
}
$result['stock_order'] = array_values($temps);
return $result;
}
/**
* 前置查询处理
*
* @param Request $request
* @return array
*/
public function preQueryData(Request $request)
{
try {
$data = $this->service->preQueryData($request->all());
return $this->success($data);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
/**
* 重提
*
* @param Request $request
* @return mixed
*/
public function resubmit(Request $request)
{
try {
$raw = $this->service->serviceResubmit($request, $request->all());
return $this->success($raw);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
}
@@ -0,0 +1,17 @@
<?php
namespace app\common\logic;
use app\common\traits\crud\CrudLogicTrait;
use app\common\model\PurchaseOrderItems;
class PurchaseOrderItemsLogic
{
use CrudLogicTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = PurchaseOrderItems::class;
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace app\common\logic;
use app\common\traits\crud\CrudLogicTrait;
use app\common\model\PurchaseOrders;
use app\common\model\StockOrderItems;
use app\common\utils\CrudUtil;
use app\common\model\StockOrders;
class PurchaseOrdersLogic
{
use CrudLogicTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = PurchaseOrders::class;
/**
* 获取备货单PI号
*/
public function getPiList()
{
return (new StockOrders())->where('pi_no', '!=', '')
->select('pi_no')
->distinct()
->get();
}
/**
* 根据PI号获取备货单
*/
public function getOrderNoListByPiNo($piNo)
{
return (new StockOrders())->where('pi_no', $piNo)
->select('order_no', 'biz_date', 'salesperson_snapshot', 'id as stock_orders_id', 'salesperson_id')
->get();
}
/**
* 根据备货单号获取备货单明细
*/
public function getOrderItemsListByOrderNo($stockOrdersId)
{
return (new StockOrderItems())->where('order_id', $stockOrdersId)
->select('model_snapshot', 'color_interior_snapshot', 'color_exterior_snapshot', 'unique_id', 'id as stock_order_items_id')
->get();
}
}
+27 -7
View File
@@ -59,6 +59,7 @@ class ApprovalInstances extends Model
'current_step', 'current_step',
'finished_at', 'finished_at',
'deadline_at', 'deadline_at',
'round'
]; ];
protected $casts = [ protected $casts = [
@@ -69,6 +70,27 @@ class ApprovalInstances extends Model
'updated_at' => 'datetime', 'updated_at' => 'datetime',
]; ];
// ====== ====== ====== 映射业务表 ====== ====== ======
protected const BIZ_CLASS = [
'stock_orders' => \app\common\model\StockOrders::class,
'purchase_orders' => \app\common\model\PurchaseOrders::class,
];
public function getBizTypeAttribute($value)
{
return self::BIZ_CLASS[$value] ?? $value;
}
public function bizInfo()
{
return $this->morphTo('bizInfo', 'biz_type', 'biz_id');
}
// ====== ====== ====== 映射表业务 ====== ====== ======
public function records() public function records()
{ {
return $this->hasMany(ApprovalRecords::class, 'instance_id', 'id'); return $this->hasMany(ApprovalRecords::class, 'instance_id', 'id');
@@ -84,18 +106,16 @@ class ApprovalInstances extends Model
return $this->belongsTo(User::class, 'initiator_id', 'id'); return $this->belongsTo(User::class, 'initiator_id', 'id');
} }
public function bizInfo() // public function bizInfo2()
{ // {
return $this->belongsTo(StockOrders::class, 'biz_id', 'id'); // return $this->belongsTo(StockOrders::class, 'biz_id', 'id');
} // }
/** /**
* 获取当前步骤的所有审批记录(pending 状态) * 获取当前步骤的所有审批记录(pending 状态)
*/ */
public function currentStepRecords() public function currentStepRecords()
{ {
return $this->approvalRecords() return $this->approvalRecords()->where('step_index', $this->current_step)->where('status', 'pending');
->where('step_index', $this->current_step)
->where('status', 'pending');
} }
} }
+1
View File
@@ -57,6 +57,7 @@ class ApprovalRecords extends Model
'status', 'status',
'comment', 'comment',
'approved_at', 'approved_at',
'round'
]; ];
protected $casts = [ protected $casts = [
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace app\common\model;
use support\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PurchaseOrderItems extends Model
{
use SoftDeletes;
/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection = 'mysql';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'purchase_order_items';
/**
* 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 = ['id', 'purchase_order_id', 'stock_id', 'stock_items_id', 'stock_items_uqid', 'quantity', 'unit_price', 'total_price', 'remark'];
/**
* 不允许自动填充模型字段
*/
protected $guarded = [];
public function purchaseOrder()
{
return $this->belongsTo(PurchaseOrders::class, 'purchase_order_id', 'id');
}
public function stockOrder()
{
return $this->belongsTo(StockOrders::class, 'stock_id', 'id');
}
public function stockOrderItems()
{
return $this->belongsTo(StockOrderItems::class, 'stock_items_id', 'id');
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace app\common\model;
use support\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PurchaseOrders extends Model
{
use SoftDeletes;
/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection = 'mysql';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'purchase_orders';
/**
* 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 = ['id', 'order_no', 'pi_no', 'buyer_id', 'buyer_name', 'contract_file', 'status', 'remark', 'is_draft', 'created_at', 'updated_at'];
/**
* 不允许自动填充模型字段
*/
protected $guarded = [];
public function items()
{
return $this->hasMany(PurchaseOrderItems::class, 'purchase_order_id', 'id');
}
public function buyer()
{
return $this->hasOne(User::class, 'id', 'buyer_id');
}
}
+68 -1
View File
@@ -57,7 +57,7 @@ class ApprovalRecordsService
if ($p['scene'] === 'todo') { if ($p['scene'] === 'todo') {
// if (!in_array(1, $request->user->role_ids)) { // if (!in_array(1, $request->user->role_ids)) {
$config['where']['approver_id'] = $request->user->uid; // $config['where']['approver_id'] = $request->user->uid;
// } // }
$config['where']['status'] = 'pending'; $config['where']['status'] = 'pending';
$config['where']['instance.status'] = 'processing'; $config['where']['instance.status'] = 'processing';
@@ -95,6 +95,17 @@ class ApprovalRecordsService
$config['where']['instance_id'] = $p['instance_id']; $config['where']['instance_id'] = $p['instance_id'];
$config['order']['id'] = 'desc'; $config['order']['id'] = 'desc';
break; break;
case 'border':
$config['where']['id'] = $p['id'];
$config['order']['id'] = 'desc';
$config['with'] = [
'instance',
'approver',
'instance.flows',
'instance.initiator',
'instance.bizInfo'
];
break;
} }
return $config; return $config;
@@ -115,4 +126,60 @@ class ApprovalRecordsService
$item = $this->logicListAll($config); $item = $this->logicListAll($config);
return $this->postProcess('Logs', $item); return $this->postProcess('Logs', $item);
} }
public function serviceBusinessOrder(Request $request, array $data = [])
{
$config = $this->buildQueryConfig($request, 'border');
$config = $this->borderConfig($config, $data['flow_type']);
$item = $this->logicShow($config);
$bizInfo = [];
$service = match ($data['flow_type']) {
'stock_orders' => new \app\common\service\StockOrdersService(),
'purchase_orders' => new \app\common\service\PurchaseOrdersService(),
default => new \app\common\service\StockOrdersService()
};
$bizInfo = $service->formatData($item->instance->bizInfo);
return $this->postProcess('Border', $bizInfo);
}
public function borderConfig($config, $type = 'stock_orders')
{
$with = match ($type) {
'stock_orders' => [
'instance.bizInfo.items',
'instance.bizInfo.items.options',
'instance.bizInfo.items.moneyValues',
'instance.bizInfo.accounts',
'instance.bizInfo.moneyValues',
'instance.bizInfo.salesperson',
],
'purchase_orders' => [
'instance.bizInfo.items',
'instance.bizInfo.items.stockOrder',
'instance.bizInfo.items.stockOrderItems'
]
};
$config['with'] = array_merge($config['with'], $with);
return $config;
}
public function transferApproval(Request $request, array $data = [])
{
$service = new \app\common\utils\approval\service\ApprovalFlowService();
$result = $service->transferApproval($data['instance_id'], $data['step_index'], $request->user->uid, $data['to_uid'], $data['reason'], 'name');
return $result;
}
public function serviceApprovalTimeline(Request $request, array $data = [])
{
$instance = \app\common\model\ApprovalInstances::where('biz_id', $data['id'])->where('flow_type', $data['flow_type'])->first();
if (!$instance) {
return [];
}
$result = \app\common\model\ApprovalRecords::where('instance_id', $instance->id)->with('approver')->orderBy('id', 'desc')->get();
return $result;
}
} }
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\PurchaseOrderItemsValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\PurchaseOrderItems;
class PurchaseOrderItemsService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = PurchaseOrderItems::class;
/**
* 验证器
*/
protected $validator = PurchaseOrderItemsValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
@@ -0,0 +1,357 @@
<?php
namespace app\common\service;
use app\common\validate\PurchaseOrdersValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\PurchaseOrders;
use app\common\logic\PurchaseOrdersLogic;
use app\common\model\PurchaseOrderItems;
use app\common\model\User;
use support\Db;
use support\exception\BusinessException;
use support\Request;
class PurchaseOrdersService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = PurchaseOrders::class;
/**
* 验证器
*/
protected $validator = PurchaseOrdersValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
public function getLogic()
{
return new PurchaseOrdersLogic();
}
/**
* 获取前置预处理数据
*
* @param array $data 原始返回值
* @return array 处理后的返回值
*/
public function preQueryData(array $data)
{
$result = match ($data['scene']) {
'pi_no' => $this->getLogic()->getPiList(),
'order_no' => $this->getLogic()->getOrderNoListByPiNo($data['pi_no']),
'order_items' => $this->getLogic()->getOrderItemsListByOrderNo($data['order_id']),
default => $data,
};
return $this->postProcess('PreData', $result->toArray());
}
public function afterServicePreData(array $data)
{
foreach ($data as $key => &$item) {
if (isset($item['biz_date'])) {
$item['biz_date'] = date('Y-m-d', $item['biz_date']);
}
}
unset($item);
return $data;
}
public function beforeServiceStore(array $data, Request $request)
{
$data['order_no'] = generateStockNo('CG');
$data['buyer_id'] = $request->user->uid;
$data['buyer_name'] = User::where('id', $request->user->uid)->value('name');
if ($data['is_draft'] == 0) {
$data['status'] = 1;
}
return $data;
}
public function serviceStore(Request $request, array $data = [], string $scene = 'store')
{
// 使用事务确保数据一致性
return Db::transaction(function () use ($request, $data, $scene) {
$data = $this->preProcess(ucfirst($scene), $data, $request);
$dl = $this->getDataLimitFromRequest($request);
// 创建采购单
$created = $this->logicCreate($data, $dl);
if (isset($data['stock_order'])) {
foreach ($data['stock_order'] as $order) {
foreach ($order['stock_items'] as $item) {
// 创建采购单明细
PurchaseOrderItems::create([
'purchase_order_id' => $created->id,
'stock_id' => $order['stock_orders_id'],
'stock_items_id' => $item['stock_order_items_id'],
'stock_items_uqid' => $item['unique_id'],
]);
}
}
}
return $this->postProcess(ucfirst($scene), $created);
});
}
/**
* 构建查询配置
*
* @param Request $request
* @param string $scene
* @return array
*/
protected function buildQueryConfig(Request $request, string $scene = 'index'): array
{
$p = $request->all();
$config = [];
$config['model'] = $this->modelClass;
switch ($scene) {
case 'index':
$config['order']['id'] = 'desc';
break;
case 'update':
$config['where']['id'] = $p['id'] ?? 0;
break;
case 'show':
$config['where']['id'] = $p['id'];
$config['with'] = [
'items', 'items.stockOrder', 'items.stockOrderItems'
];
break;
}
return $config;
}
/**
* 删除采购订单
*
* @param Request $request
* @return mixed
*/
public function serviceDestroy(Request $request)
{
// 使用事务确保数据一致性
return Db::transaction(function () use ($request) {
// 构建查询条件
$config = $this->buildQueryConfig($request, 'show');
// 软删除采购单明细
$order = $this->logicShow($config);
if ($order && $order->items) {
foreach ($order->items as $item) {
$item->delete();
}
}
// 软删除采购单主表
$res = $order->delete();
return $this->postProcess('Destroy', $res);
});
}
/**
* 创建采购单成功后处理
*/
protected function afterServiceStore($res)
{
if ($res->is_draft == 0) {
$this->startApproval($res, ['resubmitted'=>0]);
}
return $res;
}
public function startApproval($item)
{
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
$appro->start('purchase_orders', 'purchase_orders', $item->id, ['resubmitted'=>0], $item->buyer_id);
}
public function beforeServiceUpdate(array $data, Request $request)
{
if ($data['is_draft'] == 0) {
$data['status'] = 1;
}
return $data;
}
/**
* 更新采购单
*
* @param Request $request
* @param array $data
* @return mixed
*/
public function serviceUpdate(Request $request, array $data = [], string $scene = 'update')
{
// 使用事务确保数据一致性
return Db::transaction(function () use ($request, $data, $scene) {
$data = $this->preProcess(ucfirst($scene), $data, $request);
// 构建查询条件
$config = $this->buildQueryConfig($request, $scene);
// 更新主表信息
$udata = $data;
unset($udata['stock_order']);
unset($udata['is_resubmit']);
unset($udata['approval_desc']);
$this->logicUpdateBy($config, $udata);
// 获取更新后的数据
$order = $this->logicShow($config);
// 更新采购单明细
if (isset($data['stock_order'])) {
// 先删除原有的明细
PurchaseOrderItems::where('purchase_order_id', $order->id)->delete();
// 重新创建明细
foreach ($data['stock_order'] as $orderData) {
foreach ($orderData['stock_items'] as $item) {
PurchaseOrderItems::create([
'purchase_order_id' => $order->id,
'stock_id' => $orderData['stock_orders_id'],
'stock_items_id' => $item['stock_order_items_id'],
'stock_items_uqid' => $item['unique_id'],
]);
}
}
}
return $this->postProcess(
ucfirst($scene),
$order,
[
'is_resubmit'=>$data['is_resubmit'],
'approval_desc'=>$data['approval_desc']
]
);
});
}
protected function afterServiceUpdate($res, $data)
{
if ($data['is_resubmit'] == 0 && $res->status == 1) {
$this->startApproval($res);
}
if ($data['is_resubmit'] == 1) {
$instance = \app\common\model\ApprovalInstances::where('biz_id', $res->id)->where('flow_type', 'purchase_orders')->first();
if ( $instance === null) {
throw new BusinessException('未找到审批实例');
}
// 审批服务
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
// 重新提交
$appro->resubmit($instance->id, $instance->initiator_id, ['resubmitted'=>1], $data['approval_desc']);
// 添加到讨论
if (!empty($data['approval_desc'])) {
$appro->postDiscussion($instance->id, $instance->initiator_id, $data['approval_desc'], false, [], 'name');
}
}
return $res;
}
public function serviceResubmit(Request $request, array $data = [])
{
$p = $request->all();
$config = [];
$config['model'] = $this->modelClass;
$config['where']['id'] = $p['id'];
$config['where']['buyer_id'] = $request->user->uid;
$info = $this->logicShow($config);
if ($info === null) {
throw new BusinessException('未找到采购单');
}
if ($info->status != 3) {
throw new BusinessException('该状态不能重新提交');
}
$instance = \app\common\model\ApprovalInstances::where('biz_id', $info->id)->where('flow_type', 'purchase_orders')->first();
if ( $instance === null) {
throw new BusinessException('未找到审批实例');
}
// 审批服务
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
// 重新提交
$result = $appro->resubmit($instance->id, $instance->initiator_id, ['resubmitted'=>1], $data['remark']);
// 添加到讨论
if (!empty($data['remark'])) {
$appro->postDiscussion($instance->id, $instance->initiator_id, $data['remark'], false, [], 'name');
}
$info->status = 1;
$info->save();
return $result;
}
public function updateStatus(array $data = [])
{
$info = PurchaseOrders::where('id', $data['id'])->first();
if ($info === null) {
throw new BusinessException('未找到采购单');
}
$info->status = $data['status'];
return $info->save();
}
public function formatData($data)
{
$contractFile = $data['contract_file'] ? explode(',', $data['contract_file']) : [];
$contractFileUrl = [];
if (count($contractFile) > 0) {
foreach ($contractFile as $file) {
$contractFileUrl[] = (new \app\common\service\OssService)->generatePrivateUrl($file);
}
}
$result = [
'id' => $data['id'],
'order_no' => $data['order_no'],
'pi_no' => $data['pi_no'],
'buyer_id' => $data['buyer_id'],
'buyer_name' => $data['buyer_name'],
'contract_file' => $contractFile,
'contract_file_url' => $contractFileUrl,
'status' => $data['status'],
'remark' => $data['remark']
];
$temps = [];
if (isset($data['items']) && count($data['items']) > 0) {
foreach ($data['items'] as $record) {
if (!in_array($record['stockOrder']['id'], array_keys($temps))) {
$temps[$record['stockOrder']['id']] = [
'id' => $record['stockOrder']['id'],
'order_no' => $record['stockOrder']['order_no'],
'salesperson_snapshot' => $record['stockOrder']['salesperson_snapshot'],
'biz_date' => date('Y-m-d', $record['stockOrder']['biz_date'])
];
}
$temps[$record['stockOrder']['id']]['stock_order_items'][] =[
'id' => $record['stockOrderItems']['id'],
'model_snapshot' => $record['stockOrderItems']['model_snapshot'],
'unique_id' => $record['stockOrderItems']['unique_id'],
];
}
}
$result['stock_order'] = array_values($temps);
return $result;
}
}
+257 -7
View File
@@ -140,7 +140,7 @@ class StockOrdersService
{ {
// 启动审批 // 启动审批
$appro = new \app\common\utils\approval\service\ApprovalFlowService(); $appro = new \app\common\utils\approval\service\ApprovalFlowService();
$appro->start('stock_orders', 'stock_orders', $item->id, $item->toArray(), $item->salesperson_id); $appro->start('stock_orders', 'stock_orders', $item->id, [], $item->salesperson_id);
// 异步生成pdf文件 // 异步生成pdf文件
\Webman\RedisQueue\Redis::send('stock-order-pdf', ['id'=>$item->id]); \Webman\RedisQueue\Redis::send('stock-order-pdf', ['id'=>$item->id]);
} }
@@ -160,7 +160,7 @@ class StockOrdersService
$config['with'][] = 'moneyValues'; $config['with'][] = 'moneyValues';
$config['with'][] = 'salesperson'; $config['with'][] = 'salesperson';
$item = $this->logicShow($config); $item = $this->logicShow($config);
$pdfData = $this->pdfData($item); $pdfData = $this->formatData($item);
// 渲染模板为最终HTML // 渲染模板为最终HTML
$tplPath = app_path('common/utils/pdf/template/stockOrder.stub'); $tplPath = app_path('common/utils/pdf/template/stockOrder.stub');
@@ -200,7 +200,7 @@ class StockOrdersService
return $res; return $res;
} }
public function pdfData($item) public function pdfData2($item)
{ {
$vehList = []; $vehList = [];
$index = 0; $index = 0;
@@ -375,8 +375,8 @@ class StockOrdersService
{ {
$config = $this->buildQueryConfig($request, 'detail'); $config = $this->buildQueryConfig($request, 'detail');
$item = $this->logicShow($config); $item = $this->logicShow($config);
$pdfData = $this->pdfData($item); $detail = $this->formatData($item);
return $this->postProcess('Detail', $pdfData); return $this->postProcess('Detail', $detail);
} }
/** /**
@@ -620,7 +620,10 @@ class StockOrdersService
'fob_transport_fee' => 'FOB运输费', 'fob_transport_fee' => 'FOB运输费',
'port_misc_fee' => '港杂', 'port_misc_fee' => '港杂',
'retrofit_fee' => '改装费', 'retrofit_fee' => '改装费',
'ocean_freight' => '海运费' 'ocean_freight' => '海运费',
'commission' => '佣金',
'purchase_tax' => '购置税',
'tax_refund' => '预估退税'
]; ];
foreach ($priceFields as $field => $description) { foreach ($priceFields as $field => $description) {
@@ -703,8 +706,12 @@ class StockOrdersService
$portMiscFee = (float)($veh['port_misc_fee']['amount'] ?? 0); $portMiscFee = (float)($veh['port_misc_fee']['amount'] ?? 0);
$retrofitFee = (float)($veh['retrofit_fee']['amount'] ?? 0); $retrofitFee = (float)($veh['retrofit_fee']['amount'] ?? 0);
$oceanFreight = (float)($veh['ocean_freight']['amount'] ?? 0); $oceanFreight = (float)($veh['ocean_freight']['amount'] ?? 0);
$commission = (float)($veh['commission']['amount'] ?? 0);
$purchaseTax = (float)($veh['purchase_tax']['amount'] ?? 0);
$taxRefund = (float)($veh['tax_refund']['amount'] ?? 0);
return $unitPrice - $ttPrice - $ddPrice - $handlingFee - $fobTransportFee - $portMiscFee - $retrofitFee - $oceanFreight; // 退税额 是增加利润
return $unitPrice - $ttPrice - $ddPrice - $handlingFee - $fobTransportFee - $portMiscFee - $retrofitFee - $oceanFreight - $commission - $purchaseTax + $taxRefund;
} }
/** /**
@@ -739,4 +746,247 @@ class StockOrdersService
StockOrderAccounts::create($account); StockOrderAccounts::create($account);
} }
} }
// ====== ======= ====== ======= ====== 信息处理 ======= ====== ======= ====== =======
// PDF数据
public function formatData($item)
{
// 提取车辆列表信息
$vehListData = $this->prepareVehicleListData($item);
// 提取订单金额信息
$moneyValues = $this->prepareOrderMoneyValues($item);
// 提取账户列表信息
$accountList = $this->prepareAccountList($item);
// 构建返回数据
$veh = [
// 基本信息
'order_no' => $item->order_no,
'salesperson_snapshot' => $item->salesperson_snapshot,
'sign_img_url' => $this->getSignatureImageUrl($item->salesperson->sign_img ?? null),
'created_at' => date('Y-m-d', strtotime($item->created_at)),
'pi_no' => $item->pi_no,
'biz_date' => date('Y-m-d', $item->biz_date),
'clearance_country_snapshot' => $item->clearance_country_snapshot,
'customer_source_snapshot' => $item->customer_source_snapshot,
'customer_snapshot' => $item->customer_snapshot,
'customer_country_snapshot' => $item->customer_country_snapshot,
// 订单项
'veh_list' => array_values($vehListData['list']),
'contract_exchange_rate' => $item->contract_exchange_rate,
'cif_total_amount' => $moneyValues['cif_total_amount'] ?? [],
'profit_total' => $moneyValues['profit_total'] ?? [],
// 运输和交付信息
'declarant_name' => $item->declarant_name,
'eta_ship_date' => date('Y-m-d', $item->eta_ship_date),
'shipping_method_snapshot' => $item->shipping_method_snapshot,
'domestic_port_snapshot' => $item->domestic_port_snapshot,
'trade_term_snapshot' => $item->trade_term_snapshot,
'clearance_port_snapshot' => $item->clearance_port_snapshot,
'latest_arrival_date' => date('Y-m-d', $item->latest_arrival_date),
'pick_up_date' => date('Y-m-d', $item->pick_up_date),
'collect_all_date' => date('Y-m-d', $item->collect_all_date),
'is_final' => $item->is_final,
// 账户信息
'account_list' => $accountList,
'acc_index' => count($accountList) + 1,
'currency_symbol' => $item->settlement_currency,
'sign_imgs' => $this->queryAppro($item->id),
'contract_url' => $this->getContractUrl($item->contract ?? null)
];
return $veh;
}
/**
* 准备车辆列表数据
*/
private function prepareVehicleListData($item): array
{
$vehList = [];
$index = 0;
$currencyInfo = $this->getCurrencyInfo($item->settlement_currency);
foreach ($item->items as $v) {
// 如果已存在相同车辆,增加数量
if (isset($vehList[$v->unique_id])) {
$this->incrementVehicleCount($vehList[$v->unique_id], $currencyInfo);
// 拼接 remark 值
if (!empty($v->remark)) {
if (!empty($vehList[$v->unique_id]['remark'])) {
$vehList[$v->unique_id]['remark'] .= "; " . $v->remark;
} else {
$vehList[$v->unique_id]['remark'] = $v->remark;
}
}
continue;
}
$index++;
// 处理金额信息
$moneyValues = $this->processItemMoneyValues($v);
// 处理改装信息
$modificationText = $this->getModificationText($v->options);
// 计算单项利润
$itemProfit = $this->calculateProfit($moneyValues, $item);
// 构建车辆信息
$vehList[$v->unique_id] = [
'index' => $index,
'model_snapshot' => $v->model_snapshot,
'color_interior_snapshot' => $v->color_interior_snapshot,
'color_exterior_snapshot' => $v->color_exterior_snapshot,
'num' => 1,
'modify' => $modificationText,
'mileage' => $v->mileage,
'remark' => $v->remark,
] + $moneyValues;
// 添加利润信息
$vehList[$v->unique_id]['profit'] = [
'currency' => $item->settlement_currency,
'amount' => $itemProfit,
'currency_info' => $currencyInfo['currency_symbol'] . number_format($itemProfit, 2, '.', ',')
];
}
return ['list' => $vehList];
}
/**
* 处理单项金额值
*/
private function processItemMoneyValues($item): array
{
$moneyValues = [];
foreach ($item->moneyValues as $money) {
$moneyValues[$money->field] = [
'currency' => $money->currency,
'amount' => $money->amount,
'rate' => $money->exchange_rate,
'currency_info' => $this->formatCurrency($money->amount, $money->currency)
];
}
return $moneyValues;
}
/**
* 获取改装文本
*/
private function getModificationText($options): string
{
$modificationText = '';
foreach ($options as $option) {
$modificationText .= $option->option_name_snapshot . ' ';
}
return trim($modificationText);
}
/**
* 增加车辆数量并更新相关金额显示
*/
private function incrementVehicleCount(array &$vehicleData, array $currencyInfo): void
{
$vehicleData['num'] += 1;
// 更新总价显示
if (isset($vehicleData['total_price']['amount'])) {
$totalAmount = $vehicleData['total_price']['amount'] * $vehicleData['num'];
$vehicleData['total_price']['currency_info'] = $currencyInfo['currency_symbol'] . number_format($totalAmount, 2, '.', ',');
}
// 更新利润显示
if (isset($vehicleData['profit']['amount'])) {
$profitAmount = $vehicleData['profit']['amount'] * $vehicleData['num'];
$vehicleData['profit']['currency_info'] = $currencyInfo['currency_symbol'] . number_format($profitAmount, 2, '.', ',');
}
}
/**
* 准备订单金额值
*/
private function prepareOrderMoneyValues($item): array
{
$moneyValues = [];
foreach ($item->moneyValues as $money) {
$moneyValues[$money->field] = [
'currency' => $money->currency,
'amount' => $money->amount,
'rate' => $money->exchange_rate,
'currency_info' => $this->formatCurrency($money->amount, $money->currency)
];
}
return $moneyValues;
}
/**
* 准备账户列表
*/
private function prepareAccountList($item): array
{
$accountList = [];
foreach ($item->accounts as $k => $account) {
$accountList[] = [
'index' => '收款' . ($k + 1),
'remit_country_name_snapshot' => $account->remit_country_name_snapshot,
'remit_date' => date('Y-m-d', $account->remit_date),
'currency_name_snapshot' => $account->currency_name_snapshot,
'account_name_snapshot' => $account->account_name_snapshot,
'remitter_name' => $account->remitter_name,
'amount' => $account->amount,
];
}
return $accountList;
}
/**
* 获取货币信息
*/
private function getCurrencyInfo(string $currencyCode): array
{
return SysCurrency::where('currency_code', $currencyCode)
->first(['currency_symbol', 'currency_name'])
->toArray();
}
/**
* 格式化货币显示
*/
private function formatCurrency(float $amount, string $currencyCode): string
{
$currencySymbol = SysCurrency::where('currency_code', $currencyCode)->value('currency_symbol');
return $currencySymbol . number_format($amount, 2, '.', ',');
}
/**
* 获取签名图片URL
*/
private function getSignatureImageUrl(?string $signImg): string
{
if (empty($signImg)) {
return '';
}
return (new \app\common\service\OssService)->generatePrivateUrl($signImg);
}
/**
* 获取合同URL
*/
private function getContractUrl(?string $contract): string
{
if (empty($contract)) {
return '';
}
return (new \app\common\service\OssService)->generatePrivateUrl($contract);
}
} }
@@ -5,6 +5,7 @@ namespace app\common\service;
use app\common\validate\VehMoneyValueValidate; use app\common\validate\VehMoneyValueValidate;
use app\common\traits\crud\CrudServiceTrait; use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehMoneyValue; use app\common\model\VehMoneyValue;
use support\Db;
class VehMoneyValueService class VehMoneyValueService
{ {
@@ -28,4 +29,49 @@ class VehMoneyValueService
{ {
return new $this->validator; return new $this->validator;
} }
/**
* 复制金额记录
*
* @param string $fromScene 源场景
* @param int $fromId 源对象ID
* @param string $toScene 目标场景
* @param int $toId 目标对象ID
* @return int 插入条数
* @throws BusinessException
*/
public function copyMoneyValues(string $fromScene, int $fromId, string $toScene, int $toId): int
{
// 1. 查询源数据
$rows = Db::table('veh_money_value')
->where('object_scene', $fromScene)
->where('object_id', $fromId)
->get()
->toArray();
if (empty($rows)) {
return 0;
}
$now = time();
$insertData = [];
foreach ($rows as $row) {
$insertData[] = [
'object_scene' => $toScene,
'object_id' => $toId,
'field' => $row->field,
'currency' => $row->currency,
'amount' => $row->amount,
'exchange_rate' => $row->exchange_rate,
'remark' => $row->remark,
'created_at' => $now,
'updated_at' => $now,
];
}
// 2. 插入新数据
return Db::table('veh_money_value')->insert($insertData);
}
} }
+8 -3
View File
@@ -175,9 +175,14 @@ trait CrudServiceTrait
protected function postProcess(string $op, mixed $data): mixed protected function postProcess(string $op, mixed $data): mixed
{ {
$hook = "afterService{$op}"; $hook = "afterService{$op}";
return method_exists($this, $hook) if (method_exists($this, $hook)) {
? $this->{$hook}($data) $args = func_get_args();
: $data; array_shift($args);
array_shift($args);
$params = array_merge([$data], $args);
return call_user_func_array([$this, $hook], $params);
}
return $data;
} }
/** /**
+5 -1
View File
@@ -192,7 +192,11 @@ class CrudUtil
*/ */
public static function findOneBy(Builder $q): Model public static function findOneBy(Builder $q): Model
{ {
return $q->first(); $model = $q->first();
if (!$model) {
throw new BusinessException("记录不存在", 404);
}
return $model;
} }
/** /**
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -110,7 +110,7 @@
<tr> <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">阿里订单号/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 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['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_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_snapshot'] ?? ' - '); ?></span></td>
<td><span class="info-label">客户所在国:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_country_snapshot'] ?? ' - '); ?></span></td> <td><span class="info-label">客户所在国:</span> <span class="info-value"><?php echo htmlspecialchars($data['customer_country_snapshot'] ?? ' - '); ?></span></td>
@@ -174,6 +174,11 @@
<td class="nowrap"><?php echo htmlspecialchars($vehicle['total_price']['currency_info'] ?? ' - '); ?></td> <td class="nowrap"><?php echo htmlspecialchars($vehicle['total_price']['currency_info'] ?? ' - '); ?></td>
<td class="nowrap"><?php echo htmlspecialchars($vehicle['profit']['currency_info'] ?? ' - '); ?></td> <td class="nowrap"><?php echo htmlspecialchars($vehicle['profit']['currency_info'] ?? ' - '); ?></td>
</tr> </tr>
<tr>
<td colspan="11" style="text-align:left;">
<span class="info-label">备注:</span> <span class="info-value"><?php echo $vehicle['remark']; ?></span>
</td>
</tr>
<?php endforeach; ?> <?php endforeach; ?>
<tr class="summary-row"> <tr class="summary-row">
@@ -0,0 +1,29 @@
<?php
namespace app\common\validate;
use think\Validate;
class PurchaseOrderItemsValidate extends Validate
{
// 规则
protected $rule = [
];
// 提示
protected $message = [
];
// 场景
protected $scene = [
'store' => [
],
'update' => [
]
];
}
@@ -0,0 +1,29 @@
<?php
namespace app\common\validate;
use think\Validate;
class PurchaseOrdersValidate extends Validate
{
// 规则
protected $rule = [
];
// 提示
protected $message = [
];
// 场景
protected $scene = [
'store' => [
],
'update' => [
]
];
}
+188 -8
View File
@@ -6,24 +6,204 @@ use think\Validate;
class StockOrdersValidate extends Validate class StockOrdersValidate extends Validate
{ {
// 规则 /**
* 验证规则
*/
protected $rule = [ protected $rule = [
'id' => 'number|egt:0',
'order_no' => 'require|max:40|unique:stock_orders',
'pi_no' => 'require|max:64',
'biz_date' => 'require',
'salesperson_id' => 'number|egt:0',
'salesperson_snapshot' => 'max:64',
'clearance_country_id' => 'require|number|egt:0',
'clearance_country_snapshot' => 'require|max:64',
'customer_source_id' => 'require|number|egt:0',
'customer_source_snapshot' => 'require|max:64',
'customer_id' => 'require|number|egt:0',
'customer_snapshot' => 'require|max:128',
'customer_country_id' => 'require|number|egt:0',
'customer_country_snapshot' => 'require|max:64',
'declarant_name' => 'require|max:64',
'eta_ship_date' => 'number|egt:0',
'shipping_method_id' => 'require|number',
'shipping_method_snapshot' => 'require|max:32',
'cif_total_amount' => 'require|float|egt:0',
'domestic_port_id' => 'require|number|egt:0',
'domestic_port_snapshot' => 'require|max:64',
'trade_term_id' => 'require|number|egt:0',
'trade_term_snapshot' => 'require|max:64',
'clearance_port_id' => 'require|number|egt:0',
'clearance_port_snapshot' => 'require|max:64',
'latest_arrival_date' => 'number|egt:0',
'contract_exchange_rate' => 'require|float|egt:0',
'settlement_currency' => 'require|length:3|alpha',
'remark' => 'max:255',
'contract' => 'max:255',
'is_use' => 'in:0,1',
'object_id' => 'number|egt:0',
'is_final' => 'in:0,1',
'approval_status' => 'in:0,1,2,3',
'status' => 'in:0,1',
'file_url' => 'max:255',
'pick_up_date' => 'number|egt:0',
'collect_all_date' => 'number|egt:0',
'created_at' => 'number|egt:0',
'updated_at' => 'number|egt:0',
'deleted_at' => 'number|egt:0',
]; ];
// 提示 /**
* 错误提示信息
*/
protected $message = [ protected $message = [
'order_no.require' => '备货单编号不能为空',
'order_no.max' => '备货单编号长度不能超过40个字符',
'order_no.unique' => '备货单编号已存在',
'pi_no.require' => 'PI号不能为空',
'pi_no.max' => 'PI号长度不能超过64个字符',
'biz_date.require' => '单据日期不能为空',
'clearance_country_id.require' => '清关目的国ID不能为空',
'clearance_country_snapshot.require' => '清关目的国名称不能为空',
'customer_source_id.require' => '客户来源ID不能为空',
'customer_source_snapshot.require' => '客户来源名称不能为空',
'customer_id.require' => '客户ID不能为空',
'customer_snapshot.require' => '客户名称不能为空',
'customer_country_id.require' => '客户所在国ID不能为空',
'customer_country_snapshot.require' => '客户所在国名称不能为空',
'declarant_name.require' => '清关人不能为空',
'shipping_method_id.require' => '出运方式ID不能为空',
'shipping_method_snapshot.require' => '出运方式不能为空',
'cif_total_amount.require' => '合计到岸价不能为空',
'cif_total_amount.float' => '合计到岸价必须为数字',
'cif_total_amount.egt' => '合计到岸价不能为负数',
'domestic_port_id.require' => '国内收货港ID不能为空',
'domestic_port_snapshot.require' => '国内收货港名称不能为空',
'trade_term_id.require' => '贸易条款ID不能为空',
'trade_term_snapshot.require' => '贸易条款名称不能为空',
'clearance_port_id.require' => '清关目的港ID不能为空',
'clearance_port_snapshot.require' => '清关目的港名称不能为空',
'contract_exchange_rate.require' => '合同汇率不能为空',
'contract_exchange_rate.float' => '合同汇率必须为数字',
'contract_exchange_rate.egt' => '合同汇率不能为负数',
'settlement_currency.require' => '结算币种不能为空',
'settlement_currency.length' => '结算币种必须为3个字符',
'settlement_currency.alpha' => '结算币种必须为字母',
'approval_status.in' => '审批状态值不正确',
'status.in' => '状态值不正确',
'is_final.in' => '是否终版值不正确',
'is_use.in' => '是否开过终版值不正确',
]; ];
// 场景 /**
* 验证场景
*/
protected $scene = [ protected $scene = [
// 创建场景
'store' => [ 'store' => [
'pi_no', 'biz_date',
'clearance_country_id', 'clearance_country_snapshot', 'customer_source_id',
'customer_source_snapshot', 'customer_id', 'customer_snapshot',
'customer_country_id', 'customer_country_snapshot', 'declarant_name',
'shipping_method_id', 'shipping_method_snapshot',
'domestic_port_id', 'domestic_port_snapshot',
'trade_term_id', 'trade_term_snapshot', 'clearance_port_id',
'clearance_port_snapshot', 'contract_exchange_rate',
'settlement_currency'
], ],
// 更新场景
'update' => [ 'update' => [
'pi_no', 'biz_date',
'clearance_country_id', 'clearance_country_snapshot', 'customer_source_id',
'customer_source_snapshot', 'customer_id', 'customer_snapshot',
'customer_country_id', 'customer_country_snapshot', 'declarant_name',
'shipping_method_id', 'shipping_method_snapshot',
'domestic_port_id', 'domestic_port_snapshot',
'trade_term_id', 'trade_term_snapshot', 'clearance_port_id',
'clearance_port_snapshot', 'contract_exchange_rate',
'settlement_currency'
],
// 提交审批场景
'submit' => [
'id' => 'require|number|egt:1',
'status' => 'require|in:1'
],
// 审批场景
'approve' => [
'id' => 'require|number|egt:1',
'approval_status' => 'require|in:1,2,3'
],
// 状态更新场景
'status' => [
'id' => 'require|number|egt:1',
'status' => 'require|in:0,1'
],
// 简略验证场景(用于快速验证)
'simple' => [
'order_no', 'biz_date', 'cif_total_amount', 'settlement_currency'
] ]
]; ];
/**
* 自定义验证规则 - 验证时间戳是否合理
*/
protected function checkTimestamp($value, $rule, $data = [])
{
if ($value === 0 || $value === '0') {
return true;
}
// 时间戳应该在1970年到现在+1年的范围内
$minTimestamp = 0;
$maxTimestamp = time() + (365 * 24 * 60 * 60);
return $value >= $minTimestamp && $value <= $maxTimestamp;
}
/**
* 自定义验证规则 - 验证金额格式
*/
protected function checkMoney($value, $rule, $data = [])
{
if (!is_numeric($value)) {
return false;
}
// 验证小数点位数不超过2位
if (strpos($value, '.') !== false) {
$decimalPart = explode('.', $value)[1];
if (strlen($decimalPart) > 2) {
return false;
}
}
return true;
}
/**
* 场景验证前回调 - 添加自定义规则
*/
// protected function sceneBefore($scene)
// {
// // 为时间戳字段添加自定义验证
// $timestampFields = ['biz_date', 'eta_ship_date', 'latest_arrival_date', 'pick_up_date', 'collect_all_date', 'created_at', 'updated_at', 'deleted_at'];
// foreach ($timestampFields as $field) {
// if (isset($this->scene[$scene][$field])) {
// $this->rule[$field] .= '|checkTimestamp';
// }
// }
// // 为金额字段添加自定义验证
// $moneyFields = ['cif_total_amount', 'contract_exchange_rate'];
// foreach ($moneyFields as $field) {
// if (isset($this->scene[$scene][$field])) {
// $this->rule[$field] .= '|checkMoney';
// }
// }
// }
} }
+31 -30
View File
@@ -9,6 +9,7 @@ use app\common\utils\scaffold\Generate;
use support\Request; use support\Request;
use support\Db; use support\Db;
use support\Cache; use support\Cache;
use support\Redis;
class IndexController class IndexController
{ {
@@ -69,42 +70,42 @@ class IndexController
*/ */
public function createResource() public function createResource()
{ {
$options = [ // $options = [
'controller' => [ // 'controller' => [
'module' => 'crm', // 'module' => 'common',
'name' => 'approval_flows' // 'name' => 'purchase_order_items'
], // ],
'model' => [ // 'model' => [
'module' => 'crm', // 'module' => 'common',
'name' => 'approval_flows' // 'name' => 'purchase_order_items'
], // ],
'service' => [ // 'service' => [
'module' => 'crm', // 'module' => 'common',
'name' => 'approval_flows' // 'name' => 'purchase_order_items'
], // ],
'logic' => [ // 'logic' => [
'module' => 'crm', // 'module' => 'common',
'name' => 'approval_flows' // 'name' => 'purchase_order_items'
], // ],
'validate' => [ // 'validate' => [
'module' => 'crm', // 'module' => 'common',
'name' => 'approval_flows' // 'name' => 'purchase_order_items'
], // ],
'table' => 'approval_flows' // 'table' => 'purchase_order_items'
]; // ];
$result = (new Generate($options))->doGenerate(); // $result = (new Generate($options))->doGenerate();
return $result; // return $result;
} }
public function test(Request $request) public function test(Request $request)
{ {
// 菜单迁移
// $where[] = ['id', '>', 141];
// $list = (new \app\common\utils\MigrationResources())->do('resources_20250916_bak', 'resources_yuanshi', $where);
$list = (new \app\common\utils\MigrationResources())->getFullResourceTreeOptimized('resources_20250916_bak', []); $info = \app\common\model\PurchaseOrders::find(14);
var_dump($list); $service = new \app\common\service\PurchaseOrdersService();
$result = $service->startApproval($info);
return json($result);
} }
} }
+1 -677
View File
@@ -2,45 +2,12 @@
namespace app\crm\service; namespace app\crm\service;
use app\common\model\StockOrderAccounts;
use app\common\model\StockOrderItemOptions;
use app\common\model\StockOrderItems;
use app\common\validate\StockOrdersValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrders;
use app\common\model\SysCurrency;
use support\Request; use support\Request;
use app\common\model\User;
use support\Db;
use support\Model;
use app\common\model\ApprovalInstances;
use app\common\model\ApprovalRecords;
use support\exception\BusinessException; use support\exception\BusinessException;
class StockOrdersService class StockOrdersService extends \app\common\service\StockOrdersService
{ {
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrders::class;
/**
* 验证器
*/
protected $validator = StockOrdersValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
protected function buildQueryConfig(Request $request, string $scene = 'index'): array protected function buildQueryConfig(Request $request, string $scene = 'index'): array
{ {
$p = $request->all(); $p = $request->all();
@@ -97,302 +64,6 @@ class StockOrdersService
return $config; return $config;
} }
public function beforeServiceStore($data, Request $request)
{
$userId = $request->user->uid;
$data['order_no'] = generateStockNo();
$data['biz_date'] = strtotime($data['biz_date']);
$data['eta_ship_date'] = strtotime($data['eta_ship_date']);
$data['latest_arrival_date'] = strtotime($data['latest_arrival_date']);
$data['salesperson_id'] = $userId;
$data['salesperson_snapshot'] = User::where('id', $userId)->value('name') ?? '';
$data['approval_status'] = $data['approval_status'] == 1 ? 1 : 0;
// if ($data['is_final'] == 1) {
$data['pick_up_date'] = $data['pick_up_date'] ? strtotime($data['pick_up_date']) : 0;
$data['collect_all_date'] = $data['collect_all_date'] ? strtotime($data['collect_all_date']) : 0;
// }
return $data;
}
protected function afterServiceStore($res)
{
// 处理原单
if ($res->is_final == 1 && $res->object_id > 0) {
$order = StockOrders::find($res->object_id);
$order->is_use = 1;
$order->object_id = $res->id;
if (!$order->save()) {
flg('备货单【'.$order->order_no.'】创建终版成功,但更新原单失败');
}
}
// 启动审批
if ($res->approval_status == 1) {
$this->startApproval($res);
}
return $res;
}
/**
* 启动审批
*/
public function startApproval($item)
{
// 启动审批
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
$appro->start('stock_orders', 'stock_orders', $item->id, $item->toArray(), $item->salesperson_id);
// 异步生成pdf文件
\Webman\RedisQueue\Redis::send('stock-order-pdf', ['id'=>$item->id]);
}
/**
* 创建PDF文件
*/
public function createdPdfFile($id)
{
$config = [];
$config['model'] = $this->modelClass;
$config['where']['id'] = $id;
$config['with'][] = 'items';
$config['with'][] = 'items.options';
$config['with'][] = 'items.moneyValues';
$config['with'][] = 'accounts';
$config['with'][] = 'moneyValues';
$config['with'][] = 'salesperson';
$item = $this->logicShow($config);
$pdfData = $this->pdfData($item);
// 渲染模板为最终HTML
$tplPath = app_path('common/utils/pdf/template/stockOrder.stub');
$html = \app\common\utils\pdf\service\PdfHelper::render($tplPath, ['data' => $pdfData]);
// 生成PDF
$driver = new \app\common\utils\pdf\service\MpdfDriver();
$pdfBin = $driver->htmlToPdf($html);
// 存储
$dir = public_path('pdf').'/';
$fileName = ($pdfData['order_no'] ?? date('YmdHis')) . '.pdf';
// 本地保存
\app\common\utils\pdf\service\PdfStorage::saveBinary(
$pdfBin,
$dir,
$fileName
);
// 上传云端
$param = [
'path' => $dir . $fileName,
'scene' => 'stock_orders',
'category' => 'pdf',
'original_name' => $fileName
];
$up = new \app\common\service\UploadService();
$res = $up->uploadLocalFile($param);
@unlink($dir . $fileName);
// 更新文件地址
$item->file_url = $res['file_name'];
$item->save();
return $res;
}
public function pdfData($item)
{
$vehList = [];
$index = 0;
$totalProfit = 0; // 总利润
// $priceFields = [
// 'official_price', // '官方指导价',
// 'discount_price', // '优惠',
// 'listing_price', // '二手挂牌价价',
// 'reduction_price', // '优惠',
// 'handling_fee', // '手续费',
// 'retrofit_fee', // '改装费',
// 'fob_transport_fee', // 'FOB运输费',
// 'port_misc_fee', // '港杂',
// 'ocean_freight', // '海运费',
// 'unit_price', // '单价',
// 'total_price', // '总价',
// // 'profit', // '利润'
// ];
foreach ($item->items as $k => $v) {
$currencyInfo = SysCurrency::where('currency_code', $item->settlement_currency)->first(['currency_symbol', 'currency_name'])->toArray();
// 存在则数量加1
if (count($vehList) > 0 && isset($vehList[$v->unique_id])) {
$vehList[$v->unique_id]['num'] += 1;
$vehList[$v->unique_id]['total_price']['currency_info'] = $currencyInfo['currency_symbol'].number_format($vehList[$v->unique_id]['total_price']['amount']*$vehList[$v->unique_id]['num'], 2, '.', ',');
$vehList[$v->unique_id]['profit']['currency_info'] = $currencyInfo['currency_symbol'].number_format($vehList[$v->unique_id]['profit']['amount']*$vehList[$v->unique_id]['num'], 2, '.', ',');
continue;
}
$index += 1;
// 处理金额 (每次循环重新初始化)
$mv = [];
foreach ($v->moneyValues as $money) {
$mv[$money->field] = [
'currency' => $money->currency,
'amount' => $money->amount,
'rate' => $money->exchange_rate,
'currency_info' => SysCurrency::where('currency_code', $money->currency)->value('currency_symbol').number_format($money->amount, 2, '.', ',')
];
}
// 处理改装 (每次循环重新初始化)
$mfy = '';
foreach ($v->options as $my) {
$mfy .= $my->option_name_snapshot.' ';
}
// 计算单项利润并累加到总利润
$itemProfit = $this->calculateProfit($mv, $item);
$totalProfit += $itemProfit;
// 处理结果集
$vehListItem = [
'index' => $index,
'model_snapshot' => $v->model_snapshot,
'color_interior_snapshot' => $v->color_interior_snapshot,
'color_exterior_snapshot' => $v->color_exterior_snapshot,
'num' => 1,
'modify' => $mfy,
'mileage' => $v->mileage
];
$vehList[$v->unique_id] = $vehListItem + $mv;
}
$mvs = [];
foreach ($item->moneyValues as $moneys) {
$mvs[$moneys->field] = [
'currency' => $moneys->currency,
'amount' => $moneys->amount,
'rate' => $moneys->exchange_rate,
'currency_info' => SysCurrency::where('currency_code', $moneys->currency)->value('currency_symbol').number_format($moneys->amount, 2, '.', ','),
];
}
$accList = [];
foreach ($item->accounts as $k => $v) {
$accList[] = [
'index' => '收款'.($k + 1),
'remit_country_name_snapshot' => $v->remit_country_name_snapshot,
'remit_date' => date('Y-m-d', $v->remit_date),
'currency_name_snapshot' => $v->currency_name_snapshot,
'account_name_snapshot' => $v->account_name_snapshot,
'remitter_name' => $v->remitter_name,
'amount' => $v->amount,
];
}
$veh = [
'order_no' => $item->order_no,
'salesperson_snapshot' => $item->salesperson_snapshot,
'sign_img_url' => (!empty($item->salesperson->sign_img)) ?
(new \app\common\service\OssService)->generatePrivateUrl($item->salesperson->sign_img) : '',
'created_at' => date('Y-m-d', strtotime($item->created_at)),
'pi_no' => $item->pi_no,
'biz_date' => date('Y-m-d', $item->biz_date),
'clearance_country_snapshot' => $item->clearance_country_snapshot,
'customer_source_snapshot' => $item->customer_source_snapshot,
'customer_snapshot' => $item->customer_snapshot,
'customer_country_snapshot' => $item->customer_country_snapshot,
// 订单项
'veh_list' => array_values($vehList), // 重新索引数组
'contract_exchange_rate' => $item->contract_exchange_rate,
'cif_total_amount' => $mvs['cif_total_amount'],
'profit_total' => $mvs['profit_total'],
'declarant_name' => $item->declarant_name,
'eta_ship_date' => date('Y-m-d', $item->eta_ship_date),
'shipping_method_snapshot' => $item->shipping_method_snapshot,
'domestic_port_snapshot' => $item->domestic_port_snapshot,
'trade_term_snapshot' => $item->trade_term_snapshot,
'clearance_port_snapshot' => $item->clearance_port_snapshot,
'latest_arrival_date' => date('Y-m-d', $item->latest_arrival_date),
'pick_up_date' => date('Y-m-d', $item->pick_up_date),
'collect_all_date' => date('Y-m-d', $item->collect_all_date),
'is_final' => $item->is_final,
// 账户
'account_list' => $accList,
'acc_index' => count($accList)+1,
'currency_symbol' => $item->settlement_currency,
'sign_imgs' => $this->queryAppro($item->id),
'contract_url' => (!empty($item->contract)) ? (new \app\common\service\OssService)->generatePrivateUrl($item->contract) : ''
];
return $veh;
}
public function queryAppro($bizId)
{
$instances = ApprovalInstances::where('biz_id', $bizId)->where('biz_type', 'stock_orders')->first();
if (!$instances) {
return [];
}
$records = ApprovalRecords::where('instance_id', $instances->id)->where('action', 'approve')->orderBy('step_index', 'asc')->pluck('approver_id')->toArray();
if (count($records) == 0) {
return [];
}
$signImgs = [];
foreach ($records as $k => $v) {
$signImg = User::where('id', $v)->value('sign_img');
$signImgs[$k] = (!empty($signImg))?(new \app\common\service\OssService)->generatePrivateUrl($signImg):'';
}
return $signImgs;
}
/**
* 打印数据
*/
public function servicePrint(Request $request)
{
$config = $this->buildQueryConfig($request, 'show');
$item = $this->logicShow($config);
return $this->postProcess('Print', $item);
}
public function serviceDetail(Request $request)
{
$config = $this->buildQueryConfig($request, 'detail');
$item = $this->logicShow($config);
$pdfData = $this->pdfData($item);
return $this->postProcess('Detail', $pdfData);
}
/**
* 审批
*/
public function serviceApproval(Request $request)
{
$config = $this->buildQueryConfig($request, 'approval');
$this->logicUpdateBy($config, [
'approval_status' => 1
]);
$item = $this->logicShow($config);
$this->startApproval($item);
return $this->postProcess('Approval', $item);
}
/** /**
* 最终审批 * 最终审批
@@ -412,351 +83,4 @@ class StockOrdersService
$this->startApproval($item); $this->startApproval($item);
return $this->postProcess('UltimateApproval', $item); return $this->postProcess('UltimateApproval', $item);
} }
/**
* 创建
*
* @param Request $request
* @param array $data
* @return mixed
*/
public function serviceStore(Request $request, array $data = [])
{
// 关联表较多,增加事务处理
return Db::transaction(function () use ($request, $data) {
$data = $this->preProcess('Store', $data, $request);
$dl = $this->getDataLimitFromRequest($request);
$created = $this->logicCreate($data, $dl);
// 处理车辆和账户信息
$this->processOrderItems($created, $data);
return $this->postProcess('Store', $created);
});
}
protected function onlyFillableData(Model|string $model, array $data, array $extraWhitelist = []): array
{
// 兼容传类名或实例
$m = \is_string($model) ? new $model : $model;
// 1) 优先使用 fillable
$keys = $m->getFillable();
// 2) 若没配置 fillable(常见:用 guarded),回退到完整表字段,避免误伤
if (empty($keys)) {
$keys = $m->getConnection()
->getSchemaBuilder()
->getColumnListing($m->getTable());
}
// 3) 允许额外白名单(如虚拟字段、JSON映射字段)
if ($extraWhitelist) {
$keys = array_merge($keys, $extraWhitelist);
}
return array_intersect_key($data, array_flip($keys));
}
/**
* 更新前处理
*
* @param array $data
* @param Request $request
* @return array
*/
public function beforeServiceUpdate($data, Request $request)
{
$data['biz_date'] = strtotime($data['biz_date']);
$data['eta_ship_date'] = strtotime($data['eta_ship_date']);
$data['latest_arrival_date'] = strtotime($data['latest_arrival_date']);
$data['approval_status'] = $data['approval_status'] == 1 ? 1 : 0;
$data['pick_up_date'] = $data['pick_up_date'] ? strtotime($data['pick_up_date']) : 0;
$data['collect_all_date'] = $data['collect_all_date'] ? strtotime($data['collect_all_date']) : 0;
return $data;
}
/**
* 更新后处理
*
* @param mixed $res
* @return mixed
*/
protected function afterServiceUpdate($res)
{
// 启动审批
if ($res->approval_status == 1) {
$this->startApproval($res);
}
return $res;
}
/**
* 更新
*
* @param Request $request
* @param array $data
* @return mixed
*/
public function serviceUpdate(Request $request, array $data = [])
{
// 关联表较多,增加事务处理
return Db::transaction(function () use ($request, $data) {
$data = $this->preProcess('Update', $data, $request);
$config = $this->buildQueryConfig($request, 'update');
// 过滤掉非库字段
$dbData = $this->onlyFillableData($config['model'], $data);
// 更新主表
$updated = $this->logicUpdateBy($config, $dbData);
// 获取更新后的数据
$order = $this->logicShow($config);
// 处理车辆和账户信息
$this->processOrderItems($order, $data, true);
return $this->postProcess('Update', $order);
});
}
/**
* 处理订单项(车辆和账户)
* @param StockOrders $order 订单对象
* @param array $data 数据
* @param bool $isUpdate 是否为更新操作
*/
private function processOrderItems($order, array $data, bool $isUpdate = false): void
{
// 如果是更新操作,先删除原有的关联数据
if ($isUpdate) {
$this->clearExistingOrderItems($order->id);
}
// 处理车辆项
$this->processVehicleItems($order, $data['veh_list'] ?? []);
// 处理账户项
$this->processAccountItems($order, $data['account_list'] ?? []);
}
/**
* (更新时)清除已存在的订单项
* @param int $orderId 订单ID
*/
private function clearExistingOrderItems(int $orderId): void
{
// 删除车辆改装项
StockOrderItemOptions::whereHas('item', function ($query) use ($orderId) {
$query->where('order_id', $orderId);
})->delete();
// 删除车辆项及其相关金额记录
$orderItems = StockOrderItems::where('order_id', $orderId)->get();
foreach ($orderItems as $item) {
// 删除车辆项的金额记录
Db::table('veh_money_value')
->where('object_scene', 'stock_order_items')
->where('object_id', $item->id)
->delete();
}
// 删除车辆项
StockOrderItems::where('order_id', $orderId)->delete();
// 删除订单本身的金额记录
Db::table('veh_money_value')
->where('object_scene', 'stock_orders')
->where('object_id', $orderId)
->delete();
// 删除账户项
StockOrderAccounts::where('order_id', $orderId)->delete();
}
/**
* 处理车辆项
*/
private function processVehicleItems($order, array $vehList): void
{
$cifTotalAmount = 0.00;
// $cifTotalAmountRate = 0;
// $cifTotalAmountCurrency = 'CNY';
$profitTotalAmount = 0.00;
foreach ($vehList as $veh) {
$veh['order_id'] = $order->id;
$veh['unique_id'] = $this->generateVehicleUniqueId($veh);
$item = StockOrderItems::create($veh);
// 处理金额信息
$this->processVehiclePrices($item, $veh);
// 计算利润
$profit = $this->calculateProfit($veh, $order);
$item->addMoney('profit', $order->settlement_currency, $profit, $order->contract_exchange_rate, '利润');
// 累计到岸价
$cifTotalAmount += $veh['total_price']['amount'] ?? 0;
$profitTotalAmount += $profit;
// if (isset($veh['retrofit_fee']['rate'])) {
// $cifTotalAmountRate = $veh['retrofit_fee']['rate'];
// }
// if (isset($veh['retrofit_fee']['currency'])) {
// $cifTotalAmountCurrency = $veh['retrofit_fee']['currency'];
// }
// 处理改装项
$this->processModificationItems($item->id, $veh['modify_list'] ?? []);
}
// 保存合计到岸价
$order->addMoney('cif_total_amount', $order->settlement_currency, $cifTotalAmount, $order->contract_exchange_rate, '合计到岸价');
// 利润
$order->addMoney('profit_total', $order->settlement_currency, $profitTotalAmount, $order->contract_exchange_rate, '总利润');
}
/**
* 生成车辆唯一标识
*/
private function generateVehicleUniqueId(array $veh): string
{
$uniqueIdStr = "";
$uniqueIdStr .= $veh['sku_id'] ?? '';
$uniqueIdStr .= $veh['model_snapshot'] ?? '';
$uniqueIdStr .= $veh['color_interior_code'] ?? '';
$uniqueIdStr .= $veh['color_exterior_code'] ?? '';
$uniqueIdStr .= $veh['mileage'] ?? '';
$uniqueIdStr .= json_encode($veh['modify_list'] ?? []);
return md5($uniqueIdStr);
}
/**
* 处理车辆价格信息
*/
private function processVehiclePrices($item, array $veh): void
{
// 基础费用
$priceFields = [
'unit_price' => '单价',
'total_price' => '总价',
'handling_fee' => '手续费',
'fob_transport_fee' => 'FOB运输费',
'port_misc_fee' => '港杂',
'retrofit_fee' => '改装费',
'ocean_freight' => '海运费'
];
foreach ($priceFields as $field => $description) {
if (!empty($veh[$field]['amount'])) {
$item->addMoney(
$field,
$veh[$field]['currency'],
$veh[$field]['amount'],
$veh[$field]['rate'],
$description
);
}
}
// 根据里程处理新车或二手车价格
if (!empty($veh['mileage']) && $veh['mileage'] > 0) {
// 二手车
if (!empty($veh['listing_price']['amount'])) {
$item->addMoney(
'listing_price',
$veh['listing_price']['currency'],
$veh['listing_price']['amount'],
$veh['listing_price']['rate'],
'二手挂牌价'
);
}
if (!empty($veh['reduction_price']['amount'])) {
$item->addMoney(
'reduction_price',
$veh['reduction_price']['currency'],
$veh['reduction_price']['amount'],
$veh['reduction_price']['rate'],
'二手减价'
);
}
} else {
// 新车
if (!empty($veh['official_price']['amount'])) {
$item->addMoney(
'official_price',
$veh['official_price']['currency'],
$veh['official_price']['amount'],
$veh['official_price']['rate'],
'官方指导价'
);
}
if (!empty($veh['discount_price']['amount'])) {
$item->addMoney(
'discount_price',
$veh['discount_price']['currency'],
$veh['discount_price']['amount'],
$veh['discount_price']['rate'],
'优惠价'
);
}
}
}
/**
* 计算利润
*/
private function calculateProfit(array $veh, $order): float
{
$unitPrice = (float)($veh['unit_price']['amount'] ?? 0);
if (!empty($veh['mileage']) && $veh['mileage'] > 0) {
// 二手车
$ttPrice = ($veh['listing_price']['amount'] ?? 0) / ($order->contract_exchange_rate ?: 1);
$ddPrice = $veh['reduction_price']['amount'] ?? 0;
} else {
// 新车
$ttPrice = ($veh['official_price']['amount'] ?? 0) / ($order->contract_exchange_rate ?: 1);
$ddPrice = $veh['discount_price']['amount'] ?? 0;
}
$handlingFee = (float)($veh['handling_fee']['amount'] ?? 0);
$fobTransportFee = (float)($veh['fob_transport_fee']['amount'] ?? 0);
$portMiscFee = (float)($veh['port_misc_fee']['amount'] ?? 0);
$retrofitFee = (float)($veh['retrofit_fee']['amount'] ?? 0);
$oceanFreight = (float)($veh['ocean_freight']['amount'] ?? 0);
return $unitPrice - $ttPrice - $ddPrice - $handlingFee - $fobTransportFee - $portMiscFee - $retrofitFee - $oceanFreight;
}
/**
* 处理改装项
*/
private function processModificationItems(int $orderItemId, array $modifyList): void
{
if (empty($modifyList)) {
return;
}
foreach ($modifyList as $modify) {
$modify['order_item_id'] = $orderItemId;
StockOrderItemOptions::create($modify);
}
}
/**
* 处理账户项
*/
private function processAccountItems($order, array $accountList): void
{
if (empty($accountList)) {
return;
}
foreach ($accountList as $account) {
$account['order_id'] = $order->id;
if (!empty($account['remit_date'])) {
$account['remit_date'] = strtotime($account['remit_date']);
}
StockOrderAccounts::create($account);
}
}
} }
+762
View File
@@ -0,0 +1,762 @@
<?php
namespace app\crm\service;
use app\common\model\StockOrderAccounts;
use app\common\model\StockOrderItemOptions;
use app\common\model\StockOrderItems;
use app\common\validate\StockOrdersValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrders;
use app\common\model\SysCurrency;
use support\Request;
use app\common\model\User;
use support\Db;
use support\Model;
use app\common\model\ApprovalInstances;
use app\common\model\ApprovalRecords;
use support\exception\BusinessException;
class StockOrdersService_bak2
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrders::class;
/**
* 验证器
*/
protected $validator = StockOrdersValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
protected function buildQueryConfig(Request $request, string $scene = 'index'): array
{
$p = $request->all();
$config = [];
$config['model'] = $this->modelClass;
switch ($scene) {
case 'index':
// ====== ====== 筛选 ====== ======
// 业务id
if (isset($p['salesperson_id']) && $p['salesperson_id']) {
$config['where']['salesperson_id'] = $p['salesperson_id'];
}
// 初、终版
$config['where']['is_final'] = $p['is_final'] ?? 0;
// 关键字
if (isset($p['keyword']) && $p['keyword']) {
$k = '%' . $p['keyword'] . '%';
foreach (['pi_no', 'order_no', 'customer_snapshot'] as $col) {
$config['orWhere'][] = [$col, 'like', $k];
}
}
$config['order']['id'] = 'desc';
$config['where']['salesperson_id'] = $request->user->uid;
break;
case 'print':
case 'approval':
$config['where']['id'] = $p['id'];
break;
case 'detail':
case 'show':
$config['where']['id'] = $p['id'];
$config['with'][] = 'items';
$config['with'][] = 'items.options';
$config['with'][] = 'items.moneyValues';
$config['with'][] = 'accounts';
$config['with'][] = 'moneyValues';
$config['with'][] = 'salesperson';
break;
case 'store':
break;
case 'update':
$config['where']['id'] = $p['id'];
break;
case 'destroy':
$config['where']['id'] = $p['id'];
break;
}
return $config;
}
public function beforeServiceStore($data, Request $request)
{
$userId = $request->user->uid;
$data['order_no'] = generateStockNo();
$data['biz_date'] = strtotime($data['biz_date']);
$data['eta_ship_date'] = strtotime($data['eta_ship_date']);
$data['latest_arrival_date'] = strtotime($data['latest_arrival_date']);
$data['salesperson_id'] = $userId;
$data['salesperson_snapshot'] = User::where('id', $userId)->value('name') ?? '';
$data['approval_status'] = $data['approval_status'] == 1 ? 1 : 0;
// if ($data['is_final'] == 1) {
$data['pick_up_date'] = $data['pick_up_date'] ? strtotime($data['pick_up_date']) : 0;
$data['collect_all_date'] = $data['collect_all_date'] ? strtotime($data['collect_all_date']) : 0;
// }
return $data;
}
protected function afterServiceStore($res)
{
// 处理原单
if ($res->is_final == 1 && $res->object_id > 0) {
$order = StockOrders::find($res->object_id);
$order->is_use = 1;
$order->object_id = $res->id;
if (!$order->save()) {
flg('备货单【'.$order->order_no.'】创建终版成功,但更新原单失败');
}
}
// 启动审批
if ($res->approval_status == 1) {
$this->startApproval($res);
}
return $res;
}
/**
* 启动审批
*/
public function startApproval($item)
{
// 启动审批
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
$appro->start('stock_orders', 'stock_orders', $item->id, [], $item->salesperson_id);
// 异步生成pdf文件
\Webman\RedisQueue\Redis::send('stock-order-pdf', ['id'=>$item->id]);
}
/**
* 创建PDF文件
*/
public function createdPdfFile($id)
{
$config = [];
$config['model'] = $this->modelClass;
$config['where']['id'] = $id;
$config['with'][] = 'items';
$config['with'][] = 'items.options';
$config['with'][] = 'items.moneyValues';
$config['with'][] = 'accounts';
$config['with'][] = 'moneyValues';
$config['with'][] = 'salesperson';
$item = $this->logicShow($config);
$pdfData = $this->pdfData($item);
// 渲染模板为最终HTML
$tplPath = app_path('common/utils/pdf/template/stockOrder.stub');
$html = \app\common\utils\pdf\service\PdfHelper::render($tplPath, ['data' => $pdfData]);
// 生成PDF
$driver = new \app\common\utils\pdf\service\MpdfDriver();
$pdfBin = $driver->htmlToPdf($html);
// 存储
$dir = public_path('pdf').'/';
$fileName = ($pdfData['order_no'] ?? date('YmdHis')) . '.pdf';
// 本地保存
\app\common\utils\pdf\service\PdfStorage::saveBinary(
$pdfBin,
$dir,
$fileName
);
// 上传云端
$param = [
'path' => $dir . $fileName,
'scene' => 'stock_orders',
'category' => 'pdf',
'original_name' => $fileName
];
$up = new \app\common\service\UploadService();
$res = $up->uploadLocalFile($param);
@unlink($dir . $fileName);
// 更新文件地址
$item->file_url = $res['file_name'];
$item->save();
return $res;
}
public function pdfData($item)
{
$vehList = [];
$index = 0;
$totalProfit = 0; // 总利润
// $priceFields = [
// 'official_price', // '官方指导价',
// 'discount_price', // '优惠',
// 'listing_price', // '二手挂牌价价',
// 'reduction_price', // '优惠',
// 'handling_fee', // '手续费',
// 'retrofit_fee', // '改装费',
// 'fob_transport_fee', // 'FOB运输费',
// 'port_misc_fee', // '港杂',
// 'ocean_freight', // '海运费',
// 'unit_price', // '单价',
// 'total_price', // '总价',
// // 'profit', // '利润'
// ];
foreach ($item->items as $k => $v) {
$currencyInfo = SysCurrency::where('currency_code', $item->settlement_currency)->first(['currency_symbol', 'currency_name'])->toArray();
// 存在则数量加1
if (count($vehList) > 0 && isset($vehList[$v->unique_id])) {
$vehList[$v->unique_id]['num'] += 1;
$vehList[$v->unique_id]['total_price']['currency_info'] = $currencyInfo['currency_symbol'].number_format($vehList[$v->unique_id]['total_price']['amount']*$vehList[$v->unique_id]['num'], 2, '.', ',');
$vehList[$v->unique_id]['profit']['currency_info'] = $currencyInfo['currency_symbol'].number_format($vehList[$v->unique_id]['profit']['amount']*$vehList[$v->unique_id]['num'], 2, '.', ',');
continue;
}
$index += 1;
// 处理金额 (每次循环重新初始化)
$mv = [];
foreach ($v->moneyValues as $money) {
$mv[$money->field] = [
'currency' => $money->currency,
'amount' => $money->amount,
'rate' => $money->exchange_rate,
'currency_info' => SysCurrency::where('currency_code', $money->currency)->value('currency_symbol').number_format($money->amount, 2, '.', ',')
];
}
// 处理改装 (每次循环重新初始化)
$mfy = '';
foreach ($v->options as $my) {
$mfy .= $my->option_name_snapshot.' ';
}
// 计算单项利润并累加到总利润
$itemProfit = $this->calculateProfit($mv, $item);
$totalProfit += $itemProfit;
// 处理结果集
$vehListItem = [
'index' => $index,
'model_snapshot' => $v->model_snapshot,
'color_interior_snapshot' => $v->color_interior_snapshot,
'color_exterior_snapshot' => $v->color_exterior_snapshot,
'num' => 1,
'modify' => $mfy,
'mileage' => $v->mileage
];
$vehList[$v->unique_id] = $vehListItem + $mv;
}
$mvs = [];
foreach ($item->moneyValues as $moneys) {
$mvs[$moneys->field] = [
'currency' => $moneys->currency,
'amount' => $moneys->amount,
'rate' => $moneys->exchange_rate,
'currency_info' => SysCurrency::where('currency_code', $moneys->currency)->value('currency_symbol').number_format($moneys->amount, 2, '.', ','),
];
}
$accList = [];
foreach ($item->accounts as $k => $v) {
$accList[] = [
'index' => '收款'.($k + 1),
'remit_country_name_snapshot' => $v->remit_country_name_snapshot,
'remit_date' => date('Y-m-d', $v->remit_date),
'currency_name_snapshot' => $v->currency_name_snapshot,
'account_name_snapshot' => $v->account_name_snapshot,
'remitter_name' => $v->remitter_name,
'amount' => $v->amount,
];
}
$veh = [
'order_no' => $item->order_no,
'salesperson_snapshot' => $item->salesperson_snapshot,
'sign_img_url' => (!empty($item->salesperson->sign_img)) ?
(new \app\common\service\OssService)->generatePrivateUrl($item->salesperson->sign_img) : '',
'created_at' => date('Y-m-d', strtotime($item->created_at)),
'pi_no' => $item->pi_no,
'biz_date' => date('Y-m-d', $item->biz_date),
'clearance_country_snapshot' => $item->clearance_country_snapshot,
'customer_source_snapshot' => $item->customer_source_snapshot,
'customer_snapshot' => $item->customer_snapshot,
'customer_country_snapshot' => $item->customer_country_snapshot,
// 订单项
'veh_list' => array_values($vehList), // 重新索引数组
'contract_exchange_rate' => $item->contract_exchange_rate,
'cif_total_amount' => $mvs['cif_total_amount'],
'profit_total' => $mvs['profit_total'],
'declarant_name' => $item->declarant_name,
'eta_ship_date' => date('Y-m-d', $item->eta_ship_date),
'shipping_method_snapshot' => $item->shipping_method_snapshot,
'domestic_port_snapshot' => $item->domestic_port_snapshot,
'trade_term_snapshot' => $item->trade_term_snapshot,
'clearance_port_snapshot' => $item->clearance_port_snapshot,
'latest_arrival_date' => date('Y-m-d', $item->latest_arrival_date),
'pick_up_date' => date('Y-m-d', $item->pick_up_date),
'collect_all_date' => date('Y-m-d', $item->collect_all_date),
'is_final' => $item->is_final,
// 账户
'account_list' => $accList,
'acc_index' => count($accList)+1,
'currency_symbol' => $item->settlement_currency,
'sign_imgs' => $this->queryAppro($item->id),
'contract_url' => (!empty($item->contract)) ? (new \app\common\service\OssService)->generatePrivateUrl($item->contract) : ''
];
return $veh;
}
public function queryAppro($bizId)
{
$instances = ApprovalInstances::where('biz_id', $bizId)->where('biz_type', 'stock_orders')->first();
if (!$instances) {
return [];
}
$records = ApprovalRecords::where('instance_id', $instances->id)->where('action', 'approve')->orderBy('step_index', 'asc')->pluck('approver_id')->toArray();
if (count($records) == 0) {
return [];
}
$signImgs = [];
foreach ($records as $k => $v) {
$signImg = User::where('id', $v)->value('sign_img');
$signImgs[$k] = (!empty($signImg))?(new \app\common\service\OssService)->generatePrivateUrl($signImg):'';
}
return $signImgs;
}
/**
* 打印数据
*/
public function servicePrint(Request $request)
{
$config = $this->buildQueryConfig($request, 'show');
$item = $this->logicShow($config);
return $this->postProcess('Print', $item);
}
public function serviceDetail(Request $request)
{
$config = $this->buildQueryConfig($request, 'detail');
$item = $this->logicShow($config);
$pdfData = $this->pdfData($item);
return $this->postProcess('Detail', $pdfData);
}
/**
* 审批
*/
public function serviceApproval(Request $request)
{
$config = $this->buildQueryConfig($request, 'approval');
$this->logicUpdateBy($config, [
'approval_status' => 1
]);
$item = $this->logicShow($config);
$this->startApproval($item);
return $this->postProcess('Approval', $item);
}
/**
* 最终审批
*/
public function serviceUltimateApproval(Request $request)
{
$config = $this->buildQueryConfig($request, 'detail');
$item = $this->logicShow($config);
foreach ($item->items as $k => $v) {
if ($v->vin === '') {
throw new BusinessException('存在未填写vin的车辆,无法完成提交审核');
}
}
$this->logicUpdateBy($config, [
'approval_status' => 1
]);
$this->startApproval($item);
return $this->postProcess('UltimateApproval', $item);
}
/**
* 创建
*
* @param Request $request
* @param array $data
* @return mixed
*/
public function serviceStore(Request $request, array $data = [])
{
// 关联表较多,增加事务处理
return Db::transaction(function () use ($request, $data) {
$data = $this->preProcess('Store', $data, $request);
$dl = $this->getDataLimitFromRequest($request);
$created = $this->logicCreate($data, $dl);
// 处理车辆和账户信息
$this->processOrderItems($created, $data);
return $this->postProcess('Store', $created);
});
}
protected function onlyFillableData(Model|string $model, array $data, array $extraWhitelist = []): array
{
// 兼容传类名或实例
$m = \is_string($model) ? new $model : $model;
// 1) 优先使用 fillable
$keys = $m->getFillable();
// 2) 若没配置 fillable(常见:用 guarded),回退到完整表字段,避免误伤
if (empty($keys)) {
$keys = $m->getConnection()
->getSchemaBuilder()
->getColumnListing($m->getTable());
}
// 3) 允许额外白名单(如虚拟字段、JSON映射字段)
if ($extraWhitelist) {
$keys = array_merge($keys, $extraWhitelist);
}
return array_intersect_key($data, array_flip($keys));
}
/**
* 更新前处理
*
* @param array $data
* @param Request $request
* @return array
*/
public function beforeServiceUpdate($data, Request $request)
{
$data['biz_date'] = strtotime($data['biz_date']);
$data['eta_ship_date'] = strtotime($data['eta_ship_date']);
$data['latest_arrival_date'] = strtotime($data['latest_arrival_date']);
$data['approval_status'] = $data['approval_status'] == 1 ? 1 : 0;
$data['pick_up_date'] = $data['pick_up_date'] ? strtotime($data['pick_up_date']) : 0;
$data['collect_all_date'] = $data['collect_all_date'] ? strtotime($data['collect_all_date']) : 0;
return $data;
}
/**
* 更新后处理
*
* @param mixed $res
* @return mixed
*/
protected function afterServiceUpdate($res)
{
// 启动审批
if ($res->approval_status == 1) {
$this->startApproval($res);
}
return $res;
}
/**
* 更新
*
* @param Request $request
* @param array $data
* @return mixed
*/
public function serviceUpdate(Request $request, array $data = [])
{
// 关联表较多,增加事务处理
return Db::transaction(function () use ($request, $data) {
$data = $this->preProcess('Update', $data, $request);
$config = $this->buildQueryConfig($request, 'update');
// 过滤掉非库字段
$dbData = $this->onlyFillableData($config['model'], $data);
// 更新主表
$updated = $this->logicUpdateBy($config, $dbData);
// 获取更新后的数据
$order = $this->logicShow($config);
// 处理车辆和账户信息
$this->processOrderItems($order, $data, true);
return $this->postProcess('Update', $order);
});
}
/**
* 处理订单项(车辆和账户)
* @param StockOrders $order 订单对象
* @param array $data 数据
* @param bool $isUpdate 是否为更新操作
*/
private function processOrderItems($order, array $data, bool $isUpdate = false): void
{
// 如果是更新操作,先删除原有的关联数据
if ($isUpdate) {
$this->clearExistingOrderItems($order->id);
}
// 处理车辆项
$this->processVehicleItems($order, $data['veh_list'] ?? []);
// 处理账户项
$this->processAccountItems($order, $data['account_list'] ?? []);
}
/**
* (更新时)清除已存在的订单项
* @param int $orderId 订单ID
*/
private function clearExistingOrderItems(int $orderId): void
{
// 删除车辆改装项
StockOrderItemOptions::whereHas('item', function ($query) use ($orderId) {
$query->where('order_id', $orderId);
})->delete();
// 删除车辆项及其相关金额记录
$orderItems = StockOrderItems::where('order_id', $orderId)->get();
foreach ($orderItems as $item) {
// 删除车辆项的金额记录
Db::table('veh_money_value')
->where('object_scene', 'stock_order_items')
->where('object_id', $item->id)
->delete();
}
// 删除车辆项
StockOrderItems::where('order_id', $orderId)->delete();
// 删除订单本身的金额记录
Db::table('veh_money_value')
->where('object_scene', 'stock_orders')
->where('object_id', $orderId)
->delete();
// 删除账户项
StockOrderAccounts::where('order_id', $orderId)->delete();
}
/**
* 处理车辆项
*/
private function processVehicleItems($order, array $vehList): void
{
$cifTotalAmount = 0.00;
// $cifTotalAmountRate = 0;
// $cifTotalAmountCurrency = 'CNY';
$profitTotalAmount = 0.00;
foreach ($vehList as $veh) {
$veh['order_id'] = $order->id;
$veh['unique_id'] = $this->generateVehicleUniqueId($veh);
$item = StockOrderItems::create($veh);
// 处理金额信息
$this->processVehiclePrices($item, $veh);
// 计算利润
$profit = $this->calculateProfit($veh, $order);
$item->addMoney('profit', $order->settlement_currency, $profit, $order->contract_exchange_rate, '利润');
// 累计到岸价
$cifTotalAmount += $veh['total_price']['amount'] ?? 0;
$profitTotalAmount += $profit;
// if (isset($veh['retrofit_fee']['rate'])) {
// $cifTotalAmountRate = $veh['retrofit_fee']['rate'];
// }
// if (isset($veh['retrofit_fee']['currency'])) {
// $cifTotalAmountCurrency = $veh['retrofit_fee']['currency'];
// }
// 处理改装项
$this->processModificationItems($item->id, $veh['modify_list'] ?? []);
}
// 保存合计到岸价
$order->addMoney('cif_total_amount', $order->settlement_currency, $cifTotalAmount, $order->contract_exchange_rate, '合计到岸价');
// 利润
$order->addMoney('profit_total', $order->settlement_currency, $profitTotalAmount, $order->contract_exchange_rate, '总利润');
}
/**
* 生成车辆唯一标识
*/
private function generateVehicleUniqueId(array $veh): string
{
$uniqueIdStr = "";
$uniqueIdStr .= $veh['sku_id'] ?? '';
$uniqueIdStr .= $veh['model_snapshot'] ?? '';
$uniqueIdStr .= $veh['color_interior_code'] ?? '';
$uniqueIdStr .= $veh['color_exterior_code'] ?? '';
$uniqueIdStr .= $veh['mileage'] ?? '';
$uniqueIdStr .= json_encode($veh['modify_list'] ?? []);
return md5($uniqueIdStr);
}
/**
* 处理车辆价格信息
*/
private function processVehiclePrices($item, array $veh): void
{
// 基础费用
$priceFields = [
'unit_price' => '单价',
'total_price' => '总价',
'handling_fee' => '手续费',
'fob_transport_fee' => 'FOB运输费',
'port_misc_fee' => '港杂',
'retrofit_fee' => '改装费',
'ocean_freight' => '海运费'
];
foreach ($priceFields as $field => $description) {
if (!empty($veh[$field]['amount'])) {
$item->addMoney(
$field,
$veh[$field]['currency'],
$veh[$field]['amount'],
$veh[$field]['rate'],
$description
);
}
}
// 根据里程处理新车或二手车价格
if (!empty($veh['mileage']) && $veh['mileage'] > 0) {
// 二手车
if (!empty($veh['listing_price']['amount'])) {
$item->addMoney(
'listing_price',
$veh['listing_price']['currency'],
$veh['listing_price']['amount'],
$veh['listing_price']['rate'],
'二手挂牌价'
);
}
if (!empty($veh['reduction_price']['amount'])) {
$item->addMoney(
'reduction_price',
$veh['reduction_price']['currency'],
$veh['reduction_price']['amount'],
$veh['reduction_price']['rate'],
'二手减价'
);
}
} else {
// 新车
if (!empty($veh['official_price']['amount'])) {
$item->addMoney(
'official_price',
$veh['official_price']['currency'],
$veh['official_price']['amount'],
$veh['official_price']['rate'],
'官方指导价'
);
}
if (!empty($veh['discount_price']['amount'])) {
$item->addMoney(
'discount_price',
$veh['discount_price']['currency'],
$veh['discount_price']['amount'],
$veh['discount_price']['rate'],
'优惠价'
);
}
}
}
/**
* 计算利润
*/
private function calculateProfit(array $veh, $order): float
{
$unitPrice = (float)($veh['unit_price']['amount'] ?? 0);
if (!empty($veh['mileage']) && $veh['mileage'] > 0) {
// 二手车
$ttPrice = ($veh['listing_price']['amount'] ?? 0) / ($order->contract_exchange_rate ?: 1);
$ddPrice = $veh['reduction_price']['amount'] ?? 0;
} else {
// 新车
$ttPrice = ($veh['official_price']['amount'] ?? 0) / ($order->contract_exchange_rate ?: 1);
$ddPrice = $veh['discount_price']['amount'] ?? 0;
}
$handlingFee = (float)($veh['handling_fee']['amount'] ?? 0);
$fobTransportFee = (float)($veh['fob_transport_fee']['amount'] ?? 0);
$portMiscFee = (float)($veh['port_misc_fee']['amount'] ?? 0);
$retrofitFee = (float)($veh['retrofit_fee']['amount'] ?? 0);
$oceanFreight = (float)($veh['ocean_freight']['amount'] ?? 0);
return $unitPrice - $ttPrice - $ddPrice - $handlingFee - $fobTransportFee - $portMiscFee - $retrofitFee - $oceanFreight;
}
/**
* 处理改装项
*/
private function processModificationItems(int $orderItemId, array $modifyList): void
{
if (empty($modifyList)) {
return;
}
foreach ($modifyList as $modify) {
$modify['order_item_id'] = $orderItemId;
StockOrderItemOptions::create($modify);
}
}
/**
* 处理账户项
*/
private function processAccountItems($order, array $accountList): void
{
if (empty($accountList)) {
return;
}
foreach ($accountList as $account) {
$account['order_id'] = $order->id;
if (!empty($account['remit_date'])) {
$account['remit_date'] = strtotime($account['remit_date']);
}
StockOrderAccounts::create($account);
}
}
}
+2 -1
View File
@@ -119,7 +119,8 @@ if (!function_exists('flg')) {
if ($isFs) { if ($isFs) {
$data = [ $data = [
'content' => $eventData, 'content' => $eventData,
'time' => date('Y-m-d H:i:s', time()) 'time' => date('Y-m-d H:i:s', time()),
'source' => getenv('ENVIRONMENT')
]; ];
RedisQueueRedis::send("server", $data); RedisQueueRedis::send("server", $data);
} }
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace app\queue\redis;
use support\exception\BusinessException;
use Webman\RedisQueue\Consumer;
class ApprovalCallback implements Consumer
{
// 要消费的队列名
public $queue = 'approval-callback';
// 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
public $connection = 'default';
// 消费
public function consume($data)
{
try {
match ($data['flow_type']) {
'stock_orders' => $this->approvalStockOrders($data),
'purchase_orders' => $this->approvalPurchaseOrders($data),
default => throw new BusinessException('未知的审批类型,无法执行回调操作')
};
return true;
} catch (\Throwable $th) {
flg('审批回调异常:'.$th->getFile()."|".$th->getLine()."|".$th->getMessage(), false);
throw new BusinessException($th->getFile()."|".$th->getLine()."|".$th->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);
}
/**
* 备货单处理
*/
private function approvalStockOrders($data)
{
// 生成PDF文件
$service = new \app\crm\service\StockOrdersService();
$result = $service->createdPdfFile($data['biz_id']);
return $result;
}
/**
* 采购单处理
*/
private function approvalPurchaseOrders($data)
{
$udata['id'] = $data['biz_id'];
if ($data['status'] === 'approve') {
$udata['status'] = 2;
}
if ($data['status'] === 'reject') {
$udata['status'] = 3;
}
$service = new \app\common\service\PurchaseOrdersService();
$result = $service->updateStatus($udata);
return $result;
}
}
+2
View File
@@ -19,10 +19,12 @@ class Server implements Consumer
public function consume($data) public function consume($data)
{ {
try { try {
$source = $data['source'] === 'development' ? '-- 开发环境 --' : '** 生产环境 **';
$webhookUrl = 'https://open.feishu.cn/open-apis/bot/v2/hook/806c2e9d-6ca2-4345-a459-69bb2651706b'; $webhookUrl = 'https://open.feishu.cn/open-apis/bot/v2/hook/806c2e9d-6ca2-4345-a459-69bb2651706b';
$message = "====== ======\n"; $message = "====== ======\n";
$message .= $data['content']."\n"; $message .= $data['content']."\n";
$message .= "时间:".date('Y-m-d H:i:s', time())."\n"; $message .= "时间:".date('Y-m-d H:i:s', time())."\n";
$message .= "来源:".$source."\n";
$message .= "====== ======"; $message .= "====== ======";
sendFeishuTextMessage($webhookUrl, $message); sendFeishuTextMessage($webhookUrl, $message);
return true; return true;
@@ -22,7 +22,7 @@ return [
], ],
'worker' => [ 'worker' => [
'handler' => BusinessWorker::class, 'handler' => BusinessWorker::class,
'count' => cpu_count()*2, 'count' => 6,
'constructor' => ['config' => [ 'constructor' => ['config' => [
'eventHandler' => plugin\webman\gateway\Events::class, 'eventHandler' => plugin\webman\gateway\Events::class,
'name' => 'ChatBusinessWorker', 'name' => 'ChatBusinessWorker',
+14
View File
@@ -317,6 +317,9 @@ Route::group('/admin', function () {
Route::any('/action', [app\admin\controller\ApprovalRecordsController::class, 'approve']); Route::any('/action', [app\admin\controller\ApprovalRecordsController::class, 'approve']);
Route::any('/todo', [app\admin\controller\ApprovalRecordsController::class, 'todo']); Route::any('/todo', [app\admin\controller\ApprovalRecordsController::class, 'todo']);
Route::any('/border', [app\admin\controller\ApprovalRecordsController::class, 'businessOrder']);
Route::any('/transfer', [app\admin\controller\ApprovalRecordsController::class, 'transferApproval']);
Route::any('/timeline', [app\admin\controller\ApprovalRecordsController::class, 'approvalTimeline']);
}); });
Route::group('/stock/order', function () { Route::group('/stock/order', function () {
@@ -351,6 +354,17 @@ Route::group('/admin', function () {
Route::any('/user/achieved', [app\admin\targets\controller\StatisticsController::class, 'userAchieved']); Route::any('/user/achieved', [app\admin\targets\controller\StatisticsController::class, 'userAchieved']);
}); });
}); });
Route::group('/purchase/order', function () {
Route::any('/predata', [app\common\controller\PurchaseOrdersController::class, 'preQueryData']);
Route::any('/list', [app\common\controller\PurchaseOrdersController::class, 'index']);
Route::any('/show', [app\common\controller\PurchaseOrdersController::class, 'show']);
Route::any('/store', [app\common\controller\PurchaseOrdersController::class, 'store']);
Route::any('/update', [app\common\controller\PurchaseOrdersController::class, 'update']);
Route::any('/destroy', [app\common\controller\PurchaseOrdersController::class, 'destroy']);
Route::any('/resubmit', [app\common\controller\PurchaseOrdersController::class, 'resubmit']);
});
}); });