Procuremenexport.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\ProcuremenStatus;
  5. use think\Db;
  6. /**
  7. * 协助采购 — 月度报表导出列表
  8. *
  9. * @icon fa fa-file-excel-o
  10. */
  11. class Procuremenexport extends Backend
  12. {
  13. protected $searchFields = 'CCYDH,CYJMC,CGYMC';
  14. public function index()
  15. {
  16. $this->relationSearch = false;
  17. $this->request->filter(['strip_tags', 'trim']);
  18. if ($this->request->isAjax()) {
  19. $ym = trim((string)$this->request->request('ym', date('Y-m')));
  20. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  21. $ym = date('Y-m');
  22. }
  23. try {
  24. $rows = $this->buildExportableOrderRows($ym);
  25. return json(['total' => count($rows), 'rows' => $rows, 'ym' => $ym]);
  26. } catch (\Throwable $e) {
  27. return json(['total' => 0, 'rows' => [], 'ym' => $ym, 'msg' => $e->getMessage()]);
  28. }
  29. }
  30. return $this->view->fetch();
  31. }
  32. /**
  33. * 已完结、可按月份导出的订单(合并为一单一行)
  34. */
  35. public function exportable()
  36. {
  37. if (!$this->request->isAjax()) {
  38. $this->error(__('Invalid parameters'));
  39. }
  40. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  41. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  42. $ym = date('Y-m');
  43. }
  44. try {
  45. $rows = $this->buildExportableOrderRows($ym);
  46. return json(['total' => count($rows), 'rows' => $rows, 'ym' => $ym]);
  47. } catch (\Throwable $e) {
  48. return json(['total' => 0, 'rows' => [], 'ym' => $ym, 'msg' => $e->getMessage()]);
  49. }
  50. }
  51. /**
  52. * 已完结订单(与历史存证一致),按完结月份筛选后合并为一单一行
  53. *
  54. * @return array<int, array<string, mixed>>
  55. */
  56. protected function buildExportableOrderRows(string $ym): array
  57. {
  58. try {
  59. $query = Db::table('purchase_order');
  60. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  61. $dbRows = $query
  62. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_time,createtime,dStamp,updatetime')
  63. ->order('id', 'desc')
  64. ->select();
  65. } catch (\Throwable $e) {
  66. $dbRows = [];
  67. }
  68. if (!is_array($dbRows)) {
  69. $dbRows = [];
  70. }
  71. $sidList = [];
  72. foreach ($dbRows as $r) {
  73. if (!is_array($r)) {
  74. continue;
  75. }
  76. $sid = (int)($r['scydgy_id'] ?? 0);
  77. if ($sid > 0) {
  78. $sidList[$sid] = true;
  79. }
  80. }
  81. $amountMap = $this->loadDetailAmountSumByScydgyIds(array_keys($sidList));
  82. $completeTsMap = $this->loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  83. $pool = [];
  84. foreach ($dbRows as $r) {
  85. if (!is_array($r)) {
  86. continue;
  87. }
  88. $rowYm = $this->resolvePurchaseOrderRowYm($r, $completeTsMap);
  89. if ($rowYm !== $ym) {
  90. continue;
  91. }
  92. $sid = (int)($r['scydgy_id'] ?? 0);
  93. $doneText = $this->formatPurchaseOrderDoneTime($r, $completeTsMap);
  94. $pool[] = [
  95. 'id' => (int)($r['id'] ?? 0),
  96. 'scydgy_id' => $sid,
  97. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  98. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  99. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  100. 'ym' => $rowYm,
  101. 'createtime_text' => $doneText,
  102. 'detail_amount' => (float)($amountMap[$sid] ?? 0),
  103. ];
  104. }
  105. $merged = $this->collapseExportRowsByOrder($pool);
  106. foreach ($merged as &$row) {
  107. $amt = 0.0;
  108. $cnt = 0;
  109. if (!empty($row['_merge_rows']) && is_array($row['_merge_rows'])) {
  110. foreach ($row['_merge_rows'] as $mr) {
  111. if (!is_array($mr)) {
  112. continue;
  113. }
  114. $amt += (float)($mr['detail_amount'] ?? 0);
  115. $cnt++;
  116. if (trim((string)($row['ym'] ?? '')) === '') {
  117. $ymv = trim((string)($mr['ym'] ?? ''));
  118. if ($ymv !== '') {
  119. $row['ym'] = $ymv;
  120. }
  121. }
  122. }
  123. } else {
  124. $amt = (float)($row['detail_amount'] ?? 0);
  125. $cnt = 1;
  126. }
  127. $row['row_count'] = $cnt;
  128. $row['total_amount'] = round($amt, 2);
  129. $row['total_amount_text'] = number_format($amt, 2, '.', ',');
  130. unset($row['_merge_rows'], $row['detail_amount']);
  131. }
  132. unset($row);
  133. return $merged;
  134. }
  135. /**
  136. * 工序行金额合计:优先已选定明细 status=1,否则汇总有效明细上的加工金额
  137. *
  138. * @param int[] $scydgyIds
  139. * @return array<int, float>
  140. */
  141. protected function loadDetailAmountSumByScydgyIds(array $scydgyIds): array
  142. {
  143. $picked = $this->loadPickedAmountSumByScydgyIds($scydgyIds);
  144. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  145. $missing = [];
  146. foreach ($scydgyIds as $sid) {
  147. if ($sid > 0 && !isset($picked[$sid])) {
  148. $missing[] = $sid;
  149. }
  150. }
  151. if ($missing === []) {
  152. return $picked;
  153. }
  154. try {
  155. $rows = Db::table('purchase_order_detail')
  156. ->where('scydgy_id', 'in', $missing)
  157. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  158. ->field('scydgy_id,amount')
  159. ->select();
  160. } catch (\Throwable $e) {
  161. $rows = [];
  162. }
  163. if (!is_array($rows)) {
  164. return $picked;
  165. }
  166. foreach ($rows as $r) {
  167. if (!is_array($r)) {
  168. continue;
  169. }
  170. $sid = (int)($r['scydgy_id'] ?? 0);
  171. $am = trim((string)($r['amount'] ?? ''));
  172. if ($sid <= 0 || $am === '' || $am === '0' || $am === '0.00') {
  173. continue;
  174. }
  175. if (!isset($picked[$sid])) {
  176. $picked[$sid] = 0.0;
  177. }
  178. $picked[$sid] += (float)$am;
  179. }
  180. return $picked;
  181. }
  182. /**
  183. * @param int[] $scydgyIds
  184. * @return array<int, float>
  185. */
  186. protected function loadPickedAmountSumByScydgyIds(array $scydgyIds): array
  187. {
  188. $out = [];
  189. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  190. if ($scydgyIds === []) {
  191. return $out;
  192. }
  193. try {
  194. $rows = Db::table('purchase_order_detail')
  195. ->where('scydgy_id', 'in', $scydgyIds)
  196. ->whereIn('status', ProcuremenStatus::podPickedValues())
  197. ->field('scydgy_id,amount')
  198. ->select();
  199. } catch (\Throwable $e) {
  200. $rows = [];
  201. }
  202. if (!is_array($rows)) {
  203. return $out;
  204. }
  205. foreach ($rows as $r) {
  206. if (!is_array($r)) {
  207. continue;
  208. }
  209. $sid = (int)($r['scydgy_id'] ?? 0);
  210. $am = trim((string)($r['amount'] ?? ''));
  211. if ($sid <= 0 || $am === '' || $am === '0' || $am === '0.00') {
  212. continue;
  213. }
  214. if (!isset($out[$sid])) {
  215. $out[$sid] = 0.0;
  216. }
  217. $out[$sid] += (float)$am;
  218. }
  219. return $out;
  220. }
  221. /**
  222. * 归属月份:优先采购确认/完结操作时间,其次 updatetime,再 createtime
  223. *
  224. * @param array<string, mixed> $row
  225. * @param array<int, int> $completeTsMap scydgy_id => unix 完结时间
  226. */
  227. protected function resolvePurchaseOrderRowYm(array $row, array $completeTsMap = []): string
  228. {
  229. $ts = $this->resolvePurchaseOrderCompleteTimestamp($row, $completeTsMap);
  230. if ($ts > 0) {
  231. return date('Y-m', $ts);
  232. }
  233. return '';
  234. }
  235. /**
  236. * @param array<string, mixed> $row
  237. * @param array<int, int> $completeTsMap
  238. */
  239. protected function resolvePurchaseOrderCompleteTimestamp(array $row, array $completeTsMap = []): int
  240. {
  241. $sid = (int)($row['scydgy_id'] ?? 0);
  242. if ($sid > 0 && isset($completeTsMap[$sid]) && (int)$completeTsMap[$sid] > 946684800) {
  243. return (int)$completeTsMap[$sid];
  244. }
  245. foreach (['updatetime', 'createtime', 'dStamp'] as $key) {
  246. $raw = $row[$key] ?? null;
  247. if ($raw === null || $raw === '') {
  248. continue;
  249. }
  250. if (is_numeric($raw) && (int)$raw > 946684800) {
  251. return (int)$raw;
  252. }
  253. $t = trim((string)$raw);
  254. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  255. $parsed = (int)strtotime($t);
  256. return $parsed > 946684800 ? $parsed : 0;
  257. }
  258. }
  259. return 0;
  260. }
  261. /**
  262. * @param array<int, string> $actions
  263. * @return array<int, int> scydgy_id => 最近操作 unix 时间
  264. */
  265. protected function loadOperLogTimestampMap(array $scydgyIds, array $actions): array
  266. {
  267. $out = [];
  268. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  269. $actions = array_values(array_filter(array_map('strval', $actions)));
  270. if ($scydgyIds === [] || $actions === []) {
  271. return $out;
  272. }
  273. try {
  274. $logs = Db::table('purchase_order_oper_log')
  275. ->where('scydgy_id', 'in', $scydgyIds)
  276. ->where('action', 'in', $actions)
  277. ->field('scydgy_id,createtime')
  278. ->order('id', 'asc')
  279. ->select();
  280. } catch (\Throwable $e) {
  281. $logs = [];
  282. }
  283. if (!is_array($logs)) {
  284. return $out;
  285. }
  286. foreach ($logs as $log) {
  287. if (!is_array($log)) {
  288. continue;
  289. }
  290. $sid = (int)($log['scydgy_id'] ?? 0);
  291. $ct = (int)($log['createtime'] ?? 0);
  292. if ($sid > 0 && $ct > 946684800) {
  293. $out[$sid] = isset($out[$sid]) ? max($out[$sid], $ct) : $ct;
  294. }
  295. }
  296. return $out;
  297. }
  298. /**
  299. * @param array<string, mixed> $row
  300. * @param array<int, int> $completeTsMap
  301. */
  302. protected function formatPurchaseOrderDoneTime(array $row, array $completeTsMap = []): string
  303. {
  304. $ts = $this->resolvePurchaseOrderCompleteTimestamp($row, $completeTsMap);
  305. if ($ts > 0) {
  306. return date('Y-m-d H:i:s', $ts);
  307. }
  308. return '';
  309. }
  310. /**
  311. * @param array<int, array<string, mixed>> $rows
  312. * @return array<int, array<string, mixed>>
  313. */
  314. protected function collapseExportRowsByOrder(array $rows): array
  315. {
  316. if ($rows === []) {
  317. return [];
  318. }
  319. $groups = [];
  320. foreach ($rows as $row) {
  321. if (!is_array($row)) {
  322. continue;
  323. }
  324. $dh = trim((string)($row['CCYDH'] ?? ''));
  325. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['id'] ?? 0));
  326. if (!isset($groups[$key])) {
  327. $groups[$key] = [];
  328. }
  329. $groups[$key][] = $row;
  330. }
  331. $out = [];
  332. foreach ($groups as $groupRows) {
  333. if ($groupRows === []) {
  334. continue;
  335. }
  336. usort($groupRows, function ($a, $b) {
  337. return ((int)($a['id'] ?? 0)) <=> ((int)($b['id'] ?? 0));
  338. });
  339. $head = $groupRows[0];
  340. $gymcList = [];
  341. foreach ($groupRows as $r) {
  342. $g = trim((string)($r['CGYMC'] ?? ''));
  343. if ($g !== '' && !in_array($g, $gymcList, true)) {
  344. $gymcList[] = $g;
  345. }
  346. }
  347. $merged = $head;
  348. $merged['_merge_rows'] = $groupRows;
  349. if (count($groupRows) > 1) {
  350. $merged['CGYMC'] = implode('、', $gymcList);
  351. }
  352. $latestText = '';
  353. $latestTs = 0;
  354. foreach ($groupRows as $r) {
  355. $t = trim((string)($r['createtime_text'] ?? ''));
  356. $ts = $t !== '' ? (int)strtotime($t) : 0;
  357. if ($ts > $latestTs) {
  358. $latestTs = $ts;
  359. $latestText = $t;
  360. }
  361. }
  362. if ($latestText !== '') {
  363. $merged['createtime_text'] = $latestText;
  364. }
  365. $maxId = (int)($head['id'] ?? 0);
  366. foreach ($groupRows as $r) {
  367. $maxId = max($maxId, (int)($r['id'] ?? 0));
  368. }
  369. $merged['id'] = $maxId;
  370. $out[] = $merged;
  371. }
  372. usort($out, function ($a, $b) {
  373. return ((int)($b['id'] ?? 0)) <=> ((int)($a['id'] ?? 0));
  374. });
  375. return $out;
  376. }
  377. }