Supplierservicescore.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. * 本月订单明细:已下发订单按「下发批次」(pick_time) 分行;
  437. * 同一批次内多工序顿号合并,不同下发时间不合并。
  438. * 仅返回已做质量评分且已完结的订单。
  439. *
  440. * @return array<int, array<string, mixed>>
  441. */
  442. /**
  443. * 本月订单明细:与质量得分同源 —— 该供应商本月「质量评分」订单
  444. * (不再依赖招标评分表,也不强制已完结;与 calcQualityScoreFromInbound 一致)
  445. *
  446. * @return array<int, array<string, mixed>>
  447. */
  448. protected function loadMonthOrdersForSupplier(string $ym, string $companyName): array
  449. {
  450. $ym = trim($ym);
  451. $companyName = trim($companyName);
  452. if (!preg_match('/^\d{4}-\d{2}$/', $ym) || $companyName === '') {
  453. return [];
  454. }
  455. ProcuremenSupplierScore::ensureSchema();
  456. // 1) 与质量分同一来源:入库/质量评分表
  457. try {
  458. $scoreRows = \think\Db::table('purchase_order_inbound_score')
  459. ->where('company_name', $companyName)
  460. ->where(function ($q) use ($ym) {
  461. $q->where('updatetime', 'like', $ym . '%')
  462. ->whereOr('createtime', 'like', $ym . '%');
  463. })
  464. ->field('scydgy_id,ccydh,cyjmc,cgymc,result,delivery_status,customer_complaint,order_interrupt,remark,createtime,updatetime')
  465. ->order('id', 'desc')
  466. ->select();
  467. } catch (\Throwable $e) {
  468. try {
  469. $scoreRows = \think\Db::table('purchase_order_inbound_score')
  470. ->where('company_name', $companyName)
  471. ->where(function ($q) use ($ym) {
  472. $q->where('updatetime', 'like', $ym . '%')
  473. ->whereOr('createtime', 'like', $ym . '%');
  474. })
  475. ->field('scydgy_id,ccydh,cyjmc,cgymc,result,remark,createtime,updatetime')
  476. ->order('id', 'desc')
  477. ->select();
  478. } catch (\Throwable $e2) {
  479. $scoreRows = [];
  480. }
  481. }
  482. if (!is_array($scoreRows) || $scoreRows === []) {
  483. return [];
  484. }
  485. /** @var array<string, array<string, mixed>> $byCcydh */
  486. $byCcydh = [];
  487. $sidSet = [];
  488. foreach ($scoreRows as $r) {
  489. if (!is_array($r)) {
  490. continue;
  491. }
  492. $ccydh = trim((string)($r['ccydh'] ?? ''));
  493. $result = trim((string)($r['result'] ?? ''));
  494. if ($ccydh === '' || ($result !== '合格' && $result !== '不合格')) {
  495. continue;
  496. }
  497. $sid = (int)($r['scydgy_id'] ?? 0);
  498. if ($sid > 0) {
  499. $sidSet[$sid] = true;
  500. }
  501. $scoreTime = trim((string)($r['updatetime'] ?? ''));
  502. if ($scoreTime === '' || preg_match('/^0000-00-00/', $scoreTime)) {
  503. $scoreTime = trim((string)($r['createtime'] ?? ''));
  504. }
  505. if (!isset($byCcydh[$ccydh])) {
  506. $ds = trim((string)($r['delivery_status'] ?? ''));
  507. if ($ds !== '准时' && $ds !== '滞后') {
  508. $ds = '';
  509. }
  510. $byCcydh[$ccydh] = [
  511. 'CCYDH' => $ccydh,
  512. 'scydgy_id' => $sid > 0 ? $sid : 0,
  513. 'scydgy_ids' => $sid > 0 ? [$sid] : [],
  514. 'CYJMC' => trim((string)($r['cyjmc'] ?? '')),
  515. 'CGYMC_list' => [],
  516. 'inbound_result' => $result,
  517. 'delivery_status' => $ds,
  518. 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
  519. 'order_interrupt' => (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0,
  520. 'inbound_remark' => trim((string)($r['remark'] ?? '')),
  521. 'score_time' => $scoreTime,
  522. ];
  523. }
  524. $g = &$byCcydh[$ccydh];
  525. // 任一工序不合格 → 整单不合格(与质量分统计一致)
  526. if ($result === '不合格') {
  527. $g['inbound_result'] = '不合格';
  528. }
  529. if ($sid > 0) {
  530. if ($g['scydgy_id'] <= 0) {
  531. $g['scydgy_id'] = $sid;
  532. }
  533. if (!in_array($sid, $g['scydgy_ids'], true)) {
  534. $g['scydgy_ids'][] = $sid;
  535. }
  536. }
  537. $gymc = trim((string)($r['cgymc'] ?? ''));
  538. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  539. $g['CGYMC_list'][] = $gymc;
  540. }
  541. if ($g['CYJMC'] === '') {
  542. $g['CYJMC'] = trim((string)($r['cyjmc'] ?? ''));
  543. }
  544. if ($g['inbound_remark'] === '') {
  545. $g['inbound_remark'] = trim((string)($r['remark'] ?? ''));
  546. }
  547. if ($g['delivery_status'] === '') {
  548. $ds = trim((string)($r['delivery_status'] ?? ''));
  549. if ($ds === '准时' || $ds === '滞后') {
  550. $g['delivery_status'] = $ds;
  551. }
  552. }
  553. if ((int)($r['customer_complaint'] ?? 0) === 1) {
  554. $g['customer_complaint'] = 1;
  555. }
  556. if ((int)($r['order_interrupt'] ?? 0) === 1) {
  557. $g['order_interrupt'] = 1;
  558. }
  559. if ($scoreTime !== '' && ($g['score_time'] === '' || strcmp($scoreTime, $g['score_time']) > 0)) {
  560. $g['score_time'] = $scoreTime;
  561. }
  562. unset($g);
  563. }
  564. if ($byCcydh === []) {
  565. return [];
  566. }
  567. // 2) 补充采购单展示字段
  568. $poByCcydh = [];
  569. try {
  570. $poRows = \think\Db::table('purchase_order')
  571. ->where('CCYDH', 'in', array_keys($byCcydh))
  572. ->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%\')')
  573. ->field('CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,pick_company_name,wflow_status,status,pick_time,scydgy_id')
  574. ->order('id', 'asc')
  575. ->select();
  576. } catch (\Throwable $e) {
  577. $poRows = [];
  578. }
  579. if (is_array($poRows)) {
  580. foreach ($poRows as $po) {
  581. if (!is_array($po)) {
  582. continue;
  583. }
  584. $c = trim((string)($po['CCYDH'] ?? ''));
  585. if ($c === '' || !isset($byCcydh[$c])) {
  586. continue;
  587. }
  588. if (!isset($poByCcydh[$c])) {
  589. $poByCcydh[$c] = [
  590. 'CYJMC' => '',
  591. 'CCLBMMC' => '',
  592. 'CGYMC_list' => [],
  593. 'CDW' => '',
  594. 'pick_company_name' => '',
  595. 'wflow_status' => '',
  596. 'status' => '',
  597. 'pick_time' => '',
  598. 'completed' => false,
  599. 'picked_match' => false,
  600. 'scydgy_id' => 0,
  601. ];
  602. }
  603. $p = &$poByCcydh[$c];
  604. $sid = (int)($po['scydgy_id'] ?? 0);
  605. if ($p['scydgy_id'] <= 0 && $sid > 0) {
  606. $p['scydgy_id'] = $sid;
  607. }
  608. if ($p['CYJMC'] === '') {
  609. $p['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  610. }
  611. if ($p['CCLBMMC'] === '') {
  612. $p['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  613. }
  614. if ($p['CDW'] === '') {
  615. $p['CDW'] = trim((string)($po['CDW'] ?? ''));
  616. }
  617. $g = trim((string)($po['CGYMC'] ?? ''));
  618. if ($g !== '' && !in_array($g, $p['CGYMC_list'], true)) {
  619. $p['CGYMC_list'][] = $g;
  620. }
  621. $pn = trim((string)($po['pick_company_name'] ?? ''));
  622. if ($pn !== '') {
  623. if ($p['pick_company_name'] === '') {
  624. $p['pick_company_name'] = $pn;
  625. }
  626. if ($pn === $companyName) {
  627. $p['picked_match'] = true;
  628. }
  629. }
  630. $pt = trim((string)($po['pick_time'] ?? ''));
  631. if ($pt !== '' && !preg_match('/^0000-00-00/', $pt)) {
  632. if ($p['pick_time'] === '' || strcmp($pt, $p['pick_time']) < 0) {
  633. $p['pick_time'] = $pt;
  634. }
  635. }
  636. if (\app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  637. $p['completed'] = true;
  638. $p['status'] = \app\common\library\ProcuremenStatus::PO_COMPLETED;
  639. } elseif ($p['status'] === '' && trim((string)($po['status'] ?? '')) !== '') {
  640. $p['status'] = trim((string)$po['status']);
  641. }
  642. if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  643. $p['wflow_status'] = \app\common\library\ProcuremenStatus::WFLOW_APPROVED;
  644. } elseif ($p['wflow_status'] === '' && trim((string)($po['wflow_status'] ?? '')) !== '') {
  645. $p['wflow_status'] = trim((string)$po['wflow_status']);
  646. }
  647. unset($p);
  648. }
  649. }
  650. // 3) 可选:招标评分表补排名/分项(没有也不影响展示)
  651. $bidByCcydh = [];
  652. try {
  653. $bidRows = \think\Db::table(ProcuremenSupplierScore::TABLE_SCORE)
  654. ->where('ym', $ym)
  655. ->where('company_name', $companyName)
  656. ->where('ccydh', 'in', array_keys($byCcydh))
  657. ->field('ccydh,score,rank_no,quality_score,price_score,price_sum,lead_score,lead_days_sum,createtime')
  658. ->order('createtime', 'desc')
  659. ->select();
  660. } catch (\Throwable $e) {
  661. $bidRows = [];
  662. }
  663. if (is_array($bidRows)) {
  664. foreach ($bidRows as $br) {
  665. if (!is_array($br)) {
  666. continue;
  667. }
  668. $c = trim((string)($br['ccydh'] ?? ''));
  669. if ($c === '' || isset($bidByCcydh[$c])) {
  670. continue;
  671. }
  672. $bidByCcydh[$c] = $br;
  673. }
  674. }
  675. $out = [];
  676. foreach ($byCcydh as $ccydh => $g) {
  677. $po = $poByCcydh[$ccydh] ?? [];
  678. $bid = $bidByCcydh[$ccydh] ?? [];
  679. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  680. if ($gymcList === [] && is_array($po['CGYMC_list'] ?? null)) {
  681. $gymcList = $po['CGYMC_list'];
  682. }
  683. $batch = [
  684. 'completed' => !empty($po['completed']),
  685. 'status' => (string)($po['status'] ?? ''),
  686. 'wflow_status' => (string)($po['wflow_status'] ?? ''),
  687. ];
  688. $progressText = $this->formatMonthOrderProgressText($batch);
  689. // 已质量评分:进度优先显示已完结,否则显示实际流程
  690. if ($progressText === '待入库评分') {
  691. $progressText = \app\common\library\ProcuremenStatus::PO_COMPLETED;
  692. }
  693. $showBid = !empty($po['completed'])
  694. || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')
  695. || \app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '');
  696. $pickTimeRaw = trim((string)($po['pick_time'] ?? ''));
  697. if ($pickTimeRaw === '') {
  698. $pickTimeRaw = trim((string)($g['score_time'] ?? ''));
  699. }
  700. $sid = (int)($g['scydgy_id'] ?? 0);
  701. if ($sid <= 0) {
  702. $sid = (int)($po['scydgy_id'] ?? 0);
  703. }
  704. $out[] = [
  705. 'seq_no' => 0,
  706. 'scydgy_id' => $sid,
  707. 'CCYDH' => $ccydh,
  708. 'CYJMC' => (string)(($g['CYJMC'] ?? '') !== '' ? $g['CYJMC'] : ($po['CYJMC'] ?? '')),
  709. 'CCLBMMC' => (string)($po['CCLBMMC'] ?? ''),
  710. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  711. 'CDW' => (string)($po['CDW'] ?? ''),
  712. 'pick_company_name' => (string)(($po['pick_company_name'] ?? '') !== '' ? $po['pick_company_name'] : $companyName),
  713. 'wflow_status' => (string)($po['wflow_status'] ?? ''),
  714. 'status' => (string)($po['status'] ?? ''),
  715. 'progress_text' => $progressText,
  716. 'pick_time' => $pickTimeRaw,
  717. 'issue_time' => $pickTimeRaw !== ''
  718. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickTimeRaw)
  719. : '',
  720. 'score' => $bid['score'] ?? null,
  721. 'rank_no' => (int)($bid['rank_no'] ?? 0),
  722. 'quality_score' => $bid['quality_score'] ?? null,
  723. 'price_score' => $bid['price_score'] ?? null,
  724. 'price_sum' => $bid['price_sum'] ?? null,
  725. 'lead_score' => $bid['lead_score'] ?? null,
  726. 'lead_days_sum' => $bid['lead_days_sum'] ?? null,
  727. 'is_picked' => !empty($po['picked_match']) ? 1 : 1,
  728. 'show_bid_result' => $showBid ? 1 : 0,
  729. 'inbound_result' => (string)($g['inbound_result'] ?? ''),
  730. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  731. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  732. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  733. 'inbound_remark' => (string)($g['inbound_remark'] ?? ''),
  734. ];
  735. }
  736. usort($out, static function ($a, $b) {
  737. $ta = (string)($a['pick_time'] ?? '');
  738. $tb = (string)($b['pick_time'] ?? '');
  739. if ($ta !== $tb) {
  740. return strcmp($tb, $ta);
  741. }
  742. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  743. });
  744. $total = count($out);
  745. $seq = $total;
  746. foreach ($out as &$row) {
  747. $row['seq_no'] = $seq;
  748. $seq--;
  749. }
  750. unset($row);
  751. return $out;
  752. }
  753. /**
  754. * 批量取各工序首次「下发」操作时间(用于本月明细按批次拆行)
  755. *
  756. * @param int[] $scydgyIds
  757. * @return array<int, string> scydgy_id => Y-m-d H:i:s
  758. */
  759. protected function loadFirstIssueTimeByScydgyIds(array $scydgyIds): array
  760. {
  761. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds), static function ($id) {
  762. return $id > 0;
  763. })));
  764. if ($scydgyIds === []) {
  765. return [];
  766. }
  767. $acts = \app\common\library\ProcuremenOperLog::expandActionQueryValues('issue_submit');
  768. if ($acts === []) {
  769. return [];
  770. }
  771. try {
  772. $logs = \think\Db::table('purchase_order_oper_log')
  773. ->where(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID, 'in', $scydgyIds)
  774. ->where(\app\common\library\ProcuremenOperLog::COL_ACTION, 'in', $acts)
  775. ->field(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID . ',' . \app\common\library\ProcuremenOperLog::COL_TIME)
  776. ->order('id', 'asc')
  777. ->select();
  778. } catch (\Throwable $e) {
  779. return [];
  780. }
  781. $map = [];
  782. if (!is_array($logs)) {
  783. return [];
  784. }
  785. foreach ($logs as $lg) {
  786. if (!is_array($lg)) {
  787. continue;
  788. }
  789. $sid = (int)($lg[\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  790. if ($sid <= 0 || isset($map[$sid])) {
  791. continue;
  792. }
  793. $t = trim((string)($lg[\app\common\library\ProcuremenOperLog::COL_TIME] ?? ''));
  794. if ($t === '' || preg_match('/^0000-00-00/', $t)) {
  795. continue;
  796. }
  797. if (is_numeric($t) && (int)$t > 946684800) {
  798. $t = date('Y-m-d H:i:s', (int)$t);
  799. } else {
  800. $t = \app\common\library\ProcuremenTime::formatDisplayDateTime($t);
  801. }
  802. if ($t === '') {
  803. continue;
  804. }
  805. $map[$sid] = $t;
  806. }
  807. return $map;
  808. }
  809. /**
  810. * 当前进度:已完结优先;终审通过也显示已完结;其余展示流程阶段
  811. *
  812. * @param array<string, mixed> $po
  813. */
  814. protected function formatMonthOrderProgressText(array $po): string
  815. {
  816. if (!empty($po['completed']) || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  817. return \app\common\library\ProcuremenStatus::PO_COMPLETED;
  818. }
  819. // 采购终审通过后待入库评分,合格/不合格后才完结
  820. if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  821. return '待入库评分';
  822. }
  823. $w = \app\common\library\ProcuremenStatus::normalizeWflowStatus($po['wflow_status'] ?? '');
  824. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_APPROVAL) {
  825. return '待采购确认';
  826. }
  827. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_CONFIRM) {
  828. return '待确认供应商';
  829. }
  830. if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_ISSUE) {
  831. return '待协助下发';
  832. }
  833. return $w !== '' ? $w : '—';
  834. }
  835. /**
  836. * 批量读取质量评分明细(是否合格 / 交货情况 / 客户投诉 / 订单中断 / 备注)
  837. *
  838. * @param int[] $scydgyIds
  839. * @return array<int, array{result:string,delivery_status:string,customer_complaint:int,order_interrupt:int,remark:string}>
  840. */
  841. protected function loadInboundResultByScydgyIds(array $scydgyIds): array
  842. {
  843. $ids = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  844. if ($ids === []) {
  845. return [];
  846. }
  847. $out = [];
  848. try {
  849. $rows = \think\Db::table('purchase_order_inbound_score')
  850. ->where('scydgy_id', 'in', $ids)
  851. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark')
  852. ->select();
  853. } catch (\Throwable $e) {
  854. // 兼容旧表无新列
  855. try {
  856. $rows = \think\Db::table('purchase_order_inbound_score')
  857. ->where('scydgy_id', 'in', $ids)
  858. ->field('scydgy_id,result,customer_complaint,order_interrupt,remark')
  859. ->select();
  860. } catch (\Throwable $e2) {
  861. try {
  862. $rows = \think\Db::table('purchase_order_inbound_score')
  863. ->where('scydgy_id', 'in', $ids)
  864. ->field('scydgy_id,result,remark')
  865. ->select();
  866. } catch (\Throwable $e3) {
  867. return [];
  868. }
  869. }
  870. }
  871. if (!is_array($rows)) {
  872. return [];
  873. }
  874. foreach ($rows as $r) {
  875. if (!is_array($r)) {
  876. continue;
  877. }
  878. $sid = (int)($r['scydgy_id'] ?? 0);
  879. $result = trim((string)($r['result'] ?? ''));
  880. if ($sid <= 0 || ($result !== '合格' && $result !== '不合格')) {
  881. continue;
  882. }
  883. $ds = trim((string)($r['delivery_status'] ?? ''));
  884. if ($ds !== '准时' && $ds !== '滞后') {
  885. $ds = '';
  886. }
  887. $out[$sid] = [
  888. 'result' => $result,
  889. 'delivery_status' => $ds,
  890. 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
  891. 'order_interrupt' => (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0,
  892. 'remark' => trim((string)($r['remark'] ?? '')),
  893. ];
  894. }
  895. return $out;
  896. }
  897. }