IqcInspBillFlowService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using Admin.NET.Plugin.AiDOP.Entity;
  2. using Admin.NET.Plugin.AiDOP.MaterialWarehouse.Dto;
  3. using Admin.NET.Plugin.ApprovalFlow;
  4. using Admin.NET.Plugin.ApprovalFlow.Service;
  5. using Yitter.IdGenerator;
  6. namespace Admin.NET.Plugin.AiDOP.MaterialWarehouse;
  7. /// <summary>
  8. /// S5 来料检验单 检验员+主管最小审批流服务(S5-IQC-INSPBILL-INSPECTOR-SUPERVISOR-FLOW-1)。
  9. ///
  10. /// N1_INSPECT 检验员录入 pd/dhsl/bhgsl/clfs → 提交 → N2_SUP_REVIEW 检验主管审核(通过=CLOSED / 退回=回 N1)。
  11. /// 复用 ApprovalFlow 引擎扩展点(StartFlow/Approve/ReturnToPrev + IFlowBizHandler),不改 ApprovalFlow 核心。
  12. /// BizType=S5_IQC_INSPBILL,BizId=qms_qcp_inspbill.id,BizCode=FBILLNO。反查用 ApprovalFlowInstance(BizType,BizId),inspbill 不加列。
  13. /// submit-result 写 qms_qcp_inspbill.pd/dhsl/bhgsl/clfs 并推进 N1→N2;
  14. /// Q5:提交结果即推 165(IqcWmsResultPushService),主管审核不再碰 165。
  15. /// approve/reject 不写 qms。不写库存、不入库。
  16. /// </summary>
  17. [ApiDescriptionSettings(Order = 310, Description = "来料检验单流程")]
  18. [Route("api/S5IqcInspBillFlow")]
  19. [NonUnify]
  20. public class IqcInspBillFlowService : IDynamicApiController, ITransient
  21. {
  22. /// <summary>主/系统租户哨兵:超管未选择目标租户时其 JWT TenantId 即此值,拒绝作为业务租户。</summary>
  23. private const long MainTenantId = 1300000000001L;
  24. private readonly ISqlSugarClient _db;
  25. private readonly FlowEngineService _flowEngine;
  26. private readonly UserManager _userManager;
  27. private readonly IqcWmsResultPushService _wmsPush;
  28. public IqcInspBillFlowService(
  29. ISqlSugarClient db,
  30. FlowEngineService flowEngine,
  31. UserManager userManager,
  32. IqcWmsResultPushService wmsPush)
  33. {
  34. _db = db;
  35. _flowEngine = flowEngine;
  36. _userManager = userManager;
  37. _wmsPush = wmsPush;
  38. }
  39. /// <summary>严格可信租户解析:只来自认证后 JWT;无 Token(&lt;=0) 或超管未选主租户 → 拒绝;不读前端 tenantId、无默认回退。</summary>
  40. private long ResolveTenantOrThrow()
  41. {
  42. var tid = _userManager.TenantId;
  43. if (tid <= 0)
  44. throw Oops.Oh("无法确定当前租户,请重新登录或选择目标租户");
  45. if (_userManager.SuperAdmin && tid == MainTenantId)
  46. throw Oops.Oh("超级管理员操作前必须选择目标租户");
  47. return tid;
  48. }
  49. /// <summary>
  50. /// 检验单流程状态(只读,供前端按钮控制)。
  51. /// </summary>
  52. [DisplayName("来料检验单流程状态")]
  53. [HttpGet("state")]
  54. public async Task<IqcFlowStateOutput> GetState([FromQuery] long id)
  55. {
  56. await EnsureBillExistsAsync(id);
  57. return await BuildStateAsync(id);
  58. }
  59. /// <summary>
  60. /// 检验员提交检验结果(写 pd/dhsl/bhgsl/clfs + 推进 N1→N2)。
  61. /// </summary>
  62. [DisplayName("检验员提交检验结果")]
  63. [HttpPost("submit-result")]
  64. public async Task<IqcFlowStateOutput> SubmitResult([FromBody] IqcSubmitResultInput input)
  65. {
  66. var billNo = await EnsureBillExistsAsync(input.Id);
  67. // 参数校验
  68. if (input.Pd != 0 && input.Pd != 1) throw Oops.Oh("判定 pd 只能为 0(合格) 或 1(不合格)");
  69. if (input.Dhsl < 0) throw Oops.Oh("合格数量不能为负");
  70. if (input.Bhgsl < 0) throw Oops.Oh("不合格数量不能为负");
  71. if (input.Pd == 0)
  72. {
  73. if (input.Bhgsl != 0) throw Oops.Oh("判定合格时不合格数量必须为 0");
  74. }
  75. else // pd == 1
  76. {
  77. if (input.Bhgsl <= 0) throw Oops.Oh("判定不合格时不合格数量必须大于 0");
  78. if (input.Clfs is not (0 or 1 or 2)) throw Oops.Oh("判定不合格时处理方式 clfs 必填且只能为 0(让步接收)/1(挑选)/2(报废)");
  79. }
  80. var inst = await GetLatestInstanceAsync(input.Id);
  81. if (inst != null && inst.Status != FlowInstanceStatusEnum.Running)
  82. throw Oops.Oh("该检验单流程已结束,无法再提交检验结果");
  83. var tran = await _db.AsTenant().UseTranAsync(async () =>
  84. {
  85. // 无运行中实例 → 起流程(自动生成 N1 任务给检验员角色成员)
  86. long instanceId;
  87. if (inst == null)
  88. {
  89. instanceId = await _flowEngine.StartFlow(new StartFlowInput
  90. {
  91. BizType = IqcInspBillFlowConst.BizType,
  92. BizId = input.Id,
  93. BizNo = billNo,
  94. Title = $"来料检验单 {billNo}",
  95. Comment = input.Comment,
  96. });
  97. }
  98. else
  99. {
  100. instanceId = inst.Id;
  101. }
  102. var myTask = await GetMyPendingTaskAsync(instanceId);
  103. if (myTask == null)
  104. throw Oops.Oh("当前用户没有待处理的检验任务(需检验员角色成员)");
  105. if (myTask.NodeId != IqcInspBillFlowConst.NodeInspect)
  106. throw Oops.Oh("当前不在检验录入节点,无法提交检验结果");
  107. // 写库前严格解析可信租户(无 Token / 超管未选主租户 → 抛错,不落库)
  108. var tid = ResolveTenantOrThrow();
  109. // 写检验结果(仅 pd/dhsl/bhgsl/clfs)
  110. await _db.Ado.ExecuteCommandAsync(
  111. "UPDATE qms_qcp_inspbill SET pd=@pd, dhsl=@dhsl, bhgsl=@bhgsl, clfs=@clfs WHERE id=@id AND tenant_id=@TenantId",
  112. new List<SugarParameter>
  113. {
  114. new("@pd", input.Pd),
  115. new("@dhsl", input.Dhsl),
  116. new("@bhgsl", input.Bhgsl),
  117. new("@clfs", input.Pd == 1 ? input.Clfs : null),
  118. new("@id", input.Id),
  119. new("@TenantId", tid),
  120. });
  121. // 推进 N1 → N2
  122. await _flowEngine.Approve(myTask.Id, input.Comment);
  123. });
  124. if (!tran.IsSuccess) throw tran.ErrorException;
  125. // Q5:检验员提交即推 165(对齐旧 DOP submitAfter);失败不阻断主流程
  126. try
  127. {
  128. var tid = ResolveTenantOrThrow();
  129. await _wmsPush.TryEnqueueAfterSubmitAsync(input.Id, tid);
  130. }
  131. catch
  132. {
  133. // 推送失败不影响提交结果本身
  134. }
  135. return await BuildStateAsync(input.Id);
  136. }
  137. /// <summary>
  138. /// 检验主管通过(N2 → 完成)。仅走 Ai-DOP 内部审批,不再写 165。
  139. /// </summary>
  140. [DisplayName("检验主管通过")]
  141. [HttpPost("supervisor-approve")]
  142. public async Task<IqcFlowStateOutput> SupervisorApprove([FromBody] IqcSupervisorApproveInput input)
  143. {
  144. await EnsureBillExistsAsync(input.Id);
  145. var (inst, myTask) = await RequireSupervisorTaskAsync(input.Id);
  146. var tran = await _db.AsTenant().UseTranAsync(async () =>
  147. {
  148. await _flowEngine.Approve(myTask.Id, input.Comment);
  149. });
  150. if (!tran.IsSuccess) throw tran.ErrorException;
  151. return await BuildStateAsync(input.Id);
  152. }
  153. /// <summary>
  154. /// 检验主管退回(N2 → 回 N1,意见必填)。
  155. /// </summary>
  156. [DisplayName("检验主管退回")]
  157. [HttpPost("supervisor-reject")]
  158. public async Task<IqcFlowStateOutput> SupervisorReject([FromBody] IqcSupervisorRejectInput input)
  159. {
  160. if (string.IsNullOrWhiteSpace(input.Comment))
  161. throw Oops.Oh("退回必须填写意见");
  162. await EnsureBillExistsAsync(input.Id);
  163. var (inst, myTask) = await RequireSupervisorTaskAsync(input.Id);
  164. var tran = await _db.AsTenant().UseTranAsync(async () =>
  165. {
  166. await _flowEngine.ReturnToPrev(myTask.Id, input.Comment);
  167. });
  168. if (!tran.IsSuccess) throw tran.ErrorException;
  169. return await BuildStateAsync(input.Id);
  170. }
  171. /// <summary>
  172. /// SQE 提交处置方案(N3 → 完成)。写 ado_s5_iqc_sqe_disposition + 推进 N3→end。不写 qms.clfs/库存/仓储。
  173. /// </summary>
  174. [DisplayName("SQE提交处置方案")]
  175. [HttpPost("sqe-submit-disposition")]
  176. public async Task<IqcFlowStateOutput> SqeSubmitDisposition([FromBody] IqcSqeSubmitDispositionInput input)
  177. {
  178. var billNo = await EnsureBillExistsAsync(input.Id);
  179. // 参数校验
  180. if (input.DispositionType is not (0 or 1 or 2)) throw Oops.Oh("处置方式只能为 0(让步接收)/1(挑选)/2(报废)");
  181. if (string.IsNullOrWhiteSpace(input.DispositionOpinion)) throw Oops.Oh("处置意见必填");
  182. foreach (var q in new[] { input.DispositionQty, input.ConcessionQty, input.SelectionQty, input.ScrapQty })
  183. if (q.HasValue && q.Value < 0) throw Oops.Oh("处置数量不能为负");
  184. // 写库前严格解析可信租户(无 Token / 超管未选主租户 → 抛错,不落库)
  185. var tid = ResolveTenantOrThrow();
  186. // 检验单必须不合格(合格单无 SQE 节点)
  187. var pdRows = await _db.Ado.SqlQueryAsync<int?>(
  188. "SELECT pd FROM qms_qcp_inspbill WHERE id=@id AND tenant_id=@TenantId LIMIT 1",
  189. new List<SugarParameter> { new("@id", input.Id), new("@TenantId", tid) });
  190. if (pdRows.FirstOrDefault() != 1) throw Oops.Oh("仅不合格检验单(pd=1)可做 SQE 处置");
  191. var inst = await GetLatestInstanceAsync(input.Id);
  192. if (inst == null) throw Oops.Oh("该检验单尚未发起流程");
  193. if (inst.Status != FlowInstanceStatusEnum.Running) throw Oops.Oh("该检验单流程已结束");
  194. var myTask = await GetMyPendingTaskAsync(inst.Id);
  195. if (myTask == null) throw Oops.Oh("当前用户没有待处理的 SQE 处置任务(需 SQE 角色成员)");
  196. if (myTask.NodeId != IqcInspBillFlowConst.NodeSqe) throw Oops.Oh("当前不在 SQE 处置节点");
  197. // 一单一有效处置
  198. var hasEffective = await _db.Queryable<AdoS5IqcSqeDisposition>()
  199. .Where(x => x.InspbillId == input.Id && x.Status == 1)
  200. .AnyAsync();
  201. if (hasEffective) throw Oops.Oh("该检验单已有有效 SQE 处置,不可重复提交");
  202. // 来源单号
  203. var srcRows = await _db.Ado.SqlQueryAsync<string>(
  204. "SELECT lydjbh FROM qms_qcp_inspbill WHERE id=@id AND tenant_id=@TenantId LIMIT 1",
  205. new List<SugarParameter> { new("@id", input.Id), new("@TenantId", tid) });
  206. var now = DateTime.Now;
  207. var disposition = new AdoS5IqcSqeDisposition
  208. {
  209. Id = YitIdHelper.NextId(),
  210. TenantId = tid,
  211. OrgId = inst.OrgId,
  212. InspbillId = input.Id,
  213. InspbillNo = billNo,
  214. SourceBillNo = srcRows.FirstOrDefault(),
  215. BizType = IqcInspBillFlowConst.BizType,
  216. FlowInstanceId = inst.Id,
  217. DispositionNo = $"SQE-{billNo}-{now:yyyyMMddHHmmss}",
  218. DispositionType = input.DispositionType,
  219. DispositionQty = input.DispositionQty,
  220. ConcessionQty = input.ConcessionQty,
  221. SelectionQty = input.SelectionQty,
  222. ScrapQty = input.ScrapQty,
  223. SupplierResponse = input.SupplierResponse,
  224. DispositionOpinion = input.DispositionOpinion,
  225. AttachmentJson = input.AttachmentJson,
  226. SqeUserId = _userManager.UserId,
  227. SqeUserName = _userManager.RealName ?? _userManager.Account,
  228. Status = 1,
  229. SubmittedAt = now,
  230. CreateTime = now,
  231. };
  232. var tran = await _db.AsTenant().UseTranAsync(async () =>
  233. {
  234. await _db.Insertable(disposition).ExecuteCommandAsync();
  235. // 推进 N3 → end
  236. await _flowEngine.Approve(myTask.Id, input.Comment);
  237. });
  238. if (!tran.IsSuccess) throw tran.ErrorException;
  239. return await BuildStateAsync(input.Id);
  240. }
  241. // ───────────────────────── helpers ─────────────────────────
  242. /// <summary>校验检验单存在并返回 FBILLNO。</summary>
  243. private async Task<string> EnsureBillExistsAsync(long id)
  244. {
  245. if (id <= 0) throw Oops.Oh("检验单 id 非法");
  246. var tid = ResolveTenantOrThrow();
  247. var rows = await _db.Ado.SqlQueryAsync<string>(
  248. "SELECT FBILLNO FROM qms_qcp_inspbill WHERE id=@id AND tenant_id=@TenantId LIMIT 1",
  249. new List<SugarParameter> { new("@id", id), new("@TenantId", tid) });
  250. if (rows.Count == 0) throw Oops.Oh("检验单不存在");
  251. return rows[0] ?? id.ToString();
  252. }
  253. /// <summary>取该检验单最新流程实例(BizType+BizId,跨数据范围)。</summary>
  254. private async Task<ApprovalFlowInstance?> GetLatestInstanceAsync(long bizId)
  255. {
  256. return await _db.Queryable<ApprovalFlowInstance>()
  257. .ClearFilter()
  258. .Where(x => x.BizType == IqcInspBillFlowConst.BizType && x.BizId == bizId)
  259. .OrderByDescending(x => x.Id)
  260. .FirstAsync();
  261. }
  262. /// <summary>取当前用户在指定实例下的待办任务。</summary>
  263. private async Task<ApprovalFlowTask?> GetMyPendingTaskAsync(long instanceId)
  264. {
  265. var userId = _userManager.UserId;
  266. return await _db.Queryable<ApprovalFlowTask>()
  267. .ClearFilter()
  268. .Where(x => x.InstanceId == instanceId && x.AssigneeId == userId && x.Status == FlowTaskStatusEnum.Pending)
  269. .FirstAsync();
  270. }
  271. /// <summary>校验并返回主管 N2 待办任务。</summary>
  272. private async Task<(ApprovalFlowInstance inst, ApprovalFlowTask task)> RequireSupervisorTaskAsync(long bizId)
  273. {
  274. var inst = await GetLatestInstanceAsync(bizId);
  275. if (inst == null) throw Oops.Oh("该检验单尚未发起流程");
  276. if (inst.Status != FlowInstanceStatusEnum.Running) throw Oops.Oh("该检验单流程已结束");
  277. var myTask = await GetMyPendingTaskAsync(inst.Id);
  278. if (myTask == null) throw Oops.Oh("当前用户没有待处理的审核任务(需检验主管角色成员)");
  279. if (myTask.NodeId != IqcInspBillFlowConst.NodeSupervisor) throw Oops.Oh("当前不在主管审核节点");
  280. return (inst, myTask);
  281. }
  282. /// <summary>当前用户是否具备指定角色(跨数据范围)。</summary>
  283. private async Task<bool> HasRoleAsync(long roleId)
  284. {
  285. var userId = _userManager.UserId;
  286. return await _db.Queryable<SysUserRole>()
  287. .ClearFilter()
  288. .AnyAsync(x => x.UserId == userId && x.RoleId == roleId);
  289. }
  290. /// <summary>组装流程状态输出。</summary>
  291. private async Task<IqcFlowStateOutput> BuildStateAsync(long bizId)
  292. {
  293. var output = new IqcFlowStateOutput { BizId = bizId };
  294. var inst = await GetLatestInstanceAsync(bizId);
  295. if (inst == null)
  296. {
  297. output.FlowStatus = "NotStarted";
  298. output.CanSubmitResult = await HasRoleAsync(IqcInspBillFlowConst.RoleInspectorId);
  299. output.Message = output.CanSubmitResult ? "待检验员录入结果" : "尚未发起流程";
  300. return output;
  301. }
  302. output.InstanceId = inst.Id;
  303. output.FlowStatus = inst.Status.ToString();
  304. output.UpdatedAt = inst.EndTime ?? inst.StartTime;
  305. // SQE 处置摘要(不合格单可能已有处置记录,任何状态都可展示)
  306. var disp = await _db.Queryable<AdoS5IqcSqeDisposition>()
  307. .Where(x => x.InspbillId == bizId)
  308. .OrderByDescending(x => x.Id)
  309. .FirstAsync();
  310. if (disp != null)
  311. {
  312. output.HasSqeDisposition = true;
  313. output.SqeDispositionId = disp.Id;
  314. output.SqeDispositionStatus = disp.Status;
  315. output.SqeDispositionType = disp.DispositionType;
  316. }
  317. if (inst.Status != FlowInstanceStatusEnum.Running)
  318. {
  319. output.IsCompleted = true;
  320. output.Message = inst.Status == FlowInstanceStatusEnum.Approved ? "流程已完成(主管审核通过)" : $"流程已结束({inst.Status})";
  321. return output;
  322. }
  323. output.CurrentNodeCode = inst.CurrentNodeId;
  324. output.IsWaitingSqe = inst.CurrentNodeId == IqcInspBillFlowConst.NodeSqe;
  325. var myTask = await GetMyPendingTaskAsync(inst.Id);
  326. if (myTask != null)
  327. {
  328. output.CurrentNodeName = myTask.NodeName;
  329. if (myTask.NodeId == IqcInspBillFlowConst.NodeInspect)
  330. {
  331. output.CurrentAssigneeRole = IqcInspBillFlowConst.RoleInspectorCode;
  332. output.CanSubmitResult = true;
  333. output.Message = "待当前用户录入检验结果";
  334. }
  335. else if (myTask.NodeId == IqcInspBillFlowConst.NodeSupervisor)
  336. {
  337. output.CurrentAssigneeRole = IqcInspBillFlowConst.RoleSupervisorCode;
  338. output.CanSupervisorApprove = true;
  339. output.CanSupervisorReject = true;
  340. output.Message = "待当前用户主管审核";
  341. }
  342. else if (myTask.NodeId == IqcInspBillFlowConst.NodeSqe)
  343. {
  344. output.CurrentAssigneeRole = IqcInspBillFlowConst.RoleSqeCode;
  345. output.CanSqeSubmit = true;
  346. output.Message = "待当前用户提交 SQE 处置";
  347. }
  348. }
  349. else
  350. {
  351. output.CurrentAssigneeRole = inst.CurrentNodeId switch
  352. {
  353. IqcInspBillFlowConst.NodeInspect => IqcInspBillFlowConst.RoleInspectorCode,
  354. IqcInspBillFlowConst.NodeSqe => IqcInspBillFlowConst.RoleSqeCode,
  355. _ => IqcInspBillFlowConst.RoleSupervisorCode,
  356. };
  357. output.Message = "流程进行中(当前用户无待办)";
  358. }
  359. return output;
  360. }
  361. }