| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010 |
- <?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;
- }
- // 有搜索词:跨月查该供应商;无搜索:按查询月份展示当月
- $list = $keyword !== ''
- ? $this->loadSupplierScoreSearchList($keyword)
- : $this->loadMonthlySupplierScoreList($ym, '');
- $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]);
- }
- 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,避免卡顿)
- * @return array<int, array<string, mixed>>
- */
- protected function loadMonthlySupplierScoreList(string $ym, string $keyword = '', bool $resync = true): 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 date('Y-m');
- }
- 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;
- }
- }
|