Procuremenexport.php 15 KB

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