Merge branch 'develop'
This commit is contained in:
@@ -3,6 +3,7 @@ namespace app\common\utils\approval\service;
|
||||
|
||||
use support\exception\BusinessException;
|
||||
use support\Db;
|
||||
use support\Log;
|
||||
|
||||
class ApprovalFlowService
|
||||
{
|
||||
@@ -69,6 +70,8 @@ class ApprovalFlowService
|
||||
|
||||
$this->notifyCCs($firstStep, $instance, 'pending');
|
||||
|
||||
$this->pushTodoChanged($approverIds);
|
||||
|
||||
return ['instance_id' => $instanceId];
|
||||
});
|
||||
}
|
||||
@@ -151,12 +154,18 @@ class ApprovalFlowService
|
||||
$outcome = $this->getStepOutcome($instanceId, $round, $idx, $type); // 'pending' | 'approve' | 'reject'
|
||||
|
||||
if ($outcome === 'pending') {
|
||||
$this->pushTodoChanged([$approverId]);
|
||||
return ['status' => 'step_pending', 'msg' => '审批待定'];
|
||||
}
|
||||
|
||||
$otherPendingUids = $this->getPendingApproverIds($instanceId, $round, $idx);
|
||||
|
||||
// 3) 有结论:关闭本步其余 pending
|
||||
$this->closeOtherPending($instanceId, $round, $idx, [$approverId]);
|
||||
|
||||
// 这些人 pending→skipped,待办数减少
|
||||
$this->pushTodoChanged($otherPendingUids);
|
||||
|
||||
// 4) 拒绝 => 结束
|
||||
if ($outcome === 'reject') {
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update([
|
||||
@@ -164,7 +173,9 @@ class ApprovalFlowService
|
||||
'finished_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
$this->onFlowFinalized($instance, 'rejected');
|
||||
$this->sendNotification([$instance->initiator_id], $instance, 'reject', false);
|
||||
$this->pushTodoChanged([$approverId]);
|
||||
return ['status' => 'completed', 'msg' => '拒绝'];
|
||||
}
|
||||
|
||||
@@ -173,13 +184,18 @@ class ApprovalFlowService
|
||||
$nextIndex = $this->getNextStepIndex($steps, $formData, $idx);
|
||||
|
||||
if ($nextIndex === null) {
|
||||
$finalStatus = $this->normalizeFinalStatus((string)$instance->flow_type, 'approved');
|
||||
$notifyAction = ($finalStatus === 'voided') ? 'voided' : 'approve';
|
||||
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update([
|
||||
'status' => 'approved',
|
||||
'status' => $finalStatus,
|
||||
'finished_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
$this->sendNotification([$instance->initiator_id], $instance, 'approve', false);
|
||||
return ['status' => 'completed', 'msg' => '同意'];
|
||||
$this->onFlowFinalized($instance, $finalStatus);
|
||||
$this->sendNotification([$instance->initiator_id], $instance, $notifyAction, false);
|
||||
$this->pushTodoChanged([$approverId]);
|
||||
return ['status' => 'completed', 'msg' => ($finalStatus === 'voided' ? '已作废' : '同意')];
|
||||
}
|
||||
|
||||
// 乐观推进 current_step
|
||||
@@ -200,10 +216,58 @@ class ApprovalFlowService
|
||||
}
|
||||
$this->sendNotification($nextApprovers, $instance, 'pending', false);
|
||||
$this->notifyCCs($nextStep, $instance, 'pending');
|
||||
$this->pushTodoChanged(array_merge([$approverId], $nextApprovers));
|
||||
return ['status' => 'next_step', 'msg' => '进行下一步:'.$nextStep['name'] ?? ('Step '.$nextIndex)];
|
||||
});
|
||||
}
|
||||
|
||||
// 流程完结后的业务回调(approved|rejected|revoked|timeout?)
|
||||
private function onFlowFinalized(object $instance, string $final): void
|
||||
{
|
||||
try {
|
||||
switch ($instance->flow_type) {
|
||||
case 'stock_orders': {
|
||||
$order = \app\common\model\StockOrders::find($instance->biz_id);
|
||||
if (!$order) {
|
||||
throw new BusinessException('订单不存在');
|
||||
}
|
||||
if ($final === 'approved') {
|
||||
$order->approval_status = 2;
|
||||
$order->save();
|
||||
} elseif ($final === 'rejected') {
|
||||
$order->approval_status = 3;
|
||||
$order->save();
|
||||
} elseif ($final === 'revoked') {
|
||||
$order->approval_status = 0;
|
||||
$order->save();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'stock_orders_nullify':
|
||||
if ($final === 'approved') {
|
||||
$final = 'voided';
|
||||
Db::table('approval_instances')->where('id', $instance->id)->update([
|
||||
'status' => 'voided',
|
||||
]);
|
||||
}
|
||||
if (in_array($final, ['voided','approved'], true)) {
|
||||
$order = \app\common\model\StockOrders::find($instance->biz_id);
|
||||
if ($order && $order->approval_status !== 4) {
|
||||
$order->approval_status = 4;
|
||||
$order->save();
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 非作废流程,无需处理
|
||||
break;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('onFlowFinalized error: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** 撤回(仅发起人在无已处理记录前可撤回) */
|
||||
public function revoke(int $instanceId, int $initiatorId, string $reason = '')
|
||||
{
|
||||
@@ -226,12 +290,20 @@ class ApprovalFlowService
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$this->onFlowFinalized($instance, 'revoked');
|
||||
|
||||
$pendingUids = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('status', 'pending')
|
||||
->pluck('approver_id')->toArray();
|
||||
|
||||
Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('status', 'pending')
|
||||
->update(['status' => 'skipped', 'approved_at' => $now, 'updated_at' => $now]);
|
||||
|
||||
$this->sendNotification([$initiatorId], $instance, 'revoked', false);
|
||||
$this->pushTodoChanged($pendingUids);
|
||||
return ['status' => 'completed', 'result' => 'revoked'];
|
||||
});
|
||||
}
|
||||
@@ -310,8 +382,9 @@ class ApprovalFlowService
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if (!$flow) return;
|
||||
|
||||
$final = ($flow->timeout_action === 'auto_approve') ? 'approved' : 'rejected';
|
||||
$finalAction = ($flow->timeout_action === 'auto_approve') ? 'approve' : 'reject';
|
||||
$final = ($flow->timeout_action === 'auto_approve') ? 'approved' : 'rejected';
|
||||
$final = $this->normalizeFinalStatus((string)$instance->flow_type, $final);
|
||||
$finalAction = ($final === 'voided') ? 'voided' : (($final === 'approved') ? 'approve' : 'reject');
|
||||
|
||||
Db::table('approval_instances')->where('id', $instance->id)->update([
|
||||
'status' => $final,
|
||||
@@ -319,6 +392,15 @@ class ApprovalFlowService
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$this->onFlowFinalized((object)$instance, $final);
|
||||
|
||||
$pendingUids = Db::table('approval_records')
|
||||
->where('instance_id', $instance->id)
|
||||
->where('round', (int)$instance->round)
|
||||
->where('step_index', $instance->current_step)
|
||||
->where('status', 'pending')
|
||||
->pluck('approver_id')->toArray();
|
||||
|
||||
Db::table('approval_records')
|
||||
->where('instance_id', $instance->id)
|
||||
->where('round', (int)$instance->round)
|
||||
@@ -327,6 +409,8 @@ class ApprovalFlowService
|
||||
->update(['status' => 'timeout', 'approved_at' => $now, 'updated_at' => $now]);
|
||||
|
||||
$this->notifyInitiator($instance, $finalAction);
|
||||
|
||||
$this->pushTodoChanged($pendingUids);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -365,6 +449,32 @@ class ApprovalFlowService
|
||||
$head = $this->getDeptHeadId((int)$val);
|
||||
if ($head) $ids = [(int)$head];
|
||||
break;
|
||||
|
||||
case 'group_members': {
|
||||
// $gid = (int)($cfg['group_id'] ?? 0);
|
||||
$gid = (int)($cfg['value'] ?? 0);
|
||||
if ($gid <= 0) throw new BusinessException('group_members 需要 group_id');
|
||||
$ids = $this->getGroupMemberIds($gid); // A 方案
|
||||
break;
|
||||
}
|
||||
|
||||
case 'scenario_leader_of_initiator': {
|
||||
$formData = json_decode($instance->form_data ?? '{}', true) ?: [];
|
||||
// $scenario = $cfg['scenario'] ?? ($formData[$cfg['scenario_field']] ?? null);
|
||||
$scenario = $val ?? ($formData[$cfg['scenario_field']] ?? null);
|
||||
if (!$scenario) throw new BusinessException('缺少业务场景(scenario 或 scenario_field)');
|
||||
|
||||
$mustBelong = array_key_exists('must_belong', $cfg) ? (bool)$cfg['must_belong'] : true;
|
||||
$preferPrimary = array_key_exists('prefer_primary', $cfg) ? (bool)$cfg['prefer_primary'] : true;
|
||||
|
||||
$ids = $this->getLeadersByScenarioForInitiator(
|
||||
(int)$instance->initiator_id,
|
||||
(string)$scenario,
|
||||
$mustBelong,
|
||||
$preferPrimary
|
||||
); // B 方案(按场景)
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new BusinessException("不支持的审批人类型: {$typ}");
|
||||
}
|
||||
@@ -411,6 +521,28 @@ class ApprovalFlowService
|
||||
$head = $this->getDeptHeadId((int)$val);
|
||||
if ($head) $uids[] = (int)$head;
|
||||
break;
|
||||
case 'group_members': {
|
||||
$gid = (int)($val ?? 0);
|
||||
if ($gid <= 0) throw new BusinessException('group_members 需要 group_id');
|
||||
$uids = $this->getGroupMemberIds($gid); // A 方案
|
||||
break;
|
||||
}
|
||||
case 'scenario_leader_of_initiator': {
|
||||
$formData = json_decode($instance->form_data ?? '{}', true) ?: [];
|
||||
$scenario = $val ?? ($formData[$cc['scenario_field']] ?? null);
|
||||
if (!$scenario) throw new BusinessException('缺少业务场景(scenario 或 scenario_field)');
|
||||
|
||||
$mustBelong = array_key_exists('must_belong', $cc) ? (bool)$cc['must_belong'] : true;
|
||||
$preferPrimary = array_key_exists('prefer_primary', $cc) ? (bool)$cc['prefer_primary'] : true;
|
||||
|
||||
$uids = $this->getLeadersByScenarioForInitiator(
|
||||
(int)$instance->initiator_id,
|
||||
(string)$scenario,
|
||||
$mustBelong,
|
||||
$preferPrimary
|
||||
); // B 方案(按场景)
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
@@ -474,35 +606,37 @@ class ApprovalFlowService
|
||||
|
||||
/**
|
||||
* 聚合本步骤结论(按类型)
|
||||
* 返回:'pending' | 'approve' | 'reject'
|
||||
*
|
||||
* any:有 reject => reject;否则有 approve => approve;否则 pending
|
||||
* all:有 reject => reject;有 pending => pending;否则(全 approved 或 approved+skipped/timeout)=> approve
|
||||
*/
|
||||
private function getStepOutcome(int $instanceId, int $round, int $stepIndex, string $type): string
|
||||
{
|
||||
$records = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('round', $round) // ★
|
||||
->where('round', $round) //
|
||||
->where('step_index', $stepIndex)
|
||||
->get();
|
||||
|
||||
$pending = 0; $approved = 0; $rejected = 0;
|
||||
$pending = $approved = $rejected = $timeout = $skipped = 0;
|
||||
foreach ($records as $r) {
|
||||
if ($r->status === 'pending') $pending++;
|
||||
elseif ($r->status === 'approved') $approved++;
|
||||
elseif ($r->status === 'rejected') $rejected++;
|
||||
switch ($r->status) {
|
||||
case 'pending': $pending++; break;
|
||||
case 'approved': $approved++; break;
|
||||
case 'rejected': $rejected++; break;
|
||||
case 'timeout': $timeout++; break;
|
||||
case 'skipped': $skipped++; break;
|
||||
}
|
||||
}
|
||||
|
||||
$type = strtolower($type);
|
||||
if ($type === 'any') {
|
||||
if ($rejected > 0) return 'reject';
|
||||
if ($approved > 0) return 'approve';
|
||||
// 全为 skipped/timeout 且无 pending/rejected ⇒ 通过
|
||||
if ($pending === 0 && $rejected === 0 && $approved === 0) return 'approve';
|
||||
return 'pending';
|
||||
}
|
||||
if ($rejected > 0) return 'reject';
|
||||
if ($pending > 0) return 'pending';
|
||||
return $approved > 0 ? 'approve' : 'pending';
|
||||
return 'approve';
|
||||
}
|
||||
|
||||
/** 关闭本步其余待办为 skipped */
|
||||
@@ -511,7 +645,7 @@ class ApprovalFlowService
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$q = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('round', $round) // ★
|
||||
->where('round', $round) //
|
||||
->where('step_index', $stepIndex)
|
||||
->where('status', 'pending');
|
||||
|
||||
@@ -528,7 +662,7 @@ class ApprovalFlowService
|
||||
|
||||
$exists = Db::table('approval_records')
|
||||
->where('instance_id', (int)$instance->id)
|
||||
->where('round', $round) // ★ 限当前轮
|
||||
->where('round', $round) // 限当前轮
|
||||
->where('step_index', $stepIndex)
|
||||
->where('approver_id', $approverId)
|
||||
->where('status', 'pending')
|
||||
@@ -540,7 +674,7 @@ class ApprovalFlowService
|
||||
'instance_id' => (int)$instance->id,
|
||||
'approver_id' => $approverId,
|
||||
'step_index' => $stepIndex,
|
||||
'round' => $round, // ★
|
||||
'round' => $round, //
|
||||
'action' => null,
|
||||
'status' => 'pending',
|
||||
'comment' => null,
|
||||
@@ -558,6 +692,7 @@ class ApprovalFlowService
|
||||
'approve' => '已通过',
|
||||
'reject' => '已拒绝',
|
||||
'revoked' => '已撤回',
|
||||
'voided' => '已作废',
|
||||
];
|
||||
$prefix = $isCC ? '【抄送】' : '【审批】';
|
||||
$text = $map[$action] ?? $action;
|
||||
@@ -565,6 +700,10 @@ class ApprovalFlowService
|
||||
// 业务标题/内容
|
||||
$approvalType = array_flip(\app\common\service\SysDictService::pluckKeyValueByCode('approval_type'));
|
||||
|
||||
$flowTxt = $approvalType[$instance->flow_type] ?? (string)$instance->flow_type;
|
||||
$title = $prefix.'审批通知';
|
||||
$content = "{$prefix}你有一条审批 {$text}:类型 {$flowTxt},业务标识 {$instance->biz_id}";
|
||||
|
||||
switch ($instance->flow_type) {
|
||||
case 'stock_orders':
|
||||
// 备货单
|
||||
@@ -577,6 +716,17 @@ class ApprovalFlowService
|
||||
break;
|
||||
case 'stock_orders_nullify':
|
||||
// 备货单作废
|
||||
$stockOrder = \app\common\model\StockOrders::find($instance->biz_id);
|
||||
if ($stockOrder) {
|
||||
$title = $prefix."备货单作废:{$stockOrder->order_no}";
|
||||
$flowTxt = $approvalType[$instance->flow_type] ?? '备货单作废';
|
||||
$content = "{$prefix}你有一条审批 {$text}:类型 {$flowTxt},业务单号 {$stockOrder->order_no}";
|
||||
// 把作废原因附带展示更清晰(也可依赖 $extra['note'])
|
||||
$fd = json_decode($instance->form_data ?? '{}', true) ?: [];
|
||||
if (!empty($fd['_nullify_reason'])) {
|
||||
$content .= ';原因:'.(function_exists('mb_strimwidth') ? mb_strimwidth($fd['_nullify_reason'], 0, 120, '...', 'UTF-8') : $fd['_nullify_reason']);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'purchase_orders':
|
||||
// 采购单
|
||||
@@ -785,178 +935,6 @@ class ApprovalFlowService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 极简时间轴(含每步时间 & 申请人信息)
|
||||
*
|
||||
* @param int $instanceId
|
||||
* @param string|null $userNameColumn 申请人姓名列(如 'name' / 'nickname')。不需要就传 null
|
||||
* @param string $initiatorPlacement 'prepend' | 'attach'
|
||||
* - 'prepend':在最前插入一条“发起申请”块(推荐)
|
||||
* - 'attach' :把申请人信息并到第一步的返回项里(不新增块)
|
||||
*
|
||||
* 返回:按显示顺序的数组,每项:
|
||||
* {
|
||||
* index:int // 步骤索引;若为“发起申请”块则为 -1
|
||||
* name:string // 步骤名或“发起申请”
|
||||
* type:string // any|all 或 '-'(发起块)
|
||||
* status:string // approved|rejected|processing|pending|skipped|timeout|submitted(发起块)
|
||||
* started_at:?string
|
||||
* finished_at:?string
|
||||
* duration_seconds:?int
|
||||
* // 仅发起块或 attach 时的第一步会包含:
|
||||
* initiator_id?:int
|
||||
* initiator_name?:?string
|
||||
* }
|
||||
*/
|
||||
public function getSimpleTimeline2(int $instanceId, ?string $userNameColumn = null, string $initiatorPlacement = 'prepend'): array
|
||||
{
|
||||
// 基础数据
|
||||
$instance = Db::table('approval_instances')->where('id', $instanceId)->first();
|
||||
if (!$instance) throw new BusinessException('审批实例未找到');
|
||||
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if (!$flow) throw new BusinessException('审批流程定义未找到');
|
||||
|
||||
$steps = json_decode($flow->steps, true) ?: [];
|
||||
$formData = json_decode($instance->form_data ?? '{}', true) ?: [];
|
||||
$curStep = (int)$instance->current_step;
|
||||
$round = (int)$instance->round;
|
||||
|
||||
// 申请人
|
||||
$initiatorId = (int)$instance->initiator_id;
|
||||
$initiatorName = null;
|
||||
if ($userNameColumn) {
|
||||
$initiatorName = Db::table('user')->where('id', $initiatorId)->value($userNameColumn);
|
||||
}
|
||||
|
||||
// 审批记录
|
||||
$records = Db::table('approval_records as ar')
|
||||
->where('ar.instance_id', $instanceId)
|
||||
->where('ar.round', $round)
|
||||
->orderBy('ar.step_index')
|
||||
->orderByRaw('COALESCE(ar.approved_at, ar.created_at) asc')
|
||||
->select('ar.*')
|
||||
->get()
|
||||
->toArray();
|
||||
|
||||
$byStep = [];
|
||||
foreach ($records as $r) {
|
||||
$idx = (int)$r->step_index;
|
||||
$byStep[$idx][] = $r;
|
||||
}
|
||||
|
||||
$timeline = [];
|
||||
|
||||
// 可选:先插入“发起申请”块(index = -1)
|
||||
if ($initiatorPlacement === 'prepend') {
|
||||
$appliedAt = $instance->created_at ?: null;
|
||||
$timeline[] = [
|
||||
'index' => -1,
|
||||
'name' => '发起申请',
|
||||
'type' => '-',
|
||||
'status' => 'submitted',
|
||||
'started_at' => $appliedAt,
|
||||
'finished_at' => $appliedAt,
|
||||
'duration_seconds' => 0,
|
||||
'initiator_id' => $initiatorId,
|
||||
'initiator_name' => $initiatorName,
|
||||
];
|
||||
}
|
||||
|
||||
// 每一步
|
||||
foreach ($steps as $i => $meta) {
|
||||
$name = $meta['name'] ?? ('Step '.$i);
|
||||
$typeRaw = strtolower($meta['type'] ?? 'all');
|
||||
$type = in_array($typeRaw, ['any','all']) ? $typeRaw : 'all';
|
||||
$condStr = $meta['condition'] ?? null;
|
||||
$condOk = $condStr ? $this->evaluateCondition($condStr, $formData) : true;
|
||||
|
||||
$recs = $byStep[$i] ?? [];
|
||||
$hasRecs = !empty($recs);
|
||||
|
||||
$status = 'pending';
|
||||
$startedAt = null;
|
||||
$finishedAt = null;
|
||||
$durationSec = null;
|
||||
|
||||
if ($hasRecs) {
|
||||
// 统计时间
|
||||
$minCreated = null;
|
||||
$minApproveAt = null; $maxApproveAt = null;
|
||||
$minRejectAt = null;
|
||||
$maxTimeoutAt = null;
|
||||
$cnt = ['pending'=>0,'approved'=>0,'rejected'=>0,'timeout'=>0];
|
||||
|
||||
foreach ($recs as $rr) {
|
||||
if ($rr->created_at && (!$minCreated || $rr->created_at < $minCreated)) $minCreated = $rr->created_at;
|
||||
if ($rr->approved_at) {
|
||||
if ($rr->status === 'approved') {
|
||||
if (!$minApproveAt || $rr->approved_at < $minApproveAt) $minApproveAt = $rr->approved_at;
|
||||
if (!$maxApproveAt || $rr->approved_at > $maxApproveAt) $maxApproveAt = $rr->approved_at;
|
||||
} elseif ($rr->status === 'rejected') {
|
||||
if (!$minRejectAt || $rr->approved_at < $minRejectAt) $minRejectAt = $rr->approved_at;
|
||||
} elseif ($rr->status === 'timeout') {
|
||||
if (!$maxTimeoutAt || $rr->approved_at > $maxTimeoutAt) $maxTimeoutAt = $rr->approved_at;
|
||||
}
|
||||
}
|
||||
if (isset($cnt[$rr->status])) $cnt[$rr->status]++;
|
||||
}
|
||||
|
||||
$startedAt = $minCreated;
|
||||
|
||||
// 总结果
|
||||
$outcome = $this->getStepOutcome($instanceId, $round, $i, $type); // 'pending'|'approve'|'reject'
|
||||
if ($outcome === 'reject') {
|
||||
$status = 'rejected';
|
||||
$finishedAt = $minRejectAt;
|
||||
} elseif ($outcome === 'approve') {
|
||||
$status = 'approved';
|
||||
$finishedAt = ($type === 'any') ? $minApproveAt : $maxApproveAt;
|
||||
} else {
|
||||
if ($cnt['timeout'] > 0 && $cnt['approved'] === 0 && $cnt['rejected'] === 0 && $cnt['pending'] === 0) {
|
||||
$status = 'timeout';
|
||||
$finishedAt = $maxTimeoutAt;
|
||||
} else {
|
||||
$status = 'processing';
|
||||
}
|
||||
}
|
||||
|
||||
if ($startedAt && $finishedAt) {
|
||||
$durationSec = max(0, strtotime($finishedAt) - strtotime($startedAt));
|
||||
}
|
||||
} else {
|
||||
// 无记录:根据位置与条件展示
|
||||
if ($i < $curStep) {
|
||||
$status = $condOk ? 'approved' : 'skipped';
|
||||
} elseif ($i === $curStep && $instance->status === 'processing') {
|
||||
$status = 'processing';
|
||||
} else {
|
||||
$status = $condOk ? 'pending' : 'skipped';
|
||||
}
|
||||
}
|
||||
|
||||
$row = [
|
||||
'index' => (int)$i,
|
||||
'name' => $name,
|
||||
'type' => $type,
|
||||
'status' => $status,
|
||||
'started_at' => $startedAt,
|
||||
'finished_at' => $finishedAt,
|
||||
'duration_seconds' => $durationSec,
|
||||
];
|
||||
|
||||
// 如果需要把申请人信息“并到第一步”而不是独立一块
|
||||
if ($initiatorPlacement === 'attach' && empty($timeline)) {
|
||||
$row['initiator_id'] = $initiatorId;
|
||||
$row['initiator_name'] = $initiatorName;
|
||||
}
|
||||
|
||||
$timeline[] = $row;
|
||||
}
|
||||
|
||||
return $timeline;
|
||||
}
|
||||
|
||||
|
||||
public function getSimpleTimeline(int $instanceId, ?string $userNameColumn = null, string $initiatorPlacement = 'prepend'): array
|
||||
{
|
||||
@@ -1042,7 +1020,7 @@ class ApprovalFlowService
|
||||
$finishedAt = null;
|
||||
$durationSec = null;
|
||||
|
||||
// ★ 每一步的“审批意见”(只展示有内容的 comment)
|
||||
// 每一步的“审批意见”(只展示有内容的 comment)
|
||||
$opinions = []; // [{approver_id, approver_name?, action, status, comment, time}...]
|
||||
|
||||
if ($hasRecs) {
|
||||
@@ -1129,7 +1107,7 @@ class ApprovalFlowService
|
||||
'started_at' => $startedAt,
|
||||
'finished_at' => $finishedAt,
|
||||
'duration_seconds' => $durationSec,
|
||||
'opinions' => $opinions, // ★ 这就是每个审批意见
|
||||
'opinions' => $opinions, // 这就是每个审批意见
|
||||
];
|
||||
|
||||
// 把申请人信息并到第一步(可选)
|
||||
@@ -1309,13 +1287,18 @@ class ApprovalFlowService
|
||||
$deadlineAt = date('Y-m-d H:i:s', time() + $flow->timeout_hours * 3600);
|
||||
}
|
||||
|
||||
$oldPendingUids = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('status', 'pending')
|
||||
->pluck('approver_id')->toArray();
|
||||
|
||||
// 清理可能遗留的 pending
|
||||
Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('status', 'pending')
|
||||
->update(['status'=>'skipped','approved_at'=>$now,'updated_at'=>$now]);
|
||||
|
||||
// ★ 轮次 +1
|
||||
// 轮次 +1
|
||||
$newRound = ((int)$instance->round) + 1;
|
||||
|
||||
// 重新开启实例
|
||||
@@ -1350,6 +1333,7 @@ class ApprovalFlowService
|
||||
$extra = $appealText !== '' ? ['appeal' => $appealText] : [];
|
||||
$this->sendNotification($approvers, $instanceLite, 'pending', false, $extra);
|
||||
$this->notifyCCs($firstStep, $instanceLite, 'pending');
|
||||
$this->pushTodoChanged(array_merge($oldPendingUids, $approvers));
|
||||
|
||||
return [
|
||||
'status' => 'resubmitted',
|
||||
@@ -1520,95 +1504,6 @@ class ApprovalFlowService
|
||||
|
||||
// ====== ====== ====== ====== ====== ====== 转交操作 ====== ====== ====== ====== ====== ======
|
||||
|
||||
/**
|
||||
* 转交当前待办给他人
|
||||
* 仅允许【当前这条待办的审批人】把自己名下且为 pending 的记录转交给 toUserId。
|
||||
* - 若目标人在本步已有 pending:合并(把本记录标记为 skipped,保留目标人的那条)
|
||||
* - 否则:原地把该记录的 approver_id 改为 toUserId
|
||||
* - 写入转交日志
|
||||
* - 通知被转交人
|
||||
*/
|
||||
public function transferApproval2(int $instanceId, int $stepIndex, int $fromUserId, int $toUserId, string $reason = ''): array
|
||||
{
|
||||
if ($fromUserId === $toUserId) {
|
||||
return ['status' => 'noop', 'msg' => '目标与来源相同,无需转交'];
|
||||
}
|
||||
|
||||
return Db::transaction(function () use ($instanceId, $stepIndex, $fromUserId, $toUserId, $reason) {
|
||||
// 锁实例,避免并发推进
|
||||
$instance = Db::table('approval_instances')->where('id', $instanceId)->lockForUpdate()->first();
|
||||
if (!$instance) throw new BusinessException('审批实例未找到');
|
||||
if ($instance->status !== 'processing') throw new BusinessException('流程非进行中,无法转交');
|
||||
|
||||
// 锁定来源人的 pending 记录(必须是“自己名下”的记录)
|
||||
$record = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('round', (int)$instance->round)
|
||||
->where('step_index', $stepIndex)
|
||||
->where('approver_id', $fromUserId)
|
||||
->where('status', 'pending')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (!$record) {
|
||||
throw new BusinessException('未找到可转交的待办或已处理');
|
||||
}
|
||||
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
// 若目标人在本步已有 pending,合并:本记录设为 skipped,保留目标那条
|
||||
$target = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('round', (int)$instance->round)
|
||||
->where('step_index', $stepIndex)
|
||||
->where('approver_id', $toUserId)
|
||||
->where('status', 'pending')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($target) {
|
||||
Db::table('approval_records')->where('id', $record->id)->update([
|
||||
'status' => 'skipped',
|
||||
'approved_at' => $now,
|
||||
'updated_at' => $now,
|
||||
'comment' => trim(($record->comment ?? '')."\n[转交给 {$toUserId},目标已有待办,已合并]"),
|
||||
]);
|
||||
$effectiveRecordId = (int)$target->id;
|
||||
} else {
|
||||
// 原地替换 approver_id
|
||||
Db::table('approval_records')->where('id', $record->id)->update([
|
||||
'approver_id' => $toUserId,
|
||||
'updated_at' => $now,
|
||||
'comment' => trim(($record->comment ?? '')."\n[自 {$fromUserId} 转交]"),
|
||||
]);
|
||||
$effectiveRecordId = (int)$record->id;
|
||||
}
|
||||
|
||||
// 写转交日志
|
||||
Db::table('approval_transfers')->insert([
|
||||
'instance_id' => (int)$instanceId,
|
||||
'step_index' => (int)$stepIndex,
|
||||
'record_id' => $effectiveRecordId,
|
||||
'from_user_id' => (int)$fromUserId,
|
||||
'to_user_id' => (int)$toUserId,
|
||||
'reason' => $reason,
|
||||
'created_at' => $now,
|
||||
]);
|
||||
|
||||
// 通知被转交人(沿用你的 sendNotification)
|
||||
$this->sendNotification([$toUserId], (object)[
|
||||
'id' => (int)$instance->id,
|
||||
'flow_type' => (string)$instance->flow_type,
|
||||
'biz_type' => (string)$instance->biz_type,
|
||||
'biz_id' => (string)$instance->biz_id,
|
||||
'initiator_id' => (int)$instance->initiator_id,
|
||||
'form_data' => $instance->form_data,
|
||||
], 'pending', false);
|
||||
|
||||
return ['status' => 'ok', 'record_id' => $effectiveRecordId];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看某个实例的转交流水(按时间升序)
|
||||
*/
|
||||
@@ -1731,8 +1626,322 @@ class ApprovalFlowService
|
||||
'created_at' => $now,
|
||||
]);
|
||||
|
||||
$this->pushTodoChanged([$fromUserId, $toUserId]);
|
||||
return ['status' => 'ok', 'record_id' => $effectiveRecordId];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** 新增:发起“作废审批” */
|
||||
public function startNullify(
|
||||
string $voidFlowType, // 例如 'stock_orders_nullify'
|
||||
string $bizType, // 原业务类型,如 'stock_orders'
|
||||
string $bizId, // 原业务ID
|
||||
array $formData, // 可包含 ['nullify_reason'=>...]
|
||||
int $initiatorId
|
||||
): array {
|
||||
return Db::transaction(function () use ($voidFlowType, $bizType, $bizId, $formData, $initiatorId) {
|
||||
// 1) 流程定义校验
|
||||
$flow = Db::table('approval_flows')->where('type', $voidFlowType)->where('is_active', 1)->first();
|
||||
if (!$flow) throw new BusinessException("作废流程未找到或已停用: {$voidFlowType}");
|
||||
$steps = json_decode($flow->steps, true);
|
||||
if (!is_array($steps) || empty($steps)) throw new BusinessException("作废流程步骤配置错误");
|
||||
|
||||
// 2) 必须存在“已通过”的最新有效实例(非作废流程)
|
||||
$latestApproved = Db::table('approval_instances')
|
||||
->where('biz_type', $bizType)
|
||||
->where('biz_id', $bizId)
|
||||
->where('flow_type', '!=', $voidFlowType)
|
||||
->where('status', 'approved')
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
if (!$latestApproved) {
|
||||
throw new BusinessException('仅已通过的单据可发起作废');
|
||||
}
|
||||
|
||||
// 3) 不允许并行的作废流程
|
||||
$voidProcessing = Db::table('approval_instances')
|
||||
->where('flow_type', $voidFlowType)
|
||||
->where('biz_id', $bizId)
|
||||
->where('status', 'processing')
|
||||
->exists();
|
||||
if ($voidProcessing) {
|
||||
throw new BusinessException('已存在进行中的作废审批');
|
||||
}
|
||||
|
||||
// A. 基于历史“作废流程已通过”的实例拦截
|
||||
$voidApproved = Db::table('approval_instances')
|
||||
->where('flow_type', $voidFlowType)
|
||||
->where('biz_id', $bizId)
|
||||
->whereIn('status', ['approved','voided'])
|
||||
->exists();
|
||||
if ($voidApproved) {
|
||||
throw new BusinessException('该单据已作废,无需重复作废');
|
||||
}
|
||||
|
||||
// B.(可选)直接查业务表状态拦截(若你用 approval_status=4 表示已作废)
|
||||
/*
|
||||
$orderVoided = \app\common\model\StockOrders::where('id', $bizId)
|
||||
->where('approval_status', 4)
|
||||
->exists();
|
||||
if ($orderVoided) {
|
||||
throw new BusinessException('该单据已作废,无需重复作废');
|
||||
}
|
||||
*/
|
||||
|
||||
// 4) 计算首步
|
||||
// 注:作废流程可以有独立条件;若不需要条件,直接第一步
|
||||
$formData = array_merge([
|
||||
'_op' => 'nullify',
|
||||
'_nullify_reason' => $formData['nullify_reason'] ?? ($formData['reason'] ?? ''),
|
||||
'_nullify_of_instance_id' => (int)$latestApproved->id,
|
||||
], $formData);
|
||||
|
||||
$firstIndex = $this->getNextStepIndex($steps, $formData, -1);
|
||||
if ($firstIndex === null) throw new BusinessException("作废流程未命中任何审批步骤");
|
||||
$firstStep = $steps[$firstIndex];
|
||||
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$deadlineAt = null;
|
||||
if (($flow->timeout_hours ?? 0) > 0) {
|
||||
$deadlineAt = date('Y-m-d H:i:s', time() + $flow->timeout_hours * 3600);
|
||||
}
|
||||
|
||||
// 5) 新建作废实例(round 固定从 1 开始)
|
||||
$instanceId = Db::table('approval_instances')->insertGetId([
|
||||
'flow_type' => $voidFlowType,
|
||||
'biz_type' => $bizType,
|
||||
'biz_id' => $bizId,
|
||||
'form_data' => json_encode($formData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'initiator_id' => $initiatorId,
|
||||
'status' => 'processing',
|
||||
'current_step' => $firstIndex,
|
||||
'round' => 1, //
|
||||
'deadline_at' => $deadlineAt,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$instance = (object)[
|
||||
'id' => $instanceId,
|
||||
'flow_type' => $voidFlowType,
|
||||
'biz_type' => $bizType,
|
||||
'biz_id' => $bizId,
|
||||
'form_data' => json_encode($formData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
'initiator_id' => $initiatorId,
|
||||
'current_step' => $firstIndex,
|
||||
'status' => 'processing',
|
||||
'round' => 1, //
|
||||
];
|
||||
|
||||
// 6) 生成首步待办 + 通知(带上作废原因)
|
||||
$approverIds = $this->resolveApprovers($firstStep, $instance, true);
|
||||
foreach ($approverIds as $uid) {
|
||||
$this->insertApprovalRecord($instance, $firstIndex, $uid);
|
||||
}
|
||||
$extra = [];
|
||||
if (!empty($formData['_nullify_reason'])) {
|
||||
$extra['note'] = '【作废原因】'.$formData['_nullify_reason'];
|
||||
}
|
||||
$this->sendNotification($approverIds, $instance, 'pending', false, $extra);
|
||||
$this->notifyCCs($firstStep, $instance, 'pending');
|
||||
$this->pushTodoChanged($approverIds);
|
||||
return ['instance_id' => $instanceId];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// A) 取组内全部成员
|
||||
private function getGroupMemberIds(int $groupId): array
|
||||
{
|
||||
$rows = Db::table('user_group_members')
|
||||
->where('group_id', $groupId)
|
||||
->where('status', 1)
|
||||
->pluck('user_id')->toArray();
|
||||
|
||||
return array_values(array_unique(array_map('intval', $rows)));
|
||||
}
|
||||
|
||||
// B) 按“场景”在发起人所在的组里找负责人(支持主归属/排序兜底)
|
||||
private function getLeadersByScenarioForInitiator(
|
||||
int $initiatorId,
|
||||
string $scenarioCode,
|
||||
bool $mustBelong = true,
|
||||
bool $preferPrimary = true
|
||||
): array {
|
||||
// 找出“该场景下发起人所在的所有组”
|
||||
$groups = Db::table('user_group as g')
|
||||
->join('user_group_members as m', 'm.group_id', '=', 'g.id')
|
||||
->where('g.scenario_code', $scenarioCode)
|
||||
->where('g.status', 1)
|
||||
->where('m.user_id', $initiatorId)
|
||||
->where('m.status', 1)
|
||||
->orderByDesc('m.is_primary') // 主归属优先
|
||||
->orderByDesc('g.sort') // 其次按组排序
|
||||
->select('g.id', 'm.is_primary')
|
||||
->get()->toArray();
|
||||
|
||||
if (empty($groups)) {
|
||||
if ($mustBelong) {
|
||||
throw new BusinessException('发起人在该业务场景下未加入任何分组');
|
||||
}
|
||||
// 不强制属于:允许只按“该场景下任一组”的负责人(不推荐)
|
||||
$groups = Db::table('user_group as g')
|
||||
->where('g.scenario_code', $scenarioCode)
|
||||
->where('g.status', 1)
|
||||
->orderByDesc('g.sort')
|
||||
->select('g.id', Db::raw('0 as is_primary'))
|
||||
->get()->toArray();
|
||||
if (empty($groups)) {
|
||||
throw new BusinessException('该业务场景下未配置任何分组');
|
||||
}
|
||||
}
|
||||
|
||||
// 选择一个“目标组”
|
||||
$targetGroupId = null;
|
||||
if ($preferPrimary) {
|
||||
foreach ($groups as $g) {
|
||||
if ((int)$g->is_primary === 1) { $targetGroupId = (int)$g->id; break; }
|
||||
}
|
||||
}
|
||||
if (!$targetGroupId) {
|
||||
$targetGroupId = (int)$groups[0]->id; // 用排序第一的组
|
||||
}
|
||||
|
||||
// 取负责人(可支持多负责人)
|
||||
$leaders = Db::table('user_group_members')
|
||||
->where('group_id', $targetGroupId)
|
||||
->where('is_leader', 1)
|
||||
->where('status', 1)
|
||||
->pluck('user_id')->toArray();
|
||||
|
||||
$ids = array_values(array_unique(array_map('intval', $leaders)));
|
||||
if (empty($ids)) throw new BusinessException('目标分组未配置负责人');
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
//
|
||||
private function isNullifyFlow(string $flowType): bool
|
||||
{
|
||||
$t = strtolower(trim($flowType));
|
||||
return str_ends_with($t, '_nullify') || in_array($t, [
|
||||
// 所有“作废”类流程的类型
|
||||
'stock_orders_nullify',
|
||||
], true);
|
||||
}
|
||||
|
||||
// 放到工具方法区
|
||||
private function normalizeFinalStatus(string $flowType, string $final): string
|
||||
{
|
||||
if ($this->isNullifyFlow($flowType) && $final === 'approved') {
|
||||
return 'voided';
|
||||
}
|
||||
return $final;
|
||||
}
|
||||
|
||||
/** WebSocket:把一组用户的“待办数量”推送给前端 */
|
||||
private function pushTodoChanged22(array $userIds): void
|
||||
{
|
||||
$userIds = array_values(array_unique(array_map('intval', $userIds)));
|
||||
if (empty($userIds)) return;
|
||||
|
||||
// 统计这些用户当前的待办数量(以 approval_records.status = 'pending' 为准)
|
||||
$rows = Db::table('approval_records')
|
||||
->whereIn('approver_id', $userIds)
|
||||
->where('status', 'pending')
|
||||
->groupBy('approver_id')
|
||||
->select('approver_id', Db::raw('COUNT(*) as cnt'))
|
||||
->get();
|
||||
|
||||
// 默认都置 0,再填充真实值
|
||||
$payload = array_fill_keys($userIds, 0);
|
||||
foreach ($rows as $r) {
|
||||
$payload[(int)$r->approver_id] = (int)$r->cnt;
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($payload as $uid => $cnt) {
|
||||
$data = [
|
||||
'event' => 'approval.todo.counts',
|
||||
'user_id' => $uid,
|
||||
'num' => $cnt,
|
||||
];
|
||||
\Webman\RedisQueue\Redis::send('ws-msg', $data);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('ws todo push error: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 取“某实例、某轮次、某步骤”里当前 pending 的审批人(用于推送受影响的用户) */
|
||||
private function getPendingApproverIds(int $instanceId, int $round, int $stepIndex): array
|
||||
{
|
||||
$ids = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('round', $round)
|
||||
->where('step_index', $stepIndex)
|
||||
->where('status', 'pending')
|
||||
->pluck('approver_id')->toArray();
|
||||
|
||||
return array_values(array_unique(array_map('intval', $ids)));
|
||||
}
|
||||
|
||||
|
||||
/** 登录/首屏初始化:获取当前用户的待办总数(仅统计当前步骤、进行中的实例) */
|
||||
public function getInitTodoCount(int $userId): int
|
||||
{
|
||||
$userId = (int)$userId;
|
||||
if ($userId <= 0) {
|
||||
throw new BusinessException('无效的用户ID');
|
||||
}
|
||||
|
||||
$row = Db::table('approval_records as ar')
|
||||
->join('approval_instances as ai', 'ai.id', '=', 'ar.instance_id')
|
||||
->where('ar.approver_id', $userId)
|
||||
->where('ar.status', 'pending')
|
||||
->where('ai.status', 'processing')
|
||||
// 只统计实例“当前轮次、当前步骤”的待办,避免历史残留干扰
|
||||
->whereRaw('ar.round = ai.round')
|
||||
->whereRaw('ar.step_index = ai.current_step')
|
||||
->selectRaw('COUNT(*) as c')
|
||||
->first();
|
||||
|
||||
return (int)($row->c ?? 0);
|
||||
}
|
||||
|
||||
/** WebSocket:把一组用户的“待办数量”推送给前端(与 getInitTodoCount 统一口径) */
|
||||
private function pushTodoChanged(array $userIds): void
|
||||
{
|
||||
$userIds = array_values(array_unique(array_map('intval', $userIds)));
|
||||
if (empty($userIds)) return;
|
||||
|
||||
// 只统计:实例进行中 + 当前轮次 + 当前步骤 的 pending
|
||||
$rows = Db::table('approval_records as ar')
|
||||
->join('approval_instances as ai', 'ai.id', '=', 'ar.instance_id')
|
||||
->whereIn('ar.approver_id', $userIds)
|
||||
->where('ar.status', 'pending')
|
||||
->where('ai.status', 'processing')
|
||||
->whereRaw('ar.round = ai.round')
|
||||
->whereRaw('ar.step_index = ai.current_step')
|
||||
->groupBy('ar.approver_id')
|
||||
->select('ar.approver_id', Db::raw('COUNT(*) as cnt'))
|
||||
->get();
|
||||
|
||||
// 默认置 0,再填充真实值
|
||||
$payload = array_fill_keys($userIds, 0);
|
||||
foreach ($rows as $r) {
|
||||
$payload[(int)$r->approver_id] = (int)$r->cnt;
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($payload as $uid => $cnt) {
|
||||
(new \app\common\utils\WsEvents())->todoCounts($uid, $cnt);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('ws todo push error: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user