ProductionInformationStatistics.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\Exception;
  6. use think\Log;
  7. /**
  8. * 设备生产信息统计
  9. */
  10. class ProductionInformationStatistics extends Api
  11. {
  12. protected $noNeedLogin = ['*'];
  13. protected $noNeedRight = ['*'];
  14. /** @var string 主表 */
  15. protected $tableName = '设备_生产信息统计表';
  16. /** @var string 日志表 */
  17. protected $logTableName = '设备_生产信息统计操作日志';
  18. /** @var array 固定班组 */
  19. protected $defaultShifts = ['A班', 'B班'];
  20. /** @var string 设备基本资料表 */
  21. protected $equipmentTable = '设备_基本资料';
  22. /** @var array 可编辑业务字段 */
  23. protected $dataFields = [
  24. 'sczl_jtbh',
  25. 'sczl_bzdh',
  26. 'sczl_rq',
  27. 'theoretical_speed',
  28. 'scheduled_production',
  29. 'scheduled_maintenance',
  30. 'scheduled_handover',
  31. 'fault',
  32. 'changeover',
  33. 'proofing',
  34. 'abnormal',
  35. 'planned_output',
  36. 'actual_output',
  37. 'defective_product',
  38. ];
  39. /** @var array 字段中文名 */
  40. protected $fieldLabels = [
  41. 'sczl_jtbh' => '设备编号',
  42. 'sczl_bzdh' => '班组代号',
  43. 'sczl_rq' => '日期',
  44. 'theoretical_speed' => '理论速度',
  45. 'scheduled_production' => '计划生产时间',
  46. 'scheduled_maintenance'=> '计划保养时间',
  47. 'scheduled_handover' => '计划早会交接班时间',
  48. 'fault' => '设备故障时间',
  49. 'changeover' => '换型时间',
  50. 'proofing' => '打样时间',
  51. 'abnormal' => '异常时间',
  52. 'planned_output' => '计划完成产量',
  53. 'actual_output' => '实际产量',
  54. 'defective_product' => '不良品数量',
  55. ];
  56. /** @var array 按月汇总时求和的字段 */
  57. protected $sumFields = [
  58. 'scheduled_production',
  59. 'scheduled_maintenance',
  60. 'scheduled_handover',
  61. 'fault',
  62. 'changeover',
  63. 'proofing',
  64. 'abnormal',
  65. 'planned_output',
  66. 'actual_output',
  67. 'defective_product',
  68. ];
  69. /**
  70. * 1. 左侧菜单:年 -> 月 -> 日
  71. * @ApiMethod (GET)
  72. */
  73. public function getMenu()
  74. {
  75. if (!$this->request->isGet()) {
  76. $this->error('请求错误');
  77. }
  78. $dateList = Db::name($this->tableName)
  79. ->where('sczl_rq', 'not null')
  80. ->field("DISTINCT DATE_FORMAT(sczl_rq, '%Y-%m-%d') AS rq")
  81. ->order('rq DESC')
  82. ->select();
  83. $tree = [];
  84. foreach ($dateList as $item) {
  85. $rq = $item['rq'];
  86. if (empty($rq)) {
  87. continue;
  88. }
  89. $year = date('Y', strtotime($rq));
  90. $month = date('Y-m', strtotime($rq));
  91. if (!isset($tree[$year])) {
  92. $tree[$year] = [
  93. 'year' => $year,
  94. 'children' => [],
  95. ];
  96. }
  97. if (!isset($tree[$year]['children'][$month])) {
  98. $tree[$year]['children'][$month] = [
  99. 'month' => $month,
  100. 'children' => [],
  101. ];
  102. }
  103. if (!in_array($rq, $tree[$year]['children'][$month]['children'], true)) {
  104. $tree[$year]['children'][$month]['children'][] = $rq;
  105. }
  106. }
  107. $result = array_values($tree);
  108. foreach ($result as &$yearItem) {
  109. $yearItem['children'] = array_values($yearItem['children']);
  110. }
  111. unset($yearItem);
  112. $this->success('成功', $result);
  113. }
  114. /**
  115. * 2. 表格数据查询(联表设备基本资料)
  116. * @ApiMethod (GET)
  117. * @param string date 时间参数:Y-m-d 查日明细,Y-m 查月汇总
  118. */
  119. public function getList()
  120. {
  121. if (!$this->request->isGet()) {
  122. $this->error('请求错误');
  123. }
  124. $time = trim((string)$this->request->param('date', ''));
  125. if ($time === '') {
  126. $this->error('请传入 date 参数,格式 Y-m-d 或 Y-m');
  127. }
  128. $query = $this->parseQueryTime($time);
  129. $list = $this->buildDisplayList($query);
  130. $this->success('成功', $list);
  131. }
  132. /**
  133. * 解析查询时间:Y-m-d 为日,Y-m 为月
  134. */
  135. protected function parseQueryTime($time)
  136. {
  137. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $time)) {
  138. $timestamp = strtotime($time);
  139. if ($timestamp === false || date('Y-m-d', $timestamp) !== $time) {
  140. $this->error('日期格式错误,请传 Y-m-d,如 2026-07-23');
  141. }
  142. return [
  143. 'type' => 'day',
  144. 'start' => date('Y-m-d 00:00:00', $timestamp),
  145. 'end' => date('Y-m-d 23:59:59', $timestamp),
  146. ];
  147. }
  148. if (preg_match('/^\d{4}-\d{2}$/', $time)) {
  149. $timestamp = strtotime($time . '-01');
  150. if ($timestamp === false || date('Y-m', $timestamp) !== $time) {
  151. $this->error('月份格式错误,请传 Y-m,如 2026-07');
  152. }
  153. return [
  154. 'type' => 'month',
  155. 'month' => $time,
  156. 'start' => date('Y-m-01 00:00:00', $timestamp),
  157. 'end' => date('Y-m-t 23:59:59', $timestamp),
  158. ];
  159. }
  160. $this->error('时间格式错误,请传 Y-m-d(具体日期)或 Y-m(月份)');
  161. }
  162. /**
  163. * 供 Excel 导出使用的表格数据
  164. * @param string $time Y-m-d 或 Y-m
  165. * @return array
  166. */
  167. public function getExportData($time)
  168. {
  169. $time = trim((string)$time);
  170. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $time)) {
  171. $timestamp = strtotime($time);
  172. if ($timestamp === false) {
  173. return [];
  174. }
  175. $query = [
  176. 'type' => 'day',
  177. 'start' => date('Y-m-d 00:00:00', $timestamp),
  178. 'end' => date('Y-m-d 23:59:59', $timestamp),
  179. ];
  180. } elseif (preg_match('/^\d{4}-\d{2}$/', $time)) {
  181. $timestamp = strtotime($time . '-01');
  182. if ($timestamp === false) {
  183. return [];
  184. }
  185. $query = [
  186. 'type' => 'month',
  187. 'month' => $time,
  188. 'start' => date('Y-m-01 00:00:00', $timestamp),
  189. 'end' => date('Y-m-t 23:59:59', $timestamp),
  190. ];
  191. } else {
  192. return [];
  193. }
  194. return $this->buildDisplayList($query);
  195. }
  196. /**
  197. * 3. 获取车间、机组、机台编号、机台名称、班组基础数据
  198. * @ApiMethod (GET)
  199. */
  200. public function getBaseData()
  201. {
  202. if (!$this->request->isGet()) {
  203. $this->error('请求错误');
  204. }
  205. $equipmentMap = $this->fetchEquipmentMap(true);
  206. if (empty($equipmentMap)) {
  207. $this->success('未获取到机台数据', []);
  208. }
  209. $list = [];
  210. foreach ($equipmentMap as $code => $equipment) {
  211. $list[] = [
  212. '车间' => $equipment['车间'],
  213. '机组' => $equipment['机组'],
  214. '编组' => $equipment['编组'],
  215. '机台编号' => $code,
  216. '机台名称' => $equipment['机台名称'],
  217. '设备编号' => $code,
  218. '理论速度' => $equipment['理论速度'],
  219. '班组列表' => $this->defaultShifts,
  220. ];
  221. }
  222. $this->success('成功', $this->sortEquipmentList($list));
  223. }
  224. /**
  225. * 4. 批量新增(每个机台每个班组一条)
  226. * @ApiMethod (POST)
  227. * @param array list 数据列表
  228. * @param string sys_id 操作人
  229. */
  230. public function batchAdd()
  231. {
  232. if (!$this->request->isPost()) {
  233. $this->error('请求错误');
  234. }
  235. $params = $this->request->post();
  236. $list = isset($params['list']) ? $params['list'] : [];
  237. $operator = isset($params['sys_id']) ? trim($params['sys_id']) : '';
  238. if (empty($list) || !is_array($list)) {
  239. $this->error('参数 list 不能为空');
  240. }
  241. if ($operator === '') {
  242. $this->error('参数 sys_id 不能为空');
  243. }
  244. $now = date('Y-m-d H:i:s');
  245. $insertRows = [];
  246. $logs = [];
  247. Db::startTrans();
  248. try {
  249. foreach ($list as $index => $row) {
  250. if (!is_array($row)) {
  251. throw new Exception('第 ' . ($index + 1) . ' 条数据格式错误');
  252. }
  253. $data = $this->normalizeRow($row);
  254. $this->validateRow($data, $index + 1);
  255. $exists = Db::name($this->tableName)
  256. ->where('sczl_jtbh', $data['sczl_jtbh'])
  257. ->where('sczl_bzdh', $data['sczl_bzdh'])
  258. ->where('sczl_rq', $data['sczl_rq'])
  259. ->find();
  260. if ($exists) {
  261. throw new Exception(sprintf(
  262. '第 %d 条记录已存在:设备[%s] 班组[%s] 日期[%s]',
  263. $index + 1,
  264. $data['sczl_jtbh'],
  265. $data['sczl_bzdh'],
  266. date('Y-m-d', strtotime($data['sczl_rq']))
  267. ));
  268. }
  269. $data['sys_id'] = $operator;
  270. $data['sys_rq'] = $now;
  271. $insertRows[] = $data;
  272. }
  273. foreach ($insertRows as $data) {
  274. $recordId = Db::name($this->tableName)->insertGetId($data);
  275. if (!$recordId) {
  276. throw new Exception('新增失败');
  277. }
  278. $logs = array_merge($logs, $this->buildAddLogs($recordId, $data, $operator, $now));
  279. }
  280. if (!empty($logs)) {
  281. Db::name($this->logTableName)->insertAll($logs);
  282. }
  283. Db::commit();
  284. $this->success('批量新增成功', ['count' => count($insertRows)]);
  285. } catch (Exception $e) {
  286. Db::rollback();
  287. $this->error($e->getMessage());
  288. }
  289. }
  290. /**
  291. * 5. 批量修改
  292. * @ApiMethod (POST)
  293. * @param array list 含 id 的数据列表
  294. * @param string sys_id 操作人
  295. */
  296. public function batchUpdate()
  297. {
  298. if (!$this->request->isPost()) {
  299. $this->error('请求错误');
  300. }
  301. $params = $this->request->post();
  302. $list = isset($params['list']) ? $params['list'] : [];
  303. $operator = isset($params['sys_id']) ? trim($params['sys_id']) : '';
  304. if (empty($list) || !is_array($list)) {
  305. $this->error('参数 list 不能为空');
  306. }
  307. if ($operator === '') {
  308. $this->error('参数 sys_id 不能为空');
  309. }
  310. $now = date('Y-m-d H:i:s');
  311. $logs = [];
  312. $updateCount = 0;
  313. Db::startTrans();
  314. try {
  315. foreach ($list as $index => $row) {
  316. if (!is_array($row) || empty($row['id'])) {
  317. throw new Exception('第 ' . ($index + 1) . ' 条数据缺少 id');
  318. }
  319. $id = (int)$row['id'];
  320. $old = Db::name($this->tableName)->where('id', $id)->find();
  321. if (empty($old)) {
  322. throw new Exception('第 ' . ($index + 1) . ' 条记录不存在');
  323. }
  324. $data = $this->normalizeRow($row, false);
  325. unset($data['id']);
  326. if (array_key_exists('sczl_bzdh', $row)) {
  327. if ($data['sczl_bzdh'] === '' || !in_array($data['sczl_bzdh'], $this->defaultShifts, true)) {
  328. throw new Exception('第 ' . ($index + 1) . ' 条班组代号只能为 A班 或 B班');
  329. }
  330. }
  331. $checkJtbh = isset($data['sczl_jtbh']) ? $data['sczl_jtbh'] : rtrim($old['sczl_jtbh']);
  332. $checkBzdh = isset($data['sczl_bzdh']) ? $data['sczl_bzdh'] : rtrim($old['sczl_bzdh']);
  333. $checkRq = isset($data['sczl_rq']) ? $data['sczl_rq'] : $old['sczl_rq'];
  334. $duplicate = Db::name($this->tableName)
  335. ->where('sczl_jtbh', $checkJtbh)
  336. ->where('sczl_bzdh', $checkBzdh)
  337. ->where('sczl_rq', $checkRq)
  338. ->where('id', '<>', $id)
  339. ->find();
  340. if ($duplicate) {
  341. throw new Exception(sprintf(
  342. '第 %d 条修改后与已有记录冲突:设备[%s] 班组[%s] 日期[%s]',
  343. $index + 1,
  344. $checkJtbh,
  345. $checkBzdh,
  346. date('Y-m-d', strtotime($checkRq))
  347. ));
  348. }
  349. $data['mod_id'] = $operator;
  350. $data['mod_rq'] = $now;
  351. $changed = [];
  352. foreach ($data as $field => $value) {
  353. if (!array_key_exists($field, $old)) {
  354. continue;
  355. }
  356. $oldValue = $old[$field];
  357. if ((string)$oldValue !== (string)$value) {
  358. $changed[$field] = $value;
  359. }
  360. }
  361. if (empty($changed)) {
  362. continue;
  363. }
  364. $result = Db::name($this->tableName)->where('id', $id)->update($changed + [
  365. 'mod_id' => $operator,
  366. 'mod_rq' => $now,
  367. ]);
  368. if ($result === false) {
  369. throw new Exception('第 ' . ($index + 1) . ' 条修改失败');
  370. }
  371. $logs = array_merge($logs, $this->buildUpdateLogs($id, $old, $changed, $operator, $now));
  372. $updateCount++;
  373. }
  374. if (!empty($logs)) {
  375. Db::name($this->logTableName)->insertAll($logs);
  376. }
  377. Db::commit();
  378. $this->success('批量修改成功', ['count' => $updateCount]);
  379. } catch (Exception $e) {
  380. Db::rollback();
  381. $this->error($e->getMessage());
  382. }
  383. }
  384. /**
  385. * 6. 批量删除
  386. * @ApiMethod (POST)
  387. * @param string ids 逗号分隔 id
  388. * @param string sys_id 操作人
  389. */
  390. public function batchDelete()
  391. {
  392. if (!$this->request->isPost()) {
  393. $this->error('请求错误');
  394. }
  395. $params = $this->request->post();
  396. $idsParam = isset($params['ids']) ? trim($params['ids']) : '';
  397. $operator = isset($params['sys_id']) ? trim($params['sys_id']) : '';
  398. if ($idsParam === '') {
  399. $this->error('参数 ids 不能为空');
  400. }
  401. if ($operator === '') {
  402. $this->error('参数 sys_id 不能为空');
  403. }
  404. $ids = array_values(array_filter(array_map('intval', explode(',', $idsParam))));
  405. if (empty($ids)) {
  406. $this->error('ids 格式错误');
  407. }
  408. $records = Db::name($this->tableName)->where('id', 'in', $ids)->select();
  409. if (count($records) !== count($ids)) {
  410. $this->error('部分记录不存在,请刷新后重试');
  411. }
  412. $now = date('Y-m-d H:i:s');
  413. $logs = [];
  414. Db::startTrans();
  415. try {
  416. foreach ($records as $record) {
  417. $logs = array_merge($logs, $this->buildDeleteLogs((int)$record['id'], $record, $operator, $now));
  418. }
  419. $deleteResult = Db::name($this->tableName)->where('id', 'in', $ids)->delete();
  420. if ($deleteResult === false) {
  421. throw new Exception('删除失败');
  422. }
  423. if (!empty($logs)) {
  424. Db::name($this->logTableName)->insertAll($logs);
  425. }
  426. Db::commit();
  427. $this->success('批量删除成功', ['count' => $deleteResult]);
  428. } catch (Exception $e) {
  429. Db::rollback();
  430. $this->error($e->getMessage());
  431. }
  432. }
  433. /**
  434. * 构建带计算字段和汇总行的表格数据
  435. */
  436. protected function buildDisplayList(array $query)
  437. {
  438. if ($query['type'] === 'day') {
  439. $statsRows = $this->fetchStatsRows($query['start'], $query['end']);
  440. $dateMeta = [
  441. 'query_type' => 'day',
  442. 'sczl_rq' => date('Y-m-d 00:00:00', strtotime($query['start'])),
  443. 'query_month' => '',
  444. ];
  445. } else {
  446. $statsRows = $this->fetchMonthlyStatsRows($query['start'], $query['end']);
  447. $dateMeta = [
  448. 'query_type' => 'month',
  449. 'sczl_rq' => $query['month'] . '-01 00:00:00',
  450. 'query_month' => $query['month'],
  451. ];
  452. }
  453. $equipmentMap = $this->fetchEquipmentMap(true);
  454. $statsRows = $this->enrichStatsWithEquipment($statsRows, $equipmentMap);
  455. $statsMap = [];
  456. foreach ($statsRows as $row) {
  457. $key = $this->trimText($row['sczl_jtbh']) . '|' . $this->normalizeShift($row['sczl_bzdh']);
  458. $statsMap[$key] = $row;
  459. }
  460. $detailRows = [];
  461. $processedKeys = [];
  462. foreach ($equipmentMap as $code => $equipment) {
  463. foreach ($this->defaultShifts as $shift) {
  464. $key = $code . '|' . $shift;
  465. $processedKeys[$key] = true;
  466. $stat = isset($statsMap[$key]) ? $statsMap[$key] : [];
  467. $detailRows[] = $this->buildDetailRow($equipment, $shift, $stat, $dateMeta);
  468. }
  469. }
  470. // 补充统计表中有数据但未纳入骨架的行(按设备基本资料补全车间编组)
  471. foreach ($statsMap as $key => $stat) {
  472. if (isset($processedKeys[$key])) {
  473. continue;
  474. }
  475. $code = $this->trimText($stat['sczl_jtbh']);
  476. $shift = $this->normalizeShift($stat['sczl_bzdh']);
  477. if ($code === '' || $shift === '' || !isset($equipmentMap[$code])) {
  478. continue;
  479. }
  480. $detailRows[] = $this->buildDetailRow($equipmentMap[$code], $shift, $stat, $dateMeta);
  481. }
  482. return $this->assembleListWithSummaries($detailRows);
  483. }
  484. /**
  485. * 获取设备基本资料映射(key=机台编号)
  486. */
  487. protected function fetchEquipmentMap($displayOnly = true)
  488. {
  489. $query = Db::name($this->equipmentTable)
  490. ->where('使用部门', '<>', '研发中心');
  491. if ($displayOnly) {
  492. $query->where('设备编组', '<>', '')->where('sys_sbID', '<>', '');
  493. }
  494. $equipments = $query
  495. ->field([
  496. 'rtrim(使用部门) as 车间',
  497. 'rtrim(设备编组) as 机组',
  498. 'rtrim(设备编号) as 机台编号',
  499. 'rtrim(设备名称) as 机台名称',
  500. '平均车速',
  501. ])
  502. ->order('设备编组,设备编号')
  503. ->select();
  504. $map = [];
  505. foreach ($equipments as $item) {
  506. $code = $this->trimText($item['机台编号']);
  507. if ($code === '') {
  508. continue;
  509. }
  510. $map[$code] = $this->formatEquipmentItem($item, $code);
  511. }
  512. return $map;
  513. }
  514. /**
  515. * 格式化设备基本资料项
  516. */
  517. protected function formatEquipmentItem(array $item, $code = null)
  518. {
  519. $code = $code ?: $this->trimText($item['机台编号']);
  520. $group = $this->trimText($item['机组']);
  521. return [
  522. '车间' => $this->trimText($item['车间']),
  523. '机组' => $group,
  524. '编组' => $group,
  525. '机台编号' => $code,
  526. '机台名称' => $this->trimText($item['机台名称']),
  527. '理论速度' => (int)$this->formatNumber($item['平均车速']),
  528. ];
  529. }
  530. /**
  531. * 按机台编号用设备基本资料补全统计数据
  532. */
  533. protected function enrichStatsWithEquipment(array $statsRows, array $equipmentMap)
  534. {
  535. foreach ($statsRows as &$row) {
  536. $code = $this->trimText($row['sczl_jtbh']);
  537. if ($code === '' || !isset($equipmentMap[$code])) {
  538. continue;
  539. }
  540. $equipment = $equipmentMap[$code];
  541. $row['车间'] = $equipment['车间'];
  542. $row['机组'] = $equipment['机组'];
  543. $row['编组'] = $equipment['编组'];
  544. $row['机台名称'] = $equipment['机台名称'];
  545. }
  546. unset($row);
  547. return $statsRows;
  548. }
  549. /**
  550. * 查询原始统计数据(按日)
  551. */
  552. protected function fetchStatsRows($start, $end)
  553. {
  554. return Db::name($this->tableName)
  555. ->alias('a')
  556. ->where('a.sczl_rq', '>=', $start)
  557. ->where('a.sczl_rq', '<=', $end)
  558. ->field([
  559. 'a.id',
  560. 'a.sczl_jtbh',
  561. 'a.sczl_bzdh',
  562. 'a.sczl_rq',
  563. 'a.theoretical_speed',
  564. 'a.scheduled_production',
  565. 'a.scheduled_maintenance',
  566. 'a.scheduled_handover',
  567. 'a.fault',
  568. 'a.changeover',
  569. 'a.proofing',
  570. 'a.abnormal',
  571. 'a.planned_output',
  572. 'a.actual_output',
  573. 'a.defective_product',
  574. 'a.sys_id',
  575. 'a.sys_rq',
  576. 'a.mod_id',
  577. 'a.mod_rq',
  578. ])
  579. ->select();
  580. }
  581. /**
  582. * 查询原始统计数据(按月汇总)
  583. */
  584. protected function fetchMonthlyStatsRows($start, $end)
  585. {
  586. $sumExpr = [];
  587. foreach ($this->sumFields as $field) {
  588. $sumExpr[] = "SUM(a.{$field}) as {$field}";
  589. }
  590. return Db::name($this->tableName)
  591. ->alias('a')
  592. ->where('a.sczl_rq', '>=', $start)
  593. ->where('a.sczl_rq', '<=', $end)
  594. ->field(array_merge([
  595. 'MIN(a.id) as id',
  596. 'a.sczl_jtbh',
  597. 'a.sczl_bzdh',
  598. 'MAX(a.theoretical_speed) as theoretical_speed',
  599. ], $sumExpr))
  600. ->group('a.sczl_jtbh,a.sczl_bzdh')
  601. ->select();
  602. }
  603. /**
  604. * 构建明细行
  605. */
  606. protected function buildDetailRow(array $equipment, $shift, array $stat, array $dateMeta)
  607. {
  608. $row = [
  609. 'row_type' => 'detail',
  610. 'id' => isset($stat['id']) ? (int)$stat['id'] : 0,
  611. '车间' => $equipment['车间'],
  612. '机组' => $equipment['机组'],
  613. '编组' => $equipment['编组'],
  614. '机台编号' => $equipment['机台编号'],
  615. '设备编号' => $equipment['机台编号'],
  616. '机台名称' => $equipment['机台名称'],
  617. '班组' => $shift,
  618. 'sczl_jtbh' => $equipment['机台编号'],
  619. 'sczl_bzdh' => $shift,
  620. 'sczl_rq' => $dateMeta['sczl_rq'],
  621. 'query_type' => $dateMeta['query_type'],
  622. 'query_month' => $dateMeta['query_month'],
  623. 'theoretical_speed' => !empty($stat['id'])
  624. ? (int)$this->formatNumber($stat['theoretical_speed'])
  625. : $equipment['理论速度'],
  626. 'scheduled_production' => $this->formatNumber(isset($stat['scheduled_production']) ? $stat['scheduled_production'] : 0),
  627. 'scheduled_maintenance'=> $this->formatNumber(isset($stat['scheduled_maintenance']) ? $stat['scheduled_maintenance'] : 0),
  628. 'scheduled_handover' => $this->formatNumber(isset($stat['scheduled_handover']) ? $stat['scheduled_handover'] : 0),
  629. 'fault' => $this->formatNumber(isset($stat['fault']) ? $stat['fault'] : 0),
  630. 'changeover' => $this->formatNumber(isset($stat['changeover']) ? $stat['changeover'] : 0),
  631. 'proofing' => $this->formatNumber(isset($stat['proofing']) ? $stat['proofing'] : 0),
  632. 'abnormal' => $this->formatNumber(isset($stat['abnormal']) ? $stat['abnormal'] : 0),
  633. 'planned_output' => $this->formatNumber(isset($stat['planned_output']) ? $stat['planned_output'] : 0),
  634. 'actual_output' => $this->formatNumber(isset($stat['actual_output']) ? $stat['actual_output'] : 0),
  635. 'defective_product' => $this->formatNumber(isset($stat['defective_product']) ? $stat['defective_product'] : 0),
  636. 'sys_id' => isset($stat['sys_id']) ? $this->trimText($stat['sys_id']) : '',
  637. 'sys_rq' => isset($stat['sys_rq']) ? $stat['sys_rq'] : '',
  638. 'mod_id' => isset($stat['mod_id']) ? $this->trimText($stat['mod_id']) : '',
  639. 'mod_rq' => isset($stat['mod_rq']) ? $stat['mod_rq'] : '',
  640. ];
  641. return $this->appendCalculatedFields($row);
  642. }
  643. /**
  644. * 组装明细 + 汇总行
  645. */
  646. protected function assembleListWithSummaries(array $detailRows)
  647. {
  648. $result = [];
  649. $workshopGroups = [];
  650. foreach ($detailRows as $row) {
  651. $workshop = $row['车间'];
  652. $group = $row['机组'];
  653. if (!isset($workshopGroups[$workshop])) {
  654. $workshopGroups[$workshop] = [];
  655. }
  656. if (!isset($workshopGroups[$workshop][$group])) {
  657. $workshopGroups[$workshop][$group] = [];
  658. }
  659. $workshopGroups[$workshop][$group][] = $row;
  660. }
  661. uksort($workshopGroups, function ($a, $b) {
  662. return strcmp($a, $b);
  663. });
  664. foreach ($workshopGroups as $workshop => $groups) {
  665. uksort($groups, function ($a, $b) {
  666. $orderA = $this->extractGroupOrder($a);
  667. $orderB = $this->extractGroupOrder($b);
  668. if ($orderA !== $orderB) {
  669. return $orderA <=> $orderB;
  670. }
  671. return strcmp($a, $b);
  672. });
  673. $workshopRows = [];
  674. $workshopBlock = [];
  675. foreach ($groups as $group => $groupRows) {
  676. $groupRows = $this->sortEquipmentList($groupRows);
  677. $workshopRows = array_merge($workshopRows, $groupRows);
  678. $workshopBlock[] = $this->buildSummaryRow(
  679. 'group',
  680. $workshop,
  681. $group,
  682. $this->buildGroupShortName($group) . '汇总',
  683. '/',
  684. $groupRows
  685. );
  686. foreach ($this->defaultShifts as $shift) {
  687. $shiftRows = array_values(array_filter($groupRows, function ($item) use ($shift) {
  688. return $item['班组'] === $shift;
  689. }));
  690. if (!empty($shiftRows)) {
  691. $workshopBlock[] = $this->buildSummaryRow(
  692. 'group_shift',
  693. $workshop,
  694. $group,
  695. $this->buildGroupShortName($group) . $shift,
  696. $shift,
  697. $shiftRows
  698. );
  699. }
  700. }
  701. $workshopBlock = array_merge($workshopBlock, $groupRows);
  702. }
  703. if (!empty($workshopRows)) {
  704. array_unshift(
  705. $workshopBlock,
  706. $this->buildSummaryRow(
  707. 'workshop',
  708. $workshop,
  709. '全部机组',
  710. $workshop . '全部工序合计',
  711. '/',
  712. $workshopRows
  713. )
  714. );
  715. }
  716. $result = array_merge($result, $workshopBlock);
  717. }
  718. return $result;
  719. }
  720. /**
  721. * 提取机组简称(03、卷凹机组 -> 卷凹)
  722. */
  723. protected function buildGroupShortName($group)
  724. {
  725. $group = $this->trimText($group);
  726. if (preg_match('/、(.+?)机组/u', $group, $matches)) {
  727. return $matches[1];
  728. }
  729. if (preg_match('/、(.+)/u', $group, $matches)) {
  730. return $matches[1];
  731. }
  732. return $group;
  733. }
  734. /**
  735. * 构建汇总行
  736. */
  737. protected function buildSummaryRow($rowType, $workshop, $group, $machineName, $shift, array $sourceRows)
  738. {
  739. $aggregated = $this->aggregateBaseFields($sourceRows);
  740. $row = [
  741. 'row_type' => $rowType,
  742. 'id' => 0,
  743. '车间' => $workshop,
  744. '机组' => $group,
  745. '编组' => $group,
  746. '机台编号' => '',
  747. '设备编号' => '',
  748. '机台名称' => $machineName,
  749. '班组' => $shift,
  750. 'sczl_jtbh' => '',
  751. 'sczl_bzdh' => $shift === '/' ? '' : $shift,
  752. 'sczl_rq' => $sourceRows[0]['sczl_rq'],
  753. 'query_type' => $sourceRows[0]['query_type'],
  754. 'query_month' => $sourceRows[0]['query_month'],
  755. 'theoretical_speed' => 0,
  756. 'scheduled_production' => $aggregated['scheduled_production'],
  757. 'scheduled_maintenance'=> $aggregated['scheduled_maintenance'],
  758. 'scheduled_handover' => $aggregated['scheduled_handover'],
  759. 'fault' => $aggregated['fault'],
  760. 'changeover' => $aggregated['changeover'],
  761. 'proofing' => $aggregated['proofing'],
  762. 'abnormal' => $aggregated['abnormal'],
  763. 'planned_output' => $aggregated['planned_output'],
  764. 'actual_output' => $aggregated['actual_output'],
  765. 'defective_product' => $aggregated['defective_product'],
  766. 'sys_id' => '',
  767. 'sys_rq' => '',
  768. 'mod_id' => '',
  769. 'mod_rq' => '',
  770. ];
  771. return $this->appendCalculatedFields($row, $aggregated['standard_output']);
  772. }
  773. /**
  774. * 汇总基础字段
  775. */
  776. protected function aggregateBaseFields(array $rows)
  777. {
  778. $totals = [
  779. 'scheduled_production' => 0,
  780. 'scheduled_maintenance'=> 0,
  781. 'scheduled_handover' => 0,
  782. 'fault' => 0,
  783. 'changeover' => 0,
  784. 'proofing' => 0,
  785. 'abnormal' => 0,
  786. 'planned_output' => 0,
  787. 'actual_output' => 0,
  788. 'defective_product' => 0,
  789. 'standard_output' => 0,
  790. ];
  791. foreach ($rows as $row) {
  792. foreach ($this->sumFields as $field) {
  793. $totals[$field] += $this->formatNumber($row[$field]);
  794. }
  795. $totals['standard_output'] += $this->formatNumber($row['标准产量']);
  796. }
  797. return $totals;
  798. }
  799. /**
  800. * 计算并追加衍生指标
  801. */
  802. protected function appendCalculatedFields(array $row, $standardOutputOverride = null)
  803. {
  804. $scheduledProduction = $this->formatNumber($row['scheduled_production']);
  805. $scheduledMaintenance = $this->formatNumber($row['scheduled_maintenance']);
  806. $scheduledHandover = $this->formatNumber($row['scheduled_handover']);
  807. $fault = $this->formatNumber($row['fault']);
  808. $changeover = $this->formatNumber($row['changeover']);
  809. $proofing = $this->formatNumber($row['proofing']);
  810. $abnormal = $this->formatNumber($row['abnormal']);
  811. $plannedOutput = $this->formatNumber($row['planned_output']);
  812. $actualOutput = $this->formatNumber($row['actual_output']);
  813. $defectiveProduct = $this->formatNumber($row['defective_product']);
  814. $theoreticalSpeed = $this->formatNumber($row['theoretical_speed']);
  815. $loadTime = $scheduledProduction - ($scheduledMaintenance + $scheduledHandover);
  816. if ($loadTime < 0) {
  817. $loadTime = 0;
  818. }
  819. $actualRunTime = $loadTime - ($fault + $changeover + $proofing + $abnormal);
  820. if ($actualRunTime < 0) {
  821. $actualRunTime = 0;
  822. }
  823. $standardOutput = $standardOutputOverride !== null
  824. ? $this->formatNumber($standardOutputOverride)
  825. : ($theoreticalSpeed * $actualRunTime);
  826. $planAchievementRate = $plannedOutput > 0
  827. ? (($actualOutput - $defectiveProduct) / $plannedOutput)
  828. : 0;
  829. $timeUtilization = $loadTime > 0 ? ($actualRunTime / $loadTime) : 0;
  830. $speedUtilization = $standardOutput > 0 ? ($actualOutput / $standardOutput) : 0;
  831. $qualityRate = $actualOutput > 0
  832. ? (($actualOutput - $defectiveProduct) / $actualOutput)
  833. : 0;
  834. $oee = $timeUtilization * $speedUtilization * $qualityRate;
  835. $row['负荷时间'] = round($loadTime, 2);
  836. $row['实际运行时间'] = round($actualRunTime, 2);
  837. $row['生产计划达成率'] = $this->formatRate($planAchievementRate);
  838. $row['标准产量'] = round($standardOutput, 2);
  839. $row['时间利用率'] = $this->formatRate($timeUtilization);
  840. $row['速度利用率'] = $this->formatRate($speedUtilization);
  841. $row['质量合格率'] = $this->formatRate($qualityRate);
  842. $row['设备综合效率'] = $this->formatRate($oee);
  843. $row['load_time'] = $row['负荷时间'];
  844. $row['actual_run_time'] = $row['实际运行时间'];
  845. $row['plan_achievement_rate'] = $row['生产计划达成率'];
  846. $row['standard_output'] = $row['标准产量'];
  847. $row['time_utilization'] = $row['时间利用率'];
  848. $row['speed_utilization'] = $row['速度利用率'];
  849. $row['quality_rate'] = $row['质量合格率'];
  850. $row['oee'] = $row['设备综合效率'];
  851. $row['理论速度'] = (int)$theoreticalSpeed;
  852. $row['计划生产时间'] = round($scheduledProduction, 2);
  853. $row['计划保养时间'] = round($scheduledMaintenance, 2);
  854. $row['计划早会交接班时间'] = round($scheduledHandover, 2);
  855. $row['设备故障时间'] = round($fault, 2);
  856. $row['换型时间'] = round($changeover, 2);
  857. $row['打样时间'] = round($proofing, 2);
  858. $row['异常时间'] = round($abnormal, 2);
  859. $row['计划完成产量'] = round($plannedOutput, 2);
  860. $row['实际产量'] = round($actualOutput, 2);
  861. $row['不良品数量'] = round($defectiveProduct, 2);
  862. return $row;
  863. }
  864. /**
  865. * 格式化为百分比(0-100,保留2位)
  866. */
  867. protected function formatRate($value)
  868. {
  869. return round((float)$value * 100, 2);
  870. }
  871. /**
  872. * 查询字段
  873. */
  874. protected function buildSelectFields($isMonth = false)
  875. {
  876. $fields = [
  877. 'a.id',
  878. 'a.sczl_jtbh',
  879. 'a.sczl_bzdh',
  880. 'a.sczl_rq',
  881. 'a.theoretical_speed',
  882. 'a.scheduled_production',
  883. 'a.scheduled_maintenance',
  884. 'a.scheduled_handover',
  885. 'a.fault',
  886. 'a.changeover',
  887. 'a.proofing',
  888. 'a.abnormal',
  889. 'a.planned_output',
  890. 'a.actual_output',
  891. 'a.defective_product',
  892. 'a.sys_id',
  893. 'a.sys_rq',
  894. 'a.mod_id',
  895. 'a.mod_rq',
  896. 'rtrim(b.使用部门) as 车间',
  897. 'rtrim(b.设备编组) as 机组',
  898. 'rtrim(b.设备名称) as 机台名称',
  899. ];
  900. return $fields;
  901. }
  902. /**
  903. * 格式化返回列表
  904. */
  905. protected function formatList($list)
  906. {
  907. $result = [];
  908. foreach ($list as $row) {
  909. $result[] = [
  910. 'id' => (int)$row['id'],
  911. '车间' => isset($row['车间']) ? rtrim($row['车间']) : '',
  912. '机组' => isset($row['机组']) ? rtrim($row['机组']) : '',
  913. '机台编号' => rtrim($row['sczl_jtbh']),
  914. '设备编号' => rtrim($row['sczl_jtbh']),
  915. '机台名称' => isset($row['机台名称']) ? rtrim($row['机台名称']) : '',
  916. '班组' => $this->normalizeShift($row['sczl_bzdh']),
  917. 'sczl_jtbh' => rtrim($row['sczl_jtbh']),
  918. 'sczl_bzdh' => $this->normalizeShift($row['sczl_bzdh']),
  919. 'sczl_rq' => $row['sczl_rq'],
  920. 'theoretical_speed' => $this->formatNumber($row['theoretical_speed']),
  921. 'scheduled_production' => $this->formatNumber($row['scheduled_production']),
  922. 'scheduled_maintenance'=> $this->formatNumber($row['scheduled_maintenance']),
  923. 'scheduled_handover' => $this->formatNumber($row['scheduled_handover']),
  924. 'fault' => $this->formatNumber($row['fault']),
  925. 'changeover' => $this->formatNumber($row['changeover']),
  926. 'proofing' => $this->formatNumber($row['proofing']),
  927. 'abnormal' => $this->formatNumber($row['abnormal']),
  928. 'planned_output' => $this->formatNumber($row['planned_output']),
  929. 'actual_output' => $this->formatNumber($row['actual_output']),
  930. 'defective_product' => $this->formatNumber($row['defective_product']),
  931. 'sys_id' => isset($row['sys_id']) ? rtrim($row['sys_id']) : '',
  932. 'sys_rq' => isset($row['sys_rq']) ? $row['sys_rq'] : '',
  933. 'mod_id' => isset($row['mod_id']) ? rtrim($row['mod_id']) : '',
  934. 'mod_rq' => isset($row['mod_rq']) ? $row['mod_rq'] : '',
  935. 'query_type' => isset($row['query_type']) ? $row['query_type'] : 'day',
  936. 'query_month' => isset($row['query_month']) ? $row['query_month'] : '',
  937. ];
  938. }
  939. return $this->sortEquipmentList($result);
  940. }
  941. /**
  942. * 按设备编组、机台编号数字排序
  943. */
  944. protected function sortEquipmentList(array $list)
  945. {
  946. usort($list, function ($a, $b) {
  947. return $this->compareEquipmentRow($a, $b);
  948. });
  949. return $list;
  950. }
  951. /**
  952. * 设备行排序比较
  953. */
  954. protected function compareEquipmentRow($a, $b)
  955. {
  956. $groupA = $this->trimText(isset($a['机组']) ? $a['机组'] : '');
  957. $groupB = $this->trimText(isset($b['机组']) ? $b['机组'] : '');
  958. $groupOrderA = $this->extractGroupOrder($groupA);
  959. $groupOrderB = $this->extractGroupOrder($groupB);
  960. if ($groupOrderA !== $groupOrderB) {
  961. return $groupOrderA <=> $groupOrderB;
  962. }
  963. if ($groupA !== $groupB) {
  964. return strcmp($groupA, $groupB);
  965. }
  966. $codeA = $this->getMachineCodeFromRow($a);
  967. $codeB = $this->getMachineCodeFromRow($b);
  968. $numA = $this->extractMachineNumber($codeA);
  969. $numB = $this->extractMachineNumber($codeB);
  970. if ($numA !== $numB) {
  971. return $numA <=> $numB;
  972. }
  973. if ($codeA !== $codeB) {
  974. return strcmp($codeA, $codeB);
  975. }
  976. $shiftA = isset($a['班组']) ? $a['班组'] : (isset($a['sczl_bzdh']) ? $a['sczl_bzdh'] : '');
  977. $shiftB = isset($b['班组']) ? $b['班组'] : (isset($b['sczl_bzdh']) ? $b['sczl_bzdh'] : '');
  978. return strcmp($shiftA, $shiftB);
  979. }
  980. /**
  981. * 提取设备编组前缀序号(如 03、卷凹机组 -> 3)
  982. */
  983. protected function extractGroupOrder($group)
  984. {
  985. $group = $this->trimText($group);
  986. if (preg_match('/^(\d+)/', $group, $matches)) {
  987. return (int)$matches[1];
  988. }
  989. return PHP_INT_MAX;
  990. }
  991. /**
  992. * 提取机台编号中的数字(如 YWY01# -> 1)
  993. */
  994. protected function extractMachineNumber($code)
  995. {
  996. $code = $this->trimText($code);
  997. if (preg_match('/(\d+)/', $code, $matches)) {
  998. return (int)$matches[1];
  999. }
  1000. return PHP_INT_MAX;
  1001. }
  1002. /**
  1003. * 从返回行中获取机台编号
  1004. */
  1005. protected function getMachineCodeFromRow($row)
  1006. {
  1007. if (!empty($row['机台编号'])) {
  1008. return $this->trimText($row['机台编号']);
  1009. }
  1010. if (!empty($row['sczl_jtbh'])) {
  1011. return $this->trimText($row['sczl_jtbh']);
  1012. }
  1013. if (!empty($row['设备编号'])) {
  1014. return $this->trimText($row['设备编号']);
  1015. }
  1016. return '';
  1017. }
  1018. /**
  1019. * 去除字符串首尾空白(含全角空格)
  1020. */
  1021. protected function trimText($value)
  1022. {
  1023. return preg_replace('/^[\s\x{3000}]+|[\s\x{3000}]+$/u', '', (string)$value);
  1024. }
  1025. /**
  1026. * 班组名称规范化:仅支持 A班、B班
  1027. */
  1028. protected function normalizeShift($shift)
  1029. {
  1030. $shift = $this->trimText($shift);
  1031. $shift = preg_replace('/\s+/u', '', $shift);
  1032. if ($shift === '') {
  1033. return '';
  1034. }
  1035. if (preg_match('/^A(?:班)?$/iu', $shift)) {
  1036. return 'A班';
  1037. }
  1038. if (preg_match('/^B(?:班)?$/iu', $shift)) {
  1039. return 'B班';
  1040. }
  1041. return '';
  1042. }
  1043. /**
  1044. * 标准化单行数据
  1045. */
  1046. protected function normalizeRow(array $row, $requireAll = true)
  1047. {
  1048. $data = [];
  1049. foreach ($this->dataFields as $field) {
  1050. if (!array_key_exists($field, $row)) {
  1051. if (!$requireAll) {
  1052. continue;
  1053. }
  1054. $data[$field] = in_array($field, $this->sumFields, true) || $field === 'theoretical_speed' ? 0 : '';
  1055. continue;
  1056. }
  1057. if ($field === 'sczl_rq') {
  1058. $data[$field] = date('Y-m-d 00:00:00', strtotime($row[$field]));
  1059. continue;
  1060. }
  1061. if (in_array($field, ['sczl_jtbh', 'sczl_bzdh'], true)) {
  1062. $value = trim((string)$row[$field]);
  1063. $data[$field] = $field === 'sczl_bzdh' ? $this->normalizeShift($value) : $value;
  1064. continue;
  1065. }
  1066. if ($field === 'theoretical_speed') {
  1067. $data[$field] = (int)$row[$field];
  1068. continue;
  1069. }
  1070. $data[$field] = $row[$field] === '' || $row[$field] === null ? 0 : $row[$field];
  1071. }
  1072. return $data;
  1073. }
  1074. /**
  1075. * 校验单行数据
  1076. */
  1077. protected function validateRow(array $data, $lineNo)
  1078. {
  1079. if ($data['sczl_jtbh'] === '') {
  1080. throw new Exception('第 ' . $lineNo . ' 条设备编号不能为空');
  1081. }
  1082. if ($data['sczl_bzdh'] === '') {
  1083. throw new Exception('第 ' . $lineNo . ' 条班组代号不能为空,且只能为 A班 或 B班');
  1084. }
  1085. if (!in_array($data['sczl_bzdh'], $this->defaultShifts, true)) {
  1086. throw new Exception('第 ' . $lineNo . ' 条班组代号只能为 A班 或 B班');
  1087. }
  1088. if (empty($data['sczl_rq'])) {
  1089. throw new Exception('第 ' . $lineNo . ' 条日期不能为空');
  1090. }
  1091. $equipment = Db::name($this->equipmentTable)
  1092. ->where('设备编号', $data['sczl_jtbh'])
  1093. ->find();
  1094. if (empty($equipment)) {
  1095. throw new Exception('第 ' . $lineNo . ' 条设备编号不存在:' . $data['sczl_jtbh']);
  1096. }
  1097. }
  1098. /**
  1099. * 构建新增日志
  1100. */
  1101. protected function buildAddLogs($recordId, array $data, $operator, $time)
  1102. {
  1103. $logs = [];
  1104. foreach ($this->dataFields as $field) {
  1105. if (!array_key_exists($field, $data)) {
  1106. continue;
  1107. }
  1108. $logs[] = [
  1109. 'record_id' => $recordId,
  1110. 'operation_type' => 'add',
  1111. 'field_name' => isset($this->fieldLabels[$field]) ? $this->fieldLabels[$field] : $field,
  1112. 'old_value' => null,
  1113. 'new_value' => (string)$data[$field],
  1114. 'operator_id' => $operator,
  1115. 'operation_time' => $time,
  1116. ];
  1117. }
  1118. return $logs;
  1119. }
  1120. /**
  1121. * 构建修改日志
  1122. */
  1123. protected function buildUpdateLogs($recordId, array $old, array $changed, $operator, $time)
  1124. {
  1125. $logs = [];
  1126. foreach ($changed as $field => $newValue) {
  1127. if ($field === 'mod_id' || $field === 'mod_rq') {
  1128. continue;
  1129. }
  1130. $logs[] = [
  1131. 'record_id' => $recordId,
  1132. 'operation_type' => 'update',
  1133. 'field_name' => isset($this->fieldLabels[$field]) ? $this->fieldLabels[$field] : $field,
  1134. 'old_value' => isset($old[$field]) ? (string)$old[$field] : '',
  1135. 'new_value' => (string)$newValue,
  1136. 'operator_id' => $operator,
  1137. 'operation_time' => $time,
  1138. ];
  1139. }
  1140. return $logs;
  1141. }
  1142. /**
  1143. * 构建删除日志
  1144. */
  1145. protected function buildDeleteLogs($recordId, array $record, $operator, $time)
  1146. {
  1147. $logs = [];
  1148. foreach ($this->dataFields as $field) {
  1149. if (!array_key_exists($field, $record)) {
  1150. continue;
  1151. }
  1152. $logs[] = [
  1153. 'record_id' => $recordId,
  1154. 'operation_type' => 'delete',
  1155. 'field_name' => isset($this->fieldLabels[$field]) ? $this->fieldLabels[$field] : $field,
  1156. 'old_value' => (string)$record[$field],
  1157. 'new_value' => null,
  1158. 'operator_id' => $operator,
  1159. 'operation_time' => $time,
  1160. ];
  1161. }
  1162. return $logs;
  1163. }
  1164. /**
  1165. * 数值格式化
  1166. */
  1167. protected function formatNumber($value)
  1168. {
  1169. if ($value === null || $value === '') {
  1170. return 0;
  1171. }
  1172. return is_numeric($value) ? (float)$value : $value;
  1173. }
  1174. }