Procuremenexport.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\ProcuremenStatus;
  5. use app\common\library\ProcuremenTime;
  6. use think\Db;
  7. /**
  8. * 协助采购 — 月度报表导出列表
  9. *
  10. * @icon fa fa-file-excel-o
  11. */
  12. class Procuremenexport extends Backend
  13. {
  14. protected $searchFields = 'CCYDH,CYJMC,CGYMC';
  15. public function _initialize()
  16. {
  17. parent::_initialize();
  18. $canExport = $this->hasProcuremenSiblingPerm(['export_month_outward', 'exportMonthOutward']);
  19. $canDetails = $this->hasProcuremenSiblingPerm(['details']);
  20. $this->view->assign('canExportMonthOutward', $canExport);
  21. $this->assignconfig('procuremenAuth', [
  22. 'details' => $canDetails,
  23. 'export_month_outward' => $canExport,
  24. ]);
  25. }
  26. /**
  27. * 月度导出页引用的采购子权限(规则名在 procuremen 控制器下)
  28. *
  29. * @param string[] $actions
  30. */
  31. protected function hasProcuremenSiblingPerm(array $actions): bool
  32. {
  33. foreach ($actions as $action) {
  34. $action = strtolower(trim((string)$action));
  35. if ($action === '') {
  36. continue;
  37. }
  38. if (strpos($action, 'procuremen/') !== 0) {
  39. $action = 'procuremen/' . $action;
  40. }
  41. if ($this->auth->check($action)) {
  42. return true;
  43. }
  44. }
  45. $suffixes = [];
  46. foreach ($actions as $action) {
  47. $action = strtolower(trim((string)$action));
  48. $action = preg_replace('#^procuremen/#', '', $action);
  49. if ($action !== '') {
  50. $suffixes[$action] = true;
  51. }
  52. }
  53. if ($suffixes === []) {
  54. return false;
  55. }
  56. try {
  57. foreach ($this->auth->getRuleList() as $rule) {
  58. $rule = strtolower((string)$rule);
  59. if (strpos($rule, 'procuremen/') !== 0) {
  60. continue;
  61. }
  62. foreach (array_keys($suffixes) as $suffix) {
  63. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  64. return true;
  65. }
  66. }
  67. }
  68. } catch (\Throwable $e) {
  69. }
  70. return false;
  71. }
  72. public function index()
  73. {
  74. $this->relationSearch = false;
  75. $this->request->filter(['strip_tags', 'trim']);
  76. if ($this->request->isAjax()) {
  77. $ym = trim((string)$this->request->request('ym', date('Y-m')));
  78. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  79. $ym = date('Y-m');
  80. }
  81. try {
  82. // 有搜索条件时跨月份查询(用户常不知完结月份)
  83. $hasSearch = $this->exportListHasActiveSearch();
  84. $rows = $this->buildExportableOrderRows($hasSearch ? '' : $ym);
  85. $rows = $this->filterExportableRowsBySearch($rows);
  86. $total = count($rows);
  87. $offset = max(0, (int)$this->request->get('offset', 0));
  88. $limit = (int)$this->request->get('limit', 0);
  89. if ($limit > 0) {
  90. $rows = array_slice($rows, $offset, $limit);
  91. }
  92. return json([
  93. 'total' => $total,
  94. 'rows' => $rows,
  95. 'ym' => $ym,
  96. 'cross_month'=> $hasSearch ? 1 : 0,
  97. ]);
  98. } catch (\Throwable $e) {
  99. return json(['total' => 0, 'rows' => [], 'ym' => $ym, 'msg' => $e->getMessage()]);
  100. }
  101. }
  102. return $this->view->fetch();
  103. }
  104. /**
  105. * 列表是否带有有效搜索(快速搜索或通用搜索)
  106. */
  107. protected function exportListHasActiveSearch(): bool
  108. {
  109. $keyword = trim((string)$this->request->request('search', ''));
  110. if ($keyword === '') {
  111. $keyword = trim((string)$this->request->get('search', ''));
  112. }
  113. if ($keyword !== '') {
  114. return true;
  115. }
  116. $filter = $this->request->get('filter', '');
  117. if (is_string($filter) && $filter !== '') {
  118. $filterArr = (array)json_decode($filter, true);
  119. } else {
  120. $filterArr = is_array($filter) ? $filter : [];
  121. }
  122. foreach ($filterArr as $val) {
  123. if (trim((string)$val) !== '') {
  124. return true;
  125. }
  126. }
  127. return false;
  128. }
  129. /**
  130. * 已完结、可按月份导出的订单(合并为一单一行)
  131. */
  132. public function exportable()
  133. {
  134. if (!$this->request->isAjax()) {
  135. $this->error(__('Invalid parameters'));
  136. }
  137. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  138. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  139. $ym = date('Y-m');
  140. }
  141. try {
  142. $rows = $this->buildExportableOrderRows($ym);
  143. return json(['total' => count($rows), 'rows' => $rows, 'ym' => $ym]);
  144. } catch (\Throwable $e) {
  145. return json(['total' => 0, 'rows' => [], 'ym' => $ym, 'msg' => $e->getMessage()]);
  146. }
  147. }
  148. /**
  149. * 快速搜索 / 通用搜索过滤(本页数据已按月聚合,在内存中筛选)
  150. *
  151. * @param array<int, array<string, mixed>> $rows
  152. * @return array<int, array<string, mixed>>
  153. */
  154. protected function filterExportableRowsBySearch(array $rows): array
  155. {
  156. $keyword = trim((string)$this->request->request('search', ''));
  157. if ($keyword === '') {
  158. $keyword = trim((string)$this->request->get('search', ''));
  159. }
  160. $filter = $this->request->get('filter', '');
  161. $op = $this->request->get('op', '');
  162. if (is_string($filter) && $filter !== '') {
  163. $filterArr = (array)json_decode($filter, true);
  164. } else {
  165. $filterArr = is_array($filter) ? $filter : [];
  166. }
  167. if (is_string($op) && $op !== '') {
  168. $opArr = (array)json_decode($op, true);
  169. } else {
  170. $opArr = is_array($op) ? $op : [];
  171. }
  172. if ($keyword === '' && $filterArr === []) {
  173. return $rows;
  174. }
  175. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC', 'createtime_text', 'ym'];
  176. $out = [];
  177. foreach ($rows as $row) {
  178. if (!is_array($row)) {
  179. continue;
  180. }
  181. if ($keyword !== '') {
  182. $hit = false;
  183. foreach ($searchFields as $f) {
  184. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  185. $hit = true;
  186. break;
  187. }
  188. }
  189. if (!$hit) {
  190. continue;
  191. }
  192. }
  193. $passFilter = true;
  194. foreach ($filterArr as $field => $val) {
  195. $field = (string)$field;
  196. $val = trim((string)$val);
  197. if ($field === '' || $val === '') {
  198. continue;
  199. }
  200. $cell = (string)($row[$field] ?? '');
  201. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  202. if ($mode === '=' || $mode === 'EQUAL') {
  203. if (strcasecmp($cell, $val) !== 0) {
  204. $passFilter = false;
  205. break;
  206. }
  207. } elseif (mb_stripos($cell, $val) === false) {
  208. $passFilter = false;
  209. break;
  210. }
  211. }
  212. if (!$passFilter) {
  213. continue;
  214. }
  215. $out[] = $row;
  216. }
  217. return $out;
  218. }
  219. /**
  220. * 已完结订单(与历史存证一致),按完结月份筛选后合并为一单一行
  221. *
  222. * @param string $ym 完结月份 Y-m;空字符串表示不限月份(用于跨月搜索)
  223. * @return array<int, array<string, mixed>>
  224. */
  225. protected function buildExportableOrderRows(string $ym): array
  226. {
  227. try {
  228. $query = Db::table('purchase_order');
  229. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  230. $dbRows = $query
  231. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_time,createtime,dStamp')
  232. ->order('id', 'desc')
  233. ->select();
  234. } catch (\Throwable $e) {
  235. \think\Log::write('月度导出列表查询异常:' . $e->getMessage(), 'error');
  236. $dbRows = [];
  237. }
  238. if (!is_array($dbRows)) {
  239. $dbRows = [];
  240. }
  241. $sidList = [];
  242. foreach ($dbRows as $r) {
  243. if (!is_array($r)) {
  244. continue;
  245. }
  246. $sid = (int)($r['scydgy_id'] ?? 0);
  247. if ($sid > 0) {
  248. $sidList[$sid] = true;
  249. }
  250. }
  251. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  252. $amountMap = $this->loadDetailAmountSumByScydgyIds(array_keys($sidList));
  253. $pool = [];
  254. foreach ($dbRows as $r) {
  255. if (!is_array($r)) {
  256. continue;
  257. }
  258. $done = ProcuremenTime::resolveCompletedDone($r, $completeTsMap);
  259. if ($done['ts'] <= 0) {
  260. continue;
  261. }
  262. $rowYm = date('Y-m', $done['ts']);
  263. if ($ym !== '' && $rowYm !== $ym) {
  264. continue;
  265. }
  266. $sid = (int)($r['scydgy_id'] ?? 0);
  267. $pool[] = [
  268. 'id' => (int)($r['id'] ?? 0),
  269. 'scydgy_id' => $sid,
  270. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  271. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  272. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  273. 'ym' => $rowYm,
  274. 'createtime_text' => $done['text'],
  275. 'detail_amount' => (float)($amountMap[$sid] ?? 0),
  276. ];
  277. }
  278. $merged = $this->collapseExportRowsByOrder($pool);
  279. foreach ($merged as &$row) {
  280. $amt = 0.0;
  281. $cnt = 0;
  282. if (!empty($row['_merge_rows']) && is_array($row['_merge_rows'])) {
  283. foreach ($row['_merge_rows'] as $mr) {
  284. if (!is_array($mr)) {
  285. continue;
  286. }
  287. $amt += (float)($mr['detail_amount'] ?? 0);
  288. $cnt++;
  289. if (trim((string)($row['ym'] ?? '')) === '') {
  290. $ymv = trim((string)($mr['ym'] ?? ''));
  291. if ($ymv !== '') {
  292. $row['ym'] = $ymv;
  293. }
  294. }
  295. }
  296. } else {
  297. $amt = (float)($row['detail_amount'] ?? 0);
  298. $cnt = 1;
  299. }
  300. $row['row_count'] = $cnt;
  301. $row['total_amount'] = round($amt, 2);
  302. $row['total_amount_text'] = number_format($amt, 2, '.', ',');
  303. unset($row['_merge_rows'], $row['detail_amount']);
  304. }
  305. unset($row);
  306. return $merged;
  307. }
  308. /**
  309. * 工序行金额合计:优先已选定明细 status=1,否则汇总有效明细上的加工金额
  310. *
  311. * @param int[] $scydgyIds
  312. * @return array<int, float>
  313. */
  314. protected function loadDetailAmountSumByScydgyIds(array $scydgyIds): array
  315. {
  316. $picked = $this->loadPickedAmountSumByScydgyIds($scydgyIds);
  317. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  318. $missing = [];
  319. foreach ($scydgyIds as $sid) {
  320. if ($sid > 0 && !isset($picked[$sid])) {
  321. $missing[] = $sid;
  322. }
  323. }
  324. if ($missing === []) {
  325. return $picked;
  326. }
  327. try {
  328. $rows = Db::table('purchase_order_detail')
  329. ->where('scydgy_id', 'in', $missing)
  330. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  331. ->field('scydgy_id,amount')
  332. ->select();
  333. } catch (\Throwable $e) {
  334. $rows = [];
  335. }
  336. if (!is_array($rows)) {
  337. return $picked;
  338. }
  339. foreach ($rows as $r) {
  340. if (!is_array($r)) {
  341. continue;
  342. }
  343. $sid = (int)($r['scydgy_id'] ?? 0);
  344. $am = trim((string)($r['amount'] ?? ''));
  345. if ($sid <= 0 || $am === '' || $am === '0' || $am === '0.00') {
  346. continue;
  347. }
  348. if (!isset($picked[$sid])) {
  349. $picked[$sid] = 0.0;
  350. }
  351. $picked[$sid] += (float)$am;
  352. }
  353. return $picked;
  354. }
  355. /**
  356. * @param int[] $scydgyIds
  357. * @return array<int, float>
  358. */
  359. protected function loadPickedAmountSumByScydgyIds(array $scydgyIds): array
  360. {
  361. $out = [];
  362. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  363. if ($scydgyIds === []) {
  364. return $out;
  365. }
  366. try {
  367. $rows = Db::table('purchase_order_detail')
  368. ->where('scydgy_id', 'in', $scydgyIds)
  369. ->whereIn('status', ProcuremenStatus::podPickedValues())
  370. ->field('scydgy_id,amount')
  371. ->select();
  372. } catch (\Throwable $e) {
  373. $rows = [];
  374. }
  375. if (!is_array($rows)) {
  376. return $out;
  377. }
  378. foreach ($rows as $r) {
  379. if (!is_array($r)) {
  380. continue;
  381. }
  382. $sid = (int)($r['scydgy_id'] ?? 0);
  383. $am = trim((string)($r['amount'] ?? ''));
  384. if ($sid <= 0 || $am === '' || $am === '0' || $am === '0.00') {
  385. continue;
  386. }
  387. if (!isset($out[$sid])) {
  388. $out[$sid] = 0.0;
  389. }
  390. $out[$sid] += (float)$am;
  391. }
  392. return $out;
  393. }
  394. /**
  395. * 归属月份:优先采购确认/完结操作时间,其次 pick_time、createtime、dStamp
  396. *
  397. * @param array<string, mixed> $row
  398. * @param array<int, int> $completeTsMap scydgy_id => unix 完结时间
  399. */
  400. protected function resolvePurchaseOrderRowYm(array $row, array $completeTsMap = []): string
  401. {
  402. $ts = $this->resolvePurchaseOrderCompleteTimestamp($row, $completeTsMap);
  403. if ($ts > 0) {
  404. return date('Y-m', $ts);
  405. }
  406. return '';
  407. }
  408. /**
  409. * @param array<string, mixed> $row
  410. * @param array<int, int> $completeTsMap
  411. */
  412. protected function resolvePurchaseOrderCompleteTimestamp(array $row, array $completeTsMap = []): int
  413. {
  414. $sid = (int)($row['scydgy_id'] ?? 0);
  415. if ($sid > 0 && isset($completeTsMap[$sid]) && (int)$completeTsMap[$sid] > 946684800) {
  416. return (int)$completeTsMap[$sid];
  417. }
  418. foreach (['pick_time', 'createtime', 'dStamp'] as $key) {
  419. $raw = $row[$key] ?? null;
  420. if ($raw === null || $raw === '') {
  421. continue;
  422. }
  423. if (is_numeric($raw) && (int)$raw > 946684800) {
  424. return (int)$raw;
  425. }
  426. $t = trim((string)$raw);
  427. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  428. $parsed = (int)strtotime($t);
  429. return $parsed > 946684800 ? $parsed : 0;
  430. }
  431. }
  432. return 0;
  433. }
  434. /**
  435. * @param array<int, string> $actions
  436. * @return array<int, int> scydgy_id => 最近操作 unix 时间
  437. */
  438. protected function loadOperLogTimestampMap(array $scydgyIds, array $actions): array
  439. {
  440. $out = [];
  441. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  442. $actions = array_values(array_filter(array_map('strval', $actions)));
  443. if ($scydgyIds === [] || $actions === []) {
  444. return $out;
  445. }
  446. try {
  447. $logs = Db::table('purchase_order_oper_log')
  448. ->where('scydgy_id', 'in', $scydgyIds)
  449. ->where('action', 'in', $actions)
  450. ->field('scydgy_id,createtime')
  451. ->order('id', 'asc')
  452. ->select();
  453. } catch (\Throwable $e) {
  454. $logs = [];
  455. }
  456. if (!is_array($logs)) {
  457. return $out;
  458. }
  459. foreach ($logs as $log) {
  460. if (!is_array($log)) {
  461. continue;
  462. }
  463. $sid = (int)($log['scydgy_id'] ?? 0);
  464. $ct = (int)($log['createtime'] ?? 0);
  465. if ($sid > 0 && $ct > 946684800) {
  466. $out[$sid] = isset($out[$sid]) ? max($out[$sid], $ct) : $ct;
  467. }
  468. }
  469. return $out;
  470. }
  471. /**
  472. * @param array<string, mixed> $row
  473. * @param array<int, int> $completeTsMap
  474. */
  475. protected function formatPurchaseOrderDoneTime(array $row, array $completeTsMap = []): string
  476. {
  477. $ts = $this->resolvePurchaseOrderCompleteTimestamp($row, $completeTsMap);
  478. if ($ts > 0) {
  479. return date('Y-m-d H:i:s', $ts);
  480. }
  481. return '';
  482. }
  483. /**
  484. * @param array<int, array<string, mixed>> $rows
  485. * @return array<int, array<string, mixed>>
  486. */
  487. protected function collapseExportRowsByOrder(array $rows): array
  488. {
  489. if ($rows === []) {
  490. return [];
  491. }
  492. $groups = [];
  493. foreach ($rows as $row) {
  494. if (!is_array($row)) {
  495. continue;
  496. }
  497. $dh = trim((string)($row['CCYDH'] ?? ''));
  498. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['id'] ?? 0));
  499. if (!isset($groups[$key])) {
  500. $groups[$key] = [];
  501. }
  502. $groups[$key][] = $row;
  503. }
  504. $out = [];
  505. foreach ($groups as $groupRows) {
  506. if ($groupRows === []) {
  507. continue;
  508. }
  509. usort($groupRows, function ($a, $b) {
  510. return ((int)($a['id'] ?? 0)) <=> ((int)($b['id'] ?? 0));
  511. });
  512. $head = $groupRows[0];
  513. $gymcList = [];
  514. foreach ($groupRows as $r) {
  515. $g = trim((string)($r['CGYMC'] ?? ''));
  516. if ($g !== '' && !in_array($g, $gymcList, true)) {
  517. $gymcList[] = $g;
  518. }
  519. }
  520. $merged = $head;
  521. $merged['_merge_rows'] = $groupRows;
  522. if (count($groupRows) > 1) {
  523. $merged['CGYMC'] = implode('、', $gymcList);
  524. }
  525. $latestText = '';
  526. $latestTs = 0;
  527. foreach ($groupRows as $r) {
  528. $t = trim((string)($r['createtime_text'] ?? ''));
  529. $ts = ProcuremenTime::parseToTimestamp($t);
  530. if ($ts > $latestTs) {
  531. $latestTs = $ts;
  532. $latestText = ProcuremenTime::formatDisplayDateTime($t);
  533. }
  534. }
  535. if ($latestText !== '') {
  536. $merged['createtime_text'] = $latestText;
  537. }
  538. $maxId = (int)($head['id'] ?? 0);
  539. foreach ($groupRows as $r) {
  540. $maxId = max($maxId, (int)($r['id'] ?? 0));
  541. }
  542. $merged['id'] = $maxId;
  543. $out[] = $merged;
  544. }
  545. usort($out, function ($a, $b) {
  546. return ((int)($b['id'] ?? 0)) <=> ((int)($a['id'] ?? 0));
  547. });
  548. return $out;
  549. }
  550. }