Procuremenexport.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. $rows = $this->buildExportableOrderRows($ym);
  83. $rows = $this->filterExportableRowsBySearch($rows);
  84. return json(['total' => count($rows), 'rows' => $rows, 'ym' => $ym]);
  85. } catch (\Throwable $e) {
  86. return json(['total' => 0, 'rows' => [], 'ym' => $ym, 'msg' => $e->getMessage()]);
  87. }
  88. }
  89. return $this->view->fetch();
  90. }
  91. /**
  92. * 已完结、可按月份导出的订单(合并为一单一行)
  93. */
  94. public function exportable()
  95. {
  96. if (!$this->request->isAjax()) {
  97. $this->error(__('Invalid parameters'));
  98. }
  99. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  100. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  101. $ym = date('Y-m');
  102. }
  103. try {
  104. $rows = $this->buildExportableOrderRows($ym);
  105. return json(['total' => count($rows), 'rows' => $rows, 'ym' => $ym]);
  106. } catch (\Throwable $e) {
  107. return json(['total' => 0, 'rows' => [], 'ym' => $ym, 'msg' => $e->getMessage()]);
  108. }
  109. }
  110. /**
  111. * 快速搜索 / 通用搜索过滤(本页数据已按月聚合,在内存中筛选)
  112. *
  113. * @param array<int, array<string, mixed>> $rows
  114. * @return array<int, array<string, mixed>>
  115. */
  116. protected function filterExportableRowsBySearch(array $rows): array
  117. {
  118. $keyword = trim((string)$this->request->request('search', ''));
  119. if ($keyword === '') {
  120. $keyword = trim((string)$this->request->get('search', ''));
  121. }
  122. $filter = $this->request->get('filter', '');
  123. $op = $this->request->get('op', '');
  124. if (is_string($filter) && $filter !== '') {
  125. $filterArr = (array)json_decode($filter, true);
  126. } else {
  127. $filterArr = is_array($filter) ? $filter : [];
  128. }
  129. if (is_string($op) && $op !== '') {
  130. $opArr = (array)json_decode($op, true);
  131. } else {
  132. $opArr = is_array($op) ? $op : [];
  133. }
  134. if ($keyword === '' && $filterArr === []) {
  135. return $rows;
  136. }
  137. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC', 'createtime_text', 'ym'];
  138. $out = [];
  139. foreach ($rows as $row) {
  140. if (!is_array($row)) {
  141. continue;
  142. }
  143. if ($keyword !== '') {
  144. $hit = false;
  145. foreach ($searchFields as $f) {
  146. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  147. $hit = true;
  148. break;
  149. }
  150. }
  151. if (!$hit) {
  152. continue;
  153. }
  154. }
  155. $passFilter = true;
  156. foreach ($filterArr as $field => $val) {
  157. $field = (string)$field;
  158. $val = trim((string)$val);
  159. if ($field === '' || $val === '') {
  160. continue;
  161. }
  162. $cell = (string)($row[$field] ?? '');
  163. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  164. if ($mode === '=' || $mode === 'EQUAL') {
  165. if (strcasecmp($cell, $val) !== 0) {
  166. $passFilter = false;
  167. break;
  168. }
  169. } elseif (mb_stripos($cell, $val) === false) {
  170. $passFilter = false;
  171. break;
  172. }
  173. }
  174. if (!$passFilter) {
  175. continue;
  176. }
  177. $out[] = $row;
  178. }
  179. return $out;
  180. }
  181. /**
  182. * 已完结订单(与历史存证一致),按完结月份筛选后合并为一单一行
  183. *
  184. * @return array<int, array<string, mixed>>
  185. */
  186. protected function buildExportableOrderRows(string $ym): array
  187. {
  188. try {
  189. $query = Db::table('purchase_order');
  190. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  191. $dbRows = $query
  192. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_time,createtime,dStamp')
  193. ->order('id', 'desc')
  194. ->select();
  195. } catch (\Throwable $e) {
  196. \think\Log::write('月度导出列表查询异常:' . $e->getMessage(), 'error');
  197. $dbRows = [];
  198. }
  199. if (!is_array($dbRows)) {
  200. $dbRows = [];
  201. }
  202. $sidList = [];
  203. foreach ($dbRows as $r) {
  204. if (!is_array($r)) {
  205. continue;
  206. }
  207. $sid = (int)($r['scydgy_id'] ?? 0);
  208. if ($sid > 0) {
  209. $sidList[$sid] = true;
  210. }
  211. }
  212. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  213. $amountMap = $this->loadDetailAmountSumByScydgyIds(array_keys($sidList));
  214. $pool = [];
  215. foreach ($dbRows as $r) {
  216. if (!is_array($r)) {
  217. continue;
  218. }
  219. $done = ProcuremenTime::resolveCompletedDone($r, $completeTsMap);
  220. $rowYm = $done['ts'] > 0 ? date('Y-m', $done['ts']) : '';
  221. if ($rowYm !== $ym) {
  222. continue;
  223. }
  224. $sid = (int)($r['scydgy_id'] ?? 0);
  225. $pool[] = [
  226. 'id' => (int)($r['id'] ?? 0),
  227. 'scydgy_id' => $sid,
  228. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  229. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  230. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  231. 'ym' => $rowYm,
  232. 'createtime_text' => $done['text'],
  233. 'detail_amount' => (float)($amountMap[$sid] ?? 0),
  234. ];
  235. }
  236. $merged = $this->collapseExportRowsByOrder($pool);
  237. foreach ($merged as &$row) {
  238. $amt = 0.0;
  239. $cnt = 0;
  240. if (!empty($row['_merge_rows']) && is_array($row['_merge_rows'])) {
  241. foreach ($row['_merge_rows'] as $mr) {
  242. if (!is_array($mr)) {
  243. continue;
  244. }
  245. $amt += (float)($mr['detail_amount'] ?? 0);
  246. $cnt++;
  247. if (trim((string)($row['ym'] ?? '')) === '') {
  248. $ymv = trim((string)($mr['ym'] ?? ''));
  249. if ($ymv !== '') {
  250. $row['ym'] = $ymv;
  251. }
  252. }
  253. }
  254. } else {
  255. $amt = (float)($row['detail_amount'] ?? 0);
  256. $cnt = 1;
  257. }
  258. $row['row_count'] = $cnt;
  259. $row['total_amount'] = round($amt, 2);
  260. $row['total_amount_text'] = number_format($amt, 2, '.', ',');
  261. unset($row['_merge_rows'], $row['detail_amount']);
  262. }
  263. unset($row);
  264. return $merged;
  265. }
  266. /**
  267. * 工序行金额合计:优先已选定明细 status=1,否则汇总有效明细上的加工金额
  268. *
  269. * @param int[] $scydgyIds
  270. * @return array<int, float>
  271. */
  272. protected function loadDetailAmountSumByScydgyIds(array $scydgyIds): array
  273. {
  274. $picked = $this->loadPickedAmountSumByScydgyIds($scydgyIds);
  275. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  276. $missing = [];
  277. foreach ($scydgyIds as $sid) {
  278. if ($sid > 0 && !isset($picked[$sid])) {
  279. $missing[] = $sid;
  280. }
  281. }
  282. if ($missing === []) {
  283. return $picked;
  284. }
  285. try {
  286. $rows = Db::table('purchase_order_detail')
  287. ->where('scydgy_id', 'in', $missing)
  288. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  289. ->field('scydgy_id,amount')
  290. ->select();
  291. } catch (\Throwable $e) {
  292. $rows = [];
  293. }
  294. if (!is_array($rows)) {
  295. return $picked;
  296. }
  297. foreach ($rows as $r) {
  298. if (!is_array($r)) {
  299. continue;
  300. }
  301. $sid = (int)($r['scydgy_id'] ?? 0);
  302. $am = trim((string)($r['amount'] ?? ''));
  303. if ($sid <= 0 || $am === '' || $am === '0' || $am === '0.00') {
  304. continue;
  305. }
  306. if (!isset($picked[$sid])) {
  307. $picked[$sid] = 0.0;
  308. }
  309. $picked[$sid] += (float)$am;
  310. }
  311. return $picked;
  312. }
  313. /**
  314. * @param int[] $scydgyIds
  315. * @return array<int, float>
  316. */
  317. protected function loadPickedAmountSumByScydgyIds(array $scydgyIds): array
  318. {
  319. $out = [];
  320. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  321. if ($scydgyIds === []) {
  322. return $out;
  323. }
  324. try {
  325. $rows = Db::table('purchase_order_detail')
  326. ->where('scydgy_id', 'in', $scydgyIds)
  327. ->whereIn('status', ProcuremenStatus::podPickedValues())
  328. ->field('scydgy_id,amount')
  329. ->select();
  330. } catch (\Throwable $e) {
  331. $rows = [];
  332. }
  333. if (!is_array($rows)) {
  334. return $out;
  335. }
  336. foreach ($rows as $r) {
  337. if (!is_array($r)) {
  338. continue;
  339. }
  340. $sid = (int)($r['scydgy_id'] ?? 0);
  341. $am = trim((string)($r['amount'] ?? ''));
  342. if ($sid <= 0 || $am === '' || $am === '0' || $am === '0.00') {
  343. continue;
  344. }
  345. if (!isset($out[$sid])) {
  346. $out[$sid] = 0.0;
  347. }
  348. $out[$sid] += (float)$am;
  349. }
  350. return $out;
  351. }
  352. /**
  353. * 归属月份:优先采购确认/完结操作时间,其次 pick_time、createtime、dStamp
  354. *
  355. * @param array<string, mixed> $row
  356. * @param array<int, int> $completeTsMap scydgy_id => unix 完结时间
  357. */
  358. protected function resolvePurchaseOrderRowYm(array $row, array $completeTsMap = []): string
  359. {
  360. $ts = $this->resolvePurchaseOrderCompleteTimestamp($row, $completeTsMap);
  361. if ($ts > 0) {
  362. return date('Y-m', $ts);
  363. }
  364. return '';
  365. }
  366. /**
  367. * @param array<string, mixed> $row
  368. * @param array<int, int> $completeTsMap
  369. */
  370. protected function resolvePurchaseOrderCompleteTimestamp(array $row, array $completeTsMap = []): int
  371. {
  372. $sid = (int)($row['scydgy_id'] ?? 0);
  373. if ($sid > 0 && isset($completeTsMap[$sid]) && (int)$completeTsMap[$sid] > 946684800) {
  374. return (int)$completeTsMap[$sid];
  375. }
  376. foreach (['pick_time', 'createtime', 'dStamp'] as $key) {
  377. $raw = $row[$key] ?? null;
  378. if ($raw === null || $raw === '') {
  379. continue;
  380. }
  381. if (is_numeric($raw) && (int)$raw > 946684800) {
  382. return (int)$raw;
  383. }
  384. $t = trim((string)$raw);
  385. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  386. $parsed = (int)strtotime($t);
  387. return $parsed > 946684800 ? $parsed : 0;
  388. }
  389. }
  390. return 0;
  391. }
  392. /**
  393. * @param array<int, string> $actions
  394. * @return array<int, int> scydgy_id => 最近操作 unix 时间
  395. */
  396. protected function loadOperLogTimestampMap(array $scydgyIds, array $actions): array
  397. {
  398. $out = [];
  399. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  400. $actions = array_values(array_filter(array_map('strval', $actions)));
  401. if ($scydgyIds === [] || $actions === []) {
  402. return $out;
  403. }
  404. try {
  405. $logs = Db::table('purchase_order_oper_log')
  406. ->where('scydgy_id', 'in', $scydgyIds)
  407. ->where('action', 'in', $actions)
  408. ->field('scydgy_id,createtime')
  409. ->order('id', 'asc')
  410. ->select();
  411. } catch (\Throwable $e) {
  412. $logs = [];
  413. }
  414. if (!is_array($logs)) {
  415. return $out;
  416. }
  417. foreach ($logs as $log) {
  418. if (!is_array($log)) {
  419. continue;
  420. }
  421. $sid = (int)($log['scydgy_id'] ?? 0);
  422. $ct = (int)($log['createtime'] ?? 0);
  423. if ($sid > 0 && $ct > 946684800) {
  424. $out[$sid] = isset($out[$sid]) ? max($out[$sid], $ct) : $ct;
  425. }
  426. }
  427. return $out;
  428. }
  429. /**
  430. * @param array<string, mixed> $row
  431. * @param array<int, int> $completeTsMap
  432. */
  433. protected function formatPurchaseOrderDoneTime(array $row, array $completeTsMap = []): string
  434. {
  435. $ts = $this->resolvePurchaseOrderCompleteTimestamp($row, $completeTsMap);
  436. if ($ts > 0) {
  437. return date('Y-m-d H:i:s', $ts);
  438. }
  439. return '';
  440. }
  441. /**
  442. * @param array<int, array<string, mixed>> $rows
  443. * @return array<int, array<string, mixed>>
  444. */
  445. protected function collapseExportRowsByOrder(array $rows): array
  446. {
  447. if ($rows === []) {
  448. return [];
  449. }
  450. $groups = [];
  451. foreach ($rows as $row) {
  452. if (!is_array($row)) {
  453. continue;
  454. }
  455. $dh = trim((string)($row['CCYDH'] ?? ''));
  456. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['id'] ?? 0));
  457. if (!isset($groups[$key])) {
  458. $groups[$key] = [];
  459. }
  460. $groups[$key][] = $row;
  461. }
  462. $out = [];
  463. foreach ($groups as $groupRows) {
  464. if ($groupRows === []) {
  465. continue;
  466. }
  467. usort($groupRows, function ($a, $b) {
  468. return ((int)($a['id'] ?? 0)) <=> ((int)($b['id'] ?? 0));
  469. });
  470. $head = $groupRows[0];
  471. $gymcList = [];
  472. foreach ($groupRows as $r) {
  473. $g = trim((string)($r['CGYMC'] ?? ''));
  474. if ($g !== '' && !in_array($g, $gymcList, true)) {
  475. $gymcList[] = $g;
  476. }
  477. }
  478. $merged = $head;
  479. $merged['_merge_rows'] = $groupRows;
  480. if (count($groupRows) > 1) {
  481. $merged['CGYMC'] = implode('、', $gymcList);
  482. }
  483. $latestText = '';
  484. $latestTs = 0;
  485. foreach ($groupRows as $r) {
  486. $t = trim((string)($r['createtime_text'] ?? ''));
  487. $ts = ProcuremenTime::parseToTimestamp($t);
  488. if ($ts > $latestTs) {
  489. $latestTs = $ts;
  490. $latestText = ProcuremenTime::formatDisplayDateTime($t);
  491. }
  492. }
  493. if ($latestText !== '') {
  494. $merged['createtime_text'] = $latestText;
  495. }
  496. $maxId = (int)($head['id'] ?? 0);
  497. foreach ($groupRows as $r) {
  498. $maxId = max($maxId, (int)($r['id'] ?? 0));
  499. }
  500. $merged['id'] = $maxId;
  501. $out[] = $merged;
  502. }
  503. usort($out, function ($a, $b) {
  504. return ((int)($b['id'] ?? 0)) <=> ((int)($a['id'] ?? 0));
  505. });
  506. return $out;
  507. }
  508. }