调整审批流&&增加人员分组

This commit is contained in:
mzl
2025-10-10 11:09:37 +00:00
parent 5beaa11cf7
commit 11b5a694ac
17 changed files with 2648 additions and 286 deletions
@@ -19,6 +19,7 @@ use app\common\service\SystemsService;
use app\common\service\UserService;
use support\Cache;
use app\common\service\PermService;
use app\common\service\UserGroupService;
class PresetController extends BaseController
{
@@ -207,4 +208,26 @@ class PresetController extends BaseController
return $this->error($e->getMessage());
}
}
public function userGroup(Request $request)
{
try {
$result = (new UserGroupService)->userGroup($request);
return $this->success($result, '获取分组');
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
public function userGroupScene(Request $request)
{
try {
$result = (new UserGroupService)->userGroupScene($request);
return $this->success($result, '获取分组场景');
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace app\common\logic;
use app\common\traits\crud\CrudLogicTrait;
use app\common\model\UserGroup;
use app\common\model\UserGroupMembers;
class UserGroupLogic
{
use CrudLogicTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = UserGroup::class;
public function createGroup(array $data): UserGroup
{
$created = UserGroup::create($data);
if (isset($data['user_ids']) && is_array($data['user_ids']) && count($data['user_ids']) > 0) {
foreach ($data['user_ids'] as $member) {
$this->addUserGroupMembers($member, $created->id);
}
}
if ((int)$data['leader_id'] > 0) {
$leader = UserGroupMembers::where('user_id', $data['leader_id'])->where('group_id', $created->id)->first();
if ($leader) {
$leader->is_leader = 1;
$leader->save();
} else {
$this->addUserGroupMembers($data['leader_id'], $created->id, 1);
}
}
return $created;
}
public function updateGroup(UserGroup $userGroup, array $data)
{
$userGroup->title = $data['title'];
$userGroup->sort = $data['sort'] ?? 0;
$userGroup->status = $data['status'];
$userGroup->save();
// 删除所有成员
UserGroupMembers::where('group_id', $userGroup->id)->delete();
if (isset($data['user_ids']) && is_array($data['user_ids']) && count($data['user_ids']) > 0) {
foreach ($data['user_ids'] as $member) {
$this->addUserGroupMembers($member, $userGroup->id);
}
}
if ((int)$data['leader_id'] > 0) {
$leader = UserGroupMembers::where('user_id', $data['leader_id'])->where('group_id', $userGroup->id)->first();
if ($leader) {
$leader->is_leader = 1;
$leader->save();
} else {
$this->addUserGroupMembers($data['leader_id'], $userGroup->id, 1);
}
}
return $userGroup;
}
public function addUserGroupMembers(int $userId, int $groupId, int $isLeader = 0)
{
$udata = [
'user_id' => $userId,
'group_id' => $groupId,
'is_leader' => $isLeader
];
return UserGroupMembers::create($udata);
}
}
@@ -0,0 +1,22 @@
<?php
namespace app\common\logic;
use app\common\traits\crud\CrudLogicTrait;
use app\common\model\UserGroupMembers;
class UserGroupMembersLogic
{
use CrudLogicTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = UserGroupMembers::class;
public function deleteUserGroupMembers(int $groupId)
{
return UserGroupMembers::where('group_id', $groupId)->delete();
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace app\common\model;
use support\Model;
class UserGroup extends Model
{
/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection = 'mysql';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_group';
/**
* 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', 'title', 'sort', 'status', 'created_at', 'updated_at'];
/**
* 不允许自动填充模型字段
*/
protected $guarded = [];
public function groupMembers()
{
return $this->hasMany(UserGroupMembers::class, 'group_id', 'id');
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace app\common\model;
use support\Model;
class UserGroupMembers extends Model
{
/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection = 'mysql';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_group_members';
/**
* 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', 'group_id', 'user_id', 'is_leader', 'is_primary', 'status', 'created_at', 'updated_at'];
/**
* 不允许自动填充模型字段
*/
protected $guarded = [];
public function user()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function group()
{
return $this->hasOne(UserGroup::class, 'id', 'group_id');
}
}
+38
View File
@@ -393,6 +393,44 @@ class StockOrdersService
return $this->postProcess('Approval', $item);
}
/**
* 作废审批
*/
public function serviceApprovalNullify(Request $request)
{
$config = $this->buildQueryConfig($request, 'approval');
$item = $this->logicShow($config);
$this->approvalNullify($item);
return $this->postProcess('Approval', $item);
}
/**
* 审批作废
*/
public function approvalNullify($item)
{
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
$appro->startNullify('stock_orders_nullify', 'stock_orders_nullify', $item->id, [], $item->salesperson_id);
}
/**
* 撤销审批
*/
public function serviceApprovalRevoke(Request $request)
{
$config = $this->buildQueryConfig($request, 'approval');
$item = $this->logicShow($config);
$this->approvalRevoke($item);
return $this->postProcess('Approval', $item);
}
public function approvalRevoke($item)
{
$instance = \app\common\model\ApprovalInstances::where('biz_id', $item->id)->where('flow_type', 'stock_orders')->first();
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
$appro->revoke($instance->id, $item->salesperson_id);
}
/**
* 创建
*
@@ -0,0 +1,33 @@
<?php
namespace app\common\service;
use app\common\validate\UserGroupMembersValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\UserGroupMembers;
use app\common\model\UserGroup;
use support\Request;
class UserGroupMembersService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = UserGroupMembers::class;
/**
* 验证器
*/
protected $validator = UserGroupMembersValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
namespace app\common\service;
use app\common\logic\UserGroupLogic;
use app\common\logic\UserGroupMembersLogic;
use app\common\validate\UserGroupValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\UserGroup;
use support\Request;
class UserGroupService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = UserGroup::class;
/**
* 验证器
*/
protected $validator = UserGroupValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
protected function buildQueryConfig(Request $request, string $scene = 'default'): array
{
$p = $request->all();
$config = [];
$config['model'] = $this->modelClass;
switch ($scene) {
case 'default':
$config['where']['status'] = 1;
$config['order']['sort'] = 'desc';
$config['order']['id'] = 'desc';
$config['with'] = ['groupMembers', 'groupMembers.user'];
break;
case 'index':
$config['where']['status'] = 1;
$config['order']['sort'] = 'desc';
$config['order']['id'] = 'desc';
$config['with'] = ['groupMembers', 'groupMembers.user'];
break;
case 'show':
$config['where']['id'] = $p['id'];
$config['where']['status'] = 1;
break;
case 'store':
break;
case 'update':
$config['where']['id'] = $p['id'];
break;
case 'destroy':
$config['where']['id'] = $p['id'];
break;
case 'userGroup':
$config['where']['status'] = 1;
$config['order']['sort'] = 'desc';
$config['order']['id'] = 'desc';
$config['fields'] = ['id', 'title'];
break;
}
return $config;
}
public function serviceStore(Request $request, array $data = [], string $scene = 'store')
{
$data = $this->preProcess(ucfirst($scene), $data, $request);
$created = (new UserGroupLogic())->createGroup($data);
return $this->postProcess(ucfirst($scene), $created);
}
public function serviceUpdate(Request $request, array $data = [], string $scene = 'update')
{
$data = $this->preProcess(ucfirst($scene), $data, $request);
$config = $this->buildQueryConfig($request, $scene);
$userGroup = $this->logicShow($config);
$updated = (new UserGroupLogic())->updateGroup($userGroup, $data);
return $this->postProcess(ucfirst($scene), $updated);
}
public function serviceDestroy(Request $request, string $scene = 'destroy')
{
$config = $this->buildQueryConfig($request, $scene);
$deleted = $this->logicDeleteBy($config);
(new UserGroupMembersLogic())->deleteUserGroupMembers($config['where']['id']);
return $this->postProcess(ucfirst($scene), $deleted);
}
public function userGroup(Request $request, string $scene = 'userGroup')
{
$config = $this->buildQueryConfig($request, $scene);
$result = $this->logicListAll($config);
return $this->postProcess(ucfirst($scene), $result);
}
public function userGroupScene(Request $request, string $scene = 'userGroup')
{
$data = (new \app\common\service\SysDictService())->pluckKeyValueByCode('user_group_scene');
$result = [];
foreach($data as $key => $value) {
$result[] = [
'name' => $key,
'id' => $value,
];
}
return $this->postProcess(ucfirst($scene), $result);
}
}
@@ -164,6 +164,7 @@ class ApprovalFlowService
'finished_at' => $now,
'updated_at' => $now,
]);
$this->onFlowFinalized($instance, 'rejected');
$this->sendNotification([$instance->initiator_id], $instance, 'reject', false);
return ['status' => 'completed', 'msg' => '拒绝'];
}
@@ -178,6 +179,7 @@ class ApprovalFlowService
'finished_at' => $now,
'updated_at' => $now,
]);
$this->onFlowFinalized($instance, 'approved');
$this->sendNotification([$instance->initiator_id], $instance, 'approve', false);
return ['status' => 'completed', 'msg' => '同意'];
}
@@ -204,6 +206,53 @@ class ApprovalFlowService
});
}
/** ★ 新增:流程完结后的业务回调(此处处理“作废”落库) */
private function onFlowFinalized(object $instance, string $final /* 'approved'|'rejected' */): void
{
try {
switch ($instance->flow_type) {
case 'stock_orders': {
$order = \app\common\model\StockOrders::find($instance->biz_id);
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') {
// 这里按你的模型更新,状态字段请替换成你系统实际枚举
$order = \app\common\model\StockOrders::find($instance->biz_id);
if ($order && $order->approval_status !== 4) {
$order->approval_status = 4;
$order->save();
}
}
break;
// case 'purchase_orders_nullify':
// ...
// break;
default:
// 非作废流程,无需处理
break;
}
} catch (\Throwable $e) {
// 避免回写异常影响审批主流程,可按需记录日志
// logger()->error('onFlowFinalized error: '.$e->getMessage());
}
}
/** 撤回(仅发起人在无已处理记录前可撤回) */
public function revoke(int $instanceId, int $initiatorId, string $reason = '')
{
@@ -226,6 +275,8 @@ class ApprovalFlowService
'updated_at' => $now,
]);
$this->onFlowFinalized($instance, 'revoked');
Db::table('approval_records')
->where('instance_id', $instanceId)
->where('status', 'pending')
@@ -319,6 +370,8 @@ class ApprovalFlowService
'updated_at' => $now,
]);
$this->onFlowFinalized((object)$instance, $final);
Db::table('approval_records')
->where('instance_id', $instance->id)
->where('round', (int)$instance->round)
@@ -365,6 +418,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}");
}
@@ -577,6 +656,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 +875,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
{
@@ -1520,95 +1438,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];
});
}
/**
* 查看某个实例的转交流水(按时间升序)
*/
@@ -1735,4 +1564,175 @@ class ApprovalFlowService
});
}
/** ★ 新增:发起“作废审批” */
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('已存在进行中的作废审批');
}
// 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');
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;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
<?php
namespace app\common\validate;
use think\Validate;
class UserGroupMembersValidate extends Validate
{
// 规则
protected $rule = [
];
// 提示
protected $message = [
];
// 场景
protected $scene = [
'store' => [
],
'update' => [
]
];
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace app\common\validate;
use think\Validate;
class UserGroupValidate extends Validate
{
// 规则
protected $rule = [
];
// 提示
protected $message = [
];
// 场景
protected $scene = [
'store' => [
],
'update' => [
]
];
}