Procuremenexport.php 13 KB

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