| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018 |
- <?php
- namespace app\admin\controller;
- use app\common\controller\Backend;
- use app\common\library\ProcuremenSupplierScore;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\Style\Border;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- /**
- * 供应商评审表(月度记录:质量得分 / 价格得分 / 交货得分 / 最终得分)
- * 订单经入库评分(合格/不合格)完结后,可在此对供应商做月度评分
- *
- * @icon fa fa-trophy
- */
- class Supplierservicescore extends Backend
- {
- /** @var \app\admin\model\Supplierservicescore */
- protected $model = null;
- protected $searchFields = 'company_name';
- /** 有列表权限即可导出/批量保存最终得分/查看本月订单 */
- protected $noNeedRight = ['export', 'savefinalbatch', 'monthorders'];
- public function _initialize()
- {
- parent::_initialize();
- ProcuremenSupplierScore::ensureSchema();
- $this->model = new \app\admin\model\Supplierservicescore;
- }
- public function index()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- $ym = $this->resolveRequestYm();
- $keyword = $this->resolveSearchKeyword();
- $offset = max(0, (int)$this->request->get('offset', 0));
- $limit = (int)$this->request->get('limit', 50);
- if ($limit <= 0) {
- $limit = 50;
- }
- // 默认只读月度表,避免进页全量重算卡住;点「刷新」带 resync=1 再按规则同步
- $forceSync = (string)$this->request->param('resync', '0') === '1';
- $list = $keyword !== ''
- ? $this->loadSupplierScoreSearchList($keyword)
- : $this->loadMonthlySupplierScoreList($ym, '', $forceSync);
- $total = count($list);
- $pageRows = array_slice($list, $offset, $limit);
- $seqBase = $offset;
- $rows = [];
- foreach ($pageRows as $i => $item) {
- $rowYm = (string)($item['ym'] ?? $ym);
- $rows[] = [
- 'id' => $seqBase + $i + 1,
- 'seq_no' => $seqBase + $i + 1,
- 'company_name' => (string)($item['company_name'] ?? ''),
- 'quality_score' => $item['quality_score'] ?? null,
- 'quality_score_text' => (string)($item['quality_score_text'] ?? ''),
- 'price_score' => $item['price_score'] ?? null,
- 'price_score_text' => (string)($item['price_score_text'] ?? ''),
- 'delivery_score' => $item['delivery_score'] ?? null,
- 'delivery_score_text' => (string)($item['delivery_score_text'] ?? ''),
- 'value_added_score' => $item['value_added_score'] ?? null,
- 'value_added_score_text' => (string)($item['value_added_score_text'] ?? ''),
- 'final_score' => $item['final_score'] ?? null,
- 'final_score_text' => (string)($item['final_score_text'] ?? ''),
- 'final_score_saved' => !empty($item['final_score_saved']) ? 1 : 0,
- 'score_grade' => (string)($item['score_grade'] ?? ''),
- 'score_date' => (string)(($item['score_date'] ?? '') !== '' ? $item['score_date'] : $rowYm),
- 'ym' => $rowYm,
- ];
- }
- return json(['total' => $total, 'rows' => $rows]);
- }
- $defaultYm = ProcuremenSupplierScore::latestReviewYm();
- if (!preg_match('/^\d{4}-\d{2}$/', $defaultYm)) {
- $defaultYm = date('Y-m');
- }
- $this->assign('defaultYm', $defaultYm);
- $this->assignconfig('supplierScoreDefaultYm', $defaultYm);
- return $this->view->fetch();
- }
- /**
- * 批量保存当月最终得分与评分等级
- * POST: ym, rows=[{company_name, final_score, score_grade}, ...] 或 rows_json
- */
- public function savefinalbatch()
- {
- if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
- $this->error(__('You have no permission'));
- }
- ProcuremenSupplierScore::ensureFinalScoreTable();
- $ym = trim((string)$this->request->post('ym', ''));
- if ($ym === '') {
- $ym = trim((string)$this->request->param('ym', ''));
- }
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $this->error('请选择查询月份');
- }
- $rows = $this->request->post('rows/a', []);
- if (!is_array($rows) || $rows === []) {
- $rowsJson = trim((string)$this->request->post('rows_json', ''));
- if ($rowsJson !== '') {
- $decoded = json_decode($rowsJson, true);
- if (is_array($decoded)) {
- $rows = $decoded;
- }
- }
- }
- if (!is_array($rows) || $rows === []) {
- $this->error('没有可保存的数据');
- }
- // 按行自带 ym 分组(跨月搜索结果可同页保存)
- $byYm = [];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $rowYm = trim((string)($row['ym'] ?? ''));
- if (!preg_match('/^\d{4}-\d{2}$/', $rowYm)) {
- $rowYm = $ym;
- }
- if (!isset($byYm[$rowYm])) {
- $byYm[$rowYm] = [];
- }
- $byYm[$rowYm][] = $row;
- }
- $done = 0;
- $err = '';
- foreach ($byYm as $saveYm => $chunk) {
- $ret = ProcuremenSupplierScore::saveFinalScoresForYm($saveYm, $chunk);
- $done += (int)($ret['done'] ?? 0);
- if ($err === '') {
- $err = trim((string)($ret['error'] ?? ''));
- }
- }
- if ($done < 1) {
- $this->error($err !== '' ? $err : '保存失败,请检查填写的分数');
- }
- $this->success('操作成功');
- }
- /**
- * 本月订单明细(某供应商 + 年月)
- */
- public function monthorders()
- {
- if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
- $this->error(__('You have no permission'));
- }
- $this->request->filter(['strip_tags', 'trim']);
- $ym = trim((string)$this->request->param('ym', ''));
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- $ym = date('Y-m');
- }
- $company = trim((string)$this->request->param('company_name', ''));
- if ($company === '') {
- $company = trim((string)$this->request->param('company', ''));
- }
- $rows = $company !== '' ? $this->loadMonthOrdersForSupplier($ym, $company) : [];
- $this->view->assign('ym', $ym);
- $this->view->assign('company_name', $company);
- $this->view->assign('orderRows', $rows);
- $this->view->assign('orderCount', count($rows));
- return $this->view->fetch();
- }
- /**
- * 导出供应商评审表(图二样式)
- * 列:序号、供应商名称、质量、交货、价格、增值服务、总分、评审等级
- */
- public function export()
- {
- if (!$this->auth->check('supplierservicescore/index') && !$this->auth->isSuperAdmin()) {
- $this->error(__('You have no permission'));
- }
- $ym = trim((string)$this->request->param('ym', ''));
- if (!preg_match('/^(\d{4})-(\d{2})$/', $ym, $m)) {
- $this->error('请选择查询月份');
- }
- $year = (int)$m[1];
- $month = (int)$m[2];
- if ($month < 1 || $month > 12) {
- $this->error('查询月份无效');
- }
- $list = $this->loadMonthlySupplierScoreList($ym, '', false);
- $title = $year . '年' . $month . '月外协加工供应商评审表';
- $spreadsheet = new Spreadsheet();
- $sheet = $spreadsheet->getActiveSheet();
- $sheet->setTitle('供应商评审表');
- $fontName = '宋体';
- $borderStyle = [
- 'borders' => [
- 'allBorders' => [
- 'borderStyle' => Border::BORDER_THIN,
- 'color' => ['rgb' => '000000'],
- ],
- ],
- ];
- $centerAlign = [
- 'horizontal' => Alignment::HORIZONTAL_CENTER,
- 'vertical' => Alignment::VERTICAL_CENTER,
- 'wrapText' => true,
- ];
- $sheet->mergeCells('A1:H1');
- $sheet->setCellValue('A1', $title);
- $sheet->getRowDimension(1)->setRowHeight(36);
- $sheet->getStyle('A1')->getFont()->setName($fontName)->setBold(true)->setSize(20);
- $sheet->getStyle('A1')->getAlignment()->applyFromArray($centerAlign);
- $headers = ['序号', '供应商名称', '质量', '交货', '价格', '增值服务', '总分', '评审等级'];
- foreach ($headers as $idx => $label) {
- $col = chr(ord('A') + $idx);
- $sheet->setCellValue($col . '2', $label);
- }
- $sheet->getRowDimension(2)->setRowHeight(26);
- $sheet->getStyle('A2:H2')->getFont()->setName($fontName)->setBold(true)->setSize(14);
- $sheet->getStyle('A2:H2')->getAlignment()->applyFromArray($centerAlign);
- $rowNum = 3;
- if ($list === []) {
- $sheet->mergeCells('A3:H3');
- $sheet->setCellValue('A3', '(该月暂无供应商评审记录)');
- $sheet->getRowDimension(3)->setRowHeight(26);
- $sheet->getStyle('A3')->getFont()->setName($fontName)->setSize(12);
- $sheet->getStyle('A3')->getAlignment()->applyFromArray($centerAlign);
- $rowNum = 4;
- } else {
- $i = 1;
- foreach ($list as $item) {
- $sheet->setCellValue('A' . $rowNum, $i);
- $sheet->setCellValue('B' . $rowNum, (string)($item['company_name'] ?? ''));
- $sheet->setCellValue('C' . $rowNum, (string)($item['quality_score_text'] ?? ''));
- $sheet->setCellValue('D' . $rowNum, (string)($item['delivery_score_text'] ?? ''));
- $sheet->setCellValue('E' . $rowNum, (string)($item['price_score_text'] ?? ''));
- $sheet->setCellValue('F' . $rowNum, (string)($item['value_added_score_text'] ?? ''));
- $sheet->setCellValue('G' . $rowNum, (string)($item['final_score_text'] ?? ''));
- $sheet->setCellValue('H' . $rowNum, (string)($item['score_grade'] ?? ''));
- $sheet->getRowDimension($rowNum)->setRowHeight(24);
- $rowNum++;
- $i++;
- }
- }
- $lastRow = max(2, $rowNum - 1);
- $sheet->getStyle('A1:H' . $lastRow)->applyFromArray($borderStyle);
- $sheet->getStyle('A3:H' . $lastRow)->getFont()->setName($fontName)->setSize(12);
- $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->applyFromArray($centerAlign);
- $sheet->getColumnDimension('A')->setWidth(10);
- $sheet->getColumnDimension('B')->setWidth(48);
- $sheet->getColumnDimension('C')->setWidth(12);
- $sheet->getColumnDimension('D')->setWidth(12);
- $sheet->getColumnDimension('E')->setWidth(12);
- $sheet->getColumnDimension('F')->setWidth(12);
- $sheet->getColumnDimension('G')->setWidth(12);
- $sheet->getColumnDimension('H')->setWidth(12);
- $sheet->getPageSetup()->setFitToPage(true)->setFitToWidth(1)->setFitToHeight(0);
- $filenameCn = $title . '.xlsx';
- $filenameAscii = 'supplier_review_' . $ym . '.xlsx';
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header(
- 'Content-Disposition: attachment; filename="' . $filenameAscii . '"; filename*=UTF-8\'\'' . rawurlencode($filenameCn)
- );
- header('Cache-Control: max-age=0');
- header('X-Content-Type-Options: nosniff');
- $writer = new Xlsx($spreadsheet);
- $writer->save('php://output');
- $spreadsheet->disconnectWorksheets();
- unset($spreadsheet);
- exit;
- }
- /**
- * 月度评审记录列表(仅展示,最终得分可人工填写)
- *
- * @param bool $resync 是否先按规则重算(列表/导出默认 false;点刷新传 true)
- * @return array<int, array<string, mixed>>
- */
- protected function loadMonthlySupplierScoreList(string $ym, string $keyword = '', bool $resync = false): array
- {
- $ym = trim($ym);
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- return [];
- }
- ProcuremenSupplierScore::ensureSchema();
- $monthlyMap = ProcuremenSupplierScore::loadMonthlyMapByYm($ym, $resync);
- $keyword = trim($keyword);
- $list = [];
- foreach ($monthlyMap as $name => $item) {
- if ($keyword !== '' && mb_stripos($name, $keyword) === false) {
- continue;
- }
- $list[] = $this->buildSupplierScoreListItem($name, $item, $ym);
- }
- usort($list, [$this, 'sortSupplierScoreListItems']);
- return $list;
- }
- /**
- * 按供应商关键词跨月搜索(不限查询月份)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadSupplierScoreSearchList(string $keyword): array
- {
- $keyword = trim($keyword);
- if ($keyword === '') {
- return [];
- }
- ProcuremenSupplierScore::ensureSchema();
- ProcuremenSupplierScore::ensureFinalScoreTable();
- try {
- $rows = \think\Db::table(ProcuremenSupplierScore::TABLE_FINAL)
- ->where('company_name', 'like', '%' . addcslashes($keyword, '%_\\') . '%')
- ->field('ym,company_name,score,quality_score,price_score,delivery_score,value_added_score,final_score,score_grade')
- ->order('ym', 'desc')
- ->order('company_name', 'asc')
- ->select();
- } catch (\Throwable $e) {
- return [];
- }
- if (!is_array($rows)) {
- return [];
- }
- $list = [];
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $name = trim((string)($r['company_name'] ?? ''));
- $rowYm = ProcuremenSupplierScore::formatScoreYm($r['ym'] ?? '');
- if ($name === '' || $rowYm === '') {
- continue;
- }
- $quality = ProcuremenSupplierScore::readOptionalScoreValue($r['quality_score'] ?? null);
- $price = ProcuremenSupplierScore::readOptionalScoreValue($r['price_score'] ?? null);
- $delivery = ProcuremenSupplierScore::readOptionalScoreValue($r['delivery_score'] ?? null);
- $valueAdded = ProcuremenSupplierScore::readOptionalScoreValue($r['value_added_score'] ?? null);
- $final = ProcuremenSupplierScore::readOptionalScoreValue($r['final_score'] ?? null);
- $item = [
- 'quality_score' => $quality,
- 'price_score' => $price,
- 'delivery_score' => $delivery,
- 'value_added_score' => $valueAdded,
- 'final_score' => $final,
- 'final_saved' => $final !== null ? 1 : 0,
- 'score_grade' => ProcuremenSupplierScore::normalizeScoreGrade($r['score_grade'] ?? ''),
- 'score_date' => $rowYm,
- ];
- $list[] = $this->buildSupplierScoreListItem($name, $item, $rowYm);
- }
- usort($list, [$this, 'sortSupplierScoreListItems']);
- return $list;
- }
- /**
- * @param array<string, mixed> $item
- * @return array<string, mixed>
- */
- protected function buildSupplierScoreListItem(string $name, array $item, string $ym): array
- {
- $quality = array_key_exists('quality_score', $item) ? $item['quality_score'] : null;
- $price = array_key_exists('price_score', $item) ? $item['price_score'] : null;
- $delivery = array_key_exists('delivery_score', $item) ? $item['delivery_score'] : null;
- $valueAdded = array_key_exists('value_added_score', $item) ? $item['value_added_score'] : null;
- if ($quality !== null) {
- $quality = (float)$quality;
- }
- if ($price !== null) {
- $price = (float)$price;
- }
- if ($delivery !== null) {
- $delivery = (float)$delivery;
- }
- if ($valueAdded !== null) {
- $valueAdded = (float)$valueAdded;
- }
- $hasFinal = !empty($item['final_saved']);
- $final = $hasFinal ? (float)($item['final_score'] ?? 0) : null;
- if ($final === null) {
- $final = ProcuremenSupplierScore::sumFinalScore($quality, $price, $delivery, $valueAdded);
- }
- $grade = ProcuremenSupplierScore::normalizeScoreGrade($item['score_grade'] ?? '');
- if ($grade === '' && $final !== null) {
- $grade = ProcuremenSupplierScore::gradeFromFinalScore($final);
- }
- $sortScore = $final !== null
- ? (float)$final
- : (($quality ?? 0) + ($price ?? 0) + ($delivery ?? 0) + ($valueAdded ?? 0));
- $scoreDate = (string)($item['score_date'] ?? '');
- if ($scoreDate === '') {
- $scoreDate = ProcuremenSupplierScore::formatScoreYm($ym);
- }
- return [
- 'company_name' => $name,
- 'ym' => ProcuremenSupplierScore::formatScoreYm($ym),
- 'quality_score' => $quality,
- 'quality_score_text' => ProcuremenSupplierScore::formatOptionalScore($quality),
- 'price_score' => $price,
- 'price_score_text' => ProcuremenSupplierScore::formatOptionalScore($price),
- 'delivery_score' => $delivery,
- 'delivery_score_text' => ProcuremenSupplierScore::formatOptionalScore($delivery),
- 'value_added_score' => $valueAdded,
- 'value_added_score_text' => ProcuremenSupplierScore::formatOptionalScore($valueAdded),
- 'final_score' => $final,
- 'final_score_text' => $final !== null ? ProcuremenSupplierScore::formatOptionalScore($final) : '',
- 'final_score_saved' => $hasFinal ? 1 : 0,
- 'score_grade' => $grade,
- 'score_date' => $scoreDate,
- 'sort_score' => $sortScore,
- ];
- }
- /**
- * @param array<string, mixed> $a
- * @param array<string, mixed> $b
- */
- protected function sortSupplierScoreListItems(array $a, array $b): int
- {
- $ya = (string)($a['ym'] ?? '');
- $yb = (string)($b['ym'] ?? '');
- if ($ya !== $yb) {
- return strcmp($yb, $ya);
- }
- $sa = (float)($a['sort_score'] ?? 0);
- $sb = (float)($b['sort_score'] ?? 0);
- if ($sa !== $sb) {
- return $sb <=> $sa;
- }
- return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
- }
- protected function resolveRequestYm(): string
- {
- $ym = trim((string)$this->request->get('ym', ''));
- if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
- return $ym;
- }
- $filterRaw = $this->request->get('filter', '');
- if (is_string($filterRaw) && $filterRaw !== '') {
- $filter = json_decode($filterRaw, true);
- if (is_array($filter)) {
- $fy = trim((string)($filter['ym'] ?? ''));
- if (preg_match('/^\d{4}-\d{2}$/', $fy)) {
- return $fy;
- }
- }
- }
- if (preg_match('/^(\d{4})\D+(\d{1,2})/', $ym, $m)) {
- return sprintf('%04d-%02d', (int)$m[1], (int)$m[2]);
- }
- return ProcuremenSupplierScore::latestReviewYm();
- }
- protected function resolveSearchKeyword(): string
- {
- $keyword = trim((string)$this->request->get('search', ''));
- if ($keyword !== '') {
- return $keyword;
- }
- $filterRaw = $this->request->get('filter', '');
- if (is_string($filterRaw) && $filterRaw !== '') {
- $filter = json_decode($filterRaw, true);
- if (is_array($filter)) {
- return trim((string)($filter['company_name'] ?? ''));
- }
- }
- return '';
- }
- /**
- * 本月订单明细:已下发订单按「下发批次」(pick_time) 分行;
- * 同一批次内多工序顿号合并,不同下发时间不合并。
- * 仅返回已做质量评分且已完结的订单。
- *
- * @return array<int, array<string, mixed>>
- */
- /**
- * 本月订单明细:与质量得分同源 —— 该供应商「完结时间」落在本月且已质量评分的订单
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadMonthOrdersForSupplier(string $ym, string $companyName): array
- {
- $ym = trim($ym);
- $companyName = trim($companyName);
- if (!preg_match('/^\d{4}-\d{2}$/', $ym) || $companyName === '') {
- return [];
- }
- ProcuremenSupplierScore::ensureSchema();
- // 1) 入库/质量评分表(先取该供应商全部,再按完结月过滤,与月度计分一致)
- try {
- $scoreRowsRaw = \think\Db::table('purchase_order_inbound_score')
- ->where('company_name', $companyName)
- ->field('scydgy_id,ccydh,cyjmc,cgymc,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,createtime,updatetime')
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $scoreRowsRaw = \think\Db::table('purchase_order_inbound_score')
- ->where('company_name', $companyName)
- ->field('scydgy_id,ccydh,cyjmc,cgymc,result,delivery_status,customer_complaint,order_interrupt,remark,createtime,updatetime')
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e2) {
- try {
- $scoreRowsRaw = \think\Db::table('purchase_order_inbound_score')
- ->where('company_name', $companyName)
- ->field('scydgy_id,ccydh,cyjmc,cgymc,result,remark,createtime,updatetime')
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e3) {
- $scoreRowsRaw = [];
- }
- }
- }
- if (!is_array($scoreRowsRaw) || $scoreRowsRaw === []) {
- return [];
- }
- $sidSet = [];
- $inboundTimeBySid = [];
- foreach ($scoreRowsRaw as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if ($sid <= 0) {
- continue;
- }
- $sidSet[$sid] = true;
- $inboundTimeBySid[$sid] = [
- 'createtime' => $r['createtime'] ?? null,
- 'updatetime' => $r['updatetime'] ?? null,
- ];
- }
- $completedYmMap = ProcuremenSupplierScore::loadCompletedYmMapByScydgyIds(array_keys($sidSet), $inboundTimeBySid);
- $scoreRows = [];
- foreach ($scoreRowsRaw as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $rowYm = $sid > 0 ? (string)($completedYmMap[$sid] ?? '') : '';
- if ($rowYm === '' && $sid <= 0) {
- $t1 = \app\common\library\ProcuremenTime::parseToTimestamp($r['updatetime'] ?? null);
- $t2 = \app\common\library\ProcuremenTime::parseToTimestamp($r['createtime'] ?? null);
- $ts = max($t1, $t2);
- $rowYm = $ts > 946684800 ? date('Y-m', $ts) : '';
- }
- if ($rowYm !== $ym) {
- continue;
- }
- $scoreRows[] = $r;
- }
- if ($scoreRows === []) {
- return [];
- }
- /** @var array<string, array<string, mixed>> $byCcydh */
- $byCcydh = [];
- $sidSet = [];
- foreach ($scoreRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $ccydh = trim((string)($r['ccydh'] ?? ''));
- $result = trim((string)($r['result'] ?? ''));
- if ($ccydh === '' || ($result !== '合格' && $result !== '不合格')) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if ($sid > 0) {
- $sidSet[$sid] = true;
- }
- $scoreTime = trim((string)($r['updatetime'] ?? ''));
- if ($scoreTime === '' || preg_match('/^0000-00-00/', $scoreTime)) {
- $scoreTime = trim((string)($r['createtime'] ?? ''));
- }
- if (!isset($byCcydh[$ccydh])) {
- $ds = trim((string)($r['delivery_status'] ?? ''));
- if ($ds !== '准时' && $ds !== '滞后') {
- $ds = '';
- }
- $byCcydh[$ccydh] = [
- 'CCYDH' => $ccydh,
- 'scydgy_id' => $sid > 0 ? $sid : 0,
- 'scydgy_ids' => $sid > 0 ? [$sid] : [],
- 'CYJMC' => trim((string)($r['cyjmc'] ?? '')),
- 'CGYMC_list' => [],
- 'inbound_result' => $result,
- 'delivery_status' => $ds,
- 'delivery_date' => '',
- 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
- 'complaint_remark' => '',
- 'order_interrupt' => (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0,
- 'inbound_remark' => trim((string)($r['remark'] ?? '')),
- 'score_time' => $scoreTime,
- ];
- }
- $g = &$byCcydh[$ccydh];
- // 任一工序不合格 → 整单不合格(与质量分统计一致)
- if ($result === '不合格') {
- $g['inbound_result'] = '不合格';
- }
- if ($sid > 0) {
- if ($g['scydgy_id'] <= 0) {
- $g['scydgy_id'] = $sid;
- }
- if (!in_array($sid, $g['scydgy_ids'], true)) {
- $g['scydgy_ids'][] = $sid;
- }
- }
- $gymc = trim((string)($r['cgymc'] ?? ''));
- if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
- $g['CGYMC_list'][] = $gymc;
- }
- if ($g['CYJMC'] === '') {
- $g['CYJMC'] = trim((string)($r['cyjmc'] ?? ''));
- }
- if ($g['inbound_remark'] === '') {
- $g['inbound_remark'] = trim((string)($r['remark'] ?? ''));
- }
- if ($g['delivery_status'] === '') {
- $ds = trim((string)($r['delivery_status'] ?? ''));
- if ($ds === '准时' || $ds === '滞后') {
- $g['delivery_status'] = $ds;
- }
- }
- $dd = trim((string)($r['delivery_date'] ?? ''));
- if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
- $g['delivery_date'] = $mdd[1];
- }
- if ((int)($r['customer_complaint'] ?? 0) === 1) {
- $g['customer_complaint'] = 1;
- }
- $crm = trim((string)($r['complaint_remark'] ?? ''));
- if ($crm !== '' && $g['complaint_remark'] === '') {
- $g['complaint_remark'] = $crm;
- }
- if ((int)($r['order_interrupt'] ?? 0) === 1) {
- $g['order_interrupt'] = 1;
- }
- if ($scoreTime !== '' && ($g['score_time'] === '' || strcmp($scoreTime, $g['score_time']) > 0)) {
- $g['score_time'] = $scoreTime;
- }
- unset($g);
- }
- if ($byCcydh === []) {
- return [];
- }
- // 2) 补充采购单展示字段
- $poByCcydh = [];
- try {
- $poRows = \think\Db::table('purchase_order')
- ->where('CCYDH', 'in', array_keys($byCcydh))
- ->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%\')')
- ->field('CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,pick_company_name,wflow_status,status,pick_time,scydgy_id')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $poRows = [];
- }
- if (is_array($poRows)) {
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $c = trim((string)($po['CCYDH'] ?? ''));
- if ($c === '' || !isset($byCcydh[$c])) {
- continue;
- }
- if (!isset($poByCcydh[$c])) {
- $poByCcydh[$c] = [
- 'CYJMC' => '',
- 'CCLBMMC' => '',
- 'CGYMC_list' => [],
- 'CDW' => '',
- 'pick_company_name' => '',
- 'wflow_status' => '',
- 'status' => '',
- 'pick_time' => '',
- 'completed' => false,
- 'picked_match' => false,
- 'scydgy_id' => 0,
- ];
- }
- $p = &$poByCcydh[$c];
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($p['scydgy_id'] <= 0 && $sid > 0) {
- $p['scydgy_id'] = $sid;
- }
- if ($p['CYJMC'] === '') {
- $p['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
- }
- if ($p['CCLBMMC'] === '') {
- $p['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
- }
- if ($p['CDW'] === '') {
- $p['CDW'] = trim((string)($po['CDW'] ?? ''));
- }
- $g = trim((string)($po['CGYMC'] ?? ''));
- if ($g !== '' && !in_array($g, $p['CGYMC_list'], true)) {
- $p['CGYMC_list'][] = $g;
- }
- $pn = trim((string)($po['pick_company_name'] ?? ''));
- if ($pn !== '') {
- if ($p['pick_company_name'] === '') {
- $p['pick_company_name'] = $pn;
- }
- if ($pn === $companyName) {
- $p['picked_match'] = true;
- }
- }
- $pt = trim((string)($po['pick_time'] ?? ''));
- if ($pt !== '' && !preg_match('/^0000-00-00/', $pt)) {
- if ($p['pick_time'] === '' || strcmp($pt, $p['pick_time']) < 0) {
- $p['pick_time'] = $pt;
- }
- }
- if (\app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- $p['completed'] = true;
- $p['status'] = \app\common\library\ProcuremenStatus::PO_COMPLETED;
- } elseif ($p['status'] === '' && trim((string)($po['status'] ?? '')) !== '') {
- $p['status'] = trim((string)$po['status']);
- }
- if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
- $p['wflow_status'] = \app\common\library\ProcuremenStatus::WFLOW_APPROVED;
- } elseif ($p['wflow_status'] === '' && trim((string)($po['wflow_status'] ?? '')) !== '') {
- $p['wflow_status'] = trim((string)$po['wflow_status']);
- }
- unset($p);
- }
- }
- // 3) 可选:招标评分表补排名/分项(没有也不影响展示)
- $bidByCcydh = [];
- try {
- $bidRows = \think\Db::table(ProcuremenSupplierScore::TABLE_SCORE)
- ->where('ym', $ym)
- ->where('company_name', $companyName)
- ->where('ccydh', 'in', array_keys($byCcydh))
- ->field('ccydh,score,rank_no,quality_score,price_score,price_sum,lead_score,lead_days_sum,createtime')
- ->order('createtime', 'desc')
- ->select();
- } catch (\Throwable $e) {
- $bidRows = [];
- }
- if (is_array($bidRows)) {
- foreach ($bidRows as $br) {
- if (!is_array($br)) {
- continue;
- }
- $c = trim((string)($br['ccydh'] ?? ''));
- if ($c === '' || isset($bidByCcydh[$c])) {
- continue;
- }
- $bidByCcydh[$c] = $br;
- }
- }
- $out = [];
- foreach ($byCcydh as $ccydh => $g) {
- $po = $poByCcydh[$ccydh] ?? [];
- $bid = $bidByCcydh[$ccydh] ?? [];
- $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
- if ($gymcList === [] && is_array($po['CGYMC_list'] ?? null)) {
- $gymcList = $po['CGYMC_list'];
- }
- $batch = [
- 'completed' => !empty($po['completed']),
- 'status' => (string)($po['status'] ?? ''),
- 'wflow_status' => (string)($po['wflow_status'] ?? ''),
- ];
- $progressText = $this->formatMonthOrderProgressText($batch);
- // 已质量评分:进度优先显示已完结,否则显示实际流程
- if ($progressText === '待入库评分') {
- $progressText = \app\common\library\ProcuremenStatus::PO_COMPLETED;
- }
- $showBid = !empty($po['completed'])
- || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')
- || \app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '');
- $pickTimeRaw = trim((string)($po['pick_time'] ?? ''));
- if ($pickTimeRaw === '') {
- $pickTimeRaw = trim((string)($g['score_time'] ?? ''));
- }
- $sid = (int)($g['scydgy_id'] ?? 0);
- if ($sid <= 0) {
- $sid = (int)($po['scydgy_id'] ?? 0);
- }
- $out[] = [
- 'seq_no' => 0,
- 'scydgy_id' => $sid,
- 'CCYDH' => $ccydh,
- 'CYJMC' => (string)(($g['CYJMC'] ?? '') !== '' ? $g['CYJMC'] : ($po['CYJMC'] ?? '')),
- 'CCLBMMC' => (string)($po['CCLBMMC'] ?? ''),
- 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
- 'CDW' => (string)($po['CDW'] ?? ''),
- 'pick_company_name' => (string)(($po['pick_company_name'] ?? '') !== '' ? $po['pick_company_name'] : $companyName),
- 'wflow_status' => (string)($po['wflow_status'] ?? ''),
- 'status' => (string)($po['status'] ?? ''),
- 'progress_text' => $progressText,
- 'pick_time' => $pickTimeRaw,
- 'issue_time' => $pickTimeRaw !== ''
- ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickTimeRaw)
- : '',
- 'score' => $bid['score'] ?? null,
- 'rank_no' => (int)($bid['rank_no'] ?? 0),
- 'quality_score' => $bid['quality_score'] ?? null,
- 'price_score' => $bid['price_score'] ?? null,
- 'price_sum' => $bid['price_sum'] ?? null,
- 'lead_score' => $bid['lead_score'] ?? null,
- 'lead_days_sum' => $bid['lead_days_sum'] ?? null,
- 'is_picked' => !empty($po['picked_match']) ? 1 : 1,
- 'show_bid_result' => $showBid ? 1 : 0,
- 'inbound_result' => (string)($g['inbound_result'] ?? ''),
- 'delivery_status' => (string)($g['delivery_status'] ?? ''),
- 'delivery_date' => (string)($g['delivery_date'] ?? ''),
- 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
- 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
- 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
- 'inbound_remark' => (string)($g['inbound_remark'] ?? ''),
- ];
- }
- usort($out, static function ($a, $b) {
- $ta = (string)($a['pick_time'] ?? '');
- $tb = (string)($b['pick_time'] ?? '');
- if ($ta !== $tb) {
- return strcmp($tb, $ta);
- }
- return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
- });
- $total = count($out);
- $seq = $total;
- foreach ($out as &$row) {
- $row['seq_no'] = $seq;
- $seq--;
- }
- unset($row);
- return $out;
- }
- /**
- * 批量取各工序首次「下发」操作时间(用于本月明细按批次拆行)
- *
- * @param int[] $scydgyIds
- * @return array<int, string> scydgy_id => Y-m-d H:i:s
- */
- protected function loadFirstIssueTimeByScydgyIds(array $scydgyIds): array
- {
- $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds), static function ($id) {
- return $id > 0;
- })));
- if ($scydgyIds === []) {
- return [];
- }
- $acts = \app\common\library\ProcuremenOperLog::expandActionQueryValues('issue_submit');
- if ($acts === []) {
- return [];
- }
- try {
- $logs = \think\Db::table('purchase_order_oper_log')
- ->where(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID, 'in', $scydgyIds)
- ->where(\app\common\library\ProcuremenOperLog::COL_ACTION, 'in', $acts)
- ->field(\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID . ',' . \app\common\library\ProcuremenOperLog::COL_TIME)
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- return [];
- }
- $map = [];
- if (!is_array($logs)) {
- return [];
- }
- foreach ($logs as $lg) {
- if (!is_array($lg)) {
- continue;
- }
- $sid = (int)($lg[\app\common\library\ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
- if ($sid <= 0 || isset($map[$sid])) {
- continue;
- }
- $t = trim((string)($lg[\app\common\library\ProcuremenOperLog::COL_TIME] ?? ''));
- if ($t === '' || preg_match('/^0000-00-00/', $t)) {
- continue;
- }
- if (is_numeric($t) && (int)$t > 946684800) {
- $t = date('Y-m-d H:i:s', (int)$t);
- } else {
- $t = \app\common\library\ProcuremenTime::formatDisplayDateTime($t);
- }
- if ($t === '') {
- continue;
- }
- $map[$sid] = $t;
- }
- return $map;
- }
- /**
- * 当前进度:已完结优先;终审通过也显示已完结;其余展示流程阶段
- *
- * @param array<string, mixed> $po
- */
- protected function formatMonthOrderProgressText(array $po): string
- {
- if (!empty($po['completed']) || \app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- return \app\common\library\ProcuremenStatus::PO_COMPLETED;
- }
- // 采购终审通过后待入库评分,合格/不合格后才完结
- if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
- return '待入库评分';
- }
- $w = \app\common\library\ProcuremenStatus::normalizeWflowStatus($po['wflow_status'] ?? '');
- if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_APPROVAL) {
- return '待采购确认';
- }
- if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_CONFIRM) {
- return '待确认供应商';
- }
- if ($w === \app\common\library\ProcuremenStatus::WFLOW_PENDING_ISSUE) {
- return '待协助下发';
- }
- return $w !== '' ? $w : '—';
- }
- /**
- * 批量读取质量评分明细(是否合格 / 交货情况 / 客户投诉 / 订单中断 / 备注)
- *
- * @param int[] $scydgyIds
- * @return array<int, array{result:string,delivery_status:string,customer_complaint:int,order_interrupt:int,remark:string}>
- */
- protected function loadInboundResultByScydgyIds(array $scydgyIds): array
- {
- $ids = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
- if ($ids === []) {
- return [];
- }
- $out = [];
- try {
- $rows = \think\Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', $ids)
- ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark')
- ->select();
- } catch (\Throwable $e) {
- // 兼容旧表无新列
- try {
- $rows = \think\Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', $ids)
- ->field('scydgy_id,result,customer_complaint,order_interrupt,remark')
- ->select();
- } catch (\Throwable $e2) {
- try {
- $rows = \think\Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', $ids)
- ->field('scydgy_id,result,remark')
- ->select();
- } catch (\Throwable $e3) {
- return [];
- }
- }
- }
- if (!is_array($rows)) {
- return [];
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $result = trim((string)($r['result'] ?? ''));
- if ($sid <= 0 || ($result !== '合格' && $result !== '不合格')) {
- continue;
- }
- $ds = trim((string)($r['delivery_status'] ?? ''));
- if ($ds !== '准时' && $ds !== '滞后') {
- $ds = '';
- }
- $out[$sid] = [
- 'result' => $result,
- 'delivery_status' => $ds,
- 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
- 'order_interrupt' => (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0,
- 'remark' => trim((string)($r['remark'] ?? '')),
- ];
- }
- return $out;
- }
- }
|