Supplierservicescore.php 42 KB

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