Supplierservicescore.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\ProcuremenSupplierScore;
  5. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  6. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  7. use PhpOffice\PhpSpreadsheet\Style\Border;
  8. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  9. /**
  10. * 供应商评审表(月度记录:质量得分 / 价格得分 / 交货得分 / 最终得分)
  11. * 订单经入库评分(合格/不合格)完结后,可在此对供应商做月度评分
  12. *
  13. * @icon fa fa-trophy
  14. */
  15. class Supplierservicescore extends Backend
  16. {
  17. /** @var \app\admin\model\Supplierservicescore */
  18. protected $model = null;
  19. protected $searchFields = 'company_name';
  20. /** 有列表权限即可导出/批量保存最终得分/查看本月订单 */
  21. protected $noNeedRight = ['export', 'savefinalbatch', 'monthorders'];
  22. public function _initialize()
  23. {
  24. parent::_initialize();
  25. ProcuremenSupplierScore::ensureSchema();
  26. $this->model = new \app\admin\model\Supplierservicescore;
  27. }
  28. public function index()
  29. {
  30. $this->request->filter(['strip_tags', 'trim']);
  31. if ($this->request->isAjax()) {
  32. $ym = $this->resolveRequestYm();
  33. $keyword = $this->resolveSearchKeyword();
  34. $offset = max(0, (int)$this->request->get('offset', 0));
  35. $limit = (int)$this->request->get('limit', 50);
  36. if ($limit <= 0) {
  37. $limit = 50;
  38. }
  39. // 有搜索词:跨月查该供应商;无搜索:按查询月份展示当月
  40. $list = $keyword !== ''
  41. ? $this->loadSupplierScoreSearchList($keyword)
  42. : $this->loadMonthlySupplierScoreList($ym, '');
  43. $total = count($list);
  44. $pageRows = array_slice($list, $offset, $limit);
  45. $seqBase = $offset;
  46. $rows = [];
  47. foreach ($pageRows as $i => $item) {
  48. $rowYm = (string)($item['ym'] ?? $ym);
  49. $rows[] = [
  50. 'id' => $seqBase + $i + 1,
  51. 'seq_no' => $seqBase + $i + 1,
  52. 'company_name' => (string)($item['company_name'] ?? ''),
  53. 'quality_score' => $item['quality_score'] ?? null,
  54. 'quality_score_text' => (string)($item['quality_score_text'] ?? ''),
  55. 'price_score' => $item['price_score'] ?? null,
  56. 'price_score_text' => (string)($item['price_score_text'] ?? ''),
  57. 'delivery_score' => $item['delivery_score'] ?? null,
  58. 'delivery_score_text' => (string)($item['delivery_score_text'] ?? ''),
  59. 'value_added_score' => $item['value_added_score'] ?? null,
  60. 'value_added_score_text' => (string)($item['value_added_score_text'] ?? ''),
  61. 'final_score' => $item['final_score'] ?? null,
  62. 'final_score_text' => (string)($item['final_score_text'] ?? ''),
  63. 'final_score_saved' => !empty($item['final_score_saved']) ? 1 : 0,
  64. 'score_grade' => (string)($item['score_grade'] ?? ''),
  65. 'score_date' => (string)(($item['score_date'] ?? '') !== '' ? $item['score_date'] : $rowYm),
  66. 'ym' => $rowYm,
  67. ];
  68. }
  69. return json(['total' => $total, 'rows' => $rows]);
  70. }
  71. return $this->view->fetch();
  72. }
  73. /**
  74. * 批量保存当月最终得分与评分等级
  75. * POST: ym, rows=[{company_name, final_score, score_grade}, ...] 或 rows_json
  76. */
  77. public function savefinalbatch()
  78. {
  79. if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
  80. $this->error(__('You have no permission'));
  81. }
  82. ProcuremenSupplierScore::ensureFinalScoreTable();
  83. $ym = trim((string)$this->request->post('ym', ''));
  84. if ($ym === '') {
  85. $ym = trim((string)$this->request->param('ym', ''));
  86. }
  87. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  88. $this->error('请选择查询月份');
  89. }
  90. $rows = $this->request->post('rows/a', []);
  91. if (!is_array($rows) || $rows === []) {
  92. $rowsJson = trim((string)$this->request->post('rows_json', ''));
  93. if ($rowsJson !== '') {
  94. $decoded = json_decode($rowsJson, true);
  95. if (is_array($decoded)) {
  96. $rows = $decoded;
  97. }
  98. }
  99. }
  100. if (!is_array($rows) || $rows === []) {
  101. $this->error('没有可保存的数据');
  102. }
  103. // 按行自带 ym 分组(跨月搜索结果可同页保存)
  104. $byYm = [];
  105. foreach ($rows as $row) {
  106. if (!is_array($row)) {
  107. continue;
  108. }
  109. $rowYm = trim((string)($row['ym'] ?? ''));
  110. if (!preg_match('/^\d{4}-\d{2}$/', $rowYm)) {
  111. $rowYm = $ym;
  112. }
  113. if (!isset($byYm[$rowYm])) {
  114. $byYm[$rowYm] = [];
  115. }
  116. $byYm[$rowYm][] = $row;
  117. }
  118. $done = 0;
  119. $err = '';
  120. foreach ($byYm as $saveYm => $chunk) {
  121. $ret = ProcuremenSupplierScore::saveFinalScoresForYm($saveYm, $chunk);
  122. $done += (int)($ret['done'] ?? 0);
  123. if ($err === '') {
  124. $err = trim((string)($ret['error'] ?? ''));
  125. }
  126. }
  127. if ($done < 1) {
  128. $this->error($err !== '' ? $err : '保存失败,请检查填写的分数');
  129. }
  130. $this->success('操作成功');
  131. }
  132. /**
  133. * 本月订单明细(某供应商 + 年月)
  134. */
  135. public function monthorders()
  136. {
  137. if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
  138. $this->error(__('You have no permission'));
  139. }
  140. $this->request->filter(['strip_tags', 'trim']);
  141. $ym = trim((string)$this->request->param('ym', ''));
  142. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  143. $ym = date('Y-m');
  144. }
  145. $company = trim((string)$this->request->param('company_name', ''));
  146. if ($company === '') {
  147. $company = trim((string)$this->request->param('company', ''));
  148. }
  149. $rows = $company !== '' ? $this->loadMonthOrdersForSupplier($ym, $company) : [];
  150. $this->view->assign('ym', $ym);
  151. $this->view->assign('company_name', $company);
  152. $this->view->assign('orderRows', $rows);
  153. $this->view->assign('orderCount', count($rows));
  154. return $this->view->fetch();
  155. }
  156. /**
  157. * 导出供应商评审表
  158. * 列:序号、供应商、最终得分、评分等级
  159. */
  160. public function export()
  161. {
  162. if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
  163. $this->error(__('You have no permission'));
  164. }
  165. $ym = trim((string)$this->request->param('ym', ''));
  166. if (!preg_match('/^(\d{4})-(\d{2})$/', $ym, $m)) {
  167. $this->error('请选择查询月份');
  168. }
  169. $year = (int)$m[1];
  170. $month = (int)$m[2];
  171. if ($month < 1 || $month > 12) {
  172. $this->error('查询月份无效');
  173. }
  174. $list = $this->loadMonthlySupplierScoreList($ym, '');
  175. $title = $year . '年' . $month . '月外协加工供应商评审表';
  176. $spreadsheet = new Spreadsheet();
  177. $sheet = $spreadsheet->getActiveSheet();
  178. $sheet->setTitle('供应商评审表');
  179. $fontName = '宋体';
  180. $borderStyle = [
  181. 'borders' => [
  182. 'allBorders' => [
  183. 'borderStyle' => Border::BORDER_THIN,
  184. 'color' => ['rgb' => '000000'],
  185. ],
  186. ],
  187. ];
  188. $centerAlign = [
  189. 'horizontal' => Alignment::HORIZONTAL_CENTER,
  190. 'vertical' => Alignment::VERTICAL_CENTER,
  191. 'wrapText' => true,
  192. ];
  193. $sheet->mergeCells('A1:D1');
  194. $sheet->setCellValue('A1', $title);
  195. $sheet->getRowDimension(1)->setRowHeight(36);
  196. $sheet->getStyle('A1')->getFont()->setName($fontName)->setBold(true)->setSize(20);
  197. $sheet->getStyle('A1')->getAlignment()->applyFromArray($centerAlign);
  198. $sheet->setCellValue('A2', '序号');
  199. $sheet->setCellValue('B2', '供应商');
  200. $sheet->setCellValue('C2', '最终得分');
  201. $sheet->setCellValue('D2', '评分等级');
  202. $sheet->getRowDimension(2)->setRowHeight(26);
  203. $sheet->getStyle('A2:D2')->getFont()->setName($fontName)->setBold(true)->setSize(14);
  204. $sheet->getStyle('A2:D2')->getAlignment()->applyFromArray($centerAlign);
  205. $rowNum = 3;
  206. if ($list === []) {
  207. $sheet->mergeCells('A3:D3');
  208. $sheet->setCellValue('A3', '(该月暂无供应商评审记录)');
  209. $sheet->getRowDimension(3)->setRowHeight(26);
  210. $sheet->getStyle('A3')->getFont()->setName($fontName)->setSize(12);
  211. $sheet->getStyle('A3')->getAlignment()->applyFromArray($centerAlign);
  212. $rowNum = 4;
  213. } else {
  214. $i = 1;
  215. foreach ($list as $item) {
  216. $sheet->setCellValue('A' . $rowNum, $i);
  217. $sheet->setCellValue('B' . $rowNum, (string)($item['company_name'] ?? ''));
  218. $sheet->setCellValue('C' . $rowNum, (string)($item['final_score_text'] ?? ''));
  219. $sheet->setCellValue('D' . $rowNum, (string)($item['score_grade'] ?? ''));
  220. $sheet->getRowDimension($rowNum)->setRowHeight(24);
  221. $rowNum++;
  222. $i++;
  223. }
  224. }
  225. $lastRow = max(2, $rowNum - 1);
  226. $sheet->getStyle('A1:D' . $lastRow)->applyFromArray($borderStyle);
  227. $sheet->getStyle('A3:D' . $lastRow)->getFont()->setName($fontName)->setSize(12);
  228. $sheet->getStyle('A3:D' . $lastRow)->getAlignment()->applyFromArray($centerAlign);
  229. $sheet->getColumnDimension('A')->setWidth(12);
  230. $sheet->getColumnDimension('B')->setWidth(48);
  231. $sheet->getColumnDimension('C')->setWidth(14);
  232. $sheet->getColumnDimension('D')->setWidth(12);
  233. $sheet->getPageSetup()->setFitToPage(true)->setFitToWidth(1)->setFitToHeight(0);
  234. $filename = $title . '.xlsx';
  235. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  236. header('Content-Disposition: attachment;filename="' . rawurlencode($filename) . '"');
  237. header('Cache-Control: max-age=0');
  238. $writer = new Xlsx($spreadsheet);
  239. $writer->save('php://output');
  240. $spreadsheet->disconnectWorksheets();
  241. unset($spreadsheet);
  242. exit;
  243. }
  244. /**
  245. * 月度评审记录列表(仅展示,最终得分可人工填写)
  246. *
  247. * @return array<int, array<string, mixed>>
  248. */
  249. protected function loadMonthlySupplierScoreList(string $ym, string $keyword = ''): array
  250. {
  251. $ym = trim($ym);
  252. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  253. return [];
  254. }
  255. ProcuremenSupplierScore::ensureSchema();
  256. $monthlyMap = ProcuremenSupplierScore::loadMonthlyMapByYm($ym);
  257. $keyword = trim($keyword);
  258. $list = [];
  259. foreach ($monthlyMap as $name => $item) {
  260. if ($keyword !== '' && mb_stripos($name, $keyword) === false) {
  261. continue;
  262. }
  263. $list[] = $this->buildSupplierScoreListItem($name, $item, $ym);
  264. }
  265. usort($list, [$this, 'sortSupplierScoreListItems']);
  266. return $list;
  267. }
  268. /**
  269. * 按供应商关键词跨月搜索(不限查询月份)
  270. *
  271. * @return array<int, array<string, mixed>>
  272. */
  273. protected function loadSupplierScoreSearchList(string $keyword): array
  274. {
  275. $keyword = trim($keyword);
  276. if ($keyword === '') {
  277. return [];
  278. }
  279. ProcuremenSupplierScore::ensureSchema();
  280. ProcuremenSupplierScore::ensureFinalScoreTable();
  281. try {
  282. $rows = \think\Db::table(ProcuremenSupplierScore::TABLE_FINAL)
  283. ->where('company_name', 'like', '%' . addcslashes($keyword, '%_\\') . '%')
  284. ->field('ym,company_name,score,quality_score,price_score,delivery_score,value_added_score,final_score,score_grade')
  285. ->order('ym', 'desc')
  286. ->order('company_name', 'asc')
  287. ->select();
  288. } catch (\Throwable $e) {
  289. return [];
  290. }
  291. if (!is_array($rows)) {
  292. return [];
  293. }
  294. $list = [];
  295. foreach ($rows as $r) {
  296. if (!is_array($r)) {
  297. continue;
  298. }
  299. $name = trim((string)($r['company_name'] ?? ''));
  300. $rowYm = ProcuremenSupplierScore::formatScoreYm($r['ym'] ?? '');
  301. if ($name === '' || $rowYm === '') {
  302. continue;
  303. }
  304. $quality = ProcuremenSupplierScore::readOptionalScoreValue($r['quality_score'] ?? null);
  305. $price = ProcuremenSupplierScore::readOptionalScoreValue($r['price_score'] ?? null);
  306. $delivery = ProcuremenSupplierScore::readOptionalScoreValue($r['delivery_score'] ?? null);
  307. $valueAdded = ProcuremenSupplierScore::readOptionalScoreValue($r['value_added_score'] ?? null);
  308. $final = ProcuremenSupplierScore::readOptionalScoreValue($r['final_score'] ?? null);
  309. $item = [
  310. 'quality_score' => $quality,
  311. 'price_score' => $price,
  312. 'delivery_score' => $delivery,
  313. 'value_added_score' => $valueAdded,
  314. 'final_score' => $final,
  315. 'final_saved' => $final !== null ? 1 : 0,
  316. 'score_grade' => ProcuremenSupplierScore::normalizeScoreGrade($r['score_grade'] ?? ''),
  317. 'score_date' => $rowYm,
  318. ];
  319. $list[] = $this->buildSupplierScoreListItem($name, $item, $rowYm);
  320. }
  321. usort($list, [$this, 'sortSupplierScoreListItems']);
  322. return $list;
  323. }
  324. /**
  325. * @param array<string, mixed> $item
  326. * @return array<string, mixed>
  327. */
  328. protected function buildSupplierScoreListItem(string $name, array $item, string $ym): array
  329. {
  330. $quality = array_key_exists('quality_score', $item) ? $item['quality_score'] : null;
  331. $price = array_key_exists('price_score', $item) ? $item['price_score'] : null;
  332. $delivery = array_key_exists('delivery_score', $item) ? $item['delivery_score'] : null;
  333. $valueAdded = array_key_exists('value_added_score', $item) ? $item['value_added_score'] : null;
  334. if ($quality !== null) {
  335. $quality = (float)$quality;
  336. }
  337. if ($price !== null) {
  338. $price = (float)$price;
  339. }
  340. if ($delivery !== null) {
  341. $delivery = (float)$delivery;
  342. }
  343. if ($valueAdded !== null) {
  344. $valueAdded = (float)$valueAdded;
  345. }
  346. $hasFinal = !empty($item['final_saved']);
  347. $final = $hasFinal ? (float)($item['final_score'] ?? 0) : null;
  348. if ($final === null) {
  349. $final = ProcuremenSupplierScore::sumFinalScore($quality, $price, $delivery, $valueAdded);
  350. }
  351. $grade = ProcuremenSupplierScore::normalizeScoreGrade($item['score_grade'] ?? '');
  352. if ($grade === '' && $final !== null) {
  353. $grade = ProcuremenSupplierScore::gradeFromFinalScore($final);
  354. }
  355. $sortScore = $final !== null
  356. ? (float)$final
  357. : (($quality ?? 0) + ($price ?? 0) + ($delivery ?? 0) + ($valueAdded ?? 0));
  358. $scoreDate = (string)($item['score_date'] ?? '');
  359. if ($scoreDate === '') {
  360. $scoreDate = ProcuremenSupplierScore::formatScoreYm($ym);
  361. }
  362. return [
  363. 'company_name' => $name,
  364. 'ym' => ProcuremenSupplierScore::formatScoreYm($ym),
  365. 'quality_score' => $quality,
  366. 'quality_score_text' => ProcuremenSupplierScore::formatOptionalScore($quality),
  367. 'price_score' => $price,
  368. 'price_score_text' => ProcuremenSupplierScore::formatOptionalScore($price),
  369. 'delivery_score' => $delivery,
  370. 'delivery_score_text' => ProcuremenSupplierScore::formatOptionalScore($delivery),
  371. 'value_added_score' => $valueAdded,
  372. 'value_added_score_text' => ProcuremenSupplierScore::formatOptionalScore($valueAdded),
  373. 'final_score' => $final,
  374. 'final_score_text' => $final !== null ? ProcuremenSupplierScore::formatOptionalScore($final) : '',
  375. 'final_score_saved' => $hasFinal ? 1 : 0,
  376. 'score_grade' => $grade,
  377. 'score_date' => $scoreDate,
  378. 'sort_score' => $sortScore,
  379. ];
  380. }
  381. /**
  382. * @param array<string, mixed> $a
  383. * @param array<string, mixed> $b
  384. */
  385. protected function sortSupplierScoreListItems(array $a, array $b): int
  386. {
  387. $ya = (string)($a['ym'] ?? '');
  388. $yb = (string)($b['ym'] ?? '');
  389. if ($ya !== $yb) {
  390. return strcmp($yb, $ya);
  391. }
  392. $sa = (float)($a['sort_score'] ?? 0);
  393. $sb = (float)($b['sort_score'] ?? 0);
  394. if ($sa !== $sb) {
  395. return $sb <=> $sa;
  396. }
  397. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  398. }
  399. protected function resolveRequestYm(): string
  400. {
  401. $ym = trim((string)$this->request->get('ym', ''));
  402. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  403. return $ym;
  404. }
  405. $filterRaw = $this->request->get('filter', '');
  406. if (is_string($filterRaw) && $filterRaw !== '') {
  407. $filter = json_decode($filterRaw, true);
  408. if (is_array($filter)) {
  409. $fy = trim((string)($filter['ym'] ?? ''));
  410. if (preg_match('/^\d{4}-\d{2}$/', $fy)) {
  411. return $fy;
  412. }
  413. }
  414. }
  415. if (preg_match('/^(\d{4})\D+(\d{1,2})/', $ym, $m)) {
  416. return sprintf('%04d-%02d', (int)$m[1], (int)$m[2]);
  417. }
  418. return date('Y-m');
  419. }
  420. protected function resolveSearchKeyword(): string
  421. {
  422. $keyword = trim((string)$this->request->get('search', ''));
  423. if ($keyword !== '') {
  424. return $keyword;
  425. }
  426. $filterRaw = $this->request->get('filter', '');
  427. if (is_string($filterRaw) && $filterRaw !== '') {
  428. $filter = json_decode($filterRaw, true);
  429. if (is_array($filter)) {
  430. return trim((string)($filter['company_name'] ?? ''));
  431. }
  432. }
  433. return '';
  434. }
  435. /**
  436. * 某供应商某月参与评分的订单明细(开标/指定后按时间写入的评分记录)
  437. * 一单一行(多工序顿号间隔);按开标/指定时间倒序,不把整月汇总成一行
  438. *
  439. * @return array<int, array<string, mixed>>
  440. */
  441. /**
  442. * 本月订单明细:已下发订单按「下发批次」(pick_time) 分行;
  443. * 同一批次内多工序顿号合并,不同下发时间不合并。
  444. *
  445. * @return array<int, array<string, mixed>>
  446. */
  447. protected function loadMonthOrdersForSupplier(string $ym, string $companyName): array
  448. {
  449. $ym = trim($ym);
  450. $companyName = trim($companyName);
  451. if (!preg_match('/^\d{4}-\d{2}$/', $ym) || $companyName === '') {
  452. return [];
  453. }
  454. ProcuremenSupplierScore::ensureSchema();
  455. try {
  456. $scoreRows = \think\Db::table(ProcuremenSupplierScore::TABLE_SCORE)
  457. ->where('ym', $ym)
  458. ->where('company_name', $companyName)
  459. ->field('ccydh,score,rank_no,quality_score,price_score,price_sum,lead_score,lead_days_sum,createtime')
  460. ->order('createtime', 'desc')
  461. ->order('ccydh', 'asc')
  462. ->select();
  463. } catch (\Throwable $e) {
  464. return [];
  465. }
  466. if (!is_array($scoreRows) || $scoreRows === []) {
  467. return [];
  468. }
  469. $scoreByCcydh = [];
  470. foreach ($scoreRows as $r) {
  471. if (!is_array($r)) {
  472. continue;
  473. }
  474. $c = trim((string)($r['ccydh'] ?? ''));
  475. // 手工新增订单号 YW… 不进本月订单明细
  476. if ($c === '' || stripos($c, 'YW') === 0) {
  477. continue;
  478. }
  479. // 同单可能有重复评分行时保留最新一条(已按 createtime desc)
  480. if (!isset($scoreByCcydh[$c])) {
  481. $scoreByCcydh[$c] = $r;
  482. }
  483. }
  484. if ($scoreByCcydh === []) {
  485. return [];
  486. }
  487. $manualCcydh = [];
  488. /** @var array<string, array<string, array<string, mixed>>> $batchesByCcydh */
  489. $batchesByCcydh = [];
  490. /** @var array<int, array<string, mixed>> $issuedPoRows */
  491. $issuedPoRows = [];
  492. $sidList = [];
  493. try {
  494. $poRows = \think\Db::table('purchase_order')
  495. ->where('CCYDH', 'in', array_keys($scoreByCcydh))
  496. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  497. ->field('CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,ceilingPrice,pick_company_name,wflow_status,status,pick_time,scydgy_id')
  498. ->order('id', 'asc')
  499. ->select();
  500. } catch (\Throwable $e) {
  501. $poRows = [];
  502. }
  503. if (is_array($poRows)) {
  504. foreach ($poRows as $po) {
  505. if (!is_array($po)) {
  506. continue;
  507. }
  508. $c = trim((string)($po['CCYDH'] ?? ''));
  509. if ($c === '' || !isset($scoreByCcydh[$c])) {
  510. continue;
  511. }
  512. $sid = (int)($po['scydgy_id'] ?? 0);
  513. if ($sid < 0) {
  514. $manualCcydh[$c] = true;
  515. continue;
  516. }
  517. if (isset($manualCcydh[$c])) {
  518. continue;
  519. }
  520. $pickTime = trim((string)($po['pick_time'] ?? ''));
  521. if ($pickTime === '' || preg_match('/^0000-00-00/', $pickTime)) {
  522. continue;
  523. }
  524. $issuedPoRows[] = $po;
  525. if ($sid > 0) {
  526. $sidList[$sid] = true;
  527. }
  528. }
  529. }
  530. // 按工序首次下发日志时间分批(避免整单 pick_time 被后次下发覆盖后合到一行)
  531. $firstIssueBySid = $this->loadFirstIssueTimeByScydgyIds(array_keys($sidList));
  532. foreach ($issuedPoRows as $po) {
  533. if (isset($manualCcydh[trim((string)($po['CCYDH'] ?? ''))])) {
  534. continue;
  535. }
  536. $c = trim((string)($po['CCYDH'] ?? ''));
  537. $sid = (int)($po['scydgy_id'] ?? 0);
  538. $pickTime = trim((string)($po['pick_time'] ?? ''));
  539. $batchKey = '';
  540. if ($sid > 0 && isset($firstIssueBySid[$sid])) {
  541. $batchKey = $firstIssueBySid[$sid];
  542. }
  543. if ($batchKey === '') {
  544. $batchKey = $pickTime;
  545. }
  546. if ($batchKey === '' || preg_match('/^0000-00-00/', $batchKey)) {
  547. continue;
  548. }
  549. // 同一分钟内视为同一次下发(循环写入可能差 1 秒)
  550. $batchGroup = $batchKey;
  551. if (preg_match('/^(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2})/', $batchKey, $m)) {
  552. $batchGroup = $m[1];
  553. }
  554. if (!isset($batchesByCcydh[$c])) {
  555. $batchesByCcydh[$c] = [];
  556. }
  557. if (!isset($batchesByCcydh[$c][$batchGroup])) {
  558. $batchesByCcydh[$c][$batchGroup] = [
  559. 'scydgy_id' => $sid > 0 ? $sid : 0,
  560. 'scydgy_ids' => [],
  561. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  562. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  563. 'CGYMC_list' => [],
  564. 'CDW' => trim((string)($po['CDW'] ?? '')),
  565. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  566. 'wflow_status' => trim((string)($po['wflow_status'] ?? '')),
  567. 'status' => trim((string)($po['status'] ?? '')),
  568. 'pick_time' => $batchKey,
  569. 'completed' => false,
  570. 'picked_match' => false,
  571. ];
  572. }
  573. $batch = &$batchesByCcydh[$c][$batchGroup];
  574. if ($batch['scydgy_id'] <= 0 && $sid > 0) {
  575. $batch['scydgy_id'] = $sid;
  576. }
  577. if ($sid > 0 && !in_array($sid, $batch['scydgy_ids'], true)) {
  578. $batch['scydgy_ids'][] = $sid;
  579. }
  580. // 展示时间取该批次内最早时间
  581. if ($batch['pick_time'] === '' || strcmp($batchKey, $batch['pick_time']) < 0) {
  582. $batch['pick_time'] = $batchKey;
  583. }
  584. if ($batch['CYJMC'] === '') {
  585. $batch['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  586. }
  587. if ($batch['CCLBMMC'] === '') {
  588. $batch['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  589. }
  590. $g = trim((string)($po['CGYMC'] ?? ''));
  591. if ($g !== '' && !in_array($g, $batch['CGYMC_list'], true)) {
  592. $batch['CGYMC_list'][] = $g;
  593. }
  594. $pn = trim((string)($po['pick_company_name'] ?? ''));
  595. if ($pn !== '') {
  596. if ($batch['pick_company_name'] === '') {
  597. $batch['pick_company_name'] = $pn;
  598. }
  599. if ($pn === $companyName) {
  600. $batch['picked_match'] = true;
  601. }
  602. }
  603. if (\app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  604. $batch['completed'] = true;
  605. $batch['status'] = \app\common\library\ProcuremenStatus::PO_COMPLETED;
  606. }
  607. if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  608. $batch['wflow_status'] = \app\common\library\ProcuremenStatus::WFLOW_APPROVED;
  609. } elseif ($batch['wflow_status'] === '' && trim((string)($po['wflow_status'] ?? '')) !== '') {
  610. $batch['wflow_status'] = trim((string)$po['wflow_status']);
  611. }
  612. unset($batch);
  613. }
  614. $out = [];
  615. $allSids = [];
  616. foreach ($batchesByCcydh as $ccydhBatches) {
  617. if (!is_array($ccydhBatches)) {
  618. continue;
  619. }
  620. foreach ($ccydhBatches as $batch) {
  621. if (!is_array($batch)) {
  622. continue;
  623. }
  624. foreach ((array)($batch['scydgy_ids'] ?? []) as $sidItem) {
  625. $sidItem = (int)$sidItem;
  626. if ($sidItem > 0) {
  627. $allSids[$sidItem] = true;
  628. }
  629. }
  630. $one = (int)($batch['scydgy_id'] ?? 0);
  631. if ($one > 0) {
  632. $allSids[$one] = true;
  633. }
  634. }
  635. }
  636. $inboundBySid = $this->loadInboundResultByScydgyIds(array_keys($allSids));
  637. foreach ($scoreByCcydh as $ccydh => $r) {
  638. if (isset($manualCcydh[$ccydh]) || !isset($batchesByCcydh[$ccydh])) {
  639. continue;
  640. }
  641. foreach ($batchesByCcydh[$ccydh] as $batch) {
  642. if (!is_array($batch)) {
  643. continue;
  644. }
  645. $pickTimeRaw = trim((string)($batch['pick_time'] ?? ''));
  646. if ($pickTimeRaw === '') {
  647. continue;
  648. }
  649. $gymcList = is_array($batch['CGYMC_list'] ?? null) ? $batch['CGYMC_list'] : [];
  650. // 与详情页一致:采购确认通过或已完结后才展示中标/未中标
  651. $showBid = !empty($batch['completed'])
  652. || \app\common\library\ProcuremenStatus::isPoCompleted($batch['status'] ?? '')
  653. || \app\common\library\ProcuremenStatus::isWflowApproved($batch['wflow_status'] ?? '');
  654. $isPicked = !empty($batch['picked_match']) ? 1 : 0;
  655. $inboundResult = '';
  656. $sidCandidates = is_array($batch['scydgy_ids'] ?? null) ? $batch['scydgy_ids'] : [];
  657. $mainSid = (int)($batch['scydgy_id'] ?? 0);
  658. if ($mainSid > 0 && !in_array($mainSid, $sidCandidates, true)) {
  659. $sidCandidates[] = $mainSid;
  660. }
  661. foreach ($sidCandidates as $sidItem) {
  662. $sidItem = (int)$sidItem;
  663. if ($sidItem > 0 && isset($inboundBySid[$sidItem]) && $inboundBySid[$sidItem] !== '') {
  664. $inboundResult = $inboundBySid[$sidItem];
  665. break;
  666. }
  667. }
  668. $out[] = [
  669. 'seq_no' => 0,
  670. 'scydgy_id' => (int)($batch['scydgy_id'] ?? 0),
  671. 'CCYDH' => $ccydh,
  672. 'CYJMC' => (string)($batch['CYJMC'] ?? ''),
  673. 'CCLBMMC' => (string)($batch['CCLBMMC'] ?? ''),
  674. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  675. 'CDW' => (string)($batch['CDW'] ?? ''),
  676. 'pick_company_name' => (string)($batch['pick_company_name'] ?? ''),
  677. 'wflow_status' => (string)($batch['wflow_status'] ?? ''),
  678. 'status' => (string)($batch['status'] ?? ''),
  679. 'progress_text' => $this->formatMonthOrderProgressText($batch),
  680. 'pick_time' => $pickTimeRaw,
  681. 'issue_time' => \app\common\library\ProcuremenTime::formatDisplayDateTime($pickTimeRaw),
  682. 'score' => $r['score'] ?? null,
  683. 'rank_no' => (int)($r['rank_no'] ?? 0),
  684. 'quality_score' => $r['quality_score'] ?? null,
  685. 'price_score' => $r['price_score'] ?? null,
  686. 'price_sum' => $r['price_sum'] ?? null,
  687. 'lead_score' => $r['lead_score'] ?? null,
  688. 'lead_days_sum' => $r['lead_days_sum'] ?? null,
  689. 'is_picked' => $isPicked,
  690. 'show_bid_result' => $showBid ? 1 : 0,
  691. 'inbound_result' => $inboundResult,
  692. ];
  693. }
  694. }
  695. usort($out, static function ($a, $b) {
  696. $ta = (string)($a['pick_time'] ?? '');
  697. $tb = (string)($b['pick_time'] ?? '');
  698. if ($ta !== $tb) {
  699. return strcmp($tb, $ta);
  700. }
  701. $ca = (string)($a['CCYDH'] ?? '');
  702. $cb = (string)($b['CCYDH'] ?? '');
  703. return strcmp($ca, $cb);
  704. });
  705. $total = count($out);
  706. $seq = $total;
  707. foreach ($out as &$row) {
  708. $row['seq_no'] = $seq;
  709. $seq--;
  710. }
  711. unset($row);
  712. return $out;
  713. }
  714. /**
  715. * 批量取各工序首次「下发」操作时间(用于本月明细按批次拆行)
  716. *
  717. * @param int[] $scydgyIds
  718. * @return array<int, string> scydgy_id => Y-m-d H:i:s
  719. */
  720. protected function loadFirstIssueTimeByScydgyIds(array $scydgyIds): array
  721. {
  722. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds), static function ($id) {
  723. return $id > 0;
  724. })));
  725. if ($scydgyIds === []) {
  726. return [];
  727. }
  728. $acts = \app\common\library\ProcuremenOperLog::expandActionQueryValues('issue_submit');
  729. if ($acts === []) {
  730. return [];
  731. }
  732. try {
  733. $logs = \think\Db::table('purchase_order_oper_log')
  734. ->where(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID, 'in', $scydgyIds)
  735. ->where(\app\common\library\ProcuremenOperLog::COL_ACTION, 'in', $acts)
  736. ->field(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID . ',' . \app\common\library\ProcuremenOperLog::COL_TIME)
  737. ->order('id', 'asc')
  738. ->select();
  739. } catch (\Throwable $e) {
  740. return [];
  741. }
  742. $map = [];
  743. if (!is_array($logs)) {
  744. return [];
  745. }
  746. foreach ($logs as $lg) {
  747. if (!is_array($lg)) {
  748. continue;
  749. }
  750. $sid = (int)($lg[\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  751. if ($sid <= 0 || isset($map[$sid])) {
  752. continue;
  753. }
  754. $t = trim((string)($lg[\app\common\library\ProcuremenOperLog::COL_TIME] ?? ''));
  755. if ($t === '' || preg_match('/^0000-00-00/', $t)) {
  756. continue;
  757. }
  758. if (is_numeric($t) && (int)$t > 946684800) {
  759. $t = date('Y-m-d H:i:s', (int)$t);
  760. } else {
  761. $t = \app\common\library\ProcuremenTime::formatDisplayDateTime($t);
  762. }
  763. if ($t === '') {
  764. continue;
  765. }
  766. $map[$sid] = $t;
  767. }
  768. return $map;
  769. }
  770. /**
  771. * 当前进度:已完结优先;终审通过也显示已完结;其余展示流程阶段
  772. *
  773. * @param array<string, mixed> $po
  774. */
  775. protected function formatMonthOrderProgressText(array $po): string
  776. {
  777. if (!empty($po['completed']) || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  778. return \app\common\library\ProcuremenStatus::PO_COMPLETED;
  779. }
  780. // 采购终审通过后待入库评分,合格/不合格后才完结
  781. if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  782. return '待入库评分';
  783. }
  784. $w = \app\common\library\ProcuremenStatus::normalizeWflowStatus($po['wflow_status'] ?? '');
  785. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_APPROVAL) {
  786. return '待采购确认';
  787. }
  788. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_CONFIRM) {
  789. return '待确认供应商';
  790. }
  791. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_ISSUE) {
  792. return '待协助下发';
  793. }
  794. return $w !== '' ? $w : '—';
  795. }
  796. /**
  797. * 批量读取入库评分结果(合格/不合格)
  798. *
  799. * @param int[] $scydgyIds
  800. * @return array<int, string> scydgy_id => 合格|不合格
  801. */
  802. protected function loadInboundResultByScydgyIds(array $scydgyIds): array
  803. {
  804. $ids = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  805. if ($ids === []) {
  806. return [];
  807. }
  808. $out = [];
  809. try {
  810. $rows = \think\Db::table('purchase_order_inbound_score')
  811. ->where('scydgy_id', 'in', $ids)
  812. ->field('scydgy_id,result')
  813. ->select();
  814. } catch (\Throwable $e) {
  815. return [];
  816. }
  817. if (!is_array($rows)) {
  818. return [];
  819. }
  820. foreach ($rows as $r) {
  821. if (!is_array($r)) {
  822. continue;
  823. }
  824. $sid = (int)($r['scydgy_id'] ?? 0);
  825. $result = trim((string)($r['result'] ?? ''));
  826. if ($sid <= 0 || ($result !== '合格' && $result !== '不合格')) {
  827. continue;
  828. }
  829. $out[$sid] = $result;
  830. }
  831. return $out;
  832. }
  833. }