| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947 |
- <?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 '';
- }
- /**
- * 本月订单明细:已下发订单按「下发批次」(pick_time) 分行;
- * 同一批次内多工序顿号合并,不同下发时间不合并。
- * 仅返回已做质量评分且已完结的订单。
- *
- * @return array<int, array<string, mixed>>
- */
- /**
- * 本月订单明细:与质量得分同源 —— 该供应商本月「质量评分」订单
- * (不再依赖招标评分表,也不强制已完结;与 calcQualityScoreFromInbound 一致)
- *
- * @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 {
- $scoreRows = \think\Db::table('purchase_order_inbound_score')
- ->where('company_name', $companyName)
- ->where(function ($q) use ($ym) {
- $q->where('updatetime', 'like', $ym . '%')
- ->whereOr('createtime', 'like', $ym . '%');
- })
- ->field('scydgy_id,ccydh,cyjmc,cgymc,result,delivery_status,customer_complaint,order_interrupt,remark,createtime,updatetime')
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $scoreRows = \think\Db::table('purchase_order_inbound_score')
- ->where('company_name', $companyName)
- ->where(function ($q) use ($ym) {
- $q->where('updatetime', 'like', $ym . '%')
- ->whereOr('createtime', 'like', $ym . '%');
- })
- ->field('scydgy_id,ccydh,cyjmc,cgymc,result,remark,createtime,updatetime')
- ->order('id', 'desc')
- ->select();
- } catch (\Throwable $e2) {
- $scoreRows = [];
- }
- }
- if (!is_array($scoreRows) || $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,
- 'customer_complaint' => (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0,
- '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;
- }
- }
- if ((int)($r['customer_complaint'] ?? 0) === 1) {
- $g['customer_complaint'] = 1;
- }
- 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'] ?? ''),
- 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
- '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;
- }
- }
|