ProcuremenSupplierScore.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. <?php
  2. namespace app\common\library;
  3. use think\Db;
  4. use think\Log;
  5. /**
  6. * 协助采购 — 供应商服务评分
  7. *
  8. * 表分工:
  9. * - supplier_service_score:订单明细(开标后按 ccydh×供应商写入,含本单总分 score)
  10. * - supplier_service_final_score:月度评审表(开标后写入本月询价供应商名称;分项与等级人工填写,已存在不覆盖)
  11. *
  12. * 总分 = 商务/技术得分×质量% + 价格得分 [+ 交货得分×交货%]
  13. * 价格得分 = (本单最低单价合计 / 本供应商单价合计) × 价格权重% × 100
  14. * (计算过程保留四位小数,得分保留两位)
  15. * 商务/技术得分 = 月度评审表「商务/技术得分」(当月按上月起往前查,都无则默认 50)
  16. * 权重取 supplier_score_rule 中 is_default=1 的规则;开标验证通过后写入订单明细评分,并补齐月度评审供应商名称
  17. */
  18. class ProcuremenSupplierScore
  19. {
  20. public const TABLE_RULE = 'supplier_score_rule';
  21. /** 订单明细评分表 */
  22. public const TABLE_SCORE = 'supplier_service_score';
  23. /** 月度汇总表(总分 + 最终得分) */
  24. public const TABLE_FINAL = 'supplier_service_final_score';
  25. /** @var bool|null */
  26. protected static $schemaReady = null;
  27. public static function ensureSchema(): void
  28. {
  29. if (self::$schemaReady === true) {
  30. return;
  31. }
  32. try {
  33. Db::query('SELECT 1 FROM `' . self::TABLE_RULE . '` LIMIT 1');
  34. Db::query('SELECT 1 FROM `' . self::TABLE_SCORE . '` LIMIT 1');
  35. self::$schemaReady = true;
  36. self::ensureDefaultRule();
  37. self::ensureScoreWeightColumns();
  38. self::ensureLeadColumns();
  39. self::ensureIntegerColumns();
  40. self::ensureFinalScoreTable();
  41. return;
  42. } catch (\Throwable $e) {
  43. }
  44. $sqlFile = APP_PATH . 'extra' . DIRECTORY_SEPARATOR . 'supplier_score_install.sql';
  45. if (is_file($sqlFile)) {
  46. $sql = file_get_contents($sqlFile);
  47. if (is_string($sql) && $sql !== '') {
  48. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  49. $stmt = trim($stmt);
  50. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  51. continue;
  52. }
  53. try {
  54. Db::execute($stmt);
  55. } catch (\Throwable $ignore) {
  56. }
  57. }
  58. }
  59. }
  60. self::$schemaReady = true;
  61. self::ensureDefaultRule();
  62. self::ensureScoreWeightColumns();
  63. self::ensureLeadColumns();
  64. self::ensureIntegerColumns();
  65. self::ensureFinalScoreTable();
  66. }
  67. /** 月度记录表(商务技术分 / 价格分 / 最终得分,仅本页展示与导出) */
  68. public static function ensureFinalScoreTable(): void
  69. {
  70. $ddl = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_FINAL . "` (
  71. `id` int unsigned NOT NULL AUTO_INCREMENT,
  72. `ym` char(7) NOT NULL DEFAULT '' COMMENT '年月 YYYY-MM',
  73. `company_name` varchar(128) NOT NULL DEFAULT '' COMMENT '供应商名称',
  74. `score` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT '月度总分(兼容旧字段)',
  75. `quality_score` decimal(10,2) DEFAULT NULL COMMENT '商务技术分(人工,空=未填)',
  76. `price_score` decimal(10,2) DEFAULT NULL COMMENT '价格分(人工,空=未填)',
  77. `delivery_score` decimal(10,2) DEFAULT NULL COMMENT '交货分(人工,空=未填)',
  78. `final_score` decimal(10,2) DEFAULT NULL COMMENT '最终得分(人工,空=未填)',
  79. `score_grade` char(1) NOT NULL DEFAULT '' COMMENT '评分等级 A/B/C/D',
  80. `qp_manual` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=商务技术分/价格分/交货分已人工修改',
  81. `createtime` datetime DEFAULT NULL,
  82. `updatetime` datetime DEFAULT NULL,
  83. PRIMARY KEY (`id`),
  84. UNIQUE KEY `uk_ym_company` (`ym`,`company_name`),
  85. KEY `idx_ym` (`ym`)
  86. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='供应商月度评审记录'";
  87. try {
  88. Db::execute($ddl);
  89. } catch (\Throwable $e) {
  90. Log::write('supplier monthly score table: ' . $e->getMessage(), 'error');
  91. }
  92. self::ensureMonthlyScoreColumns();
  93. }
  94. /** 历史月度表补商务技术分/价格分等字段 */
  95. protected static function ensureMonthlyScoreColumns(): void
  96. {
  97. $adds = [
  98. 'score' => "ADD COLUMN `score` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT '月度总分(兼容旧字段)' AFTER `company_name`",
  99. 'quality_score' => "ADD COLUMN `quality_score` decimal(10,2) DEFAULT NULL COMMENT '商务技术分(人工,空=未填)' AFTER `score`",
  100. 'price_score' => "ADD COLUMN `price_score` decimal(10,2) DEFAULT NULL COMMENT '价格分(人工,空=未填)' AFTER `quality_score`",
  101. 'delivery_score' => "ADD COLUMN `delivery_score` decimal(10,2) DEFAULT NULL COMMENT '交货分(人工,空=未填)' AFTER `price_score`",
  102. 'score_grade' => "ADD COLUMN `score_grade` char(1) NOT NULL DEFAULT '' COMMENT '评分等级 A/B/C/D' AFTER `final_score`",
  103. 'qp_manual' => "ADD COLUMN `qp_manual` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=商务技术分/价格分/交货分已人工修改' AFTER `score_grade`",
  104. ];
  105. foreach ($adds as $col => $ddl) {
  106. try {
  107. $cols = Db::query("SHOW COLUMNS FROM `" . self::TABLE_FINAL . "` LIKE '{$col}'");
  108. if (!is_array($cols) || $cols === []) {
  109. Db::execute("ALTER TABLE `" . self::TABLE_FINAL . "` {$ddl}");
  110. }
  111. } catch (\Throwable $e) {
  112. Log::write("supplier monthly {$col} column: " . $e->getMessage(), 'error');
  113. }
  114. }
  115. // 分数字段允许 NULL:空=未填,列表不显示 0
  116. foreach ([
  117. 'quality_score' => '商务技术分(人工,空=未填)',
  118. 'price_score' => '价格分(人工,空=未填)',
  119. 'delivery_score' => '交货分(人工,空=未填)',
  120. 'final_score' => '最终得分(人工,空=未填)',
  121. ] as $col => $comment) {
  122. try {
  123. $info = Db::query("SHOW COLUMNS FROM `" . self::TABLE_FINAL . "` LIKE '{$col}'");
  124. if (is_array($info) && $info !== []) {
  125. $null = strtoupper((string)($info[0]['Null'] ?? ''));
  126. if ($null !== 'YES') {
  127. Db::execute(
  128. "ALTER TABLE `" . self::TABLE_FINAL . "` MODIFY COLUMN `{$col}` decimal(10,2) DEFAULT NULL COMMENT '{$comment}'"
  129. );
  130. }
  131. }
  132. } catch (\Throwable $e) {
  133. Log::write("supplier monthly {$col} null: " . $e->getMessage(), 'error');
  134. }
  135. }
  136. }
  137. /** 规范化评分等级:空 / A / B / C / D */
  138. public static function normalizeScoreGrade($raw): string
  139. {
  140. $g = strtoupper(trim((string)$raw));
  141. if (in_array($g, ['A', 'B', 'C', 'D'], true)) {
  142. return $g;
  143. }
  144. return '';
  145. }
  146. /**
  147. * 按订单明细重算并写入某月评审记录(商务技术分/价格分;保留已填最终得分)
  148. *
  149. * @param array<int, string>|null $onlyCompanies 仅同步这些供应商;null=当月全部
  150. */
  151. public static function syncMonthlyScoresForYm(string $ym, ?array $onlyCompanies = null): void
  152. {
  153. $ym = trim($ym);
  154. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  155. return;
  156. }
  157. self::ensureSchema();
  158. self::ensureFinalScoreTable();
  159. try {
  160. $query = Db::table(self::TABLE_SCORE)
  161. ->where('ym', $ym)
  162. ->field('company_name,score,quality_score,price_score,lead_score');
  163. if (is_array($onlyCompanies) && $onlyCompanies !== []) {
  164. $names = [];
  165. foreach ($onlyCompanies as $n) {
  166. $n = trim((string)$n);
  167. if ($n !== '') {
  168. $names[$n] = true;
  169. }
  170. }
  171. if ($names === []) {
  172. return;
  173. }
  174. $query->where('company_name', 'in', array_keys($names));
  175. }
  176. $rows = $query->select();
  177. } catch (\Throwable $e) {
  178. // 无 lead_score 列时回退
  179. try {
  180. $query = Db::table(self::TABLE_SCORE)
  181. ->where('ym', $ym)
  182. ->field('company_name,score,quality_score,price_score');
  183. if (is_array($onlyCompanies) && $onlyCompanies !== []) {
  184. $names = [];
  185. foreach ($onlyCompanies as $n) {
  186. $n = trim((string)$n);
  187. if ($n !== '') {
  188. $names[$n] = true;
  189. }
  190. }
  191. if ($names === []) {
  192. return;
  193. }
  194. $query->where('company_name', 'in', array_keys($names));
  195. }
  196. $rows = $query->select();
  197. } catch (\Throwable $e2) {
  198. Log::write('supplier monthly sync read: ' . $e2->getMessage(), 'error');
  199. return;
  200. }
  201. }
  202. if (!is_array($rows)) {
  203. return;
  204. }
  205. $agg = [];
  206. foreach ($rows as $r) {
  207. if (!is_array($r)) {
  208. continue;
  209. }
  210. $cn = trim((string)($r['company_name'] ?? ''));
  211. if ($cn === '') {
  212. continue;
  213. }
  214. if (!isset($agg[$cn])) {
  215. $agg[$cn] = [
  216. 'score_sum' => 0.0,
  217. 'quality_sum' => 0.0,
  218. 'price_sum' => 0.0,
  219. 'delivery_sum' => 0.0,
  220. 'cnt' => 0,
  221. ];
  222. }
  223. $agg[$cn]['score_sum'] += (float)($r['score'] ?? 0);
  224. $agg[$cn]['quality_sum'] += (float)($r['quality_score'] ?? 0);
  225. $agg[$cn]['price_sum'] += (float)($r['price_score'] ?? 0);
  226. $agg[$cn]['delivery_sum'] += (float)($r['lead_score'] ?? 0);
  227. $agg[$cn]['cnt']++;
  228. }
  229. $now = date('Y-m-d H:i:s');
  230. foreach ($agg as $cn => $a) {
  231. $cnt = (int)$a['cnt'];
  232. $avgScore = $cnt > 0 ? round($a['score_sum'] / $cnt, 2) : 0.0;
  233. $avgQuality = $cnt > 0 ? round($a['quality_sum'] / $cnt, 2) : 0.0;
  234. $avgPrice = $cnt > 0 ? round($a['price_sum'] / $cnt, 2) : 0.0;
  235. $avgDelivery = $cnt > 0 ? round($a['delivery_sum'] / $cnt, 2) : 0.0;
  236. try {
  237. $exists = Db::table(self::TABLE_FINAL)->where('ym', $ym)->where('company_name', $cn)->find();
  238. if (is_array($exists) && $exists !== []) {
  239. $upd = [
  240. 'score' => $avgScore,
  241. 'updatetime' => $now,
  242. ];
  243. // 人工改过商务技术分/价格分/交货分后,同步不再覆盖
  244. if ((int)($exists['qp_manual'] ?? 0) !== 1) {
  245. $upd['quality_score'] = $avgQuality;
  246. $upd['price_score'] = $avgPrice;
  247. $upd['delivery_score'] = $avgDelivery;
  248. }
  249. Db::table(self::TABLE_FINAL)->where('id', (int)($exists['id'] ?? 0))->update($upd);
  250. } else {
  251. Db::table(self::TABLE_FINAL)->insert([
  252. 'ym' => $ym,
  253. 'company_name' => $cn,
  254. 'score' => $avgScore,
  255. 'quality_score' => $avgQuality,
  256. 'price_score' => $avgPrice,
  257. 'delivery_score' => $avgDelivery,
  258. 'final_score' => null,
  259. 'score_grade' => '',
  260. 'qp_manual' => 0,
  261. 'createtime' => $now,
  262. 'updatetime' => $now,
  263. ]);
  264. }
  265. } catch (\Throwable $e) {
  266. Log::write('supplier monthly sync write: ' . $e->getMessage(), 'error');
  267. }
  268. }
  269. }
  270. /**
  271. * 读取某月各供应商最终得分(仅已人工填写的)
  272. *
  273. * @return array<string, float> company_name => final_score
  274. */
  275. public static function loadFinalScoreMapByYm(string $ym): array
  276. {
  277. $ym = trim($ym);
  278. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  279. return [];
  280. }
  281. self::ensureFinalScoreTable();
  282. try {
  283. $rows = Db::table(self::TABLE_FINAL)
  284. ->where('ym', $ym)
  285. ->whereNotNull('final_score')
  286. ->field('company_name,final_score')
  287. ->select();
  288. } catch (\Throwable $e) {
  289. return [];
  290. }
  291. if (!is_array($rows)) {
  292. return [];
  293. }
  294. $out = [];
  295. foreach ($rows as $r) {
  296. if (!is_array($r)) {
  297. continue;
  298. }
  299. $cn = trim((string)($r['company_name'] ?? ''));
  300. if ($cn === '') {
  301. continue;
  302. }
  303. $out[$cn] = round((float)($r['final_score'] ?? 0), 2);
  304. }
  305. return $out;
  306. }
  307. /**
  308. * 读取库中可选分数:NULL/空串 → null;合法数字 → float
  309. *
  310. * @param mixed $raw
  311. */
  312. public static function readOptionalScoreValue($raw): ?float
  313. {
  314. if ($raw === null) {
  315. return null;
  316. }
  317. if (is_string($raw) && trim($raw) === '') {
  318. return null;
  319. }
  320. if (!is_numeric($raw)) {
  321. return null;
  322. }
  323. return round((float)$raw, 2);
  324. }
  325. /**
  326. * 可选分数展示:空不显示 0
  327. *
  328. * @param float|null $n
  329. */
  330. public static function formatOptionalScore(?float $n): string
  331. {
  332. if ($n === null) {
  333. return '';
  334. }
  335. return self::formatScore($n);
  336. }
  337. /**
  338. * 开标后把本月询价供应商名称写入月度评审表:不存在则插入空行,已存在不改(分数人工填)
  339. *
  340. * @param array<int, string> $companyNames
  341. * @return int 新插入条数
  342. */
  343. public static function ensureMonthlySupplierNames(string $ym, array $companyNames): int
  344. {
  345. $ym = trim($ym);
  346. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  347. return 0;
  348. }
  349. $uniq = [];
  350. foreach ($companyNames as $n) {
  351. $n = trim((string)$n);
  352. if ($n !== '') {
  353. $uniq[$n] = true;
  354. }
  355. }
  356. if ($uniq === []) {
  357. return 0;
  358. }
  359. self::ensureFinalScoreTable();
  360. $now = date('Y-m-d H:i:s');
  361. $inserted = 0;
  362. foreach (array_keys($uniq) as $cn) {
  363. try {
  364. $exists = Db::table(self::TABLE_FINAL)->where('ym', $ym)->where('company_name', $cn)->find();
  365. if (is_array($exists) && $exists !== []) {
  366. continue;
  367. }
  368. Db::table(self::TABLE_FINAL)->insert([
  369. 'ym' => $ym,
  370. 'company_name' => $cn,
  371. 'score' => 0,
  372. 'quality_score' => null,
  373. 'price_score' => null,
  374. 'delivery_score' => null,
  375. 'final_score' => null,
  376. 'score_grade' => '',
  377. 'qp_manual' => 0,
  378. 'createtime' => $now,
  379. 'updatetime' => $now,
  380. ]);
  381. $inserted++;
  382. } catch (\Throwable $e) {
  383. // 并发下唯一键冲突视为已存在
  384. if (stripos($e->getMessage(), 'Duplicate') === false) {
  385. Log::write('supplier monthly ensure name: ' . $e->getMessage(), 'error');
  386. }
  387. }
  388. }
  389. return $inserted;
  390. }
  391. /**
  392. * 按当月订单评分表中的供应商,补齐月度评审表名称(仅新增空行)
  393. */
  394. public static function ensureMonthlySupplierNamesFromOrderYm(string $ym): void
  395. {
  396. $ym = trim($ym);
  397. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  398. return;
  399. }
  400. self::ensureSchema();
  401. self::ensureFinalScoreTable();
  402. try {
  403. $rows = Db::table(self::TABLE_SCORE)
  404. ->where('ym', $ym)
  405. ->field('company_name')
  406. ->group('company_name')
  407. ->select();
  408. } catch (\Throwable $e) {
  409. return;
  410. }
  411. if (!is_array($rows) || $rows === []) {
  412. return;
  413. }
  414. $names = [];
  415. foreach ($rows as $r) {
  416. if (!is_array($r)) {
  417. continue;
  418. }
  419. $cn = trim((string)($r['company_name'] ?? ''));
  420. if ($cn !== '') {
  421. $names[] = $cn;
  422. }
  423. }
  424. self::ensureMonthlySupplierNames($ym, $names);
  425. }
  426. /**
  427. * 读取某月评审记录(仅读月度表;先按当月开标/询价供应商补齐名称)
  428. *
  429. * @return array<string, array{score:float,quality_score:?float,price_score:?float,delivery_score:?float,final_score:?float,final_saved:int,score_grade:string}>
  430. */
  431. public static function loadMonthlyMapByYm(string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return [];
  436. }
  437. self::ensureFinalScoreTable();
  438. // 本月询价(开标后已写入订单评分表)的供应商:名称不存在则加空行,已存在不动
  439. self::ensureMonthlySupplierNamesFromOrderYm($ym);
  440. try {
  441. $rows = Db::table(self::TABLE_FINAL)
  442. ->where('ym', $ym)
  443. ->field('company_name,score,quality_score,price_score,delivery_score,final_score,score_grade')
  444. ->select();
  445. } catch (\Throwable $e) {
  446. return [];
  447. }
  448. if (!is_array($rows)) {
  449. return [];
  450. }
  451. $out = [];
  452. foreach ($rows as $r) {
  453. if (!is_array($r)) {
  454. continue;
  455. }
  456. $cn = trim((string)($r['company_name'] ?? ''));
  457. if ($cn === '') {
  458. continue;
  459. }
  460. $quality = self::readOptionalScoreValue($r['quality_score'] ?? null);
  461. $price = self::readOptionalScoreValue($r['price_score'] ?? null);
  462. $delivery = self::readOptionalScoreValue($r['delivery_score'] ?? null);
  463. $final = self::readOptionalScoreValue($r['final_score'] ?? null);
  464. $out[$cn] = [
  465. 'score' => round((float)($r['score'] ?? 0), 2),
  466. 'quality_score' => $quality,
  467. 'price_score' => $price,
  468. 'delivery_score' => $delivery,
  469. 'final_score' => $final,
  470. 'final_saved' => $final !== null ? 1 : 0,
  471. 'score_grade' => self::normalizeScoreGrade($r['score_grade'] ?? ''),
  472. ];
  473. }
  474. return $out;
  475. }
  476. /**
  477. * 解析可选分数:空=null;非法=false;合法=float
  478. *
  479. * @param mixed $raw
  480. * @return float|null|false
  481. */
  482. protected static function parseOptionalScore($raw)
  483. {
  484. if ($raw === null) {
  485. return null;
  486. }
  487. if (is_string($raw) && trim($raw) === '') {
  488. return null;
  489. }
  490. if (!is_numeric($raw)) {
  491. return false;
  492. }
  493. return round((float)$raw, 2);
  494. }
  495. /**
  496. * 批量保存某月评审分:商务技术分 / 价格分 / 交货分 / 最终得分 / 评分等级
  497. *
  498. * @param array<int, array{company_name?:string,quality_score?:mixed,price_score?:mixed,delivery_score?:mixed,final_score?:mixed,score_grade?:mixed}> $items
  499. * @return array{done:int,saved:int,cleared:int,error:string}
  500. */
  501. public static function saveFinalScoresForYm(string $ym, array $items): array
  502. {
  503. $ym = trim($ym);
  504. $result = ['done' => 0, 'saved' => 0, 'cleared' => 0, 'error' => ''];
  505. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  506. $result['error'] = '月份无效';
  507. return $result;
  508. }
  509. if ($items === []) {
  510. $result['error'] = '没有可保存的数据';
  511. return $result;
  512. }
  513. self::ensureFinalScoreTable();
  514. try {
  515. Db::query('SELECT 1 FROM `' . self::TABLE_FINAL . '` LIMIT 1');
  516. } catch (\Throwable $e) {
  517. $result['error'] = '月度汇总表未创建,请联系管理员';
  518. return $result;
  519. }
  520. $now = date('Y-m-d H:i:s');
  521. foreach ($items as $it) {
  522. if (!is_array($it)) {
  523. continue;
  524. }
  525. $cn = trim((string)($it['company_name'] ?? ''));
  526. if ($cn === '') {
  527. continue;
  528. }
  529. $grade = self::normalizeScoreGrade($it['score_grade'] ?? '');
  530. $quality = self::parseOptionalScore($it['quality_score'] ?? null);
  531. $price = self::parseOptionalScore($it['price_score'] ?? null);
  532. $delivery = self::parseOptionalScore($it['delivery_score'] ?? null);
  533. $final = self::parseOptionalScore($it['final_score'] ?? null);
  534. if ($quality === false || $price === false || $delivery === false || $final === false) {
  535. continue;
  536. }
  537. $hasQp = array_key_exists('quality_score', $it)
  538. || array_key_exists('price_score', $it)
  539. || array_key_exists('delivery_score', $it);
  540. try {
  541. $exists = Db::table(self::TABLE_FINAL)->where('ym', $ym)->where('company_name', $cn)->find();
  542. $upd = [
  543. 'final_score' => $final,
  544. 'score_grade' => $grade,
  545. 'updatetime' => $now,
  546. ];
  547. if ($hasQp) {
  548. // 空值存 NULL,列表显示空白而不是 0
  549. $upd['quality_score'] = $quality;
  550. $upd['price_score'] = $price;
  551. $upd['delivery_score'] = $delivery;
  552. $upd['score'] = round(($quality ?? 0) + ($price ?? 0) + ($delivery ?? 0), 2);
  553. $upd['qp_manual'] = 1;
  554. }
  555. if (is_array($exists) && $exists !== []) {
  556. Db::table(self::TABLE_FINAL)->where('id', (int)($exists['id'] ?? 0))->update($upd);
  557. } else {
  558. Db::table(self::TABLE_FINAL)->insert([
  559. 'ym' => $ym,
  560. 'company_name' => $cn,
  561. 'score' => $hasQp ? round(($quality ?? 0) + ($price ?? 0) + ($delivery ?? 0), 2) : 0,
  562. 'quality_score' => $hasQp ? $quality : null,
  563. 'price_score' => $hasQp ? $price : null,
  564. 'delivery_score' => $hasQp ? $delivery : null,
  565. 'final_score' => $final,
  566. 'score_grade' => $grade,
  567. 'qp_manual' => $hasQp ? 1 : 0,
  568. 'createtime' => $now,
  569. 'updatetime' => $now,
  570. ]);
  571. }
  572. if ($final === null && $grade === '' && !$hasQp) {
  573. $result['cleared']++;
  574. } else {
  575. $result['saved']++;
  576. }
  577. $result['done']++;
  578. } catch (\Throwable $e) {
  579. Log::write('supplier final score save: ' . $e->getMessage(), 'error');
  580. $result['error'] = $e->getMessage();
  581. }
  582. }
  583. return $result;
  584. }
  585. /** 历史表补质量/价格百分比字段 */
  586. protected static function ensureScoreWeightColumns(): void
  587. {
  588. try {
  589. $cols = Db::query("SHOW COLUMNS FROM `" . self::TABLE_SCORE . "` LIKE 'quality_weight'");
  590. if (!is_array($cols) || $cols === []) {
  591. Db::execute(
  592. "ALTER TABLE `" . self::TABLE_SCORE . "` ADD COLUMN `quality_weight` int unsigned NOT NULL DEFAULT 50 COMMENT '质量百分比' AFTER `quality_score`"
  593. );
  594. }
  595. $cols2 = Db::query("SHOW COLUMNS FROM `" . self::TABLE_SCORE . "` LIKE 'price_weight'");
  596. if (!is_array($cols2) || $cols2 === []) {
  597. Db::execute(
  598. "ALTER TABLE `" . self::TABLE_SCORE . "` ADD COLUMN `price_weight` int unsigned NOT NULL DEFAULT 50 COMMENT '价格百分比' AFTER `price_sum`"
  599. );
  600. }
  601. } catch (\Throwable $e) {
  602. Log::write('supplier score weight columns: ' . $e->getMessage(), 'error');
  603. }
  604. }
  605. /** 历史表补交货期权重/得分字段 */
  606. protected static function ensureLeadColumns(): void
  607. {
  608. $adds = [
  609. self::TABLE_RULE => [
  610. 'lead_weight' => "ADD COLUMN `lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '交货期得分权重(%)' AFTER `price_weight`",
  611. 'lead_enabled' => "ADD COLUMN `lead_enabled` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=交货期纳入总分' AFTER `lead_weight`",
  612. ],
  613. self::TABLE_SCORE => [
  614. 'lead_days_sum' => "ADD COLUMN `lead_days_sum` int NOT NULL DEFAULT 0 COMMENT '本单工序工期合计(天)' AFTER `price_score`",
  615. 'lead_weight' => "ADD COLUMN `lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '交货期百分比' AFTER `lead_days_sum`",
  616. 'lead_enabled' => "ADD COLUMN `lead_enabled` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=当时纳入总分' AFTER `lead_weight`",
  617. 'lead_score' => "ADD COLUMN `lead_score` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT '交货期评分值' AFTER `lead_enabled`",
  618. ],
  619. ];
  620. foreach ($adds as $table => $cols) {
  621. foreach ($cols as $col => $ddl) {
  622. try {
  623. $info = Db::query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  624. if (is_array($info) && $info !== []) {
  625. continue;
  626. }
  627. Db::execute("ALTER TABLE `{$table}` {$ddl}");
  628. } catch (\Throwable $e) {
  629. Log::write("supplier score lead column {$table}.{$col}: " . $e->getMessage(), 'error');
  630. }
  631. }
  632. }
  633. }
  634. /** 将权重/质量分/单价合计等字段改为整数(去掉 .00) */
  635. protected static function ensureIntegerColumns(): void
  636. {
  637. $defs = [
  638. self::TABLE_RULE => [
  639. 'quality_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '上年度质量评分权重(%)'",
  640. 'price_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '单价评分权重(%)'",
  641. 'lead_weight' => "int unsigned NOT NULL DEFAULT 0 COMMENT '交货期得分权重(%)'",
  642. ],
  643. self::TABLE_SCORE => [
  644. 'quality_score' => "int NOT NULL DEFAULT 0 COMMENT '上年度质量评分'",
  645. 'quality_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '质量百分比'",
  646. 'price_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '价格百分比'",
  647. 'lead_days_sum' => "int NOT NULL DEFAULT 0 COMMENT '本单工序工期合计(天)'",
  648. 'lead_weight' => "int unsigned NOT NULL DEFAULT 0 COMMENT '交货期百分比'",
  649. ],
  650. ];
  651. foreach ($defs as $table => $cols) {
  652. foreach ($cols as $col => $def) {
  653. try {
  654. $info = Db::query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  655. if (!is_array($info) || $info === []) {
  656. continue;
  657. }
  658. $type = strtolower((string)($info[0]['Type'] ?? $info[0]['type'] ?? ''));
  659. if (preg_match('/^(tiny|small|medium|big)?int\b/', $type)) {
  660. continue;
  661. }
  662. Db::execute("ALTER TABLE `{$table}` MODIFY COLUMN `{$col}` {$def}");
  663. } catch (\Throwable $e) {
  664. Log::write("supplier score int column {$table}.{$col}: " . $e->getMessage(), 'error');
  665. }
  666. }
  667. }
  668. // 单价合计需保留小数(如 0.25),不可用 int
  669. try {
  670. $info = Db::query("SHOW COLUMNS FROM `" . self::TABLE_SCORE . "` LIKE 'price_sum'");
  671. if (is_array($info) && $info !== []) {
  672. $type = strtolower((string)($info[0]['Type'] ?? $info[0]['type'] ?? ''));
  673. if (preg_match('/^(tiny|small|medium|big)?int\b/', $type)) {
  674. Db::execute(
  675. "ALTER TABLE `" . self::TABLE_SCORE . "` MODIFY COLUMN `price_sum` decimal(12,4) NOT NULL DEFAULT 0.0000 COMMENT '本单工序单价合计'"
  676. );
  677. }
  678. }
  679. } catch (\Throwable $e) {
  680. Log::write('supplier score price_sum decimal: ' . $e->getMessage(), 'error');
  681. }
  682. }
  683. protected static function ensureDefaultRule(): void
  684. {
  685. try {
  686. $cnt = (int)Db::table(self::TABLE_RULE)->count();
  687. if ($cnt > 0) {
  688. $hasDefault = Db::table(self::TABLE_RULE)->where('is_default', 1)->find();
  689. if (!is_array($hasDefault)) {
  690. $first = Db::table(self::TABLE_RULE)->order('id', 'asc')->find();
  691. if (is_array($first)) {
  692. Db::table(self::TABLE_RULE)->where('id', (int)$first['id'])->update([
  693. 'is_default' => 1,
  694. 'updatetime' => date('Y-m-d H:i:s'),
  695. ]);
  696. }
  697. }
  698. return;
  699. }
  700. $now = date('Y-m-d H:i:s');
  701. Db::table(self::TABLE_RULE)->insert([
  702. 'name' => '默认规则(商务/技术50%+单价50%)',
  703. 'quality_weight' => 50,
  704. 'price_weight' => 50,
  705. 'is_default' => 1,
  706. 'status' => 'normal',
  707. 'createtime' => $now,
  708. 'updatetime' => $now,
  709. ]);
  710. } catch (\Throwable $e) {
  711. Log::write('supplier score ensureDefaultRule: ' . $e->getMessage(), 'error');
  712. }
  713. }
  714. /**
  715. * @return array{id:int,name:string,quality_weight:int,price_weight:int,lead_weight:int,lead_enabled:int}
  716. */
  717. public static function getDefaultRule(): array
  718. {
  719. self::ensureSchema();
  720. try {
  721. $row = Db::table(self::TABLE_RULE)
  722. ->where('is_default', 1)
  723. ->where('status', 'normal')
  724. ->order('id', 'desc')
  725. ->find();
  726. if (!is_array($row)) {
  727. $row = Db::table(self::TABLE_RULE)->where('status', 'normal')->order('id', 'asc')->find();
  728. }
  729. if (is_array($row)) {
  730. $lw = (int)($row['lead_weight'] ?? 0);
  731. return [
  732. 'id' => (int)($row['id'] ?? 0),
  733. 'name' => trim((string)($row['name'] ?? '')),
  734. 'quality_weight' => (int)($row['quality_weight'] ?? 50),
  735. 'price_weight' => (int)($row['price_weight'] ?? 50),
  736. 'lead_weight' => $lw,
  737. // 权重大于 0 即纳入;兼容旧 lead_enabled 字段
  738. 'lead_enabled' => $lw > 0 ? 1 : 0,
  739. ];
  740. }
  741. } catch (\Throwable $e) {
  742. }
  743. return [
  744. 'id' => 0,
  745. 'name' => '内置默认',
  746. 'quality_weight' => 50,
  747. 'price_weight' => 50,
  748. 'lead_weight' => 0,
  749. 'lead_enabled' => 0,
  750. ];
  751. }
  752. /**
  753. * 规范年月;空则取当前月
  754. */
  755. public static function normalizeYm(?string $ym): string
  756. {
  757. $ym = trim((string)$ym);
  758. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  759. return $ym;
  760. }
  761. return date('Y-m');
  762. }
  763. /**
  764. * 上一自然月 YYYY-MM
  765. */
  766. public static function previousYm(string $ym): string
  767. {
  768. $ym = self::normalizeYm($ym);
  769. $ts = strtotime($ym . '-01');
  770. if ($ts === false) {
  771. $ts = time();
  772. }
  773. return date('Y-m', strtotime('-1 month', $ts));
  774. }
  775. /**
  776. * 从月度评审表取商务技术分:当月按上月起往前查,都没有则默认 50
  777. *
  778. * @param array<int, string> $companyNames
  779. * @return array<string, float> company_name => quality_score
  780. */
  781. public static function loadReviewQualityScoreMap(array $companyNames, ?string $asOfYm = null): array
  782. {
  783. $asOfYm = self::normalizeYm($asOfYm);
  784. $default = 50.0;
  785. $map = [];
  786. $names = [];
  787. foreach ($companyNames as $n) {
  788. $n = trim((string)$n);
  789. if ($n !== '') {
  790. $names[$n] = true;
  791. $map[$n] = $default;
  792. }
  793. }
  794. if ($names === []) {
  795. return $map;
  796. }
  797. self::ensureFinalScoreTable();
  798. try {
  799. // 当月按上个月起查:ym < asOfYm,且商务技术分已填写
  800. $rows = Db::table(self::TABLE_FINAL)
  801. ->where('company_name', 'in', array_keys($names))
  802. ->where('ym', '<', $asOfYm)
  803. ->whereNotNull('quality_score')
  804. ->field('company_name,ym,quality_score')
  805. ->order('ym', 'desc')
  806. ->select();
  807. } catch (\Throwable $e) {
  808. return $map;
  809. }
  810. if (!is_array($rows)) {
  811. return $map;
  812. }
  813. $seen = [];
  814. foreach ($rows as $r) {
  815. if (!is_array($r)) {
  816. continue;
  817. }
  818. $cn = trim((string)($r['company_name'] ?? ''));
  819. if ($cn === '' || isset($seen[$cn])) {
  820. continue;
  821. }
  822. $score = self::readOptionalScoreValue($r['quality_score'] ?? null);
  823. if ($score === null) {
  824. continue;
  825. }
  826. $seen[$cn] = true;
  827. $map[$cn] = round((float)$score, 2);
  828. }
  829. return $map;
  830. }
  831. /**
  832. * 按公司名批量取供应商 id(兼容旧调用保留评分字段结构)
  833. *
  834. * @param array<int, string> $companyNames
  835. * @return array<string, array{id:int,score:float,monthly_score:?float,quality_avg:float}>
  836. */
  837. public static function loadCustomerScoreMap(array $companyNames): array
  838. {
  839. $map = [];
  840. $names = [];
  841. foreach ($companyNames as $n) {
  842. $n = trim((string)$n);
  843. if ($n !== '') {
  844. $names[$n] = true;
  845. }
  846. }
  847. if ($names === []) {
  848. return $map;
  849. }
  850. try {
  851. $rows = Db::table('customer')
  852. ->where('company_name', 'in', array_keys($names))
  853. ->field('id,company_name')
  854. ->select();
  855. } catch (\Throwable $e) {
  856. return $map;
  857. }
  858. if (!is_array($rows)) {
  859. return $map;
  860. }
  861. foreach ($rows as $r) {
  862. if (!is_array($r)) {
  863. continue;
  864. }
  865. $cn = trim((string)($r['company_name'] ?? ''));
  866. if ($cn === '') {
  867. continue;
  868. }
  869. $map[$cn] = [
  870. 'id' => (int)($r['id'] ?? 0),
  871. 'score' => 0.0,
  872. 'monthly_score' => null,
  873. 'quality_avg' => 50.0,
  874. ];
  875. }
  876. return $map;
  877. }
  878. /**
  879. * 从报价组计算本单各供应商得分(不写库)
  880. *
  881. * @param array<int, array<string, mixed>> $quoteGroups loadAuditSupplierQuoteGroups 结构(name/lines[].amount)
  882. * @param string|null $asOfYm 订单所属月;商务/技术分从该月的上月起往前查评审表
  883. * @return array<string, array{
  884. * company_name:string,customer_id:int,quality_score:float,price_sum:float,
  885. * price_score:float,score:float,rank_no:int,score_text:string,rank_text:string
  886. * }>
  887. */
  888. public static function calculateForQuoteGroups(array $quoteGroups, ?array $rule = null, ?string $asOfYm = null): array
  889. {
  890. $rule = $rule ?: self::getDefaultRule();
  891. $qw = max(0, (float)($rule['quality_weight'] ?? 50));
  892. $pw = max(0, (float)($rule['price_weight'] ?? 50));
  893. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  894. // 填 0 的权重不参与计算
  895. $leadEnabled = $lw > 0 ? 1 : 0;
  896. $wSum = $qw + $pw + $lw;
  897. if ($wSum <= 0) {
  898. $qw = 50;
  899. $pw = 50;
  900. $lw = 0;
  901. $leadEnabled = 0;
  902. $wSum = 100;
  903. }
  904. $names = [];
  905. foreach ($quoteGroups as $g) {
  906. if (!is_array($g)) {
  907. continue;
  908. }
  909. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  910. if ($cn !== '') {
  911. $names[] = $cn;
  912. }
  913. }
  914. $custMap = self::loadCustomerScoreMap($names);
  915. $reviewMap = self::loadReviewQualityScoreMap($names, $asOfYm);
  916. $items = [];
  917. $priceSums = [];
  918. $leadSums = [];
  919. foreach ($quoteGroups as $g) {
  920. if (!is_array($g)) {
  921. continue;
  922. }
  923. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  924. if ($cn === '') {
  925. continue;
  926. }
  927. $priceSum = 0.0;
  928. $hasPrice = false;
  929. $leadSum = 0;
  930. $hasLead = false;
  931. // 确认页用 lines,审批页用 pick_lines
  932. $lineRows = $g['lines'] ?? $g['pick_lines'] ?? [];
  933. if (!is_array($lineRows)) {
  934. $lineRows = [];
  935. }
  936. foreach ($lineRows as $ln) {
  937. if (!is_array($ln)) {
  938. continue;
  939. }
  940. if (empty($ln['amount_quote_pending'])) {
  941. $am = self::resolveQuoteLineAmountRaw($ln);
  942. if ($am !== '' && $am !== '0' && $am !== '0.00' && is_numeric($am)) {
  943. $priceSum += (float)$am;
  944. $hasPrice = true;
  945. }
  946. }
  947. if (empty($ln['lead_days_quote_pending'])) {
  948. $ldRaw = $ln['lead_days'] ?? null;
  949. if ($ldRaw !== null && $ldRaw !== '' && is_numeric($ldRaw)) {
  950. $ld = (int)$ldRaw;
  951. if ($ld > 0) {
  952. $leadSum += $ld;
  953. $hasLead = true;
  954. }
  955. }
  956. }
  957. }
  958. // 商务/技术得分:月度评审「商务技术分」,当月按上月起往前,默认 50
  959. $quality = (float)($reviewMap[$cn] ?? 50);
  960. $psum = $hasPrice ? round($priceSum, 2) : 0;
  961. $lsum = $hasLead ? (int)$leadSum : 0;
  962. $items[$cn] = [
  963. 'company_name' => $cn,
  964. 'customer_id' => (int)($custMap[$cn]['id'] ?? 0),
  965. 'quality_score' => $quality,
  966. 'quality_score_text' => self::formatScore($quality),
  967. 'quality_weight' => (int)$qw,
  968. 'price_sum' => $psum,
  969. 'price_sum_text' => self::formatScore($psum),
  970. 'price_weight' => (int)$pw,
  971. 'has_price' => $hasPrice,
  972. 'price_score' => 0.0,
  973. 'price_score_text' => '0',
  974. 'lead_days_sum' => $lsum,
  975. 'lead_days_sum_text' => (string)$lsum,
  976. 'lead_weight' => (int)$lw,
  977. 'lead_enabled' => $leadEnabled,
  978. 'has_lead' => $hasLead,
  979. 'lead_score' => 0.0,
  980. 'lead_score_text' => '0',
  981. 'score' => 0.0,
  982. 'rank_no' => 0,
  983. 'score_text' => '',
  984. 'rank_text' => '',
  985. ];
  986. if ($hasPrice && $priceSum > 0) {
  987. $priceSums[$cn] = $priceSum;
  988. }
  989. if ($hasLead && $leadSum > 0) {
  990. $leadSums[$cn] = $leadSum;
  991. }
  992. }
  993. $minSum = null;
  994. foreach ($priceSums as $ps) {
  995. if ($minSum === null || $ps < $minSum) {
  996. $minSum = $ps;
  997. }
  998. }
  999. $minLead = null;
  1000. foreach ($leadSums as $ls) {
  1001. if ($minLead === null || $ls < $minLead) {
  1002. $minLead = $ls;
  1003. }
  1004. }
  1005. foreach ($items as $cn => &$it) {
  1006. // 价格得分 = (最低单价合计 / 本供应商单价合计) × 价格权重% × 100
  1007. if ($pw > 0 && !empty($it['has_price']) && $it['price_sum'] > 0 && $minSum !== null && $minSum > 0) {
  1008. $ratio = round($minSum / (float)$it['price_sum'], 4);
  1009. $it['price_score'] = round($ratio * ($pw / 100) * 100, 2);
  1010. } else {
  1011. $it['price_score'] = 0.0;
  1012. }
  1013. $it['price_score_text'] = self::formatScore($it['price_score']);
  1014. if ($leadEnabled && !empty($it['has_lead']) && $it['lead_days_sum'] > 0 && $minLead !== null && $minLead > 0) {
  1015. $leadRatio = round($minLead / (float)$it['lead_days_sum'], 4);
  1016. $it['lead_score'] = round($leadRatio * 100, 2);
  1017. } else {
  1018. $it['lead_score'] = 0.0;
  1019. }
  1020. $it['lead_score_text'] = self::formatScore($it['lead_score']);
  1021. // 总分 = 商务/技术得分×质量% + 价格得分(已含价格权重) [+ 交货得分×交货%]
  1022. $total = 0.0;
  1023. if ($qw > 0) {
  1024. $total += $it['quality_score'] * ($qw / 100);
  1025. }
  1026. if ($pw > 0) {
  1027. $total += (float)$it['price_score'];
  1028. }
  1029. if ($lw > 0) {
  1030. $total += $it['lead_score'] * ($lw / 100);
  1031. }
  1032. $it['score'] = round($total, 2);
  1033. $it['score_text'] = self::formatScore($it['score']);
  1034. }
  1035. unset($it);
  1036. $sorted = $items;
  1037. uasort($sorted, function ($a, $b) {
  1038. $sa = (float)($a['score'] ?? 0);
  1039. $sb = (float)($b['score'] ?? 0);
  1040. if ($sa !== $sb) {
  1041. return $sb <=> $sa;
  1042. }
  1043. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  1044. });
  1045. $rank = 0;
  1046. foreach ($sorted as $cn => $row) {
  1047. $rank++;
  1048. $items[$cn]['rank_no'] = $rank;
  1049. $items[$cn]['rank_text'] = (string)$rank;
  1050. }
  1051. return $items;
  1052. }
  1053. public static function formatScore($n): string
  1054. {
  1055. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  1056. return $s === '' ? '0' : $s;
  1057. }
  1058. /**
  1059. * 报价行单价原文(兼容确认页 amount、审批页 unit_price_text/amount_text)
  1060. *
  1061. * @param array<string, mixed> $ln
  1062. */
  1063. protected static function resolveQuoteLineAmountRaw(array $ln): string
  1064. {
  1065. foreach (['amount', 'unit_price_text', 'amount_text'] as $k) {
  1066. if (!array_key_exists($k, $ln) || $ln[$k] === null) {
  1067. continue;
  1068. }
  1069. $am = trim((string)$ln[$k]);
  1070. if ($am === '' || $am === '未填写' || $am === '未开标验证' || $am === '开标验证后查看') {
  1071. continue;
  1072. }
  1073. // 去掉千分位等
  1074. $am = str_replace([',', ',', ' '], '', $am);
  1075. if ($am !== '' && is_numeric($am)) {
  1076. return $am;
  1077. }
  1078. }
  1079. return '';
  1080. }
  1081. /**
  1082. * 总分简要文案(仅总分数字;分项见独立字段)
  1083. *
  1084. * @param array<string, mixed> $hit calculate/loadSaved 单项
  1085. */
  1086. public static function formatScoreDetailText(array $hit): string
  1087. {
  1088. return self::formatScore($hit['score'] ?? 0);
  1089. }
  1090. /**
  1091. * 分项得分展示文案(确认/详情表格用)
  1092. *
  1093. * @param array<string, mixed> $hit
  1094. */
  1095. public static function formatScorePartsHtml(array $hit): string
  1096. {
  1097. $qw = (float)($hit['quality_weight'] ?? 0);
  1098. $pw = (float)($hit['price_weight'] ?? 0);
  1099. $lw = (float)($hit['lead_weight'] ?? 0);
  1100. $lines = [];
  1101. if ($qw > 0) {
  1102. $lines[] = '商务/技术 ' . self::formatScore($hit['quality_score'] ?? 0);
  1103. }
  1104. if ($pw > 0) {
  1105. $lines[] = '价格得分 ' . self::formatScore($hit['price_score'] ?? 0);
  1106. }
  1107. if ($lw > 0) {
  1108. $lines[] = '交货得分 ' . self::formatScore($hit['lead_score'] ?? 0);
  1109. }
  1110. $lines[] = '总分 ' . self::formatScore($hit['score'] ?? 0);
  1111. return implode("\n", $lines);
  1112. }
  1113. /**
  1114. * 评分规则文案(用于确认页 / 详情展示)
  1115. * 百分比取当前默认规则;权重大于 0 的项才写入公式
  1116. *
  1117. * @param array{quality_weight?:float|int|string,price_weight?:float|int|string,lead_weight?:float|int|string}|null $rule
  1118. */
  1119. public static function formatRuleFormulaText(?array $rule = null): string
  1120. {
  1121. $rule = $rule ?: self::getDefaultRule();
  1122. $qw = (float)($rule['quality_weight'] ?? 50);
  1123. $pw = (float)($rule['price_weight'] ?? 50);
  1124. $lw = (float)($rule['lead_weight'] ?? 0);
  1125. $parts = [];
  1126. if ($qw > 0) {
  1127. $parts[] = '(商务/技术得分×' . self::formatWeightPercent($qw) . '%)';
  1128. }
  1129. if ($pw > 0) {
  1130. $parts[] = '(价格得分)';
  1131. }
  1132. if ($lw > 0) {
  1133. $parts[] = '(交货得分×' . self::formatWeightPercent($lw) . '%)';
  1134. }
  1135. $formula = $parts === []
  1136. ? '(总分)=(商务/技术得分×50%)+(价格得分)'
  1137. : '(总分)=' . implode('+', $parts);
  1138. $formula .= ';商务/技术得分取月度评审「商务/技术得分」(当月按上月起往前查,无则默认50)';
  1139. if ($pw > 0) {
  1140. $formula .= ';价格得分=(最低单价合计/本供应商单价合计)×'
  1141. . self::formatWeightPercent($pw) . '%×100';
  1142. }
  1143. return $formula;
  1144. }
  1145. /**
  1146. * 报价组是否展示交货期留痕列(已落库纳入,或尚无落库且当前默认规则交货分>0)
  1147. *
  1148. * @param array<int, array<string, mixed>> $quoteGroups
  1149. */
  1150. public static function detectShowLeadScore(array $quoteGroups = [], ?array $rule = null): bool
  1151. {
  1152. $hasSavedScore = false;
  1153. foreach ($quoteGroups as $g) {
  1154. if (!is_array($g)) {
  1155. continue;
  1156. }
  1157. if (!empty($g['show_service_lead_score'])) {
  1158. return true;
  1159. }
  1160. if (!empty($g['show_service_score'])) {
  1161. $hasSavedScore = true;
  1162. }
  1163. }
  1164. // 历史单已按旧规则落库且交货期权重为 0:不显示这两列
  1165. if ($hasSavedScore) {
  1166. return false;
  1167. }
  1168. $rule = $rule ?: self::getDefaultRule();
  1169. return (float)($rule['lead_weight'] ?? 0) > 0;
  1170. }
  1171. /**
  1172. * 评分规则提示:始终按当前默认规则比例显示(切换默认后即时变化)
  1173. *
  1174. * @param array<int, array<string, mixed>> $quoteGroups 保留参数兼容调用方,不参与文案
  1175. */
  1176. public static function formatRuleFormulaTextForGroups(array $quoteGroups = []): string
  1177. {
  1178. return self::formatRuleFormulaText();
  1179. }
  1180. protected static function formatWeightPercent($n): string
  1181. {
  1182. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  1183. return $s === '' ? '0' : $s;
  1184. }
  1185. /**
  1186. * 开标验证通过后:计算并写入供应商服务评分表
  1187. *
  1188. * @param array<int, array<string, mixed>> $quoteGroups
  1189. */
  1190. public static function saveForOrder(string $ccydh, array $quoteGroups, ?string $ym = null): void
  1191. {
  1192. $ccydh = trim($ccydh);
  1193. if ($ccydh === '') {
  1194. return;
  1195. }
  1196. self::ensureSchema();
  1197. $rule = self::getDefaultRule();
  1198. if ($ym === null || $ym === '') {
  1199. $ym = date('Y-m');
  1200. }
  1201. $ym = self::normalizeYm($ym);
  1202. $calc = self::calculateForQuoteGroups($quoteGroups, $rule, $ym);
  1203. if ($calc === []) {
  1204. return;
  1205. }
  1206. $now = date('Y-m-d H:i:s');
  1207. try {
  1208. Db::table(self::TABLE_SCORE)->where('ccydh', $ccydh)->delete();
  1209. $rows = [];
  1210. foreach ($calc as $it) {
  1211. $rows[] = [
  1212. 'customer_id' => (int)($it['customer_id'] ?? 0),
  1213. 'company_name' => (string)($it['company_name'] ?? ''),
  1214. 'ym' => $ym,
  1215. 'ccydh' => $ccydh,
  1216. 'score' => (float)($it['score'] ?? 0),
  1217. 'rank_no' => (int)($it['rank_no'] ?? 0),
  1218. 'quality_score' => (int)round((float)($it['quality_score'] ?? 0)),
  1219. 'quality_weight' => (int)($rule['quality_weight'] ?? 50),
  1220. 'price_sum' => round((float)($it['price_sum'] ?? 0), 4),
  1221. 'price_weight' => (int)($rule['price_weight'] ?? 50),
  1222. 'price_score' => (float)($it['price_score'] ?? 0),
  1223. 'lead_days_sum' => (int)round((float)($it['lead_days_sum'] ?? 0)),
  1224. 'lead_weight' => (int)($rule['lead_weight'] ?? 0),
  1225. 'lead_enabled' => ((int)($rule['lead_weight'] ?? 0) > 0) ? 1 : 0,
  1226. 'lead_score' => (float)($it['lead_score'] ?? 0),
  1227. 'rule_id' => (int)($rule['id'] ?? 0),
  1228. 'createtime' => $now,
  1229. 'updatetime' => $now,
  1230. ];
  1231. }
  1232. if ($rows !== []) {
  1233. Db::table(self::TABLE_SCORE)->insertAll($rows);
  1234. }
  1235. // 开标后:本月询价供应商名称写入月度评审表(不存在才加空行,已有记录不覆盖)
  1236. $monthNames = [];
  1237. foreach ($quoteGroups as $g) {
  1238. if (!is_array($g)) {
  1239. continue;
  1240. }
  1241. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  1242. if ($cn !== '') {
  1243. $monthNames[] = $cn;
  1244. }
  1245. }
  1246. foreach ($rows as $row) {
  1247. $cn = trim((string)($row['company_name'] ?? ''));
  1248. if ($cn !== '') {
  1249. $monthNames[] = $cn;
  1250. }
  1251. }
  1252. self::ensureMonthlySupplierNames($ym, $monthNames);
  1253. } catch (\Throwable $e) {
  1254. Log::write('supplier service score save: ' . $e->getMessage(), 'error');
  1255. }
  1256. }
  1257. /**
  1258. * 读取某订单已落库评分;无则返回空
  1259. *
  1260. * @return array<string, array<string, mixed>>
  1261. */
  1262. public static function loadSavedByCcydh(string $ccydh): array
  1263. {
  1264. $ccydh = trim($ccydh);
  1265. if ($ccydh === '') {
  1266. return [];
  1267. }
  1268. self::ensureSchema();
  1269. try {
  1270. $rows = Db::table(self::TABLE_SCORE)->where('ccydh', $ccydh)->select();
  1271. } catch (\Throwable $e) {
  1272. return [];
  1273. }
  1274. if (!is_array($rows)) {
  1275. return [];
  1276. }
  1277. $out = [];
  1278. foreach ($rows as $r) {
  1279. if (!is_array($r)) {
  1280. continue;
  1281. }
  1282. $cn = trim((string)($r['company_name'] ?? ''));
  1283. if ($cn === '') {
  1284. continue;
  1285. }
  1286. $score = (float)($r['score'] ?? 0);
  1287. $rank = (int)($r['rank_no'] ?? 0);
  1288. $qualityScore = (int)round((float)($r['quality_score'] ?? 0));
  1289. $priceSum = round((float)($r['price_sum'] ?? 0), 4);
  1290. $priceScore = (float)($r['price_score'] ?? 0);
  1291. $qw = (int)($r['quality_weight'] ?? 50);
  1292. $pw = (int)($r['price_weight'] ?? 50);
  1293. $lw = (int)($r['lead_weight'] ?? 0);
  1294. $leadEnabled = $lw > 0 ? 1 : 0;
  1295. $leadSum = (int)round((float)($r['lead_days_sum'] ?? 0));
  1296. $leadScore = (float)($r['lead_score'] ?? 0);
  1297. $out[$cn] = [
  1298. 'company_name' => $cn,
  1299. 'customer_id' => (int)($r['customer_id'] ?? 0),
  1300. 'quality_score' => $qualityScore,
  1301. 'quality_score_text' => (string)$qualityScore,
  1302. 'quality_weight' => $qw,
  1303. 'price_sum' => $priceSum,
  1304. 'price_sum_text' => self::formatScore($priceSum),
  1305. 'price_weight' => $pw,
  1306. 'price_score' => $priceScore,
  1307. 'price_score_text' => self::formatScore($priceScore),
  1308. 'lead_days_sum' => $leadSum,
  1309. 'lead_days_sum_text' => $leadEnabled ? (string)$leadSum : '',
  1310. 'lead_weight' => $lw,
  1311. 'lead_enabled' => $leadEnabled,
  1312. 'lead_score' => $leadScore,
  1313. 'lead_score_text' => $leadEnabled ? self::formatScore($leadScore) : '',
  1314. 'score' => $score,
  1315. 'rank_no' => $rank,
  1316. 'score_text' => self::formatScore($score),
  1317. 'rank_text' => $rank > 0 ? (string)$rank : '',
  1318. ];
  1319. }
  1320. return $out;
  1321. }
  1322. /**
  1323. * 清空报价组上的评分留痕字段
  1324. *
  1325. * @param array<string, mixed> $g
  1326. */
  1327. protected static function clearScoreTrailOnGroup(array &$g, int $showFlag = 0): void
  1328. {
  1329. $g['service_rank'] = '';
  1330. $g['service_score'] = '';
  1331. $g['service_rank_text'] = '';
  1332. $g['service_score_text'] = '';
  1333. $g['service_score_parts_text'] = '';
  1334. $g['service_quality_score'] = '';
  1335. $g['service_quality_score_text'] = '';
  1336. $g['service_price_sum'] = '';
  1337. $g['service_price_sum_text'] = '';
  1338. $g['service_price_score'] = '';
  1339. $g['service_price_score_text'] = '';
  1340. $g['service_lead_days_sum'] = '';
  1341. $g['service_lead_days_sum_text'] = '';
  1342. $g['service_lead_score'] = '';
  1343. $g['service_lead_score_text'] = '';
  1344. $g['service_lead_enabled'] = 0;
  1345. $g['service_quality_weight'] = '';
  1346. $g['service_price_weight'] = '';
  1347. $g['service_lead_weight'] = '';
  1348. $g['show_service_score'] = $showFlag;
  1349. $g['show_service_lead_score'] = 0;
  1350. }
  1351. /**
  1352. * 把排名/评分/计算留痕挂到报价组上(开标后可见)
  1353. *
  1354. * @param array<int, array<string, mixed>> $quoteGroups
  1355. * @return array<int, array<string, mixed>>
  1356. */
  1357. public static function attachToQuoteGroups(array $quoteGroups, string $ccydh, bool $quoteVisible): array
  1358. {
  1359. if (!$quoteVisible || $quoteGroups === []) {
  1360. foreach ($quoteGroups as &$g) {
  1361. if (!is_array($g)) {
  1362. continue;
  1363. }
  1364. self::clearScoreTrailOnGroup($g, 0);
  1365. }
  1366. unset($g);
  1367. return $quoteGroups;
  1368. }
  1369. // 每次按最新规则重算并落库,避免历史错误总分残留
  1370. $ym = date('Y-m');
  1371. $saved = self::calculateForQuoteGroups($quoteGroups, null, $ym);
  1372. try {
  1373. self::saveForOrder($ccydh, $quoteGroups, $ym);
  1374. } catch (\Throwable $e) {
  1375. }
  1376. foreach ($quoteGroups as &$g) {
  1377. if (!is_array($g)) {
  1378. continue;
  1379. }
  1380. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  1381. $hit = $saved[$cn] ?? null;
  1382. if (is_array($hit)) {
  1383. $g['service_rank'] = (int)($hit['rank_no'] ?? 0);
  1384. $g['service_score'] = (float)($hit['score'] ?? 0);
  1385. $g['service_rank_text'] = (string)($hit['rank_text'] ?? '');
  1386. $g['service_score_text'] = self::formatScoreDetailText($hit);
  1387. $g['service_score_parts_text'] = self::formatScorePartsHtml($hit);
  1388. $qs = round((float)($hit['quality_score'] ?? 0), 2);
  1389. $ps = (float)($hit['price_score'] ?? 0);
  1390. $psum = round((float)($hit['price_sum'] ?? 0), 2);
  1391. $leadEnabled = ((int)($hit['lead_weight'] ?? 0) > 0) ? 1 : 0;
  1392. $ls = (float)($hit['lead_score'] ?? 0);
  1393. $lsum = (int)round((float)($hit['lead_days_sum'] ?? 0));
  1394. $g['service_quality_score'] = $qs;
  1395. $g['service_quality_score_text'] = (string)($hit['quality_score_text'] ?? self::formatScore($qs));
  1396. $g['service_price_sum'] = $psum;
  1397. $g['service_price_sum_text'] = (string)($hit['price_sum_text'] ?? $psum);
  1398. $g['service_price_score'] = $ps;
  1399. $g['service_price_score_text'] = (string)($hit['price_score_text'] ?? self::formatScore($ps));
  1400. $g['service_lead_enabled'] = $leadEnabled;
  1401. $g['show_service_lead_score'] = $leadEnabled;
  1402. $g['service_lead_days_sum'] = $lsum;
  1403. $g['service_lead_days_sum_text'] = $leadEnabled ? (string)($hit['lead_days_sum_text'] ?? $lsum) : '';
  1404. $g['service_lead_score'] = $ls;
  1405. $g['service_lead_score_text'] = $leadEnabled ? (string)($hit['lead_score_text'] ?? self::formatScore($ls)) : '';
  1406. $g['service_quality_weight'] = (int)($hit['quality_weight'] ?? 50);
  1407. $g['service_price_weight'] = (int)($hit['price_weight'] ?? 50);
  1408. $g['service_lead_weight'] = (int)($hit['lead_weight'] ?? 0);
  1409. $g['show_service_score'] = 1;
  1410. } else {
  1411. self::clearScoreTrailOnGroup($g, 1);
  1412. }
  1413. }
  1414. unset($g);
  1415. // 开标后按排名升序(第1名在最前);无排名的放最后
  1416. usort($quoteGroups, function ($a, $b) {
  1417. $ra = is_array($a) ? (int)($a['service_rank'] ?? 0) : 0;
  1418. $rb = is_array($b) ? (int)($b['service_rank'] ?? 0) : 0;
  1419. $ha = $ra > 0;
  1420. $hb = $rb > 0;
  1421. if ($ha !== $hb) {
  1422. return $ha ? -1 : 1;
  1423. }
  1424. if ($ha && $ra !== $rb) {
  1425. return $ra <=> $rb;
  1426. }
  1427. $sa = is_array($a) ? (float)($a['service_score'] ?? 0) : 0.0;
  1428. $sb = is_array($b) ? (float)($b['service_score'] ?? 0) : 0.0;
  1429. if ($sa !== $sb) {
  1430. return $sb <=> $sa;
  1431. }
  1432. $na = is_array($a) ? trim((string)($a['name'] ?? $a['company_name'] ?? '')) : '';
  1433. $nb = is_array($b) ? trim((string)($b['name'] ?? $b['company_name'] ?? '')) : '';
  1434. return strcmp($na, $nb);
  1435. });
  1436. return $quoteGroups;
  1437. }
  1438. }