Supplierservicescore.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. // 默认只读月度表,避免进页全量重算卡住;点「刷新」带 resync=1 再按规则同步
  40. $forceSync = (string)$this->request->param('resync', '0') === '1';
  41. $list = $keyword !== ''
  42. ? $this->loadSupplierScoreSearchList($keyword)
  43. : $this->loadMonthlySupplierScoreList($ym, '', $forceSync);
  44. $total = count($list);
  45. $pageRows = array_slice($list, $offset, $limit);
  46. $seqBase = $offset;
  47. $rows = [];
  48. foreach ($pageRows as $i => $item) {
  49. $rowYm = (string)($item['ym'] ?? $ym);
  50. $rows[] = [
  51. 'id' => $seqBase + $i + 1,
  52. 'seq_no' => $seqBase + $i + 1,
  53. 'company_name' => (string)($item['company_name'] ?? ''),
  54. 'quality_score' => $item['quality_score'] ?? null,
  55. 'quality_score_text' => (string)($item['quality_score_text'] ?? ''),
  56. 'price_score' => $item['price_score'] ?? null,
  57. 'price_score_text' => (string)($item['price_score_text'] ?? ''),
  58. 'delivery_score' => $item['delivery_score'] ?? null,
  59. 'delivery_score_text' => (string)($item['delivery_score_text'] ?? ''),
  60. 'value_added_score' => $item['value_added_score'] ?? null,
  61. 'value_added_score_text' => (string)($item['value_added_score_text'] ?? ''),
  62. 'final_score' => $item['final_score'] ?? null,
  63. 'final_score_text' => (string)($item['final_score_text'] ?? ''),
  64. 'final_score_saved' => !empty($item['final_score_saved']) ? 1 : 0,
  65. 'score_grade' => (string)($item['score_grade'] ?? ''),
  66. 'score_date' => (string)(($item['score_date'] ?? '') !== '' ? $item['score_date'] : $rowYm),
  67. 'ym' => $rowYm,
  68. ];
  69. }
  70. return json(['total' => $total, 'rows' => $rows]);
  71. }
  72. $defaultYm = ProcuremenSupplierScore::latestReviewYm();
  73. if (!preg_match('/^\d{4}-\d{2}$/', $defaultYm)) {
  74. $defaultYm = date('Y-m');
  75. }
  76. $this->assign('defaultYm', $defaultYm);
  77. $this->assignconfig('supplierScoreDefaultYm', $defaultYm);
  78. return $this->view->fetch();
  79. }
  80. /**
  81. * 批量保存当月最终得分与评分等级
  82. * POST: ym, rows=[{company_name, final_score, score_grade}, ...] 或 rows_json
  83. */
  84. public function savefinalbatch()
  85. {
  86. if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
  87. $this->error(__('You have no permission'));
  88. }
  89. ProcuremenSupplierScore::ensureFinalScoreTable();
  90. $ym = trim((string)$this->request->post('ym', ''));
  91. if ($ym === '') {
  92. $ym = trim((string)$this->request->param('ym', ''));
  93. }
  94. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  95. $this->error('请选择查询月份');
  96. }
  97. $rows = $this->request->post('rows/a', []);
  98. if (!is_array($rows) || $rows === []) {
  99. $rowsJson = trim((string)$this->request->post('rows_json', ''));
  100. if ($rowsJson !== '') {
  101. $decoded = json_decode($rowsJson, true);
  102. if (is_array($decoded)) {
  103. $rows = $decoded;
  104. }
  105. }
  106. }
  107. if (!is_array($rows) || $rows === []) {
  108. $this->error('没有可保存的数据');
  109. }
  110. // 按行自带 ym 分组(跨月搜索结果可同页保存)
  111. $byYm = [];
  112. foreach ($rows as $row) {
  113. if (!is_array($row)) {
  114. continue;
  115. }
  116. $rowYm = trim((string)($row['ym'] ?? ''));
  117. if (!preg_match('/^\d{4}-\d{2}$/', $rowYm)) {
  118. $rowYm = $ym;
  119. }
  120. if (!isset($byYm[$rowYm])) {
  121. $byYm[$rowYm] = [];
  122. }
  123. $byYm[$rowYm][] = $row;
  124. }
  125. $done = 0;
  126. $err = '';
  127. foreach ($byYm as $saveYm => $chunk) {
  128. $ret = ProcuremenSupplierScore::saveFinalScoresForYm($saveYm, $chunk);
  129. $done += (int)($ret['done'] ?? 0);
  130. if ($err === '') {
  131. $err = trim((string)($ret['error'] ?? ''));
  132. }
  133. }
  134. if ($done < 1) {
  135. $this->error($err !== '' ? $err : '保存失败,请检查填写的分数');
  136. }
  137. $this->success('操作成功');
  138. }
  139. /**
  140. * 本月订单明细(某供应商 + 年月)
  141. */
  142. public function monthorders()
  143. {
  144. if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
  145. $this->error(__('You have no permission'));
  146. }
  147. $this->request->filter(['strip_tags', 'trim']);
  148. $ym = trim((string)$this->request->param('ym', ''));
  149. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  150. $ym = date('Y-m');
  151. }
  152. $company = trim((string)$this->request->param('company_name', ''));
  153. if ($company === '') {
  154. $company = trim((string)$this->request->param('company', ''));
  155. }
  156. $rows = $company !== '' ? $this->loadMonthOrdersForSupplier($ym, $company) : [];
  157. $this->view->assign('ym', $ym);
  158. $this->view->assign('company_name', $company);
  159. $this->view->assign('orderRows', $rows);
  160. $this->view->assign('orderCount', count($rows));
  161. return $this->view->fetch();
  162. }
  163. /**
  164. * 导出供应商评审表(图二样式)
  165. * 列:序号、供应商名称、质量、交货、价格、增值服务、总分、评审等级
  166. */
  167. public function export()
  168. {
  169. if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
  170. $this->error(__('You have no permission'));
  171. }
  172. $ym = trim((string)$this->request->param('ym', ''));
  173. if (!preg_match('/^(\d{4})-(\d{2})$/', $ym, $m)) {
  174. $this->error('请选择查询月份');
  175. }
  176. $year = (int)$m[1];
  177. $month = (int)$m[2];
  178. if ($month < 1 || $month > 12) {
  179. $this->error('查询月份无效');
  180. }
  181. $list = $this->loadMonthlySupplierScoreList($ym, '', false);
  182. $title = $year . '年' . $month . '月外协加工供应商评审表';
  183. $spreadsheet = new Spreadsheet();
  184. $sheet = $spreadsheet->getActiveSheet();
  185. $sheet->setTitle('供应商评审表');
  186. $fontName = '宋体';
  187. $borderStyle = [
  188. 'borders' => [
  189. 'allBorders' => [
  190. 'borderStyle' => Border::BORDER_THIN,
  191. 'color' => ['rgb' => '000000'],
  192. ],
  193. ],
  194. ];
  195. $centerAlign = [
  196. 'horizontal' => Alignment::HORIZONTAL_CENTER,
  197. 'vertical' => Alignment::VERTICAL_CENTER,
  198. 'wrapText' => true,
  199. ];
  200. $sheet->mergeCells('A1:H1');
  201. $sheet->setCellValue('A1', $title);
  202. $sheet->getRowDimension(1)->setRowHeight(36);
  203. $sheet->getStyle('A1')->getFont()->setName($fontName)->setBold(true)->setSize(20);
  204. $sheet->getStyle('A1')->getAlignment()->applyFromArray($centerAlign);
  205. $headers = ['序号', '供应商名称', '质量', '交货', '价格', '增值服务', '总分', '评审等级'];
  206. foreach ($headers as $idx => $label) {
  207. $col = chr(ord('A') + $idx);
  208. $sheet->setCellValue($col . '2', $label);
  209. }
  210. $sheet->getRowDimension(2)->setRowHeight(26);
  211. $sheet->getStyle('A2:H2')->getFont()->setName($fontName)->setBold(true)->setSize(14);
  212. $sheet->getStyle('A2:H2')->getAlignment()->applyFromArray($centerAlign);
  213. $rowNum = 3;
  214. if ($list === []) {
  215. $sheet->mergeCells('A3:H3');
  216. $sheet->setCellValue('A3', '(该月暂无供应商评审记录)');
  217. $sheet->getRowDimension(3)->setRowHeight(26);
  218. $sheet->getStyle('A3')->getFont()->setName($fontName)->setSize(12);
  219. $sheet->getStyle('A3')->getAlignment()->applyFromArray($centerAlign);
  220. $rowNum = 4;
  221. } else {
  222. $i = 1;
  223. foreach ($list as $item) {
  224. $sheet->setCellValue('A' . $rowNum, $i);
  225. $sheet->setCellValue('B' . $rowNum, (string)($item['company_name'] ?? ''));
  226. $sheet->setCellValue('C' . $rowNum, (string)($item['quality_score_text'] ?? ''));
  227. $sheet->setCellValue('D' . $rowNum, (string)($item['delivery_score_text'] ?? ''));
  228. $sheet->setCellValue('E' . $rowNum, (string)($item['price_score_text'] ?? ''));
  229. $sheet->setCellValue('F' . $rowNum, (string)($item['value_added_score_text'] ?? ''));
  230. $sheet->setCellValue('G' . $rowNum, (string)($item['final_score_text'] ?? ''));
  231. $sheet->setCellValue('H' . $rowNum, (string)($item['score_grade'] ?? ''));
  232. $sheet->getRowDimension($rowNum)->setRowHeight(24);
  233. $rowNum++;
  234. $i++;
  235. }
  236. }
  237. $lastRow = max(2, $rowNum - 1);
  238. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray($borderStyle);
  239. $sheet->getStyle('A3:H' . $lastRow)->getFont()->setName($fontName)->setSize(12);
  240. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->applyFromArray($centerAlign);
  241. $sheet->getColumnDimension('A')->setWidth(10);
  242. $sheet->getColumnDimension('B')->setWidth(48);
  243. $sheet->getColumnDimension('C')->setWidth(12);
  244. $sheet->getColumnDimension('D')->setWidth(12);
  245. $sheet->getColumnDimension('E')->setWidth(12);
  246. $sheet->getColumnDimension('F')->setWidth(12);
  247. $sheet->getColumnDimension('G')->setWidth(12);
  248. $sheet->getColumnDimension('H')->setWidth(12);
  249. $sheet->getPageSetup()->setFitToPage(true)->setFitToWidth(1)->setFitToHeight(0);
  250. $filenameCn = $title . '.xlsx';
  251. $filenameAscii = 'supplier_review_' . $ym . '.xlsx';
  252. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  253. header(
  254. 'Content-Disposition: attachment; filename="' . $filenameAscii . '"; filename*=UTF-8\'\'' . rawurlencode($filenameCn)
  255. );
  256. header('Cache-Control: max-age=0');
  257. header('X-Content-Type-Options: nosniff');
  258. $writer = new Xlsx($spreadsheet);
  259. $writer->save('php://output');
  260. $spreadsheet->disconnectWorksheets();
  261. unset($spreadsheet);
  262. exit;
  263. }
  264. /**
  265. * 月度评审记录列表(仅展示,最终得分可人工填写)
  266. *
  267. * @param bool $resync 是否先按规则重算(列表/导出默认 false;点刷新传 true)
  268. * @return array<int, array<string, mixed>>
  269. */
  270. protected function loadMonthlySupplierScoreList(string $ym, string $keyword = '', bool $resync = false): array
  271. {
  272. $ym = trim($ym);
  273. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  274. return [];
  275. }
  276. ProcuremenSupplierScore::ensureSchema();
  277. $monthlyMap = ProcuremenSupplierScore::loadMonthlyMapByYm($ym, $resync);
  278. $keyword = trim($keyword);
  279. $list = [];
  280. foreach ($monthlyMap as $name => $item) {
  281. if ($keyword !== '' && mb_stripos($name, $keyword) === false) {
  282. continue;
  283. }
  284. $list[] = $this->buildSupplierScoreListItem($name, $item, $ym);
  285. }
  286. usort($list, [$this, 'sortSupplierScoreListItems']);
  287. return $list;
  288. }
  289. /**
  290. * 按供应商关键词跨月搜索(不限查询月份)
  291. *
  292. * @return array<int, array<string, mixed>>
  293. */
  294. protected function loadSupplierScoreSearchList(string $keyword): array
  295. {
  296. $keyword = trim($keyword);
  297. if ($keyword === '') {
  298. return [];
  299. }
  300. ProcuremenSupplierScore::ensureSchema();
  301. ProcuremenSupplierScore::ensureFinalScoreTable();
  302. try {
  303. $rows = \think\Db::table(ProcuremenSupplierScore::TABLE_FINAL)
  304. ->where('company_name', 'like', '%' . addcslashes($keyword, '%_\\') . '%')
  305. ->field('ym,company_name,score,quality_score,price_score,delivery_score,value_added_score,final_score,score_grade')
  306. ->order('ym', 'desc')
  307. ->order('company_name', 'asc')
  308. ->select();
  309. } catch (\Throwable $e) {
  310. return [];
  311. }
  312. if (!is_array($rows)) {
  313. return [];
  314. }
  315. $list = [];
  316. foreach ($rows as $r) {
  317. if (!is_array($r)) {
  318. continue;
  319. }
  320. $name = trim((string)($r['company_name'] ?? ''));
  321. $rowYm = ProcuremenSupplierScore::formatScoreYm($r['ym'] ?? '');
  322. if ($name === '' || $rowYm === '') {
  323. continue;
  324. }
  325. $quality = ProcuremenSupplierScore::readOptionalScoreValue($r['quality_score'] ?? null);
  326. $price = ProcuremenSupplierScore::readOptionalScoreValue($r['price_score'] ?? null);
  327. $delivery = ProcuremenSupplierScore::readOptionalScoreValue($r['delivery_score'] ?? null);
  328. $valueAdded = ProcuremenSupplierScore::readOptionalScoreValue($r['value_added_score'] ?? null);
  329. $final = ProcuremenSupplierScore::readOptionalScoreValue($r['final_score'] ?? null);
  330. $item = [
  331. 'quality_score' => $quality,
  332. 'price_score' => $price,
  333. 'delivery_score' => $delivery,
  334. 'value_added_score' => $valueAdded,
  335. 'final_score' => $final,
  336. 'final_saved' => $final !== null ? 1 : 0,
  337. 'score_grade' => ProcuremenSupplierScore::normalizeScoreGrade($r['score_grade'] ?? ''),
  338. 'score_date' => $rowYm,
  339. ];
  340. $list[] = $this->buildSupplierScoreListItem($name, $item, $rowYm);
  341. }
  342. usort($list, [$this, 'sortSupplierScoreListItems']);
  343. return $list;
  344. }
  345. /**
  346. * @param array<string, mixed> $item
  347. * @return array<string, mixed>
  348. */
  349. protected function buildSupplierScoreListItem(string $name, array $item, string $ym): array
  350. {
  351. $quality = array_key_exists('quality_score', $item) ? $item['quality_score'] : null;
  352. $price = array_key_exists('price_score', $item) ? $item['price_score'] : null;
  353. $delivery = array_key_exists('delivery_score', $item) ? $item['delivery_score'] : null;
  354. $valueAdded = array_key_exists('value_added_score', $item) ? $item['value_added_score'] : null;
  355. if ($quality !== null) {
  356. $quality = (float)$quality;
  357. }
  358. if ($price !== null) {
  359. $price = (float)$price;
  360. }
  361. if ($delivery !== null) {
  362. $delivery = (float)$delivery;
  363. }
  364. if ($valueAdded !== null) {
  365. $valueAdded = (float)$valueAdded;
  366. }
  367. $hasFinal = !empty($item['final_saved']);
  368. $final = $hasFinal ? (float)($item['final_score'] ?? 0) : null;
  369. if ($final === null) {
  370. $final = ProcuremenSupplierScore::sumFinalScore($quality, $price, $delivery, $valueAdded);
  371. }
  372. $grade = ProcuremenSupplierScore::normalizeScoreGrade($item['score_grade'] ?? '');
  373. if ($grade === '' && $final !== null) {
  374. $grade = ProcuremenSupplierScore::gradeFromFinalScore($final);
  375. }
  376. $sortScore = $final !== null
  377. ? (float)$final
  378. : (($quality ?? 0) + ($price ?? 0) + ($delivery ?? 0) + ($valueAdded ?? 0));
  379. $scoreDate = (string)($item['score_date'] ?? '');
  380. if ($scoreDate === '') {
  381. $scoreDate = ProcuremenSupplierScore::formatScoreYm($ym);
  382. }
  383. return [
  384. 'company_name' => $name,
  385. 'ym' => ProcuremenSupplierScore::formatScoreYm($ym),
  386. 'quality_score' => $quality,
  387. 'quality_score_text' => ProcuremenSupplierScore::formatOptionalScore($quality),
  388. 'price_score' => $price,
  389. 'price_score_text' => ProcuremenSupplierScore::formatOptionalScore($price),
  390. 'delivery_score' => $delivery,
  391. 'delivery_score_text' => ProcuremenSupplierScore::formatOptionalScore($delivery),
  392. 'value_added_score' => $valueAdded,
  393. 'value_added_score_text' => ProcuremenSupplierScore::formatOptionalScore($valueAdded),
  394. 'final_score' => $final,
  395. 'final_score_text' => $final !== null ? ProcuremenSupplierScore::formatOptionalScore($final) : '',
  396. 'final_score_saved' => $hasFinal ? 1 : 0,
  397. 'score_grade' => $grade,
  398. 'score_date' => $scoreDate,
  399. 'sort_score' => $sortScore,
  400. ];
  401. }
  402. /**
  403. * @param array<string, mixed> $a
  404. * @param array<string, mixed> $b
  405. */
  406. protected function sortSupplierScoreListItems(array $a, array $b): int
  407. {
  408. $ya = (string)($a['ym'] ?? '');
  409. $yb = (string)($b['ym'] ?? '');
  410. if ($ya !== $yb) {
  411. return strcmp($yb, $ya);
  412. }
  413. $sa = (float)($a['sort_score'] ?? 0);
  414. $sb = (float)($b['sort_score'] ?? 0);
  415. if ($sa !== $sb) {
  416. return $sb <=> $sa;
  417. }
  418. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  419. }
  420. protected function resolveRequestYm(): string
  421. {
  422. $ym = trim((string)$this->request->get('ym', ''));
  423. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  424. return $ym;
  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. $fy = trim((string)($filter['ym'] ?? ''));
  431. if (preg_match('/^\d{4}-\d{2}$/', $fy)) {
  432. return $fy;
  433. }
  434. }
  435. }
  436. if (preg_match('/^(\d{4})\D+(\d{1,2})/', $ym, $m)) {
  437. return sprintf('%04d-%02d', (int)$m[1], (int)$m[2]);
  438. }
  439. return ProcuremenSupplierScore::latestReviewYm();
  440. }
  441. protected function resolveSearchKeyword(): string
  442. {
  443. $keyword = trim((string)$this->request->get('search', ''));
  444. if ($keyword !== '') {
  445. return $keyword;
  446. }
  447. $filterRaw = $this->request->get('filter', '');
  448. if (is_string($filterRaw) && $filterRaw !== '') {
  449. $filter = json_decode($filterRaw, true);
  450. if (is_array($filter)) {
  451. return trim((string)($filter['company_name'] ?? ''));
  452. }
  453. }
  454. return '';
  455. }
  456. /**
  457. * 本月订单明细:已下发订单按「下发批次」(pick_time) 分行;
  458. * 同一批次内多工序顿号合并,不同下发时间不合并。
  459. * 仅返回已做质量评分且已完结的订单。
  460. *
  461. * @return array<int, array<string, mixed>>
  462. */
  463. /**
  464. * 本月订单明细:与质量得分同源 —— 该供应商「完结时间」落在本月且已质量评分的订单
  465. *
  466. * @return array<int, array<string, mixed>>
  467. */
  468. protected function loadMonthOrdersForSupplier(string $ym, string $companyName): array
  469. {
  470. $ym = trim($ym);
  471. $companyName = trim($companyName);
  472. if (!preg_match('/^\d{4}-\d{2}$/', $ym) || $companyName === '') {
  473. return [];
  474. }
  475. ProcuremenSupplierScore::ensureSchema();
  476. // 1) 入库/质量评分表(先取该供应商全部,再按完结月过滤,与月度计分一致)
  477. try {
  478. $scoreRowsRaw = \think\Db::table('purchase_order_inbound_score')
  479. ->where('company_name', $companyName)
  480. ->field('scydgy_id,ccydh,cyjmc,cgymc,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,createtime,updatetime')
  481. ->order('id', 'desc')
  482. ->select();
  483. } catch (\Throwable $e) {
  484. try {
  485. $scoreRowsRaw = \think\Db::table('purchase_order_inbound_score')
  486. ->where('company_name', $companyName)
  487. ->field('scydgy_id,ccydh,cyjmc,cgymc,result,delivery_status,customer_complaint,order_interrupt,remark,createtime,updatetime')
  488. ->order('id', 'desc')
  489. ->select();
  490. } catch (\Throwable $e2) {
  491. try {
  492. $scoreRowsRaw = \think\Db::table('purchase_order_inbound_score')
  493. ->where('company_name', $companyName)
  494. ->field('scydgy_id,ccydh,cyjmc,cgymc,result,remark,createtime,updatetime')
  495. ->order('id', 'desc')
  496. ->select();
  497. } catch (\Throwable $e3) {
  498. $scoreRowsRaw = [];
  499. }
  500. }
  501. }
  502. if (!is_array($scoreRowsRaw) || $scoreRowsRaw === []) {
  503. return [];
  504. }
  505. $sidSet = [];
  506. $inboundTimeBySid = [];
  507. foreach ($scoreRowsRaw as $r) {
  508. if (!is_array($r)) {
  509. continue;
  510. }
  511. $sid = (int)($r['scydgy_id'] ?? 0);
  512. if ($sid <= 0) {
  513. continue;
  514. }
  515. $sidSet[$sid] = true;
  516. $inboundTimeBySid[$sid] = [
  517. 'createtime' => $r['createtime'] ?? null,
  518. 'updatetime' => $r['updatetime'] ?? null,
  519. ];
  520. }
  521. $completedYmMap = ProcuremenSupplierScore::loadCompletedYmMapByScydgyIds(array_keys($sidSet), $inboundTimeBySid);
  522. $scoreRows = [];
  523. foreach ($scoreRowsRaw as $r) {
  524. if (!is_array($r)) {
  525. continue;
  526. }
  527. $sid = (int)($r['scydgy_id'] ?? 0);
  528. $rowYm = $sid > 0 ? (string)($completedYmMap[$sid] ?? '') : '';
  529. if ($rowYm === '' && $sid <= 0) {
  530. $t1 = \app\common\library\ProcuremenTime::parseToTimestamp($r['updatetime'] ?? null);
  531. $t2 = \app\common\library\ProcuremenTime::parseToTimestamp($r['createtime'] ?? null);
  532. $ts = max($t1, $t2);
  533. $rowYm = $ts > 946684800 ? date('Y-m', $ts) : '';
  534. }
  535. if ($rowYm !== $ym) {
  536. continue;
  537. }
  538. $scoreRows[] = $r;
  539. }
  540. if ($scoreRows === []) {
  541. return [];
  542. }
  543. /** @var array<string, array<string, mixed>> $byCcydh */
  544. $byCcydh = [];
  545. $sidSet = [];
  546. foreach ($scoreRows as $r) {
  547. if (!is_array($r)) {
  548. continue;
  549. }
  550. $ccydh = trim((string)($r['ccydh'] ?? ''));
  551. $result = trim((string)($r['result'] ?? ''));
  552. if ($ccydh === '' || ($result !== '合格' && $result !== '不合格')) {
  553. continue;
  554. }
  555. $sid = (int)($r['scydgy_id'] ?? 0);
  556. if ($sid > 0) {
  557. $sidSet[$sid] = true;
  558. }
  559. $scoreTime = trim((string)($r['updatetime'] ?? ''));
  560. if ($scoreTime === '' || preg_match('/^0000-00-00/', $scoreTime)) {
  561. $scoreTime = trim((string)($r['createtime'] ?? ''));
  562. }
  563. if (!isset($byCcydh[$ccydh])) {
  564. $ds = trim((string)($r['delivery_status'] ?? ''));
  565. if ($ds !== '准时' && $ds !== '滞后') {
  566. $ds = '';
  567. }
  568. $byCcydh[$ccydh] = [
  569. 'CCYDH' => $ccydh,
  570. 'scydgy_id' => $sid > 0 ? $sid : 0,
  571. 'scydgy_ids' => $sid > 0 ? [$sid] : [],
  572. 'CYJMC' => trim((string)($r['cyjmc'] ?? '')),
  573. 'CGYMC_list' => [],
  574. 'inbound_result' => $result,
  575. 'delivery_status' => $ds,
  576. 'delivery_date' => '',
  577. 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
  578. 'complaint_remark' => '',
  579. 'order_interrupt' => (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0,
  580. 'inbound_remark' => trim((string)($r['remark'] ?? '')),
  581. 'score_time' => $scoreTime,
  582. ];
  583. }
  584. $g = &$byCcydh[$ccydh];
  585. // 任一工序不合格 → 整单不合格(与质量分统计一致)
  586. if ($result === '不合格') {
  587. $g['inbound_result'] = '不合格';
  588. }
  589. if ($sid > 0) {
  590. if ($g['scydgy_id'] <= 0) {
  591. $g['scydgy_id'] = $sid;
  592. }
  593. if (!in_array($sid, $g['scydgy_ids'], true)) {
  594. $g['scydgy_ids'][] = $sid;
  595. }
  596. }
  597. $gymc = trim((string)($r['cgymc'] ?? ''));
  598. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  599. $g['CGYMC_list'][] = $gymc;
  600. }
  601. if ($g['CYJMC'] === '') {
  602. $g['CYJMC'] = trim((string)($r['cyjmc'] ?? ''));
  603. }
  604. if ($g['inbound_remark'] === '') {
  605. $g['inbound_remark'] = trim((string)($r['remark'] ?? ''));
  606. }
  607. if ($g['delivery_status'] === '') {
  608. $ds = trim((string)($r['delivery_status'] ?? ''));
  609. if ($ds === '准时' || $ds === '滞后') {
  610. $g['delivery_status'] = $ds;
  611. }
  612. }
  613. $dd = trim((string)($r['delivery_date'] ?? ''));
  614. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  615. $g['delivery_date'] = $mdd[1];
  616. }
  617. if ((int)($r['customer_complaint'] ?? 0) === 1) {
  618. $g['customer_complaint'] = 1;
  619. }
  620. $crm = trim((string)($r['complaint_remark'] ?? ''));
  621. if ($crm !== '' && $g['complaint_remark'] === '') {
  622. $g['complaint_remark'] = $crm;
  623. }
  624. if ((int)($r['order_interrupt'] ?? 0) === 1) {
  625. $g['order_interrupt'] = 1;
  626. }
  627. if ($scoreTime !== '' && ($g['score_time'] === '' || strcmp($scoreTime, $g['score_time']) > 0)) {
  628. $g['score_time'] = $scoreTime;
  629. }
  630. unset($g);
  631. }
  632. if ($byCcydh === []) {
  633. return [];
  634. }
  635. // 2) 补充采购单展示字段
  636. $poByCcydh = [];
  637. try {
  638. $poRows = \think\Db::table('purchase_order')
  639. ->where('CCYDH', 'in', array_keys($byCcydh))
  640. ->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%\')')
  641. ->field('CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,pick_company_name,wflow_status,status,pick_time,scydgy_id')
  642. ->order('id', 'asc')
  643. ->select();
  644. } catch (\Throwable $e) {
  645. $poRows = [];
  646. }
  647. if (is_array($poRows)) {
  648. foreach ($poRows as $po) {
  649. if (!is_array($po)) {
  650. continue;
  651. }
  652. $c = trim((string)($po['CCYDH'] ?? ''));
  653. if ($c === '' || !isset($byCcydh[$c])) {
  654. continue;
  655. }
  656. if (!isset($poByCcydh[$c])) {
  657. $poByCcydh[$c] = [
  658. 'CYJMC' => '',
  659. 'CCLBMMC' => '',
  660. 'CGYMC_list' => [],
  661. 'CDW' => '',
  662. 'pick_company_name' => '',
  663. 'wflow_status' => '',
  664. 'status' => '',
  665. 'pick_time' => '',
  666. 'completed' => false,
  667. 'picked_match' => false,
  668. 'scydgy_id' => 0,
  669. ];
  670. }
  671. $p = &$poByCcydh[$c];
  672. $sid = (int)($po['scydgy_id'] ?? 0);
  673. if ($p['scydgy_id'] <= 0 && $sid > 0) {
  674. $p['scydgy_id'] = $sid;
  675. }
  676. if ($p['CYJMC'] === '') {
  677. $p['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  678. }
  679. if ($p['CCLBMMC'] === '') {
  680. $p['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  681. }
  682. if ($p['CDW'] === '') {
  683. $p['CDW'] = trim((string)($po['CDW'] ?? ''));
  684. }
  685. $g = trim((string)($po['CGYMC'] ?? ''));
  686. if ($g !== '' && !in_array($g, $p['CGYMC_list'], true)) {
  687. $p['CGYMC_list'][] = $g;
  688. }
  689. $pn = trim((string)($po['pick_company_name'] ?? ''));
  690. if ($pn !== '') {
  691. if ($p['pick_company_name'] === '') {
  692. $p['pick_company_name'] = $pn;
  693. }
  694. if ($pn === $companyName) {
  695. $p['picked_match'] = true;
  696. }
  697. }
  698. $pt = trim((string)($po['pick_time'] ?? ''));
  699. if ($pt !== '' && !preg_match('/^0000-00-00/', $pt)) {
  700. if ($p['pick_time'] === '' || strcmp($pt, $p['pick_time']) < 0) {
  701. $p['pick_time'] = $pt;
  702. }
  703. }
  704. if (\app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  705. $p['completed'] = true;
  706. $p['status'] = \app\common\library\ProcuremenStatus::PO_COMPLETED;
  707. } elseif ($p['status'] === '' && trim((string)($po['status'] ?? '')) !== '') {
  708. $p['status'] = trim((string)$po['status']);
  709. }
  710. if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  711. $p['wflow_status'] = \app\common\library\ProcuremenStatus::WFLOW_APPROVED;
  712. } elseif ($p['wflow_status'] === '' && trim((string)($po['wflow_status'] ?? '')) !== '') {
  713. $p['wflow_status'] = trim((string)$po['wflow_status']);
  714. }
  715. unset($p);
  716. }
  717. }
  718. // 3) 可选:招标评分表补排名/分项(没有也不影响展示)
  719. $bidByCcydh = [];
  720. try {
  721. $bidRows = \think\Db::table(ProcuremenSupplierScore::TABLE_SCORE)
  722. ->where('ym', $ym)
  723. ->where('company_name', $companyName)
  724. ->where('ccydh', 'in', array_keys($byCcydh))
  725. ->field('ccydh,score,rank_no,quality_score,price_score,price_sum,lead_score,lead_days_sum,createtime')
  726. ->order('createtime', 'desc')
  727. ->select();
  728. } catch (\Throwable $e) {
  729. $bidRows = [];
  730. }
  731. if (is_array($bidRows)) {
  732. foreach ($bidRows as $br) {
  733. if (!is_array($br)) {
  734. continue;
  735. }
  736. $c = trim((string)($br['ccydh'] ?? ''));
  737. if ($c === '' || isset($bidByCcydh[$c])) {
  738. continue;
  739. }
  740. $bidByCcydh[$c] = $br;
  741. }
  742. }
  743. $out = [];
  744. foreach ($byCcydh as $ccydh => $g) {
  745. $po = $poByCcydh[$ccydh] ?? [];
  746. $bid = $bidByCcydh[$ccydh] ?? [];
  747. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  748. if ($gymcList === [] && is_array($po['CGYMC_list'] ?? null)) {
  749. $gymcList = $po['CGYMC_list'];
  750. }
  751. $batch = [
  752. 'completed' => !empty($po['completed']),
  753. 'status' => (string)($po['status'] ?? ''),
  754. 'wflow_status' => (string)($po['wflow_status'] ?? ''),
  755. ];
  756. $progressText = $this->formatMonthOrderProgressText($batch);
  757. // 已质量评分:进度优先显示已完结,否则显示实际流程
  758. if ($progressText === '待入库评分') {
  759. $progressText = \app\common\library\ProcuremenStatus::PO_COMPLETED;
  760. }
  761. $showBid = !empty($po['completed'])
  762. || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')
  763. || \app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '');
  764. $pickTimeRaw = trim((string)($po['pick_time'] ?? ''));
  765. if ($pickTimeRaw === '') {
  766. $pickTimeRaw = trim((string)($g['score_time'] ?? ''));
  767. }
  768. $sid = (int)($g['scydgy_id'] ?? 0);
  769. if ($sid <= 0) {
  770. $sid = (int)($po['scydgy_id'] ?? 0);
  771. }
  772. $out[] = [
  773. 'seq_no' => 0,
  774. 'scydgy_id' => $sid,
  775. 'CCYDH' => $ccydh,
  776. 'CYJMC' => (string)(($g['CYJMC'] ?? '') !== '' ? $g['CYJMC'] : ($po['CYJMC'] ?? '')),
  777. 'CCLBMMC' => (string)($po['CCLBMMC'] ?? ''),
  778. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  779. 'CDW' => (string)($po['CDW'] ?? ''),
  780. 'pick_company_name' => (string)(($po['pick_company_name'] ?? '') !== '' ? $po['pick_company_name'] : $companyName),
  781. 'wflow_status' => (string)($po['wflow_status'] ?? ''),
  782. 'status' => (string)($po['status'] ?? ''),
  783. 'progress_text' => $progressText,
  784. 'pick_time' => $pickTimeRaw,
  785. 'issue_time' => $pickTimeRaw !== ''
  786. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickTimeRaw)
  787. : '',
  788. 'score' => $bid['score'] ?? null,
  789. 'rank_no' => (int)($bid['rank_no'] ?? 0),
  790. 'quality_score' => $bid['quality_score'] ?? null,
  791. 'price_score' => $bid['price_score'] ?? null,
  792. 'price_sum' => $bid['price_sum'] ?? null,
  793. 'lead_score' => $bid['lead_score'] ?? null,
  794. 'lead_days_sum' => $bid['lead_days_sum'] ?? null,
  795. 'is_picked' => !empty($po['picked_match']) ? 1 : 1,
  796. 'show_bid_result' => $showBid ? 1 : 0,
  797. 'inbound_result' => (string)($g['inbound_result'] ?? ''),
  798. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  799. 'delivery_date' => (string)($g['delivery_date'] ?? ''),
  800. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  801. 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
  802. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  803. 'inbound_remark' => (string)($g['inbound_remark'] ?? ''),
  804. ];
  805. }
  806. usort($out, static function ($a, $b) {
  807. $ta = (string)($a['pick_time'] ?? '');
  808. $tb = (string)($b['pick_time'] ?? '');
  809. if ($ta !== $tb) {
  810. return strcmp($tb, $ta);
  811. }
  812. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  813. });
  814. $total = count($out);
  815. $seq = $total;
  816. foreach ($out as &$row) {
  817. $row['seq_no'] = $seq;
  818. $seq--;
  819. }
  820. unset($row);
  821. return $out;
  822. }
  823. /**
  824. * 批量取各工序首次「下发」操作时间(用于本月明细按批次拆行)
  825. *
  826. * @param int[] $scydgyIds
  827. * @return array<int, string> scydgy_id => Y-m-d H:i:s
  828. */
  829. protected function loadFirstIssueTimeByScydgyIds(array $scydgyIds): array
  830. {
  831. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds), static function ($id) {
  832. return $id > 0;
  833. })));
  834. if ($scydgyIds === []) {
  835. return [];
  836. }
  837. $acts = \app\common\library\ProcuremenOperLog::expandActionQueryValues('issue_submit');
  838. if ($acts === []) {
  839. return [];
  840. }
  841. try {
  842. $logs = \think\Db::table('purchase_order_oper_log')
  843. ->where(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID, 'in', $scydgyIds)
  844. ->where(\app\common\library\ProcuremenOperLog::COL_ACTION, 'in', $acts)
  845. ->field(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID . ',' . \app\common\library\ProcuremenOperLog::COL_TIME)
  846. ->order('id', 'asc')
  847. ->select();
  848. } catch (\Throwable $e) {
  849. return [];
  850. }
  851. $map = [];
  852. if (!is_array($logs)) {
  853. return [];
  854. }
  855. foreach ($logs as $lg) {
  856. if (!is_array($lg)) {
  857. continue;
  858. }
  859. $sid = (int)($lg[\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  860. if ($sid <= 0 || isset($map[$sid])) {
  861. continue;
  862. }
  863. $t = trim((string)($lg[\app\common\library\ProcuremenOperLog::COL_TIME] ?? ''));
  864. if ($t === '' || preg_match('/^0000-00-00/', $t)) {
  865. continue;
  866. }
  867. if (is_numeric($t) && (int)$t > 946684800) {
  868. $t = date('Y-m-d H:i:s', (int)$t);
  869. } else {
  870. $t = \app\common\library\ProcuremenTime::formatDisplayDateTime($t);
  871. }
  872. if ($t === '') {
  873. continue;
  874. }
  875. $map[$sid] = $t;
  876. }
  877. return $map;
  878. }
  879. /**
  880. * 当前进度:已完结优先;终审通过也显示已完结;其余展示流程阶段
  881. *
  882. * @param array<string, mixed> $po
  883. */
  884. protected function formatMonthOrderProgressText(array $po): string
  885. {
  886. if (!empty($po['completed']) || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  887. return \app\common\library\ProcuremenStatus::PO_COMPLETED;
  888. }
  889. // 采购终审通过后待入库评分,合格/不合格后才完结
  890. if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  891. return '待入库评分';
  892. }
  893. $w = \app\common\library\ProcuremenStatus::normalizeWflowStatus($po['wflow_status'] ?? '');
  894. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_APPROVAL) {
  895. return '待采购确认';
  896. }
  897. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_CONFIRM) {
  898. return '待确认供应商';
  899. }
  900. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_ISSUE) {
  901. return '待协助下发';
  902. }
  903. return $w !== '' ? $w : '—';
  904. }
  905. /**
  906. * 批量读取质量评分明细(是否合格 / 交货情况 / 客户投诉 / 订单中断 / 备注)
  907. *
  908. * @param int[] $scydgyIds
  909. * @return array<int, array{result:string,delivery_status:string,customer_complaint:int,order_interrupt:int,remark:string}>
  910. */
  911. protected function loadInboundResultByScydgyIds(array $scydgyIds): array
  912. {
  913. $ids = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  914. if ($ids === []) {
  915. return [];
  916. }
  917. $out = [];
  918. try {
  919. $rows = \think\Db::table('purchase_order_inbound_score')
  920. ->where('scydgy_id', 'in', $ids)
  921. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark')
  922. ->select();
  923. } catch (\Throwable $e) {
  924. // 兼容旧表无新列
  925. try {
  926. $rows = \think\Db::table('purchase_order_inbound_score')
  927. ->where('scydgy_id', 'in', $ids)
  928. ->field('scydgy_id,result,customer_complaint,order_interrupt,remark')
  929. ->select();
  930. } catch (\Throwable $e2) {
  931. try {
  932. $rows = \think\Db::table('purchase_order_inbound_score')
  933. ->where('scydgy_id', 'in', $ids)
  934. ->field('scydgy_id,result,remark')
  935. ->select();
  936. } catch (\Throwable $e3) {
  937. return [];
  938. }
  939. }
  940. }
  941. if (!is_array($rows)) {
  942. return [];
  943. }
  944. foreach ($rows as $r) {
  945. if (!is_array($r)) {
  946. continue;
  947. }
  948. $sid = (int)($r['scydgy_id'] ?? 0);
  949. $result = trim((string)($r['result'] ?? ''));
  950. if ($sid <= 0 || ($result !== '合格' && $result !== '不合格')) {
  951. continue;
  952. }
  953. $ds = trim((string)($r['delivery_status'] ?? ''));
  954. if ($ds !== '准时' && $ds !== '滞后') {
  955. $ds = '';
  956. }
  957. $out[$sid] = [
  958. 'result' => $result,
  959. 'delivery_status' => $ds,
  960. 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
  961. 'order_interrupt' => (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0,
  962. 'remark' => trim((string)($r['remark'] ?? '')),
  963. ];
  964. }
  965. return $out;
  966. }
  967. }