| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880 |
- <?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, '');
- $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:D1');
- $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);
- $sheet->setCellValue('A2', '序号');
- $sheet->setCellValue('B2', '供应商');
- $sheet->setCellValue('C2', '最终得分');
- $sheet->setCellValue('D2', '评分等级');
- $sheet->getRowDimension(2)->setRowHeight(26);
- $sheet->getStyle('A2:D2')->getFont()->setName($fontName)->setBold(true)->setSize(14);
- $sheet->getStyle('A2:D2')->getAlignment()->applyFromArray($centerAlign);
- $rowNum = 3;
- if ($list === []) {
- $sheet->mergeCells('A3:D3');
- $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['final_score_text'] ?? ''));
- $sheet->setCellValue('D' . $rowNum, (string)($item['score_grade'] ?? ''));
- $sheet->getRowDimension($rowNum)->setRowHeight(24);
- $rowNum++;
- $i++;
- }
- }
- $lastRow = max(2, $rowNum - 1);
- $sheet->getStyle('A1:D' . $lastRow)->applyFromArray($borderStyle);
- $sheet->getStyle('A3:D' . $lastRow)->getFont()->setName($fontName)->setSize(12);
- $sheet->getStyle('A3:D' . $lastRow)->getAlignment()->applyFromArray($centerAlign);
- $sheet->getColumnDimension('A')->setWidth(12);
- $sheet->getColumnDimension('B')->setWidth(48);
- $sheet->getColumnDimension('C')->setWidth(14);
- $sheet->getColumnDimension('D')->setWidth(12);
- $sheet->getPageSetup()->setFitToPage(true)->setFitToWidth(1)->setFitToHeight(0);
- $filename = $title . '.xlsx';
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename="' . rawurlencode($filename) . '"');
- header('Cache-Control: max-age=0');
- $writer = new Xlsx($spreadsheet);
- $writer->save('php://output');
- $spreadsheet->disconnectWorksheets();
- unset($spreadsheet);
- exit;
- }
- /**
- * 月度评审记录列表(仅展示,最终得分可人工填写)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function loadMonthlySupplierScoreList(string $ym, string $keyword = ''): array
- {
- $ym = trim($ym);
- if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
- return [];
- }
- ProcuremenSupplierScore::ensureSchema();
- $monthlyMap = ProcuremenSupplierScore::loadMonthlyMapByYm($ym);
- $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 '';
- }
- /**
- * 某供应商某月参与评分的订单明细(开标/指定后按时间写入的评分记录)
- * 一单一行(多工序顿号间隔);按开标/指定时间倒序,不把整月汇总成一行
- *
- * @return array<int, array<string, mixed>>
- */
- /**
- * 本月订单明细:已下发订单按「下发批次」(pick_time) 分行;
- * 同一批次内多工序顿号合并,不同下发时间不合并。
- *
- * @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();
- try {
- $scoreRows = \think\Db::table(ProcuremenSupplierScore::TABLE_SCORE)
- ->where('ym', $ym)
- ->where('company_name', $companyName)
- ->field('ccydh,score,rank_no,quality_score,price_score,price_sum,lead_score,lead_days_sum,createtime')
- ->order('createtime', 'desc')
- ->order('ccydh', 'asc')
- ->select();
- } catch (\Throwable $e) {
- return [];
- }
- if (!is_array($scoreRows) || $scoreRows === []) {
- return [];
- }
- $scoreByCcydh = [];
- foreach ($scoreRows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $c = trim((string)($r['ccydh'] ?? ''));
- // 手工新增订单号 YW… 不进本月订单明细
- if ($c === '' || stripos($c, 'YW') === 0) {
- continue;
- }
- // 同单可能有重复评分行时保留最新一条(已按 createtime desc)
- if (!isset($scoreByCcydh[$c])) {
- $scoreByCcydh[$c] = $r;
- }
- }
- if ($scoreByCcydh === []) {
- return [];
- }
- $manualCcydh = [];
- /** @var array<string, array<string, array<string, mixed>>> $batchesByCcydh */
- $batchesByCcydh = [];
- /** @var array<int, array<string, mixed>> $issuedPoRows */
- $issuedPoRows = [];
- $sidList = [];
- try {
- $poRows = \think\Db::table('purchase_order')
- ->where('CCYDH', 'in', array_keys($scoreByCcydh))
- ->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,This_quantity,ceilingPrice,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($scoreByCcydh[$c])) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($sid < 0) {
- $manualCcydh[$c] = true;
- continue;
- }
- if (isset($manualCcydh[$c])) {
- continue;
- }
- $pickTime = trim((string)($po['pick_time'] ?? ''));
- if ($pickTime === '' || preg_match('/^0000-00-00/', $pickTime)) {
- continue;
- }
- $issuedPoRows[] = $po;
- if ($sid > 0) {
- $sidList[$sid] = true;
- }
- }
- }
- // 按工序首次下发日志时间分批(避免整单 pick_time 被后次下发覆盖后合到一行)
- $firstIssueBySid = $this->loadFirstIssueTimeByScydgyIds(array_keys($sidList));
- foreach ($issuedPoRows as $po) {
- if (isset($manualCcydh[trim((string)($po['CCYDH'] ?? ''))])) {
- continue;
- }
- $c = trim((string)($po['CCYDH'] ?? ''));
- $sid = (int)($po['scydgy_id'] ?? 0);
- $pickTime = trim((string)($po['pick_time'] ?? ''));
- $batchKey = '';
- if ($sid > 0 && isset($firstIssueBySid[$sid])) {
- $batchKey = $firstIssueBySid[$sid];
- }
- if ($batchKey === '') {
- $batchKey = $pickTime;
- }
- if ($batchKey === '' || preg_match('/^0000-00-00/', $batchKey)) {
- continue;
- }
- // 同一分钟内视为同一次下发(循环写入可能差 1 秒)
- $batchGroup = $batchKey;
- if (preg_match('/^(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2})/', $batchKey, $m)) {
- $batchGroup = $m[1];
- }
- if (!isset($batchesByCcydh[$c])) {
- $batchesByCcydh[$c] = [];
- }
- if (!isset($batchesByCcydh[$c][$batchGroup])) {
- $batchesByCcydh[$c][$batchGroup] = [
- 'scydgy_id' => $sid > 0 ? $sid : 0,
- 'scydgy_ids' => [],
- 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
- 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
- 'CGYMC_list' => [],
- 'CDW' => trim((string)($po['CDW'] ?? '')),
- 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
- 'wflow_status' => trim((string)($po['wflow_status'] ?? '')),
- 'status' => trim((string)($po['status'] ?? '')),
- 'pick_time' => $batchKey,
- 'completed' => false,
- 'picked_match' => false,
- ];
- }
- $batch = &$batchesByCcydh[$c][$batchGroup];
- if ($batch['scydgy_id'] <= 0 && $sid > 0) {
- $batch['scydgy_id'] = $sid;
- }
- if ($sid > 0 && !in_array($sid, $batch['scydgy_ids'], true)) {
- $batch['scydgy_ids'][] = $sid;
- }
- // 展示时间取该批次内最早时间
- if ($batch['pick_time'] === '' || strcmp($batchKey, $batch['pick_time']) < 0) {
- $batch['pick_time'] = $batchKey;
- }
- if ($batch['CYJMC'] === '') {
- $batch['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
- }
- if ($batch['CCLBMMC'] === '') {
- $batch['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
- }
- $g = trim((string)($po['CGYMC'] ?? ''));
- if ($g !== '' && !in_array($g, $batch['CGYMC_list'], true)) {
- $batch['CGYMC_list'][] = $g;
- }
- $pn = trim((string)($po['pick_company_name'] ?? ''));
- if ($pn !== '') {
- if ($batch['pick_company_name'] === '') {
- $batch['pick_company_name'] = $pn;
- }
- if ($pn === $companyName) {
- $batch['picked_match'] = true;
- }
- }
- if (\app\common\library\ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
- $batch['completed'] = true;
- $batch['status'] = \app\common\library\ProcuremenStatus::PO_COMPLETED;
- }
- if (\app\common\library\ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
- $batch['wflow_status'] = \app\common\library\ProcuremenStatus::WFLOW_APPROVED;
- } elseif ($batch['wflow_status'] === '' && trim((string)($po['wflow_status'] ?? '')) !== '') {
- $batch['wflow_status'] = trim((string)$po['wflow_status']);
- }
- unset($batch);
- }
- $out = [];
- $allSids = [];
- foreach ($batchesByCcydh as $ccydhBatches) {
- if (!is_array($ccydhBatches)) {
- continue;
- }
- foreach ($ccydhBatches as $batch) {
- if (!is_array($batch)) {
- continue;
- }
- foreach ((array)($batch['scydgy_ids'] ?? []) as $sidItem) {
- $sidItem = (int)$sidItem;
- if ($sidItem > 0) {
- $allSids[$sidItem] = true;
- }
- }
- $one = (int)($batch['scydgy_id'] ?? 0);
- if ($one > 0) {
- $allSids[$one] = true;
- }
- }
- }
- $inboundBySid = $this->loadInboundResultByScydgyIds(array_keys($allSids));
- foreach ($scoreByCcydh as $ccydh => $r) {
- if (isset($manualCcydh[$ccydh]) || !isset($batchesByCcydh[$ccydh])) {
- continue;
- }
- foreach ($batchesByCcydh[$ccydh] as $batch) {
- if (!is_array($batch)) {
- continue;
- }
- $pickTimeRaw = trim((string)($batch['pick_time'] ?? ''));
- if ($pickTimeRaw === '') {
- continue;
- }
- $gymcList = is_array($batch['CGYMC_list'] ?? null) ? $batch['CGYMC_list'] : [];
- // 与详情页一致:采购确认通过或已完结后才展示中标/未中标
- $showBid = !empty($batch['completed'])
- || \app\common\library\ProcuremenStatus::isPoCompleted($batch['status'] ?? '')
- || \app\common\library\ProcuremenStatus::isWflowApproved($batch['wflow_status'] ?? '');
- $isPicked = !empty($batch['picked_match']) ? 1 : 0;
- $inboundResult = '';
- $sidCandidates = is_array($batch['scydgy_ids'] ?? null) ? $batch['scydgy_ids'] : [];
- $mainSid = (int)($batch['scydgy_id'] ?? 0);
- if ($mainSid > 0 && !in_array($mainSid, $sidCandidates, true)) {
- $sidCandidates[] = $mainSid;
- }
- foreach ($sidCandidates as $sidItem) {
- $sidItem = (int)$sidItem;
- if ($sidItem > 0 && isset($inboundBySid[$sidItem]) && $inboundBySid[$sidItem] !== '') {
- $inboundResult = $inboundBySid[$sidItem];
- break;
- }
- }
- $out[] = [
- 'seq_no' => 0,
- 'scydgy_id' => (int)($batch['scydgy_id'] ?? 0),
- 'CCYDH' => $ccydh,
- 'CYJMC' => (string)($batch['CYJMC'] ?? ''),
- 'CCLBMMC' => (string)($batch['CCLBMMC'] ?? ''),
- 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
- 'CDW' => (string)($batch['CDW'] ?? ''),
- 'pick_company_name' => (string)($batch['pick_company_name'] ?? ''),
- 'wflow_status' => (string)($batch['wflow_status'] ?? ''),
- 'status' => (string)($batch['status'] ?? ''),
- 'progress_text' => $this->formatMonthOrderProgressText($batch),
- 'pick_time' => $pickTimeRaw,
- 'issue_time' => \app\common\library\ProcuremenTime::formatDisplayDateTime($pickTimeRaw),
- 'score' => $r['score'] ?? null,
- 'rank_no' => (int)($r['rank_no'] ?? 0),
- 'quality_score' => $r['quality_score'] ?? null,
- 'price_score' => $r['price_score'] ?? null,
- 'price_sum' => $r['price_sum'] ?? null,
- 'lead_score' => $r['lead_score'] ?? null,
- 'lead_days_sum' => $r['lead_days_sum'] ?? null,
- 'is_picked' => $isPicked,
- 'show_bid_result' => $showBid ? 1 : 0,
- 'inbound_result' => $inboundResult,
- ];
- }
- }
- usort($out, static function ($a, $b) {
- $ta = (string)($a['pick_time'] ?? '');
- $tb = (string)($b['pick_time'] ?? '');
- if ($ta !== $tb) {
- return strcmp($tb, $ta);
- }
- $ca = (string)($a['CCYDH'] ?? '');
- $cb = (string)($b['CCYDH'] ?? '');
- return strcmp($ca, $cb);
- });
- $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, string> scydgy_id => 合格|不合格
- */
- 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')
- ->select();
- } catch (\Throwable $e) {
- 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;
- }
- $out[$sid] = $result;
- }
- return $out;
- }
- }
|