ProcuremenOperLog.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. <?php
  2. namespace app\common\library;
  3. use think\Db;
  4. use think\Log;
  5. /**
  6. * 协助采购操作日志(purchase_order_oper_log)
  7. *
  8. * 表字段为英文;写入时「action」存中文操作类型,查询时兼容历史英文码。
  9. */
  10. class ProcuremenOperLog
  11. {
  12. public const COL_SCYDGY_ID = 'scydgy_id';
  13. public const COL_PO_ID = 'purchase_order_id';
  14. public const COL_ADMIN_ID = 'admin_id';
  15. public const COL_ADMIN_NAME = 'admin_name';
  16. public const COL_ACTION = 'action';
  17. public const COL_CONTENT = 'content';
  18. public const COL_TIME = 'createtime';
  19. /**
  20. * 英文码 => 中文操作类型(入库展示用;与库中已有中文值对齐)
  21. *
  22. * @return array<string, string>
  23. */
  24. public static function actionLabelMap(): array
  25. {
  26. return [
  27. 'issue_submit' => '下发通知',
  28. 'audit_select' => '确认供应商',
  29. 'purchase_confirm' => '审核确认供应商',
  30. 'purchase_reject' => '审核驳回',
  31. 'bid_open_verify' => '开标验证',
  32. 'manual_pick' => '指定供应商',
  33. 'audit_append_supplier' => '补加供应商',
  34. 'audit_resend_sms' => '重发短信',
  35. 'audit_resend_email' => '重发邮件',
  36. 'manual_add' => '手工新增',
  37. 'pick_soft_delete' => '初选删除',
  38. 'save_qty_price' => '保存数量限价',
  39. 'mark_complete' => '直接完结',
  40. 'inbound_score' => '质量评分',
  41. 'audit_abandon' => '审批重新下发',
  42. 'archive_abandon' => '历史重新下发',
  43. ];
  44. }
  45. /**
  46. * 同一业务动作的可选别名(查询时一并匹配)
  47. *
  48. * @return array<string, string[]>
  49. */
  50. public static function actionAliases(): array
  51. {
  52. return [
  53. 'issue_submit' => ['下发通知', '下发', 'issue_submit'],
  54. 'audit_select' => ['确认供应商', 'audit_select'],
  55. 'purchase_confirm' => ['审核确认供应商', 'purchase_confirm'],
  56. 'purchase_reject' => ['审核驳回', 'purchase_reject'],
  57. 'bid_open_verify' => ['开标验证', 'bid_open_verify'],
  58. 'manual_pick' => ['指定供应商', 'manual_pick'],
  59. 'audit_append_supplier' => ['补加供应商', 'audit_append_supplier'],
  60. 'audit_resend_sms' => ['重发短信', 'audit_resend_sms'],
  61. 'audit_resend_email' => ['重发邮件', 'audit_resend_email'],
  62. 'manual_add' => ['手工新增', 'manual_add'],
  63. 'pick_soft_delete' => ['初选删除', 'pick_soft_delete'],
  64. 'save_qty_price' => ['保存数量限价', 'save_qty_price'],
  65. 'mark_complete' => ['直接完结', '完结', 'mark_complete'],
  66. 'inbound_score' => ['质量评分', '入库评分', '是否合格', 'inbound_score'],
  67. 'audit_abandon' => ['审批重新下发', '重新下发', 'audit_abandon'],
  68. 'archive_abandon' => ['历史重新下发', '存证重新下发', 'archive_abandon'],
  69. ];
  70. }
  71. public static function toActionLabel(string $action): string
  72. {
  73. $action = trim($action);
  74. if ($action === '') {
  75. return '';
  76. }
  77. $map = self::actionLabelMap();
  78. if (isset($map[$action])) {
  79. return $map[$action];
  80. }
  81. // 已是中文别名时,归一到主标签
  82. foreach (self::actionAliases() as $code => $aliases) {
  83. if (in_array($action, $aliases, true)) {
  84. return $map[$code] ?? $action;
  85. }
  86. }
  87. return $action;
  88. }
  89. /**
  90. * 查询用:同时匹配中文标签、别名与历史英文码
  91. *
  92. * @param string|array<int, string> $actions
  93. * @return string[]
  94. */
  95. public static function expandActionQueryValues($actions): array
  96. {
  97. $aliases = self::actionAliases();
  98. $map = self::actionLabelMap();
  99. $out = [];
  100. foreach ((array)$actions as $a) {
  101. $a = trim((string)$a);
  102. if ($a === '') {
  103. continue;
  104. }
  105. $out[$a] = true;
  106. $code = $a;
  107. if (!isset($aliases[$code])) {
  108. foreach ($aliases as $c => $list) {
  109. if (in_array($a, $list, true) || (isset($map[$c]) && $map[$c] === $a)) {
  110. $code = $c;
  111. break;
  112. }
  113. }
  114. }
  115. if (isset($aliases[$code])) {
  116. foreach ($aliases[$code] as $v) {
  117. $out[$v] = true;
  118. }
  119. }
  120. if (isset($map[$code])) {
  121. $out[$map[$code]] = true;
  122. }
  123. }
  124. return array_keys($out);
  125. }
  126. /**
  127. * 组装入库行(英文字段,操作类型存中文)
  128. *
  129. * @return array<string, mixed>
  130. */
  131. public static function buildInsertRow(
  132. int $scydgyId,
  133. string $action,
  134. string $content,
  135. ?int $purchaseOrderId,
  136. int $adminId,
  137. string $adminName
  138. ): array {
  139. return [
  140. self::COL_SCYDGY_ID => $scydgyId,
  141. self::COL_PO_ID => $purchaseOrderId,
  142. self::COL_ADMIN_ID => $adminId,
  143. self::COL_ADMIN_NAME => self::cut($adminName !== '' ? $adminName : '未知用户', 64),
  144. self::COL_ACTION => self::cut(self::toActionLabel($action), 64),
  145. self::COL_CONTENT => self::cut($content, 1000),
  146. self::COL_TIME => ProcuremenTime::nowDateTime(),
  147. ];
  148. }
  149. /**
  150. * @param array{0:int,1:string} $admin [id, name]
  151. */
  152. public static function write(int $scydgyId, string $action, string $content, ?int $purchaseOrderId, array $admin): void
  153. {
  154. if (!ProcuremenGuard::isValidScydgyId($scydgyId) || $content === '') {
  155. return;
  156. }
  157. $adminId = (int)($admin[0] ?? 0);
  158. $adminName = (string)($admin[1] ?? '未知用户');
  159. try {
  160. Db::table('purchase_order_oper_log')->insert(
  161. self::buildInsertRow($scydgyId, $action, $content, $purchaseOrderId, $adminId, $adminName)
  162. );
  163. } catch (\Throwable $e) {
  164. Log::write('procuremen oper log: ' . $e->getMessage(), 'error');
  165. }
  166. }
  167. /**
  168. * 查询结果规范化(兼容偶发中文列名 → 英文键)
  169. *
  170. * @param array<string, mixed> $log
  171. * @return array<string, mixed>
  172. */
  173. public static function normalizeRow(array $log): array
  174. {
  175. $map = [
  176. '工序ID' => 'scydgy_id',
  177. '采购订单ID' => 'purchase_order_id',
  178. '操作人ID' => 'admin_id',
  179. '操作人' => 'admin_name',
  180. '操作类型' => 'action',
  181. '操作内容' => 'content',
  182. '创建时间' => 'createtime',
  183. ];
  184. foreach ($map as $cn => $en) {
  185. if (array_key_exists($cn, $log) && !array_key_exists($en, $log)) {
  186. $log[$en] = $log[$cn];
  187. }
  188. }
  189. if (isset($log['action'])) {
  190. $log['action'] = self::toActionLabel((string)$log['action']);
  191. }
  192. return $log;
  193. }
  194. /**
  195. * @param string|array<int, string> $actions
  196. */
  197. public static function resolveLatestTime(int $scydgyId, $actions): string
  198. {
  199. if (!ProcuremenGuard::isValidScydgyId($scydgyId)) {
  200. return '';
  201. }
  202. $acts = self::expandActionQueryValues($actions);
  203. if ($acts === []) {
  204. return '';
  205. }
  206. try {
  207. $log = Db::table('purchase_order_oper_log')
  208. ->where(self::COL_SCYDGY_ID, $scydgyId)
  209. ->where(self::COL_ACTION, 'in', $acts)
  210. ->order('id', 'desc')
  211. ->find();
  212. if (is_array($log)) {
  213. $log = self::normalizeRow($log);
  214. $text = ProcuremenTime::formatDisplayDateTime($log['createtime'] ?? null);
  215. if ($text !== '') {
  216. return $text;
  217. }
  218. }
  219. } catch (\Throwable $e) {
  220. }
  221. return '';
  222. }
  223. /**
  224. * 从已加载的操作日志中取最近时间(避免详情页重复查库)
  225. *
  226. * @param array<int, array<string, mixed>> $logs
  227. * @param string|array<int, string> $actions
  228. */
  229. public static function resolveLatestTimeFromLogs(array $logs, int $scydgyId, $actions): string
  230. {
  231. if (!ProcuremenGuard::isValidScydgyId($scydgyId) || $logs === []) {
  232. return '';
  233. }
  234. $acts = self::expandActionQueryValues($actions);
  235. if ($acts === []) {
  236. return '';
  237. }
  238. $actSet = [];
  239. foreach ($acts as $a) {
  240. $actSet[(string)$a] = true;
  241. $actSet[self::toActionLabel((string)$a)] = true;
  242. }
  243. $bestId = -1;
  244. $bestText = '';
  245. foreach ($logs as $log) {
  246. if (!is_array($log)) {
  247. continue;
  248. }
  249. $sid = (int)($log[self::COL_SCYDGY_ID] ?? 0);
  250. if ($sid !== $scydgyId) {
  251. continue;
  252. }
  253. $action = trim((string)($log[self::COL_ACTION] ?? ''));
  254. if ($action === '' || (!isset($actSet[$action]) && !isset($actSet[self::toActionLabel($action)]))) {
  255. continue;
  256. }
  257. $id = (int)($log['id'] ?? $log['ID'] ?? 0);
  258. if ($id < $bestId) {
  259. continue;
  260. }
  261. $text = ProcuremenTime::formatDisplayDateTime($log['createtime'] ?? null);
  262. if ($text === '') {
  263. continue;
  264. }
  265. $bestId = $id;
  266. $bestText = $text;
  267. }
  268. return $bestText;
  269. }
  270. public static function resolveMarkCompleteTime(int $scydgyId): string
  271. {
  272. return self::resolveLatestTime($scydgyId, 'mark_complete');
  273. }
  274. /**
  275. * @param array<int, array<string, mixed>> $logs
  276. * @param array<int, string> $processNameBySid scydgy_id => 工序名称
  277. * @return array<int, array<string, mixed>>
  278. */
  279. public static function formatLogRowsForDisplay(array $logs, array $processNameBySid = []): array
  280. {
  281. foreach ($logs as &$lg) {
  282. if (!is_array($lg)) {
  283. continue;
  284. }
  285. $lg = self::normalizeRow($lg);
  286. $lg['createtime_text'] = ProcuremenTime::formatDisplayDateTime($lg['createtime'] ?? null);
  287. $lg['content'] = ProcuremenTime::formatOperLogContent(
  288. (string)($lg['content'] ?? ''),
  289. (string)($lg['action'] ?? '')
  290. );
  291. $lg['action_text'] = self::toActionLabel((string)($lg['action'] ?? ''));
  292. $lg = self::enrichSaveQtyPriceProcessName($lg, $processNameBySid);
  293. }
  294. unset($lg);
  295. $logs = self::mergeDuplicateProcessLogs($logs, $processNameBySid);
  296. $logs = self::enrichAdminDisplayFields($logs);
  297. foreach ($logs as &$lg) {
  298. if (!is_array($lg)) {
  299. continue;
  300. }
  301. $lg = self::splitActionAndDetailForDisplay($lg);
  302. }
  303. unset($lg);
  304. return $logs;
  305. }
  306. /**
  307. * 展示拆成「操作类型」+「操作说明」,说明里不再重复类型前缀
  308. *
  309. * @param array<string, mixed> $lg
  310. * @return array<string, mixed>
  311. */
  312. protected static function splitActionAndDetailForDisplay(array $lg): array
  313. {
  314. $action = trim((string)($lg['action_text'] ?? ''));
  315. if ($action === '') {
  316. $action = self::toActionLabel((string)($lg[self::COL_ACTION] ?? ''));
  317. }
  318. $content = trim((string)($lg[self::COL_CONTENT] ?? ''));
  319. $content = self::stripLeadingActionPrefixes($content, $action);
  320. // 入库评分:只展示合格/不合格,去掉工序括号
  321. if ($action === '入库评分' || self::toActionLabel((string)($lg[self::COL_ACTION] ?? '')) === '入库评分') {
  322. if (preg_match('/(合格|不合格)/u', $content, $m)) {
  323. $content = $m[1];
  324. }
  325. }
  326. if ($action === '') {
  327. $action = '操作';
  328. }
  329. $lg['action_text'] = $action;
  330. $lg[self::COL_CONTENT] = $content;
  331. return $lg;
  332. }
  333. /**
  334. * @return string[] 按长度降序
  335. */
  336. protected static function contentActionPrefixes(string $action): array
  337. {
  338. $action = self::toActionLabel(trim($action));
  339. $list = [];
  340. if ($action !== '') {
  341. $list[] = $action;
  342. }
  343. // 历史/文案别名
  344. $aliases = [
  345. '下发通知' => ['下发', '下发通知'],
  346. '保存数量限价' => ['保存数量限价', '保存本次数量、最高限价'],
  347. '审批重新下发' => ['审批重新下发', '重新下发'],
  348. '历史重新下发' => ['历史重新下发', '存证重新下发', '重新下发'],
  349. '审核确认供应商' => ['审核确认供应商', '采购确认'],
  350. '确认供应商' => ['确认供应商'],
  351. '开标验证' => ['开标验证'],
  352. '补加供应商' => ['补加供应商'],
  353. '直接完结' => ['直接完结', '完结'],
  354. '审核驳回' => ['审核驳回', '采购终审驳回'],
  355. ];
  356. if (isset($aliases[$action])) {
  357. foreach ($aliases[$action] as $a) {
  358. $list[] = $a;
  359. }
  360. }
  361. $list = array_values(array_unique(array_filter(array_map('trim', $list))));
  362. usort($list, static function ($a, $b) {
  363. return mb_strlen((string)$b, 'UTF-8') <=> mb_strlen((string)$a, 'UTF-8');
  364. });
  365. return $list;
  366. }
  367. protected static function stripLeadingActionPrefixes(string $content, string $action): string
  368. {
  369. $content = trim($content);
  370. if ($content === '') {
  371. return '';
  372. }
  373. foreach (self::contentActionPrefixes($action) as $p) {
  374. foreach ([$p . ':', $p . ':'] as $pref) {
  375. if (mb_strpos($content, $pref, 0, 'UTF-8') === 0) {
  376. return trim(mb_substr($content, mb_strlen($pref, 'UTF-8'), null, 'UTF-8'));
  377. }
  378. }
  379. }
  380. return $content;
  381. }
  382. /**
  383. * 历史「保存数量限价」说明补工序名:…:压折线本次数量「330」,最高限价「10」
  384. *
  385. * @param array<string, mixed> $lg
  386. * @param array<int, string> $processNameBySid
  387. * @return array<string, mixed>
  388. */
  389. protected static function enrichSaveQtyPriceProcessName(array $lg, array $processNameBySid): array
  390. {
  391. $action = trim((string)($lg['action_text'] ?? $lg[self::COL_ACTION] ?? ''));
  392. if ($action !== '保存数量限价' && $action !== 'save_qty_price') {
  393. return $lg;
  394. }
  395. $content = trim((string)($lg[self::COL_CONTENT] ?? ''));
  396. if ($content === '') {
  397. return $lg;
  398. }
  399. $sid = (int)($lg[self::COL_SCYDGY_ID] ?? 0);
  400. $proc = trim((string)($processNameBySid[$sid] ?? ''));
  401. if ($proc === '') {
  402. return $lg;
  403. }
  404. // 已含工序名则不重复
  405. if (mb_strpos($content, $proc . '本次数量', 0, 'UTF-8') !== false
  406. || mb_strpos($content, '(' . $proc . ')', 0, 'UTF-8') !== false) {
  407. return $lg;
  408. }
  409. if (mb_strpos($content, ':本次数量', 0, 'UTF-8') !== false) {
  410. $lg[self::COL_CONTENT] = preg_replace('/:本次数量/u', ':' . $proc . '本次数量', $content, 1);
  411. } elseif (mb_strpos($content, ':本次数量', 0, 'UTF-8') !== false) {
  412. $lg[self::COL_CONTENT] = preg_replace('/:本次数量/u', ':' . $proc . '本次数量', $content, 1);
  413. }
  414. return $lg;
  415. }
  416. /**
  417. * 操作人前加所属组别;说明文案中的人员名同样补组别
  418. *
  419. * @param array<int, array<string, mixed>> $logs
  420. * @return array<int, array<string, mixed>>
  421. */
  422. public static function enrichAdminDisplayFields(array $logs): array
  423. {
  424. $ids = [];
  425. foreach ($logs as $lg) {
  426. if (!is_array($lg)) {
  427. continue;
  428. }
  429. $id = (int)($lg[self::COL_ADMIN_ID] ?? 0);
  430. if ($id > 0) {
  431. $ids[$id] = true;
  432. }
  433. }
  434. $map = self::loadAdminGroupNicknameMap(array_keys($ids));
  435. // 仅用于纠正历史误伤:说明里曾把「组别 昵称」拼进供应商名,展示时还原为昵称/公司名
  436. $nameToLabeled = self::buildAdminNameLabelMap(self::loadAllAdminGroupNicknameMap());
  437. foreach (self::buildAdminNameLabelMap($map) as $name => $labeled) {
  438. $nameToLabeled[$name] = $labeled;
  439. }
  440. uksort($nameToLabeled, static function ($a, $b) {
  441. return mb_strlen((string)$b, 'UTF-8') <=> mb_strlen((string)$a, 'UTF-8');
  442. });
  443. foreach ($logs as &$lg) {
  444. if (!is_array($lg)) {
  445. continue;
  446. }
  447. $id = (int)($lg[self::COL_ADMIN_ID] ?? 0);
  448. $info = ($id > 0 && isset($map[$id])) ? $map[$id] : null;
  449. $nick = is_array($info) ? trim((string)($info['nickname'] ?? '')) : '';
  450. if ($nick === '') {
  451. $nick = trim((string)($lg[self::COL_ADMIN_NAME] ?? ''));
  452. }
  453. if ($nick === '') {
  454. $nick = '未知用户';
  455. }
  456. $group = is_array($info) ? trim((string)($info['group_name'] ?? '')) : '';
  457. $lg['admin_group'] = $group !== '' ? $group : '—';
  458. $lg['admin_nickname'] = $nick;
  459. // 操作人显示「组别 昵称」
  460. $lg[self::COL_ADMIN_NAME] = self::formatAdminWithGroup($group, $nick);
  461. $content = (string)($lg[self::COL_CONTENT] ?? '');
  462. if ($content !== '' && $nameToLabeled !== []) {
  463. // 先还原历史误伤的供应商名
  464. $content = self::unprefixMistakenNamesInText($content, $nameToLabeled);
  465. // 开标验证等说明里是人员名,再补组别
  466. $actionLabel = self::toActionLabel((string)($lg['action_text'] ?? $lg[self::COL_ACTION] ?? ''));
  467. if (self::actionContentNeedsPersonGroup($actionLabel)) {
  468. $content = self::prefixNamesInText($content, $nameToLabeled);
  469. }
  470. $lg[self::COL_CONTENT] = $content;
  471. }
  472. }
  473. unset($lg);
  474. return $logs;
  475. }
  476. /** 操作说明里会出现人员姓名、需补所属组别的类型 */
  477. protected static function actionContentNeedsPersonGroup(string $action): bool
  478. {
  479. $action = self::toActionLabel(trim($action));
  480. return $action === '开标验证';
  481. }
  482. /**
  483. * 按 admin.id 解析展示名「组别 昵称」
  484. *
  485. * @param array<int, int> $adminIds
  486. * @return array<int, string>
  487. */
  488. public static function resolveAdminDisplayLabels(array $adminIds): array
  489. {
  490. $map = self::loadAdminGroupNicknameMap($adminIds);
  491. $out = [];
  492. foreach ($adminIds as $rawId) {
  493. $id = (int)$rawId;
  494. if ($id <= 0) {
  495. continue;
  496. }
  497. $info = isset($map[$id]) && is_array($map[$id]) ? $map[$id] : null;
  498. $nick = is_array($info) ? trim((string)($info['nickname'] ?? '')) : '';
  499. $group = is_array($info) ? trim((string)($info['group_name'] ?? '')) : '';
  500. if ($nick === '') {
  501. $nick = 'ID' . $id;
  502. }
  503. $out[$id] = self::formatAdminWithGroup($group, $nick);
  504. }
  505. return $out;
  506. }
  507. /**
  508. * @param array<int, array{nickname:string,group_name:string}> $adminMap
  509. * @return array<string, string> 原名 => 「组别 名称」
  510. */
  511. protected static function buildAdminNameLabelMap(array $adminMap): array
  512. {
  513. $out = [];
  514. foreach ($adminMap as $info) {
  515. if (!is_array($info)) {
  516. continue;
  517. }
  518. $nick = trim((string)($info['nickname'] ?? ''));
  519. if ($nick === '') {
  520. continue;
  521. }
  522. $group = trim((string)($info['group_name'] ?? ''));
  523. $labeled = self::formatAdminWithGroup($group, $nick);
  524. if ($labeled !== $nick) {
  525. $out[$nick] = $labeled;
  526. }
  527. }
  528. // 长名优先,避免短名误伤
  529. uksort($out, static function ($a, $b) {
  530. return mb_strlen((string)$b, 'UTF-8') <=> mb_strlen((string)$a, 'UTF-8');
  531. });
  532. return $out;
  533. }
  534. protected static function formatAdminWithGroup(string $group, string $name): string
  535. {
  536. $name = trim($name);
  537. $group = trim($group);
  538. if ($name === '') {
  539. return $group !== '' ? $group : '未知用户';
  540. }
  541. if ($group === '' || $group === '—' || $group === $name) {
  542. return $name;
  543. }
  544. // 已带组别则不再重复
  545. if (mb_strpos($name, $group, 0, 'UTF-8') === 0) {
  546. return $name;
  547. }
  548. return $group . ' ' . $name;
  549. }
  550. /**
  551. * @param array<string, string> $nameToLabeled
  552. */
  553. protected static function prefixNamesInText(string $text, array $nameToLabeled): string
  554. {
  555. foreach ($nameToLabeled as $name => $labeled) {
  556. if ($name === '' || $labeled === '' || $name === $labeled) {
  557. continue;
  558. }
  559. if (mb_strpos($text, $labeled, 0, 'UTF-8') !== false) {
  560. continue;
  561. }
  562. if (mb_strpos($text, $name, 0, 'UTF-8') === false) {
  563. continue;
  564. }
  565. $text = str_replace($name, $labeled, $text);
  566. }
  567. return $text;
  568. }
  569. /**
  570. * 还原说明里误拼的「组别 昵称」→ 原名(避免供应商名被改成「浙江新华管理员 新华印刷…」)
  571. *
  572. * @param array<string, string> $nameToLabeled
  573. */
  574. protected static function unprefixMistakenNamesInText(string $text, array $nameToLabeled): string
  575. {
  576. // 长标签优先替换
  577. $pairs = [];
  578. foreach ($nameToLabeled as $name => $labeled) {
  579. if ($name === '' || $labeled === '' || $name === $labeled) {
  580. continue;
  581. }
  582. $pairs[$labeled] = $name;
  583. }
  584. uksort($pairs, static function ($a, $b) {
  585. return mb_strlen((string)$b, 'UTF-8') <=> mb_strlen((string)$a, 'UTF-8');
  586. });
  587. foreach ($pairs as $labeled => $name) {
  588. if (mb_strpos($text, $labeled, 0, 'UTF-8') === false) {
  589. continue;
  590. }
  591. $text = str_replace($labeled, $name, $text);
  592. }
  593. return $text;
  594. }
  595. /**
  596. * @return array<int, array{nickname:string,group_name:string,username?:string}>
  597. */
  598. public static function loadAllAdminGroupNicknameMap(): array
  599. {
  600. try {
  601. $ids = Db::name('admin')->column('id');
  602. } catch (\Throwable $e) {
  603. $ids = [];
  604. }
  605. if (!is_array($ids) || $ids === []) {
  606. return [];
  607. }
  608. return self::loadAdminGroupNicknameMap(array_map('intval', $ids));
  609. }
  610. /**
  611. * @param array<int, int> $adminIds
  612. * @return array<int, array{nickname:string,group_name:string,username?:string}>
  613. */
  614. public static function loadAdminGroupNicknameMap(array $adminIds): array
  615. {
  616. $out = [];
  617. $adminIds = array_values(array_filter(array_map('intval', $adminIds)));
  618. if ($adminIds === []) {
  619. return $out;
  620. }
  621. try {
  622. $admins = Db::name('admin')->where('id', 'in', $adminIds)->field('id,nickname,username')->select();
  623. } catch (\Throwable $e) {
  624. $admins = [];
  625. }
  626. if (is_array($admins)) {
  627. foreach ($admins as $a) {
  628. if (!is_array($a)) {
  629. continue;
  630. }
  631. $id = (int)($a['id'] ?? 0);
  632. if ($id <= 0) {
  633. continue;
  634. }
  635. $nick = trim((string)($a['nickname'] ?? ''));
  636. if ($nick === '') {
  637. $nick = trim((string)($a['username'] ?? ''));
  638. }
  639. $out[$id] = ['nickname' => $nick, 'group_name' => '', 'username' => trim((string)($a['username'] ?? ''))];
  640. }
  641. }
  642. try {
  643. $rows = Db::name('auth_group_access')
  644. ->alias('aga')
  645. ->join('auth_group ag', 'aga.group_id = ag.id', 'LEFT')
  646. ->where('aga.uid', 'in', $adminIds)
  647. ->field('aga.uid,ag.name')
  648. ->select();
  649. } catch (\Throwable $e) {
  650. $rows = [];
  651. }
  652. if (is_array($rows)) {
  653. foreach ($rows as $r) {
  654. if (!is_array($r)) {
  655. continue;
  656. }
  657. $uid = (int)($r['uid'] ?? 0);
  658. $gname = trim((string)($r['name'] ?? ''));
  659. if ($uid <= 0 || $gname === '') {
  660. continue;
  661. }
  662. if (!isset($out[$uid])) {
  663. $out[$uid] = ['nickname' => '', 'group_name' => $gname];
  664. } elseif ($out[$uid]['group_name'] === '') {
  665. $out[$uid]['group_name'] = $gname;
  666. } elseif (strpos($out[$uid]['group_name'], $gname) === false) {
  667. $out[$uid]['group_name'] .= '、' . $gname;
  668. }
  669. }
  670. }
  671. return $out;
  672. }
  673. /**
  674. * 多工序短时间内相同操作合并为一条,并带上工序名称
  675. * 例:审核确认供应商:配套、快递已选定「xxx」
  676. *
  677. * @param array<int, array<string, mixed>> $logs
  678. * @param array<int, string> $processNameBySid
  679. * @return array<int, array<string, mixed>>
  680. */
  681. public static function mergeDuplicateProcessLogs(array $logs, array $processNameBySid = []): array
  682. {
  683. if ($logs === []) {
  684. return [];
  685. }
  686. $groups = [];
  687. $order = [];
  688. foreach ($logs as $idx => $lg) {
  689. if (!is_array($lg)) {
  690. continue;
  691. }
  692. $adminId = (int)($lg[self::COL_ADMIN_ID] ?? 0);
  693. $admin = trim((string)($lg[self::COL_ADMIN_NAME] ?? ''));
  694. $action = trim((string)($lg['action_text'] ?? $lg[self::COL_ACTION] ?? ''));
  695. $content = trim((string)($lg[self::COL_CONTENT] ?? ''));
  696. $contentCore = self::normalizeMergeContentCore($action, $content);
  697. $ts = self::logTimeTs($lg);
  698. // 60 秒内、同操作人+同操作类型+同说明核心 → 合并
  699. $bucket = null;
  700. foreach ($groups as $gk => $g) {
  701. if (($g['admin_id'] !== $adminId && $g['admin'] !== $admin)
  702. || $g['action'] !== $action
  703. || $g['content_core'] !== $contentCore) {
  704. continue;
  705. }
  706. if (abs($ts - (int)$g['ts']) <= 60) {
  707. $bucket = $gk;
  708. break;
  709. }
  710. }
  711. if ($bucket === null) {
  712. $bucket = 'g' . $idx;
  713. $groups[$bucket] = [
  714. 'admin_id' => $adminId,
  715. 'admin' => $admin,
  716. 'action' => $action,
  717. 'content_core' => $contentCore,
  718. 'ts' => $ts,
  719. 'row' => $lg,
  720. 'sids' => [],
  721. 'contents' => [],
  722. ];
  723. $order[] = $bucket;
  724. }
  725. $sid = (int)($lg[self::COL_SCYDGY_ID] ?? 0);
  726. if ($sid !== 0) {
  727. $groups[$bucket]['sids'][$sid] = true;
  728. }
  729. $groups[$bucket]['contents'][] = $content;
  730. // 保留最早一条作展示底稿,时间用最早
  731. $rowTs = self::logTimeTs($groups[$bucket]['row']);
  732. if ($ts > 0 && ($rowTs === 0 || $ts < $rowTs)) {
  733. $groups[$bucket]['row'] = $lg;
  734. $groups[$bucket]['ts'] = $ts;
  735. }
  736. }
  737. $out = [];
  738. foreach ($order as $gk) {
  739. $g = $groups[$gk];
  740. $row = $g['row'];
  741. $sids = array_keys($g['sids']);
  742. $processNames = [];
  743. foreach ($sids as $sid) {
  744. $nm = trim((string)($processNameBySid[$sid] ?? ''));
  745. if ($nm !== '' && !in_array($nm, $processNames, true)) {
  746. $processNames[] = $nm;
  747. }
  748. }
  749. $content = trim((string)($row[self::COL_CONTENT] ?? ''));
  750. if (count($sids) > 1 || count($processNames) > 1) {
  751. $content = self::buildMergedProcessContent(
  752. (string)($g['action'] ?? ''),
  753. $content,
  754. $processNames
  755. );
  756. }
  757. $row[self::COL_CONTENT] = $content;
  758. $row['action_text'] = (string)($g['action'] !== '' ? $g['action'] : ($row['action_text'] ?? ''));
  759. $out[] = $row;
  760. }
  761. return $out;
  762. }
  763. /**
  764. * 提取可合并的内容核心(去掉前缀动作名后的业务说明)
  765. */
  766. protected static function normalizeMergeContentCore(string $action, string $content): string
  767. {
  768. $core = self::stripLeadingActionPrefixes(trim($content), trim($action));
  769. $actionLabel = self::toActionLabel(trim($action));
  770. // 入库评分:同结果多工序分条 → 只按「合格/不合格」合并
  771. if ($actionLabel === '入库评分' || trim($action) === 'inbound_score') {
  772. if (preg_match('/^(合格|不合格)/u', $core, $m)) {
  773. return $m[1];
  774. }
  775. if (preg_match('/(合格|不合格)/u', $core, $m)) {
  776. return $m[1];
  777. }
  778. }
  779. return $core;
  780. }
  781. /**
  782. * @param array<int, string> $processNames
  783. */
  784. protected static function buildMergedProcessContent(string $action, string $content, array $processNames): string
  785. {
  786. $core = self::normalizeMergeContentCore($action, $content);
  787. $actionLabel = self::toActionLabel(trim($action));
  788. // 入库评分:只保留合格/不合格,不拼工序名
  789. if ($actionLabel === '入库评分' || trim($action) === 'inbound_score') {
  790. $result = $core !== '' ? $core : '合格';
  791. if (preg_match('/(合格|不合格)/u', $result, $m)) {
  792. $result = $m[1];
  793. }
  794. return $result;
  795. }
  796. $procText = implode('、', $processNames);
  797. if ($procText === '') {
  798. return $core !== '' ? $core : $content;
  799. }
  800. // 工序名放在操作说明里,不盖住操作类型
  801. if ($core !== '') {
  802. return $procText . ' ' . $core;
  803. }
  804. return $procText;
  805. }
  806. /**
  807. * @param array<string, mixed> $lg
  808. */
  809. protected static function logTimeTs(array $lg): int
  810. {
  811. $raw = trim((string)($lg['createtime_text'] ?? $lg[self::COL_TIME] ?? ''));
  812. if ($raw === '') {
  813. return 0;
  814. }
  815. $ts = strtotime(str_replace('T', ' ', $raw));
  816. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  817. }
  818. private static function cut(string $s, int $max): string
  819. {
  820. if (function_exists('mb_substr')) {
  821. return mb_substr($s, 0, $max, 'UTF-8');
  822. }
  823. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  824. }
  825. }