Procuremenexport.php 20 KB

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