ProcuremenSupplierScore.php 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322
  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:月度评审表(四项自动统计,满分 105;qp_manual=1 手工锁定不覆盖)
  11. *
  12. * 开标单笔总分 = 质量得分×质量% + 价格得分 [+ 交货得分×交货%]
  13. * 开标质量得分:取月度评审表(当月按上月起往前查,无则默认 40)
  14. * 开标交货得分:月度交货分×50% + 本单报价交期分×50%(按订单算,一批多订单取平均)
  15. * 报价交期分:满分40,相对订单交货截止日每提前1天+1、滞后1天-1
  16. * 开标价格得分 = (本单最低单价合计 / 本供应商单价合计) × 价格权重% × 100
  17. *
  18. * 月度评审(与开标单笔分离):
  19. * 质量40 = 合格率对照(20) + 客户投诉(10) + 生产中断(10)
  20. * 价格15 = 全部严格低于最高限价→15,否则(等于限价/限价空)→10
  21. * 交货40 = 准时率对照(30) + 生产中断(10,出现一次得0)
  22. * 增值10 = 未报价订单数≤3→10,>3→0(按订单号去重)
  23. * 最终得分 = 四项相加;等级 A≥90 / B≥70 / C≥60 / D
  24. */
  25. class ProcuremenSupplierScore
  26. {
  27. public const TABLE_RULE = 'supplier_score_rule';
  28. /** 订单明细评分表 */
  29. public const TABLE_SCORE = 'supplier_service_score';
  30. /** 月度汇总表(总分 + 最终得分) */
  31. public const TABLE_FINAL = 'supplier_service_final_score';
  32. /** @var bool|null */
  33. protected static $schemaReady = null;
  34. /** 请求内缓存:供应商+月份 → 入库订单聚合,避免质量/价格/交货各查一遍 */
  35. protected static $inboundAggCache = [];
  36. /** 结构探测缓存键(升版本可强制再跑一遍迁移) */
  37. const SCHEMA_CACHE_KEY = 'procuremen_supplier_score_schema_ok_v6';
  38. public static function ensureSchema(): void
  39. {
  40. if (self::$schemaReady === true) {
  41. return;
  42. }
  43. // 跨请求缓存:命中后直接返回,禁止再跑 SHOW COLUMNS / ALTER / 规则种子
  44. try {
  45. if (\think\Cache::get(self::SCHEMA_CACHE_KEY)) {
  46. self::$schemaReady = true;
  47. return;
  48. }
  49. try {
  50. \think\Cache::rm('procuremen_supplier_score_schema_ok_v1');
  51. \think\Cache::rm('procuremen_supplier_score_schema_ok_v2');
  52. \think\Cache::rm('procuremen_supplier_score_schema_ok_v3');
  53. \think\Cache::rm('procuremen_supplier_score_schema_ok_v4');
  54. \think\Cache::rm('procuremen_supplier_score_schema_ok_v5');
  55. } catch (\Throwable $e) {
  56. }
  57. } catch (\Throwable $e) {
  58. }
  59. try {
  60. Db::query('SELECT 1 FROM `' . self::TABLE_RULE . '` LIMIT 1');
  61. Db::query('SELECT 1 FROM `' . self::TABLE_SCORE . '` LIMIT 1');
  62. self::runSchemaMigrations();
  63. self::$schemaReady = true;
  64. try {
  65. \think\Cache::set(self::SCHEMA_CACHE_KEY, 1, 86400);
  66. } catch (\Throwable $e) {
  67. }
  68. return;
  69. } catch (\Throwable $e) {
  70. }
  71. $sqlFile = APP_PATH . 'extra' . DIRECTORY_SEPARATOR . 'supplier_score_install.sql';
  72. if (is_file($sqlFile)) {
  73. $sql = file_get_contents($sqlFile);
  74. if (is_string($sql) && $sql !== '') {
  75. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  76. $stmt = trim($stmt);
  77. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  78. continue;
  79. }
  80. try {
  81. Db::execute($stmt);
  82. } catch (\Throwable $ignore) {
  83. }
  84. }
  85. }
  86. }
  87. self::runSchemaMigrations();
  88. self::$schemaReady = true;
  89. try {
  90. \think\Cache::set(self::SCHEMA_CACHE_KEY, 1, 86400);
  91. } catch (\Throwable $e) {
  92. }
  93. }
  94. /** 首次(或缓存失效)时执行表结构迁移与默认规则种子 */
  95. protected static function runSchemaMigrations(): void
  96. {
  97. self::ensureRuleNameColumn();
  98. self::dropObsoleteRuleColumns();
  99. self::ensureDefaultRule();
  100. self::ensureOrderTypeRules();
  101. self::ensureScoreWeightColumns();
  102. self::ensureLeadColumns();
  103. self::ensureIntegerColumns();
  104. self::ensureFinalScoreTable();
  105. }
  106. /** 月度记录表(商务技术分 / 价格分 / 最终得分,仅本页展示与导出) */
  107. public static function ensureFinalScoreTable(): void
  108. {
  109. static $done = false;
  110. if ($done) {
  111. return;
  112. }
  113. try {
  114. if (\think\Cache::get('procuremen_supplier_final_score_table_ok_v1')) {
  115. $done = true;
  116. return;
  117. }
  118. } catch (\Throwable $e) {
  119. }
  120. $ddl = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_FINAL . "` (
  121. `id` int unsigned NOT NULL AUTO_INCREMENT,
  122. `ym` char(7) NOT NULL DEFAULT '' COMMENT '年月 YYYY-MM',
  123. `company_name` varchar(128) NOT NULL DEFAULT '' COMMENT '供应商名称',
  124. `score` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT '月度总分(兼容旧字段)',
  125. `quality_score` decimal(10,2) DEFAULT NULL COMMENT '商务技术分(人工,空=未填)',
  126. `price_score` decimal(10,2) DEFAULT NULL COMMENT '价格分(人工,空=未填)',
  127. `delivery_score` decimal(10,2) DEFAULT NULL COMMENT '交货分(人工,空=未填)',
  128. `value_added_score` decimal(10,2) DEFAULT NULL COMMENT '增值服务(人工,空=未填)',
  129. `final_score` decimal(10,2) DEFAULT NULL COMMENT '最终得分(人工,空=未填)',
  130. `score_grade` char(1) NOT NULL DEFAULT '' COMMENT '评分等级 A/B/C/D',
  131. `qp_manual` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=商务技术分/价格分/交货分已人工修改',
  132. `createtime` datetime DEFAULT NULL,
  133. `updatetime` datetime DEFAULT NULL,
  134. PRIMARY KEY (`id`),
  135. UNIQUE KEY `uk_ym_company` (`ym`,`company_name`),
  136. KEY `idx_ym` (`ym`)
  137. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='供应商月度评审记录'";
  138. try {
  139. Db::execute($ddl);
  140. } catch (\Throwable $e) {
  141. Log::write('supplier monthly score table: ' . $e->getMessage(), 'error');
  142. }
  143. self::ensureMonthlyScoreColumns();
  144. $done = true;
  145. try {
  146. \think\Cache::set('procuremen_supplier_final_score_table_ok_v1', 1, 86400);
  147. } catch (\Throwable $e) {
  148. }
  149. }
  150. /** 历史月度表补商务技术分/价格分等字段 */
  151. protected static function ensureMonthlyScoreColumns(): void
  152. {
  153. $adds = [
  154. 'score' => "ADD COLUMN `score` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT '月度总分(兼容旧字段)' AFTER `company_name`",
  155. 'quality_score' => "ADD COLUMN `quality_score` decimal(10,2) DEFAULT NULL COMMENT '商务技术分(人工,空=未填)' AFTER `score`",
  156. 'price_score' => "ADD COLUMN `price_score` decimal(10,2) DEFAULT NULL COMMENT '价格分(人工,空=未填)' AFTER `quality_score`",
  157. 'delivery_score' => "ADD COLUMN `delivery_score` decimal(10,2) DEFAULT NULL COMMENT '交货分(人工,空=未填)' AFTER `price_score`",
  158. 'value_added_score' => "ADD COLUMN `value_added_score` decimal(10,2) DEFAULT NULL COMMENT '增值服务(人工,空=未填)' AFTER `delivery_score`",
  159. 'score_grade' => "ADD COLUMN `score_grade` char(1) NOT NULL DEFAULT '' COMMENT '评分等级 A/B/C/D' AFTER `final_score`",
  160. 'qp_manual' => "ADD COLUMN `qp_manual` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=商务技术分/价格分/交货分/增值服务已人工修改' AFTER `score_grade`",
  161. ];
  162. foreach ($adds as $col => $ddl) {
  163. try {
  164. $cols = Db::query("SHOW COLUMNS FROM `" . self::TABLE_FINAL . "` LIKE '{$col}'");
  165. if (!is_array($cols) || $cols === []) {
  166. Db::execute("ALTER TABLE `" . self::TABLE_FINAL . "` {$ddl}");
  167. }
  168. } catch (\Throwable $e) {
  169. Log::write("supplier monthly {$col} column: " . $e->getMessage(), 'error');
  170. }
  171. }
  172. // 分数字段允许 NULL:空=未填,列表不显示 0
  173. foreach ([
  174. 'quality_score' => '商务技术分(人工,空=未填)',
  175. 'price_score' => '价格分(人工,空=未填)',
  176. 'delivery_score' => '交货分(人工,空=未填)',
  177. 'value_added_score' => '增值服务(人工,空=未填)',
  178. 'final_score' => '最终得分(人工,空=未填)',
  179. ] as $col => $comment) {
  180. try {
  181. $info = Db::query("SHOW COLUMNS FROM `" . self::TABLE_FINAL . "` LIKE '{$col}'");
  182. if (is_array($info) && $info !== []) {
  183. $null = strtoupper((string)($info[0]['Null'] ?? ''));
  184. if ($null !== 'YES') {
  185. Db::execute(
  186. "ALTER TABLE `" . self::TABLE_FINAL . "` MODIFY COLUMN `{$col}` decimal(10,2) DEFAULT NULL COMMENT '{$comment}'"
  187. );
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. Log::write("supplier monthly {$col} null: " . $e->getMessage(), 'error');
  192. }
  193. }
  194. }
  195. /** 规范化评分等级:空 / A / B / C / D */
  196. public static function normalizeScoreGrade($raw): string
  197. {
  198. $g = strtoupper(trim((string)$raw));
  199. if (in_array($g, ['A', 'B', 'C', 'D'], true)) {
  200. return $g;
  201. }
  202. return '';
  203. }
  204. /**
  205. * 综合评分标准:A≥90 B 70-89 C 60-69 D<60
  206. *
  207. * @param mixed $score
  208. */
  209. public static function gradeFromFinalScore($score): string
  210. {
  211. if ($score === null || $score === '') {
  212. return '';
  213. }
  214. if (!is_numeric($score)) {
  215. return '';
  216. }
  217. $n = (float)$score;
  218. if ($n >= 90) {
  219. return 'A';
  220. }
  221. if ($n >= 70) {
  222. return 'B';
  223. }
  224. if ($n >= 60) {
  225. return 'C';
  226. }
  227. return 'D';
  228. }
  229. /**
  230. * 最终得分 = 质量 + 价格 + 交货 + 增值服务(空项按 0;四项全空则 null)
  231. *
  232. * @param mixed $quality
  233. * @param mixed $price
  234. * @param mixed $delivery
  235. * @param mixed $valueAdded
  236. */
  237. public static function sumFinalScore($quality, $price, $delivery, $valueAdded): ?float
  238. {
  239. $parts = [$quality, $price, $delivery, $valueAdded];
  240. $any = false;
  241. $sum = 0.0;
  242. foreach ($parts as $p) {
  243. if ($p === null || $p === '') {
  244. continue;
  245. }
  246. if (!is_numeric($p)) {
  247. continue;
  248. }
  249. $any = true;
  250. $sum += (float)$p;
  251. }
  252. return $any ? round($sum, 2) : null;
  253. }
  254. /**
  255. * 按订单明细重算并写入某月评审记录(商务技术分/价格分;保留已填最终得分)
  256. *
  257. * @param array<int, string>|null $onlyCompanies 仅同步这些供应商;null=当月全部
  258. */
  259. public static function syncMonthlyScoresForYm(string $ym, ?array $onlyCompanies = null): void
  260. {
  261. $ym = trim($ym);
  262. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  263. return;
  264. }
  265. self::ensureSchema();
  266. self::ensureFinalScoreTable();
  267. try {
  268. $query = Db::table(self::TABLE_SCORE)
  269. ->where('ym', $ym)
  270. ->field('company_name,score,quality_score,price_score,lead_score');
  271. if (is_array($onlyCompanies) && $onlyCompanies !== []) {
  272. $names = [];
  273. foreach ($onlyCompanies as $n) {
  274. $n = trim((string)$n);
  275. if ($n !== '') {
  276. $names[$n] = true;
  277. }
  278. }
  279. if ($names === []) {
  280. return;
  281. }
  282. $query->where('company_name', 'in', array_keys($names));
  283. }
  284. $rows = $query->select();
  285. } catch (\Throwable $e) {
  286. // 无 lead_score 列时回退
  287. try {
  288. $query = Db::table(self::TABLE_SCORE)
  289. ->where('ym', $ym)
  290. ->field('company_name,score,quality_score,price_score');
  291. if (is_array($onlyCompanies) && $onlyCompanies !== []) {
  292. $names = [];
  293. foreach ($onlyCompanies as $n) {
  294. $n = trim((string)$n);
  295. if ($n !== '') {
  296. $names[$n] = true;
  297. }
  298. }
  299. if ($names === []) {
  300. return;
  301. }
  302. $query->where('company_name', 'in', array_keys($names));
  303. }
  304. $rows = $query->select();
  305. } catch (\Throwable $e2) {
  306. Log::write('supplier monthly sync read: ' . $e2->getMessage(), 'error');
  307. return;
  308. }
  309. }
  310. if (!is_array($rows)) {
  311. return;
  312. }
  313. $agg = [];
  314. foreach ($rows as $r) {
  315. if (!is_array($r)) {
  316. continue;
  317. }
  318. $cn = trim((string)($r['company_name'] ?? ''));
  319. if ($cn === '') {
  320. continue;
  321. }
  322. if (!isset($agg[$cn])) {
  323. $agg[$cn] = [
  324. 'score_sum' => 0.0,
  325. 'quality_sum' => 0.0,
  326. 'price_sum' => 0.0,
  327. 'delivery_sum' => 0.0,
  328. 'cnt' => 0,
  329. ];
  330. }
  331. $agg[$cn]['score_sum'] += (float)($r['score'] ?? 0);
  332. $agg[$cn]['quality_sum'] += (float)($r['quality_score'] ?? 0);
  333. $agg[$cn]['price_sum'] += (float)($r['price_score'] ?? 0);
  334. $agg[$cn]['delivery_sum'] += (float)($r['lead_score'] ?? 0);
  335. $agg[$cn]['cnt']++;
  336. }
  337. $now = date('Y-m-d H:i:s');
  338. foreach ($agg as $cn => $a) {
  339. $cnt = (int)$a['cnt'];
  340. $avgScore = $cnt > 0 ? round($a['score_sum'] / $cnt, 2) : 0.0;
  341. $avgPrice = $cnt > 0 ? round($a['price_sum'] / $cnt, 2) : 0.0;
  342. $avgDelivery = $cnt > 0 ? round($a['delivery_sum'] / $cnt, 2) : 0.0;
  343. try {
  344. $exists = Db::table(self::TABLE_FINAL)->where('ym', $ym)->where('company_name', $cn)->find();
  345. if (is_array($exists) && $exists !== []) {
  346. // 已手工保存:不再按订单明细重算覆盖
  347. if ((int)($exists['qp_manual'] ?? 0) === 1) {
  348. continue;
  349. }
  350. $upd = [
  351. 'score' => $avgScore,
  352. 'price_score' => $avgPrice,
  353. 'delivery_score' => $avgDelivery,
  354. 'updatetime' => $now,
  355. ];
  356. Db::table(self::TABLE_FINAL)->where('id', (int)($exists['id'] ?? 0))->update($upd);
  357. } else {
  358. Db::table(self::TABLE_FINAL)->insert([
  359. 'ym' => $ym,
  360. 'company_name' => $cn,
  361. 'score' => $avgScore,
  362. 'quality_score' => null,
  363. 'price_score' => $avgPrice,
  364. 'delivery_score' => $avgDelivery,
  365. 'value_added_score' => null,
  366. 'final_score' => null,
  367. 'score_grade' => '',
  368. 'qp_manual' => 0,
  369. 'createtime' => $now,
  370. 'updatetime' => $now,
  371. ]);
  372. }
  373. } catch (\Throwable $e) {
  374. Log::write('supplier monthly sync write: ' . $e->getMessage(), 'error');
  375. }
  376. }
  377. }
  378. /**
  379. * 读取某月各供应商最终得分(仅已人工填写的)
  380. *
  381. * @return array<string, float> company_name => final_score
  382. */
  383. public static function loadFinalScoreMapByYm(string $ym): array
  384. {
  385. $ym = trim($ym);
  386. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  387. return [];
  388. }
  389. self::ensureFinalScoreTable();
  390. try {
  391. $rows = Db::table(self::TABLE_FINAL)
  392. ->where('ym', $ym)
  393. ->whereNotNull('final_score')
  394. ->field('company_name,final_score')
  395. ->select();
  396. } catch (\Throwable $e) {
  397. return [];
  398. }
  399. if (!is_array($rows)) {
  400. return [];
  401. }
  402. $out = [];
  403. foreach ($rows as $r) {
  404. if (!is_array($r)) {
  405. continue;
  406. }
  407. $cn = trim((string)($r['company_name'] ?? ''));
  408. if ($cn === '') {
  409. continue;
  410. }
  411. $out[$cn] = round((float)($r['final_score'] ?? 0), 2);
  412. }
  413. return $out;
  414. }
  415. /**
  416. * 读取库中可选分数:NULL/空串 → null;合法数字 → float
  417. *
  418. * @param mixed $raw
  419. */
  420. public static function readOptionalScoreValue($raw): ?float
  421. {
  422. if ($raw === null) {
  423. return null;
  424. }
  425. if (is_string($raw) && trim($raw) === '') {
  426. return null;
  427. }
  428. if (!is_numeric($raw)) {
  429. return null;
  430. }
  431. return round((float)$raw, 2);
  432. }
  433. /**
  434. * 可选分数展示:空不显示 0
  435. *
  436. * @param float|null $n
  437. */
  438. public static function formatOptionalScore(?float $n): string
  439. {
  440. if ($n === null) {
  441. return '';
  442. }
  443. return self::formatScore($n);
  444. }
  445. /**
  446. * 开标后把本月询价供应商名称写入月度评审表:不存在则插入空行,已存在不改(分数人工填)
  447. *
  448. * @param array<int, string> $companyNames
  449. * @return int 新插入条数
  450. */
  451. public static function ensureMonthlySupplierNames(string $ym, array $companyNames): int
  452. {
  453. $ym = trim($ym);
  454. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  455. return 0;
  456. }
  457. $uniq = [];
  458. foreach ($companyNames as $n) {
  459. $n = trim((string)$n);
  460. if ($n !== '') {
  461. $uniq[$n] = true;
  462. }
  463. }
  464. if ($uniq === []) {
  465. return 0;
  466. }
  467. self::ensureFinalScoreTable();
  468. $existMap = [];
  469. try {
  470. $existRows = Db::table(self::TABLE_FINAL)
  471. ->where('ym', $ym)
  472. ->where('company_name', 'in', array_keys($uniq))
  473. ->field('company_name')
  474. ->select();
  475. if (is_array($existRows)) {
  476. foreach ($existRows as $er) {
  477. if (!is_array($er)) {
  478. continue;
  479. }
  480. $ecn = trim((string)($er['company_name'] ?? ''));
  481. if ($ecn !== '') {
  482. $existMap[$ecn] = true;
  483. }
  484. }
  485. }
  486. } catch (\Throwable $e) {
  487. }
  488. $now = date('Y-m-d H:i:s');
  489. $inserted = 0;
  490. foreach (array_keys($uniq) as $cn) {
  491. if (!empty($existMap[$cn])) {
  492. continue;
  493. }
  494. try {
  495. Db::table(self::TABLE_FINAL)->insert([
  496. 'ym' => $ym,
  497. 'company_name' => $cn,
  498. 'score' => 0,
  499. 'quality_score' => null,
  500. 'price_score' => null,
  501. 'delivery_score' => null,
  502. 'value_added_score' => null,
  503. 'final_score' => null,
  504. 'score_grade' => '',
  505. 'qp_manual' => 0,
  506. 'createtime' => $now,
  507. 'updatetime' => $now,
  508. ]);
  509. $inserted++;
  510. } catch (\Throwable $e) {
  511. // 并发下唯一键冲突视为已存在
  512. if (stripos($e->getMessage(), 'Duplicate') === false) {
  513. Log::write('supplier monthly ensure name: ' . $e->getMessage(), 'error');
  514. }
  515. }
  516. }
  517. return $inserted;
  518. }
  519. /**
  520. * 按当月订单评分表中的供应商,补齐月度评审表名称(仅新增空行)
  521. */
  522. public static function ensureMonthlySupplierNamesFromOrderYm(string $ym): void
  523. {
  524. $ym = trim($ym);
  525. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  526. return;
  527. }
  528. self::ensureSchema();
  529. self::ensureFinalScoreTable();
  530. try {
  531. $rows = Db::table(self::TABLE_SCORE)
  532. ->where('ym', $ym)
  533. ->field('company_name')
  534. ->group('company_name')
  535. ->select();
  536. } catch (\Throwable $e) {
  537. return;
  538. }
  539. if (!is_array($rows) || $rows === []) {
  540. return;
  541. }
  542. $names = [];
  543. foreach ($rows as $r) {
  544. if (!is_array($r)) {
  545. continue;
  546. }
  547. $cn = trim((string)($r['company_name'] ?? ''));
  548. if ($cn !== '') {
  549. $names[] = $cn;
  550. }
  551. }
  552. self::ensureMonthlySupplierNames($ym, $names);
  553. }
  554. /**
  555. * 合格率百分比 → 质量「合格率」分项(满分 20)
  556. * 100→20;95-99→18;90-94→16;85-89→14;70-84→12;&lt;70→10
  557. */
  558. public static function mapPassRatePercentToQualityScore(float $passRatePercent): float
  559. {
  560. if ($passRatePercent >= 100) {
  561. return 20.0;
  562. }
  563. if ($passRatePercent >= 95) {
  564. return 18.0;
  565. }
  566. if ($passRatePercent >= 90) {
  567. return 16.0;
  568. }
  569. if ($passRatePercent >= 85) {
  570. return 14.0;
  571. }
  572. if ($passRatePercent >= 70) {
  573. return 12.0;
  574. }
  575. return 10.0;
  576. }
  577. /**
  578. * 交货准时率百分比 → 交货「准时率」分项(满分 30)
  579. * 100→30;95-99→20;90-94→15;85-89→10;70-84→5;&lt;70→0
  580. */
  581. public static function mapOnTimeRatePercentToDeliveryScore(float $onTimeRatePercent): float
  582. {
  583. if ($onTimeRatePercent >= 100) {
  584. return 30.0;
  585. }
  586. if ($onTimeRatePercent >= 95) {
  587. return 20.0;
  588. }
  589. if ($onTimeRatePercent >= 90) {
  590. return 15.0;
  591. }
  592. if ($onTimeRatePercent >= 85) {
  593. return 10.0;
  594. }
  595. if ($onTimeRatePercent >= 70) {
  596. return 5.0;
  597. }
  598. return 0.0;
  599. }
  600. /**
  601. * 解析金额/限价;空或非数字返回 null
  602. *
  603. * @param mixed $raw
  604. */
  605. public static function parseMoneyValue($raw): ?float
  606. {
  607. if ($raw === null) {
  608. return null;
  609. }
  610. $s = trim((string)$raw);
  611. if ($s === '') {
  612. return null;
  613. }
  614. $s = str_replace([',', ',', ' '], '', $s);
  615. if ($s === '' || !is_numeric($s)) {
  616. return null;
  617. }
  618. return (float)$s;
  619. }
  620. /**
  621. * 报价是否视为未填(空 / 0 / 0.00)
  622. *
  623. * @param mixed $raw
  624. */
  625. public static function isBlankQuoteAmount($raw): bool
  626. {
  627. $v = self::parseMoneyValue($raw);
  628. if ($v === null) {
  629. return true;
  630. }
  631. return abs($v) < 0.0000001;
  632. }
  633. /**
  634. * 工序完结年月(YYYY-MM)
  635. * 优先:采购确认 / 直接完结操作时间;其次采购单 pick_time/createtime/dStamp;再无:入库评分时间
  636. *
  637. * @param int[] $scydgyIds
  638. * @param array<int, array{createtime?:mixed,updatetime?:mixed}> $inboundTimeBySid
  639. * @return array<int, string> scydgy_id => YYYY-MM
  640. */
  641. public static function loadCompletedYmMapByScydgyIds(array $scydgyIds, array $inboundTimeBySid = []): array
  642. {
  643. $ids = [];
  644. foreach ($scydgyIds as $sid) {
  645. $sid = (int)$sid;
  646. if ($sid > 0) {
  647. $ids[$sid] = true;
  648. }
  649. }
  650. if ($ids === []) {
  651. return [];
  652. }
  653. $sidList = array_keys($ids);
  654. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap($sidList, ['purchase_confirm', 'mark_complete']);
  655. $poBySid = [];
  656. try {
  657. $poRows = Db::table('purchase_order')
  658. ->where('scydgy_id', 'in', $sidList)
  659. ->field('scydgy_id,pick_time,createtime,dStamp')
  660. ->select();
  661. } catch (\Throwable $e) {
  662. $poRows = [];
  663. }
  664. if (is_array($poRows)) {
  665. foreach ($poRows as $po) {
  666. if (!is_array($po)) {
  667. continue;
  668. }
  669. $sid = (int)($po['scydgy_id'] ?? 0);
  670. if ($sid > 0) {
  671. $poBySid[$sid] = $po;
  672. }
  673. }
  674. }
  675. $out = [];
  676. foreach ($sidList as $sid) {
  677. $row = $poBySid[$sid] ?? ['scydgy_id' => $sid];
  678. $done = ProcuremenTime::resolveCompletedDone($row, $completeTsMap);
  679. $ts = (int)($done['ts'] ?? 0);
  680. if ($ts <= 946684800 && isset($inboundTimeBySid[$sid])) {
  681. $t1 = ProcuremenTime::parseToTimestamp($inboundTimeBySid[$sid]['updatetime'] ?? null);
  682. $t2 = ProcuremenTime::parseToTimestamp($inboundTimeBySid[$sid]['createtime'] ?? null);
  683. $ts = max($t1, $t2);
  684. }
  685. if ($ts > 946684800) {
  686. $out[$sid] = date('Y-m', $ts);
  687. }
  688. }
  689. return $out;
  690. }
  691. /**
  692. * 某供应商某月入库评分订单聚合(按订单号去重)
  693. * 月份按工序「完结时间」归属,不用质量评分创建/更新时间
  694. *
  695. * @return array<string, array{result:string,delivery_status:string,customer_complaint:int,order_interrupt:int}>
  696. */
  697. public static function loadInboundOrderAggByCompanyYm(string $companyName, string $ym): array
  698. {
  699. $companyName = trim($companyName);
  700. $ym = self::formatScoreYm($ym);
  701. if ($companyName === '' || $ym === '') {
  702. return [];
  703. }
  704. $cacheKey = $companyName . "\0" . $ym;
  705. if (isset(self::$inboundAggCache[$cacheKey])) {
  706. return self::$inboundAggCache[$cacheKey];
  707. }
  708. /** @var array<string, array{result:string,delivery_status:string,customer_complaint:int,order_interrupt:int}> $byOrder */
  709. $byOrder = [];
  710. try {
  711. $rows = Db::table('purchase_order_inbound_score')
  712. ->where('company_name', $companyName)
  713. ->field('scydgy_id,ccydh,result,delivery_status,customer_complaint,order_interrupt,createtime,updatetime')
  714. ->select();
  715. } catch (\Throwable $e) {
  716. try {
  717. $rows = Db::table('purchase_order_inbound_score')
  718. ->where('company_name', $companyName)
  719. ->field('scydgy_id,ccydh,result,createtime,updatetime')
  720. ->select();
  721. } catch (\Throwable $e2) {
  722. $rows = [];
  723. Log::write('loadInboundOrderAgg table: ' . $e2->getMessage(), 'error');
  724. }
  725. }
  726. if (!is_array($rows) || $rows === []) {
  727. $legacy = self::loadInboundOrderResultsFromOperLogs($companyName, $ym);
  728. foreach ($legacy as $ccydh => $res) {
  729. $byOrder[$ccydh] = [
  730. 'result' => $res,
  731. 'delivery_status' => '',
  732. 'customer_complaint' => 0,
  733. 'order_interrupt' => 0,
  734. ];
  735. }
  736. return self::$inboundAggCache[$cacheKey] = $byOrder;
  737. }
  738. $sidSet = [];
  739. $inboundTimeBySid = [];
  740. foreach ($rows as $r) {
  741. if (!is_array($r)) {
  742. continue;
  743. }
  744. $sid = (int)($r['scydgy_id'] ?? 0);
  745. if ($sid <= 0) {
  746. continue;
  747. }
  748. $sidSet[$sid] = true;
  749. $inboundTimeBySid[$sid] = [
  750. 'createtime' => $r['createtime'] ?? null,
  751. 'updatetime' => $r['updatetime'] ?? null,
  752. ];
  753. }
  754. $completedYmMap = self::loadCompletedYmMapByScydgyIds(array_keys($sidSet), $inboundTimeBySid);
  755. foreach ($rows as $r) {
  756. if (!is_array($r)) {
  757. continue;
  758. }
  759. $sid = (int)($r['scydgy_id'] ?? 0);
  760. $rowYm = $sid > 0 ? (string)($completedYmMap[$sid] ?? '') : '';
  761. if ($rowYm === '' && $sid <= 0) {
  762. // 无工序 id:回退评分时间
  763. $t1 = ProcuremenTime::parseToTimestamp($r['updatetime'] ?? null);
  764. $t2 = ProcuremenTime::parseToTimestamp($r['createtime'] ?? null);
  765. $ts = max($t1, $t2);
  766. $rowYm = $ts > 946684800 ? date('Y-m', $ts) : '';
  767. }
  768. if ($rowYm !== $ym) {
  769. continue;
  770. }
  771. $ccydh = trim((string)($r['ccydh'] ?? ''));
  772. $res = trim((string)($r['result'] ?? ''));
  773. if ($ccydh === '' || ($res !== '合格' && $res !== '不合格')) {
  774. continue;
  775. }
  776. $ds = trim((string)($r['delivery_status'] ?? ''));
  777. if ($ds !== '准时' && $ds !== '滞后') {
  778. $ds = '';
  779. }
  780. $complaint = (int)($r['customer_complaint'] ?? 0) === 1 ? 1 : 0;
  781. $interrupt = (int)($r['order_interrupt'] ?? 0) === 1 ? 1 : 0;
  782. if (!isset($byOrder[$ccydh])) {
  783. $byOrder[$ccydh] = [
  784. 'result' => $res,
  785. 'delivery_status' => $ds,
  786. 'customer_complaint' => $complaint,
  787. 'order_interrupt' => $interrupt,
  788. ];
  789. continue;
  790. }
  791. if ($res === '不合格') {
  792. $byOrder[$ccydh]['result'] = '不合格';
  793. }
  794. if ($byOrder[$ccydh]['delivery_status'] === '' && $ds !== '') {
  795. $byOrder[$ccydh]['delivery_status'] = $ds;
  796. }
  797. if ($complaint === 1) {
  798. $byOrder[$ccydh]['customer_complaint'] = 1;
  799. }
  800. if ($interrupt === 1) {
  801. $byOrder[$ccydh]['order_interrupt'] = 1;
  802. }
  803. }
  804. if ($byOrder !== []) {
  805. return self::$inboundAggCache[$cacheKey] = $byOrder;
  806. }
  807. // 回退:操作日志仅能还原合格/不合格(同样按完结月过滤)
  808. $legacy = self::loadInboundOrderResultsFromOperLogs($companyName, $ym);
  809. foreach ($legacy as $ccydh => $res) {
  810. $byOrder[$ccydh] = [
  811. 'result' => $res,
  812. 'delivery_status' => '',
  813. 'customer_complaint' => 0,
  814. 'order_interrupt' => 0,
  815. ];
  816. }
  817. return self::$inboundAggCache[$cacheKey] = $byOrder;
  818. }
  819. /**
  820. * 某供应商某月:订单号 => 合格|不合格(兼容旧调用)
  821. *
  822. * @return array<string, string>
  823. */
  824. public static function loadInboundOrderResultsByCompanyYm(string $companyName, string $ym): array
  825. {
  826. $out = [];
  827. foreach (self::loadInboundOrderAggByCompanyYm($companyName, $ym) as $ccydh => $agg) {
  828. $out[$ccydh] = (string)($agg['result'] ?? '');
  829. }
  830. return $out;
  831. }
  832. /**
  833. * 操作日志回退:订单号 => 合格|不合格(按工序完结月过滤)
  834. *
  835. * @return array<string, string>
  836. */
  837. protected static function loadInboundOrderResultsFromOperLogs(string $companyName, string $ym): array
  838. {
  839. $byOrder = [];
  840. try {
  841. $logs = Db::table('purchase_order_oper_log')
  842. ->where(function ($q) {
  843. $q->where('action', '入库评分')->whereOr('action', 'inbound_score');
  844. })
  845. ->field('scydgy_id,content,createtime')
  846. ->order('id', 'asc')
  847. ->select();
  848. } catch (\Throwable $e) {
  849. Log::write('loadInboundOrderResults logs: ' . $e->getMessage(), 'error');
  850. return [];
  851. }
  852. if (!is_array($logs) || $logs === []) {
  853. return [];
  854. }
  855. $sidResult = [];
  856. $inboundTimeBySid = [];
  857. foreach ($logs as $lg) {
  858. if (!is_array($lg)) {
  859. continue;
  860. }
  861. $sid = (int)($lg['scydgy_id'] ?? 0);
  862. if ($sid <= 0) {
  863. continue;
  864. }
  865. $content = trim((string)($lg['content'] ?? ''));
  866. if (!preg_match('/(合格|不合格)/u', $content, $m)) {
  867. continue;
  868. }
  869. $sidResult[$sid] = $m[1];
  870. $inboundTimeBySid[$sid] = [
  871. 'createtime' => $lg['createtime'] ?? null,
  872. 'updatetime' => $lg['createtime'] ?? null,
  873. ];
  874. }
  875. if ($sidResult === []) {
  876. return [];
  877. }
  878. try {
  879. $poRows = Db::table('purchase_order')
  880. ->where('scydgy_id', 'in', array_keys($sidResult))
  881. ->where('pick_company_name', $companyName)
  882. ->field('scydgy_id,CCYDH,pick_company_name')
  883. ->select();
  884. } catch (\Throwable $e) {
  885. return [];
  886. }
  887. if (!is_array($poRows)) {
  888. return [];
  889. }
  890. $completedYmMap = self::loadCompletedYmMapByScydgyIds(array_keys($sidResult), $inboundTimeBySid);
  891. foreach ($poRows as $po) {
  892. if (!is_array($po)) {
  893. continue;
  894. }
  895. $sid = (int)($po['scydgy_id'] ?? 0);
  896. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  897. $res = $sidResult[$sid] ?? '';
  898. if ($sid <= 0 || $ccydh === '' || ($res !== '合格' && $res !== '不合格')) {
  899. continue;
  900. }
  901. if ((string)($completedYmMap[$sid] ?? '') !== $ym) {
  902. continue;
  903. }
  904. if (!isset($byOrder[$ccydh]) || $res === '不合格') {
  905. $byOrder[$ccydh] = $res;
  906. }
  907. }
  908. return $byOrder;
  909. }
  910. /**
  911. * 质量得分(满分 40)= 合格率分(20) + 客户投诉(10) + 生产中断(10)
  912. *
  913. * @return float|null 无入库评分订单时返回 null
  914. */
  915. public static function calcQualityScoreFromInbound(string $companyName, string $ym): ?float
  916. {
  917. $companyName = trim($companyName);
  918. $ym = self::formatScoreYm($ym);
  919. if ($companyName === '' || $ym === '') {
  920. return null;
  921. }
  922. $byOrder = self::loadInboundOrderAggByCompanyYm($companyName, $ym);
  923. $total = count($byOrder);
  924. if ($total < 1) {
  925. return null;
  926. }
  927. $fail = 0;
  928. $complaintAny = false;
  929. $interruptCnt = 0;
  930. foreach ($byOrder as $agg) {
  931. if (($agg['result'] ?? '') === '不合格') {
  932. $fail++;
  933. }
  934. if ((int)($agg['customer_complaint'] ?? 0) === 1) {
  935. $complaintAny = true;
  936. }
  937. if ((int)($agg['order_interrupt'] ?? 0) === 1) {
  938. $interruptCnt++;
  939. }
  940. }
  941. $passRate = (1 - ($fail / $total)) * 100;
  942. $passScore = self::mapPassRatePercentToQualityScore($passRate);
  943. $complaintScore = $complaintAny ? 0.0 : 10.0;
  944. if ($interruptCnt >= 3) {
  945. $interruptScore = 0.0;
  946. } else {
  947. $interruptScore = max(0.0, 10.0 - 2.0 * $interruptCnt);
  948. }
  949. return round($passScore + $complaintScore + $interruptScore, 2);
  950. }
  951. /**
  952. * 交货得分(满分 40)= 准时率分(30) + 生产中断(10,出现一次得 0)
  953. *
  954. * @return float|null 无入库评分订单时返回 null
  955. */
  956. public static function calcDeliveryScoreFromInbound(string $companyName, string $ym): ?float
  957. {
  958. $companyName = trim($companyName);
  959. $ym = self::formatScoreYm($ym);
  960. if ($companyName === '' || $ym === '') {
  961. return null;
  962. }
  963. $byOrder = self::loadInboundOrderAggByCompanyYm($companyName, $ym);
  964. $total = count($byOrder);
  965. if ($total < 1) {
  966. return null;
  967. }
  968. $late = 0;
  969. $interruptAny = false;
  970. foreach ($byOrder as $agg) {
  971. if (($agg['delivery_status'] ?? '') === '滞后') {
  972. $late++;
  973. }
  974. if ((int)($agg['order_interrupt'] ?? 0) === 1) {
  975. $interruptAny = true;
  976. }
  977. }
  978. $onTimeRate = (1 - ($late / $total)) * 100;
  979. $onTimeScore = self::mapOnTimeRatePercentToDeliveryScore($onTimeRate);
  980. $interruptScore = $interruptAny ? 0.0 : 10.0;
  981. return round($onTimeScore + $interruptScore, 2);
  982. }
  983. /**
  984. * 价格得分(满分 15):全部严格低于最高限价→15;任一单等于限价或限价为空→10
  985. *
  986. * @return float|null 无比价订单时返回 null
  987. */
  988. public static function calcPriceScoreFromCeiling(string $companyName, string $ym): ?float
  989. {
  990. $companyName = trim($companyName);
  991. $ym = self::formatScoreYm($ym);
  992. if ($companyName === '' || $ym === '') {
  993. return null;
  994. }
  995. $byOrder = self::loadInboundOrderAggByCompanyYm($companyName, $ym);
  996. if ($byOrder === []) {
  997. return null;
  998. }
  999. $ccydhList = array_keys($byOrder);
  1000. $compared = 0;
  1001. $allStrictlyBelow = true;
  1002. try {
  1003. $poRows = Db::table('purchase_order')
  1004. ->alias('po')
  1005. ->join('purchase_order_detail d', 'd.scydgy_id = po.scydgy_id')
  1006. ->where('po.CCYDH', 'in', $ccydhList)
  1007. ->where('d.company_name', $companyName)
  1008. ->whereRaw(
  1009. '(po.mod_rq IS NULL OR TRIM(CAST(po.mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(po.mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  1010. )
  1011. ->field('po.CCYDH,po.ceilingPrice,d.amount')
  1012. ->select();
  1013. } catch (\Throwable $e) {
  1014. try {
  1015. $poRows = Db::table('purchase_order')
  1016. ->alias('po')
  1017. ->join('purchase_order_detail d', 'd.scydgy_id = po.scydgy_id')
  1018. ->where('po.CCYDH', 'in', $ccydhList)
  1019. ->where('d.company_name', $companyName)
  1020. ->field('po.CCYDH,po.ceilingPrice,d.amount')
  1021. ->select();
  1022. } catch (\Throwable $e2) {
  1023. Log::write('calcPriceScoreFromCeiling: ' . $e2->getMessage(), 'error');
  1024. return null;
  1025. }
  1026. }
  1027. if (!is_array($poRows) || $poRows === []) {
  1028. return null;
  1029. }
  1030. /** @var array<string, bool> $orderStrictBelow 订单是否全部严格低于限价 */
  1031. $orderStrictBelow = [];
  1032. foreach ($poRows as $r) {
  1033. if (!is_array($r)) {
  1034. continue;
  1035. }
  1036. $ccydh = trim((string)($r['CCYDH'] ?? $r['ccydh'] ?? ''));
  1037. if ($ccydh === '' || !isset($byOrder[$ccydh])) {
  1038. continue;
  1039. }
  1040. if (self::isBlankQuoteAmount($r['amount'] ?? null)) {
  1041. continue;
  1042. }
  1043. $amount = self::parseMoneyValue($r['amount'] ?? null);
  1044. if ($amount === null) {
  1045. continue;
  1046. }
  1047. $compared++;
  1048. if (!isset($orderStrictBelow[$ccydh])) {
  1049. $orderStrictBelow[$ccydh] = true;
  1050. }
  1051. $ceiling = self::parseMoneyValue($r['ceilingPrice'] ?? $r['ceiling_price'] ?? null);
  1052. if ($ceiling === null) {
  1053. // 限价空 → 该单非严格低于
  1054. $orderStrictBelow[$ccydh] = false;
  1055. continue;
  1056. }
  1057. // 严格低于才算;等于或高于都不算
  1058. if ($amount >= $ceiling - 0.0000001) {
  1059. $orderStrictBelow[$ccydh] = false;
  1060. }
  1061. }
  1062. if ($compared < 1 || $orderStrictBelow === []) {
  1063. return null;
  1064. }
  1065. foreach ($orderStrictBelow as $ok) {
  1066. if (!$ok) {
  1067. $allStrictlyBelow = false;
  1068. break;
  1069. }
  1070. }
  1071. return $allStrictlyBelow ? 15.0 : 10.0;
  1072. }
  1073. /**
  1074. * 增值服务(满分 10):未报价订单数(按订单号去重)≤3 →10;>3 →0
  1075. * 须当月已有完结/入库评分订单才计分(与本月订单明细同源);仅有询价无完结单 → null
  1076. *
  1077. * @return float|null 无本月完结订单或无询价记录时返回 null
  1078. */
  1079. public static function calcValueAddedScoreFromUnquoted(string $companyName, string $ym): ?float
  1080. {
  1081. $companyName = trim($companyName);
  1082. $ym = self::formatScoreYm($ym);
  1083. if ($companyName === '' || $ym === '') {
  1084. return null;
  1085. }
  1086. // 无本月入库完结订单则不计增值(避免「明细 0 单却有 10 分」)
  1087. $inboundOrders = self::loadInboundOrderAggByCompanyYm($companyName, $ym);
  1088. if ($inboundOrders === []) {
  1089. return null;
  1090. }
  1091. $stats = self::loadUnquotedOrderStatsByCompanyYm($companyName, $ym);
  1092. if ($stats === null) {
  1093. return null;
  1094. }
  1095. $unquoted = (int)($stats['unquoted'] ?? 0);
  1096. return $unquoted <= 3 ? 10.0 : 0.0;
  1097. }
  1098. /**
  1099. * 某供应商某月询价订单:总数 / 未报价数(均按 CCYDH 去重)
  1100. *
  1101. * @return array{total:int,unquoted:int}|null 无询价记录时 null
  1102. */
  1103. public static function loadUnquotedOrderStatsByCompanyYm(string $companyName, string $ym): ?array
  1104. {
  1105. $companyName = trim($companyName);
  1106. $ym = self::formatScoreYm($ym);
  1107. if ($companyName === '' || $ym === '') {
  1108. return null;
  1109. }
  1110. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  1111. try {
  1112. $rows = Db::table('purchase_order_detail')
  1113. ->alias('d')
  1114. ->join('purchase_order po', 'po.scydgy_id = d.scydgy_id')
  1115. ->where('d.company_name', $companyName)
  1116. ->whereRaw(
  1117. "("
  1118. . "CASE "
  1119. . "WHEN po.createtime IS NOT NULL AND CAST(po.createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  1120. . "THEN FROM_UNIXTIME(CAST(po.createtime AS UNSIGNED)) "
  1121. . "WHEN po.createtime IS NOT NULL AND TRIM(CAST(po.createtime AS CHAR(32))) <> '' "
  1122. . "AND TRIM(CAST(po.createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  1123. . "THEN TRIM(CAST(po.createtime AS CHAR(32))) "
  1124. . "ELSE TRIM(CAST(IFNULL(po.dStamp, '') AS CHAR(32))) "
  1125. . "END"
  1126. . ") LIKE '{$ymEsc}-%'"
  1127. )
  1128. ->whereRaw(
  1129. '(po.mod_rq IS NULL OR TRIM(CAST(po.mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(po.mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  1130. )
  1131. ->field('po.CCYDH,d.amount')
  1132. ->select();
  1133. } catch (\Throwable $e) {
  1134. Log::write('loadUnquotedOrderStats: ' . $e->getMessage(), 'error');
  1135. return null;
  1136. }
  1137. if (!is_array($rows) || $rows === []) {
  1138. return null;
  1139. }
  1140. /** @var array<string, bool> $quotedByOrder 订单是否至少有一条有效报价 */
  1141. $quotedByOrder = [];
  1142. foreach ($rows as $r) {
  1143. if (!is_array($r)) {
  1144. continue;
  1145. }
  1146. $ccydh = trim((string)($r['CCYDH'] ?? $r['ccydh'] ?? ''));
  1147. if ($ccydh === '') {
  1148. continue;
  1149. }
  1150. if (!isset($quotedByOrder[$ccydh])) {
  1151. $quotedByOrder[$ccydh] = false;
  1152. }
  1153. if (!self::isBlankQuoteAmount($r['amount'] ?? null)) {
  1154. $quotedByOrder[$ccydh] = true;
  1155. }
  1156. }
  1157. if ($quotedByOrder === []) {
  1158. return null;
  1159. }
  1160. $total = count($quotedByOrder);
  1161. $unquoted = 0;
  1162. foreach ($quotedByOrder as $quoted) {
  1163. if (!$quoted) {
  1164. $unquoted++;
  1165. }
  1166. }
  1167. return ['total' => $total, 'unquoted' => $unquoted];
  1168. }
  1169. /**
  1170. * 收集某月需重算的供应商名称
  1171. * (按完结月有入库评分的供应商 + 当月询价明细 + 月度表已有行,便于清掉错月脏数据)
  1172. *
  1173. * @return string[]
  1174. */
  1175. public static function collectMonthlyReviewCompanyNames(string $ym, ?string $onlyCompany = null): array
  1176. {
  1177. $ym = self::formatScoreYm($ym);
  1178. if ($ym === '') {
  1179. return [];
  1180. }
  1181. $onlyCompany = $onlyCompany !== null ? trim($onlyCompany) : '';
  1182. if ($onlyCompany !== '') {
  1183. return [$onlyCompany];
  1184. }
  1185. $companies = [];
  1186. // 1) 当月完结(采购确认/直接完结)的工序 → 供应商
  1187. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  1188. try {
  1189. $completeActs = ProcuremenOperLog::expandActionQueryValues(['purchase_confirm', 'mark_complete']);
  1190. $clog = Db::table('purchase_order_oper_log')
  1191. ->where(ProcuremenOperLog::COL_ACTION, 'in', $completeActs)
  1192. ->where(ProcuremenOperLog::COL_TIME, 'like', $ym . '%')
  1193. ->field(ProcuremenOperLog::COL_SCYDGY_ID)
  1194. ->select();
  1195. } catch (\Throwable $e) {
  1196. $clog = [];
  1197. }
  1198. $completeSids = [];
  1199. if (is_array($clog)) {
  1200. foreach ($clog as $lg) {
  1201. if (!is_array($lg)) {
  1202. continue;
  1203. }
  1204. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? $lg['scydgy_id'] ?? 0);
  1205. if ($sid > 0) {
  1206. $completeSids[$sid] = true;
  1207. }
  1208. }
  1209. }
  1210. // 2) 当月完结工序 + 当月入库评分时间,再按完结月精确过滤(勿全表拉取入库评分)
  1211. $scoreRows = [];
  1212. try {
  1213. $scoreQuery = Db::table('purchase_order_inbound_score')
  1214. ->field('scydgy_id,company_name,createtime,updatetime');
  1215. $completeSidList = array_keys($completeSids);
  1216. if ($completeSidList !== []) {
  1217. $scoreQuery->where(function ($q) use ($completeSidList, $ym) {
  1218. $q->where('scydgy_id', 'in', $completeSidList)
  1219. ->whereOr('createtime', 'like', $ym . '%')
  1220. ->whereOr('updatetime', 'like', $ym . '%');
  1221. });
  1222. } else {
  1223. $scoreQuery->where(function ($q) use ($ym) {
  1224. $q->where('createtime', 'like', $ym . '%')
  1225. ->whereOr('updatetime', 'like', $ym . '%');
  1226. });
  1227. }
  1228. $scoreRows = $scoreQuery->select();
  1229. } catch (\Throwable $e) {
  1230. $scoreRows = [];
  1231. Log::write('collectMonthlyReviewCompanyNames inbound: ' . $e->getMessage(), 'error');
  1232. }
  1233. $sidSet = $completeSids;
  1234. $inboundTimeBySid = [];
  1235. $companyBySid = [];
  1236. if (is_array($scoreRows)) {
  1237. foreach ($scoreRows as $r) {
  1238. if (!is_array($r)) {
  1239. continue;
  1240. }
  1241. $sid = (int)($r['scydgy_id'] ?? 0);
  1242. $cn = trim((string)($r['company_name'] ?? ''));
  1243. if ($sid > 0) {
  1244. $sidSet[$sid] = true;
  1245. $inboundTimeBySid[$sid] = [
  1246. 'createtime' => $r['createtime'] ?? null,
  1247. 'updatetime' => $r['updatetime'] ?? null,
  1248. ];
  1249. if ($cn !== '') {
  1250. $companyBySid[$sid] = $cn;
  1251. }
  1252. } elseif ($cn !== '') {
  1253. // 无工序 id:按评分时间归月
  1254. $t1 = ProcuremenTime::parseToTimestamp($r['updatetime'] ?? null);
  1255. $t2 = ProcuremenTime::parseToTimestamp($r['createtime'] ?? null);
  1256. $ts = max($t1, $t2);
  1257. if ($ts > 946684800 && date('Y-m', $ts) === $ym) {
  1258. $companies[$cn] = true;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. if ($sidSet !== []) {
  1264. $completedYmMap = self::loadCompletedYmMapByScydgyIds(array_keys($sidSet), $inboundTimeBySid);
  1265. $needPoNames = [];
  1266. foreach ($completedYmMap as $sid => $rowYm) {
  1267. if ($rowYm !== $ym) {
  1268. continue;
  1269. }
  1270. if (isset($companyBySid[$sid]) && $companyBySid[$sid] !== '') {
  1271. $companies[$companyBySid[$sid]] = true;
  1272. } else {
  1273. $needPoNames[(int)$sid] = true;
  1274. }
  1275. }
  1276. if ($needPoNames !== []) {
  1277. try {
  1278. $poRows = Db::table('purchase_order')
  1279. ->where('scydgy_id', 'in', array_keys($needPoNames))
  1280. ->field('scydgy_id,pick_company_name')
  1281. ->select();
  1282. } catch (\Throwable $e) {
  1283. $poRows = [];
  1284. }
  1285. if (is_array($poRows)) {
  1286. foreach ($poRows as $po) {
  1287. if (!is_array($po)) {
  1288. continue;
  1289. }
  1290. $cn = trim((string)($po['pick_company_name'] ?? ''));
  1291. if ($cn !== '') {
  1292. $companies[$cn] = true;
  1293. }
  1294. }
  1295. }
  1296. }
  1297. }
  1298. // 3) 并入当月有询价明细的供应商(增值服务未报价统计)
  1299. try {
  1300. $detailRows = Db::table('purchase_order_detail')
  1301. ->alias('d')
  1302. ->join('purchase_order po', 'po.scydgy_id = d.scydgy_id')
  1303. ->whereRaw(
  1304. "("
  1305. . "CASE "
  1306. . "WHEN po.createtime IS NOT NULL AND CAST(po.createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  1307. . "THEN FROM_UNIXTIME(CAST(po.createtime AS UNSIGNED)) "
  1308. . "WHEN po.createtime IS NOT NULL AND TRIM(CAST(po.createtime AS CHAR(32))) <> '' "
  1309. . "AND TRIM(CAST(po.createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  1310. . "THEN TRIM(CAST(po.createtime AS CHAR(32))) "
  1311. . "ELSE TRIM(CAST(IFNULL(po.dStamp, '') AS CHAR(32))) "
  1312. . "END"
  1313. . ") LIKE '{$ymEsc}-%'"
  1314. )
  1315. ->field('d.company_name')
  1316. ->group('d.company_name')
  1317. ->select();
  1318. } catch (\Throwable $e) {
  1319. $detailRows = [];
  1320. }
  1321. if (is_array($detailRows)) {
  1322. foreach ($detailRows as $dr) {
  1323. if (!is_array($dr)) {
  1324. continue;
  1325. }
  1326. $cn = trim((string)($dr['company_name'] ?? ''));
  1327. if ($cn !== '') {
  1328. $companies[$cn] = true;
  1329. }
  1330. }
  1331. }
  1332. // 4) 月度表已有行:重算时可清掉错月残留
  1333. try {
  1334. $finalRows = Db::table(self::TABLE_FINAL)
  1335. ->where('ym', $ym)
  1336. ->field('company_name')
  1337. ->select();
  1338. } catch (\Throwable $e) {
  1339. $finalRows = [];
  1340. }
  1341. if (is_array($finalRows)) {
  1342. foreach ($finalRows as $fr) {
  1343. if (!is_array($fr)) {
  1344. continue;
  1345. }
  1346. $cn = trim((string)($fr['company_name'] ?? ''));
  1347. if ($cn !== '') {
  1348. $companies[$cn] = true;
  1349. }
  1350. }
  1351. }
  1352. return array_keys($companies);
  1353. }
  1354. /**
  1355. * 按新月度规则重算四项得分 + 最终分/等级(满分 105)
  1356. * 已手工保存(qp_manual=1)的供应商跳过
  1357. *
  1358. * @param string|null $onlyCompany 仅同步该供应商;null=当月相关全部
  1359. * @return array{updated:int,skipped:int}
  1360. */
  1361. public static function syncMonthlyReviewScoresFromRules(string $ym, ?string $onlyCompany = null): array
  1362. {
  1363. $ym = self::formatScoreYm($ym);
  1364. $result = ['updated' => 0, 'skipped' => 0];
  1365. if ($ym === '') {
  1366. return $result;
  1367. }
  1368. self::ensureFinalScoreTable();
  1369. // 单家同步(入库评分后)不必全月扫操作日志回填
  1370. if ($onlyCompany === null || trim($onlyCompany) === '') {
  1371. self::repairInboundScoreFromOperLogs($ym);
  1372. }
  1373. $companies = self::collectMonthlyReviewCompanyNames($ym, $onlyCompany);
  1374. if ($companies === []) {
  1375. return $result;
  1376. }
  1377. self::ensureMonthlySupplierNames($ym, $companies);
  1378. $now = date('Y-m-d H:i:s');
  1379. foreach ($companies as $cn) {
  1380. $cn = trim((string)$cn);
  1381. if ($cn === '') {
  1382. continue;
  1383. }
  1384. try {
  1385. $exists = Db::table(self::TABLE_FINAL)->where('ym', $ym)->where('company_name', $cn)->find();
  1386. if (is_array($exists) && $exists !== [] && (int)($exists['qp_manual'] ?? 0) === 1) {
  1387. $result['skipped']++;
  1388. continue;
  1389. }
  1390. $quality = self::calcQualityScoreFromInbound($cn, $ym);
  1391. $price = self::calcPriceScoreFromCeiling($cn, $ym);
  1392. $delivery = self::calcDeliveryScoreFromInbound($cn, $ym);
  1393. // 与「本月订单明细」一致:当月无完结/入库评分订单时,增值也不单独给分
  1394. $valueAdded = null;
  1395. if ($quality !== null || $price !== null || $delivery !== null) {
  1396. $valueAdded = self::calcValueAddedScoreFromUnquoted($cn, $ym);
  1397. }
  1398. $final = self::sumFinalScore($quality, $price, $delivery, $valueAdded);
  1399. $grade = $final !== null ? self::gradeFromFinalScore($final) : '';
  1400. $scoreCompat = $final !== null ? $final : 0.0;
  1401. if (!is_array($exists) || $exists === []) {
  1402. Db::table(self::TABLE_FINAL)->insert([
  1403. 'ym' => $ym,
  1404. 'company_name' => $cn,
  1405. 'score' => $scoreCompat,
  1406. 'quality_score' => $quality,
  1407. 'price_score' => $price,
  1408. 'delivery_score' => $delivery,
  1409. 'value_added_score' => $valueAdded,
  1410. 'final_score' => $final,
  1411. 'score_grade' => $grade,
  1412. 'qp_manual' => 0,
  1413. 'createtime' => $now,
  1414. 'updatetime' => $now,
  1415. ]);
  1416. } else {
  1417. Db::table(self::TABLE_FINAL)->where('id', (int)($exists['id'] ?? 0))->update([
  1418. 'score' => $scoreCompat,
  1419. 'quality_score' => $quality,
  1420. 'price_score' => $price,
  1421. 'delivery_score' => $delivery,
  1422. 'value_added_score' => $valueAdded,
  1423. 'final_score' => $final,
  1424. 'score_grade' => $grade,
  1425. 'updatetime' => $now,
  1426. ]);
  1427. }
  1428. $result['updated']++;
  1429. } catch (\Throwable $e) {
  1430. Log::write('syncMonthlyReviewScoresFromRules write: ' . $e->getMessage(), 'error');
  1431. }
  1432. }
  1433. return $result;
  1434. }
  1435. /**
  1436. * 兼容旧入口:改为按月度四项规则同步
  1437. *
  1438. * @param string|null $onlyCompany 仅同步该供应商;null=当月相关全部
  1439. */
  1440. public static function syncQualityScoreFromInbound(string $ym, ?string $onlyCompany = null): void
  1441. {
  1442. self::syncMonthlyReviewScoresFromRules($ym, $onlyCompany);
  1443. }
  1444. /**
  1445. * 操作日志有入库评分、评分表缺失时,回填 purchase_order_inbound_score
  1446. */
  1447. public static function repairInboundScoreFromOperLogs(string $ym): void
  1448. {
  1449. $ym = self::formatScoreYm($ym);
  1450. if ($ym === '') {
  1451. return;
  1452. }
  1453. try {
  1454. $logs = Db::table('purchase_order_oper_log')
  1455. ->where(function ($q) {
  1456. $q->where('action', '入库评分')->whereOr('action', 'inbound_score');
  1457. })
  1458. ->where('createtime', 'like', $ym . '%')
  1459. ->field('scydgy_id,content,createtime,admin_id,admin_name,purchase_order_id')
  1460. ->order('id', 'asc')
  1461. ->select();
  1462. } catch (\Throwable $e) {
  1463. return;
  1464. }
  1465. if (!is_array($logs) || $logs === []) {
  1466. return;
  1467. }
  1468. $best = [];
  1469. foreach ($logs as $lg) {
  1470. if (!is_array($lg)) {
  1471. continue;
  1472. }
  1473. $sid = (int)($lg['scydgy_id'] ?? 0);
  1474. if ($sid <= 0) {
  1475. continue;
  1476. }
  1477. $content = trim((string)($lg['content'] ?? ''));
  1478. if (!preg_match('/(合格|不合格)/u', $content, $m)) {
  1479. continue;
  1480. }
  1481. $best[$sid] = [
  1482. 'result' => $m[1],
  1483. 'createtime' => trim((string)($lg['createtime'] ?? '')),
  1484. 'admin_id' => (int)($lg['admin_id'] ?? 0),
  1485. 'admin_name' => trim((string)($lg['admin_name'] ?? '')),
  1486. 'purchase_order_id' => (int)($lg['purchase_order_id'] ?? 0),
  1487. ];
  1488. }
  1489. if ($best === []) {
  1490. return;
  1491. }
  1492. try {
  1493. $existRows = Db::table('purchase_order_inbound_score')
  1494. ->where('scydgy_id', 'in', array_keys($best))
  1495. ->field('scydgy_id')
  1496. ->select();
  1497. } catch (\Throwable $e) {
  1498. return;
  1499. }
  1500. $existSids = [];
  1501. if (is_array($existRows)) {
  1502. foreach ($existRows as $er) {
  1503. if (is_array($er)) {
  1504. $existSids[(int)($er['scydgy_id'] ?? 0)] = true;
  1505. }
  1506. }
  1507. }
  1508. $needSids = [];
  1509. foreach (array_keys($best) as $sid) {
  1510. if (empty($existSids[$sid])) {
  1511. $needSids[] = $sid;
  1512. }
  1513. }
  1514. if ($needSids === []) {
  1515. return;
  1516. }
  1517. try {
  1518. $poRows = Db::table('purchase_order')
  1519. ->where('scydgy_id', 'in', $needSids)
  1520. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name')
  1521. ->select();
  1522. } catch (\Throwable $e) {
  1523. return;
  1524. }
  1525. if (!is_array($poRows)) {
  1526. return;
  1527. }
  1528. foreach ($poRows as $po) {
  1529. if (!is_array($po)) {
  1530. continue;
  1531. }
  1532. $sid = (int)($po['scydgy_id'] ?? 0);
  1533. if ($sid <= 0 || empty($best[$sid])) {
  1534. continue;
  1535. }
  1536. $b = $best[$sid];
  1537. $now = $b['createtime'] !== '' ? $b['createtime'] : date('Y-m-d H:i:s');
  1538. $data = [
  1539. 'scydgy_id' => $sid,
  1540. 'purchase_order_id' => (int)($po['id'] ?? 0) > 0 ? (int)$po['id'] : (int)$b['purchase_order_id'],
  1541. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  1542. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  1543. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  1544. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  1545. 'result' => $b['result'],
  1546. 'admin_id' => (int)$b['admin_id'],
  1547. 'admin_name' => (string)$b['admin_name'],
  1548. 'createtime' => $now,
  1549. 'updatetime' => $now,
  1550. ];
  1551. if ($data['company_name'] === '' || $data['ccydh'] === '') {
  1552. continue;
  1553. }
  1554. try {
  1555. Db::table('purchase_order_inbound_score')->insert($data);
  1556. } catch (\Throwable $e) {
  1557. // 唯一键冲突忽略
  1558. if (stripos($e->getMessage(), 'Duplicate') === false) {
  1559. Log::write('repairInboundScoreFromOperLogs: ' . $e->getMessage(), 'error');
  1560. }
  1561. }
  1562. }
  1563. }
  1564. /**
  1565. * 默认查询月份:优先月度评审表已有记录的最近一月,其次询价评分表,再次入库评分时间
  1566. */
  1567. public static function latestReviewYm(): string
  1568. {
  1569. self::ensureFinalScoreTable();
  1570. foreach ([self::TABLE_FINAL, self::TABLE_SCORE] as $table) {
  1571. try {
  1572. $raw = Db::table($table)->max('ym');
  1573. $ym = self::formatScoreYm($raw);
  1574. if ($ym !== '') {
  1575. return $ym;
  1576. }
  1577. } catch (\Throwable $e) {
  1578. }
  1579. }
  1580. try {
  1581. $row = Db::query(
  1582. "SELECT DATE_FORMAT(MAX(`createtime`), '%Y-%m') AS `ym` FROM `purchase_order_inbound_score`"
  1583. . " WHERE `createtime` IS NOT NULL AND CAST(`createtime` AS CHAR(32)) NOT LIKE '0000-00-00%'"
  1584. );
  1585. if (is_array($row) && isset($row[0])) {
  1586. $ym = self::formatScoreYm($row[0]['ym'] ?? '');
  1587. if ($ym !== '') {
  1588. return $ym;
  1589. }
  1590. }
  1591. } catch (\Throwable $e) {
  1592. }
  1593. return date('Y-m');
  1594. }
  1595. /**
  1596. * 读取某月评审记录(仅读月度表)
  1597. *
  1598. * @param bool $resync true=先补齐供应商并按规则重算;false=只读库(列表/导出默认,避免卡顿)
  1599. * @return array<string, array{score:float,quality_score:?float,price_score:?float,delivery_score:?float,final_score:?float,final_saved:int,score_grade:string,score_date:string}>
  1600. */
  1601. public static function loadMonthlyMapByYm(string $ym, bool $resync = false): array
  1602. {
  1603. $ym = trim($ym);
  1604. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1605. return [];
  1606. }
  1607. self::ensureFinalScoreTable();
  1608. if ($resync) {
  1609. // 本月询价(开标后已写入订单评分表)的供应商:名称不存在则加空行,已存在不动
  1610. self::ensureMonthlySupplierNamesFromOrderYm($ym);
  1611. // 按月度规则重算质量/价格/交货/增值(满分105;qp_manual=1 跳过)
  1612. self::syncMonthlyReviewScoresFromRules($ym);
  1613. }
  1614. $fetchRows = function () use ($ym) {
  1615. try {
  1616. $rows = Db::table(self::TABLE_FINAL)
  1617. ->where('ym', $ym)
  1618. ->field('company_name,score,quality_score,price_score,delivery_score,value_added_score,final_score,score_grade,ym')
  1619. ->select();
  1620. } catch (\Throwable $e) {
  1621. return [];
  1622. }
  1623. return is_array($rows) ? $rows : [];
  1624. };
  1625. $rows = $fetchRows();
  1626. // 只读进页时若月度表还没行,先按询价明细补名称,避免选错月份外看起来像「没数据」
  1627. if ($rows === [] && !$resync) {
  1628. self::ensureMonthlySupplierNamesFromOrderYm($ym);
  1629. $rows = $fetchRows();
  1630. }
  1631. $out = [];
  1632. foreach ($rows as $r) {
  1633. if (!is_array($r)) {
  1634. continue;
  1635. }
  1636. $cn = trim((string)($r['company_name'] ?? $r['Company_name'] ?? ''));
  1637. if ($cn === '') {
  1638. continue;
  1639. }
  1640. $quality = self::readOptionalScoreValue($r['quality_score'] ?? null);
  1641. $price = self::readOptionalScoreValue($r['price_score'] ?? null);
  1642. $delivery = self::readOptionalScoreValue($r['delivery_score'] ?? null);
  1643. $valueAdded = self::readOptionalScoreValue($r['value_added_score'] ?? null);
  1644. $final = self::readOptionalScoreValue($r['final_score'] ?? null);
  1645. $out[$cn] = [
  1646. 'score' => round((float)($r['score'] ?? 0), 2),
  1647. 'quality_score' => $quality,
  1648. 'price_score' => $price,
  1649. 'delivery_score' => $delivery,
  1650. 'value_added_score' => $valueAdded,
  1651. 'final_score' => $final,
  1652. 'final_saved' => $final !== null ? 1 : 0,
  1653. 'score_grade' => self::normalizeScoreGrade($r['score_grade'] ?? ''),
  1654. // 列表「日期」列按 ym(YYYY-MM)展示,不到日
  1655. 'score_date' => self::formatScoreYm($r['ym'] ?? $ym),
  1656. ];
  1657. }
  1658. return $out;
  1659. }
  1660. /**
  1661. * 规范为 YYYY-MM(月度评审日期)
  1662. *
  1663. * @param mixed $raw
  1664. */
  1665. public static function formatScoreYm($raw): string
  1666. {
  1667. $raw = trim((string)$raw);
  1668. if (preg_match('/^\d{4}-\d{2}$/', $raw)) {
  1669. return $raw;
  1670. }
  1671. if (preg_match('/^(\d{4})\D+(\d{1,2})/', $raw, $m)) {
  1672. return sprintf('%04d-%02d', (int)$m[1], (int)$m[2]);
  1673. }
  1674. return '';
  1675. }
  1676. /**
  1677. * @param mixed $raw
  1678. */
  1679. public static function formatScoreDateYmd($raw): string
  1680. {
  1681. $raw = trim((string)$raw);
  1682. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  1683. return '';
  1684. }
  1685. $ts = strtotime(str_replace('T', ' ', $raw));
  1686. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  1687. }
  1688. /**
  1689. * 解析可选分数:空=null;非法=false;合法=float
  1690. *
  1691. * @param mixed $raw
  1692. * @return float|null|false
  1693. */
  1694. protected static function parseOptionalScore($raw)
  1695. {
  1696. if ($raw === null) {
  1697. return null;
  1698. }
  1699. if (is_string($raw) && trim($raw) === '') {
  1700. return null;
  1701. }
  1702. if (!is_numeric($raw)) {
  1703. return false;
  1704. }
  1705. return round((float)$raw, 2);
  1706. }
  1707. /**
  1708. * 批量保存某月评审分:商务技术分 / 价格分 / 交货分 / 最终得分 / 评分等级
  1709. *
  1710. * @param array<int, array{company_name?:string,quality_score?:mixed,price_score?:mixed,delivery_score?:mixed,final_score?:mixed,score_grade?:mixed}> $items
  1711. * @return array{done:int,saved:int,cleared:int,error:string}
  1712. */
  1713. public static function saveFinalScoresForYm(string $ym, array $items): array
  1714. {
  1715. $ym = trim($ym);
  1716. $result = ['done' => 0, 'saved' => 0, 'cleared' => 0, 'error' => ''];
  1717. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1718. $result['error'] = '月份无效';
  1719. return $result;
  1720. }
  1721. if ($items === []) {
  1722. $result['error'] = '没有可保存的数据';
  1723. return $result;
  1724. }
  1725. self::ensureFinalScoreTable();
  1726. try {
  1727. Db::query('SELECT 1 FROM `' . self::TABLE_FINAL . '` LIMIT 1');
  1728. } catch (\Throwable $e) {
  1729. $result['error'] = '月度汇总表未创建,请联系管理员';
  1730. return $result;
  1731. }
  1732. $now = date('Y-m-d H:i:s');
  1733. foreach ($items as $it) {
  1734. if (!is_array($it)) {
  1735. continue;
  1736. }
  1737. $cn = trim((string)($it['company_name'] ?? ''));
  1738. if ($cn === '') {
  1739. continue;
  1740. }
  1741. $grade = self::normalizeScoreGrade($it['score_grade'] ?? '');
  1742. $quality = self::parseOptionalScore($it['quality_score'] ?? null);
  1743. $price = self::parseOptionalScore($it['price_score'] ?? null);
  1744. $delivery = self::parseOptionalScore($it['delivery_score'] ?? null);
  1745. $valueAdded = self::parseOptionalScore($it['value_added_score'] ?? null);
  1746. $final = self::parseOptionalScore($it['final_score'] ?? null);
  1747. if ($quality === false || $price === false || $delivery === false || $valueAdded === false || $final === false) {
  1748. continue;
  1749. }
  1750. // 未填最终得分时,按四项自动汇总
  1751. if ($final === null) {
  1752. $final = self::sumFinalScore($quality, $price, $delivery, $valueAdded);
  1753. }
  1754. // 未选等级时,按最终得分自动定级
  1755. if ($grade === '' && $final !== null) {
  1756. $grade = self::gradeFromFinalScore($final);
  1757. }
  1758. $hasQp = array_key_exists('quality_score', $it)
  1759. || array_key_exists('price_score', $it)
  1760. || array_key_exists('delivery_score', $it)
  1761. || array_key_exists('value_added_score', $it);
  1762. $hasAny = $final !== null || $grade !== ''
  1763. || $quality !== null || $price !== null || $delivery !== null || $valueAdded !== null;
  1764. // 全空行不写入,避免误把未改供应商标成手工锁定
  1765. if (!$hasAny) {
  1766. continue;
  1767. }
  1768. try {
  1769. $exists = Db::table(self::TABLE_FINAL)->where('ym', $ym)->where('company_name', $cn)->find();
  1770. $upd = [
  1771. 'final_score' => $final,
  1772. 'score_grade' => $grade,
  1773. 'updatetime' => $now,
  1774. // 保存即视为手工确认,之后不再跑查询计算规则覆盖
  1775. 'qp_manual' => 1,
  1776. ];
  1777. if ($hasQp) {
  1778. // 空值存 NULL,列表显示空白而不是 0
  1779. $upd['quality_score'] = $quality;
  1780. $upd['price_score'] = $price;
  1781. $upd['delivery_score'] = $delivery;
  1782. $upd['value_added_score'] = $valueAdded;
  1783. $upd['score'] = self::sumFinalScore($quality, $price, $delivery, $valueAdded) ?? 0;
  1784. }
  1785. if (is_array($exists) && $exists !== []) {
  1786. Db::table(self::TABLE_FINAL)->where('id', (int)($exists['id'] ?? 0))->update($upd);
  1787. } else {
  1788. Db::table(self::TABLE_FINAL)->insert([
  1789. 'ym' => $ym,
  1790. 'company_name' => $cn,
  1791. 'score' => $hasQp ? (self::sumFinalScore($quality, $price, $delivery, $valueAdded) ?? 0) : 0,
  1792. 'quality_score' => $hasQp ? $quality : null,
  1793. 'price_score' => $hasQp ? $price : null,
  1794. 'delivery_score' => $hasQp ? $delivery : null,
  1795. 'value_added_score' => $hasQp ? $valueAdded : null,
  1796. 'final_score' => $final,
  1797. 'score_grade' => $grade,
  1798. 'qp_manual' => 1,
  1799. 'createtime' => $now,
  1800. 'updatetime' => $now,
  1801. ]);
  1802. }
  1803. if ($final === null && $grade === '' && !$hasQp) {
  1804. $result['cleared']++;
  1805. } else {
  1806. $result['saved']++;
  1807. }
  1808. $result['done']++;
  1809. } catch (\Throwable $e) {
  1810. Log::write('supplier final score save: ' . $e->getMessage(), 'error');
  1811. $result['error'] = $e->getMessage();
  1812. }
  1813. }
  1814. return $result;
  1815. }
  1816. /** 历史表补质量/价格百分比字段 */
  1817. protected static function ensureScoreWeightColumns(): void
  1818. {
  1819. try {
  1820. $cols = Db::query("SHOW COLUMNS FROM `" . self::TABLE_SCORE . "` LIKE 'quality_weight'");
  1821. if (!is_array($cols) || $cols === []) {
  1822. Db::execute(
  1823. "ALTER TABLE `" . self::TABLE_SCORE . "` ADD COLUMN `quality_weight` int unsigned NOT NULL DEFAULT 50 COMMENT '质量百分比' AFTER `quality_score`"
  1824. );
  1825. }
  1826. $cols2 = Db::query("SHOW COLUMNS FROM `" . self::TABLE_SCORE . "` LIKE 'price_weight'");
  1827. if (!is_array($cols2) || $cols2 === []) {
  1828. Db::execute(
  1829. "ALTER TABLE `" . self::TABLE_SCORE . "` ADD COLUMN `price_weight` int unsigned NOT NULL DEFAULT 50 COMMENT '价格百分比' AFTER `price_sum`"
  1830. );
  1831. }
  1832. } catch (\Throwable $e) {
  1833. Log::write('supplier score weight columns: ' . $e->getMessage(), 'error');
  1834. }
  1835. }
  1836. /** 历史表补交货期权重/得分字段 */
  1837. protected static function ensureLeadColumns(): void
  1838. {
  1839. $adds = [
  1840. self::TABLE_RULE => [
  1841. 'lead_weight' => "ADD COLUMN `lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '交货期得分权重(%)' AFTER `price_weight`",
  1842. ],
  1843. self::TABLE_SCORE => [
  1844. 'lead_days_sum' => "ADD COLUMN `lead_days_sum` int NOT NULL DEFAULT 0 COMMENT '本单工序工期合计(天)' AFTER `price_score`",
  1845. 'lead_weight' => "ADD COLUMN `lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '交货期百分比' AFTER `lead_days_sum`",
  1846. 'lead_enabled' => "ADD COLUMN `lead_enabled` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=当时纳入总分' AFTER `lead_weight`",
  1847. 'lead_score' => "ADD COLUMN `lead_score` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT '交货期评分值' AFTER `lead_enabled`",
  1848. ],
  1849. ];
  1850. foreach ($adds as $table => $cols) {
  1851. foreach ($cols as $col => $ddl) {
  1852. try {
  1853. $info = Db::query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  1854. if (is_array($info) && $info !== []) {
  1855. continue;
  1856. }
  1857. Db::execute("ALTER TABLE `{$table}` {$ddl}");
  1858. } catch (\Throwable $e) {
  1859. Log::write("supplier score lead column {$table}.{$col}: " . $e->getMessage(), 'error');
  1860. }
  1861. }
  1862. }
  1863. }
  1864. /** 将权重/质量分/单价合计等字段改为整数(去掉 .00) */
  1865. protected static function ensureIntegerColumns(): void
  1866. {
  1867. $defs = [
  1868. self::TABLE_RULE => [
  1869. 'quality_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '上年度质量评分权重(%)'",
  1870. 'price_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '单价评分权重(%)'",
  1871. 'lead_weight' => "int unsigned NOT NULL DEFAULT 0 COMMENT '交货期得分权重(%)'",
  1872. ],
  1873. self::TABLE_SCORE => [
  1874. 'quality_score' => "int NOT NULL DEFAULT 0 COMMENT '上年度质量评分'",
  1875. 'quality_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '质量百分比'",
  1876. 'price_weight' => "int unsigned NOT NULL DEFAULT 50 COMMENT '价格百分比'",
  1877. 'lead_days_sum' => "int NOT NULL DEFAULT 0 COMMENT '本单工序工期合计(天)'",
  1878. 'lead_weight' => "int unsigned NOT NULL DEFAULT 0 COMMENT '交货期百分比'",
  1879. ],
  1880. ];
  1881. foreach ($defs as $table => $cols) {
  1882. foreach ($cols as $col => $def) {
  1883. try {
  1884. $info = Db::query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  1885. if (!is_array($info) || $info === []) {
  1886. continue;
  1887. }
  1888. $type = strtolower((string)($info[0]['Type'] ?? $info[0]['type'] ?? ''));
  1889. if (preg_match('/^(tiny|small|medium|big)?int\b/', $type)) {
  1890. continue;
  1891. }
  1892. Db::execute("ALTER TABLE `{$table}` MODIFY COLUMN `{$col}` {$def}");
  1893. } catch (\Throwable $e) {
  1894. Log::write("supplier score int column {$table}.{$col}: " . $e->getMessage(), 'error');
  1895. }
  1896. }
  1897. }
  1898. // 单价合计需保留小数(如 0.25),不可用 int
  1899. try {
  1900. $info = Db::query("SHOW COLUMNS FROM `" . self::TABLE_SCORE . "` LIKE 'price_sum'");
  1901. if (is_array($info) && $info !== []) {
  1902. $type = strtolower((string)($info[0]['Type'] ?? $info[0]['type'] ?? ''));
  1903. if (preg_match('/^(tiny|small|medium|big)?int\b/', $type)) {
  1904. Db::execute(
  1905. "ALTER TABLE `" . self::TABLE_SCORE . "` MODIFY COLUMN `price_sum` decimal(12,4) NOT NULL DEFAULT 0.0000 COMMENT '本单工序单价合计'"
  1906. );
  1907. }
  1908. }
  1909. } catch (\Throwable $e) {
  1910. Log::write('supplier score price_sum decimal: ' . $e->getMessage(), 'error');
  1911. }
  1912. }
  1913. protected static function ensureDefaultRule(): void
  1914. {
  1915. self::ensureRuleNameColumn();
  1916. self::ensureOrderTypeRules();
  1917. }
  1918. /**
  1919. * 规则表去掉页面未用字段:lead_enabled、status
  1920. * (交期是否纳入由 lead_weight>0 判断;删除用物理删除)
  1921. */
  1922. protected static function dropObsoleteRuleColumns(): void
  1923. {
  1924. static $done = false;
  1925. if ($done) {
  1926. return;
  1927. }
  1928. $done = true;
  1929. foreach (['lead_enabled', 'status'] as $col) {
  1930. try {
  1931. $cols = Db::query('SHOW COLUMNS FROM `' . self::TABLE_RULE . '` LIKE \'' . $col . '\'');
  1932. if (is_array($cols) && $cols !== []) {
  1933. Db::execute('ALTER TABLE `' . self::TABLE_RULE . '` DROP COLUMN `' . $col . '`');
  1934. }
  1935. } catch (\Throwable $e) {
  1936. Log::write('supplier_score_rule drop ' . $col . ': ' . $e->getMessage(), 'error');
  1937. }
  1938. }
  1939. }
  1940. /**
  1941. * 规则表补「规则名称/订单类型」字段(历史库可能缺此列)
  1942. */
  1943. protected static function ensureRuleNameColumn(): void
  1944. {
  1945. static $done = false;
  1946. if ($done) {
  1947. return;
  1948. }
  1949. try {
  1950. $cols = Db::query('SHOW COLUMNS FROM `' . self::TABLE_RULE . '` LIKE \'name\'');
  1951. if (!is_array($cols) || $cols === []) {
  1952. Db::execute(
  1953. 'ALTER TABLE `' . self::TABLE_RULE . '` ADD COLUMN `name` varchar(100) NOT NULL DEFAULT \'\' COMMENT \'规则名称/订单类型\' AFTER `id`'
  1954. );
  1955. $cols = Db::query('SHOW COLUMNS FROM `' . self::TABLE_RULE . '` LIKE \'name\'');
  1956. }
  1957. if (is_array($cols) && $cols !== []) {
  1958. $done = true;
  1959. }
  1960. } catch (\Throwable $e) {
  1961. Log::write('supplier_score_rule.name: ' . $e->getMessage(), 'error');
  1962. }
  1963. }
  1964. /**
  1965. * 写入/对齐「不同订单供应商评分权重方案」三条规则
  1966. */
  1967. protected static function ensureOrderTypeRules(): void
  1968. {
  1969. static $done = false;
  1970. if ($done) {
  1971. return;
  1972. }
  1973. try {
  1974. if (\think\Cache::get('procuremen_supplier_order_type_rules_ok_v1')) {
  1975. $done = true;
  1976. return;
  1977. }
  1978. } catch (\Throwable $e) {
  1979. }
  1980. self::ensureRuleNameColumn();
  1981. $schemes = [
  1982. [
  1983. 'name' => '普通订单(价格优先)',
  1984. 'quality_weight' => 30,
  1985. 'price_weight' => 50,
  1986. 'lead_weight' => 20,
  1987. ],
  1988. [
  1989. 'name' => '急单(交期优先)',
  1990. 'quality_weight' => 30,
  1991. 'price_weight' => 20,
  1992. 'lead_weight' => 50,
  1993. ],
  1994. [
  1995. 'name' => '重点产品(质量优先)',
  1996. 'quality_weight' => 50,
  1997. 'price_weight' => 20,
  1998. 'lead_weight' => 30,
  1999. ],
  2000. ];
  2001. $now = date('Y-m-d H:i:s');
  2002. try {
  2003. // 确认 name 列已存在再继续
  2004. $cols = Db::query('SHOW COLUMNS FROM `' . self::TABLE_RULE . '` LIKE \'name\'');
  2005. if (!is_array($cols) || $cols === []) {
  2006. Log::write('supplier_score_rule.name still missing, skip seed', 'error');
  2007. return;
  2008. }
  2009. foreach ($schemes as $s) {
  2010. $exist = Db::table(self::TABLE_RULE)->where('name', $s['name'])->find();
  2011. if (!is_array($exist)) {
  2012. // 兼容旧数据:无 name 时按三档百分比匹配
  2013. $exist = Db::table(self::TABLE_RULE)
  2014. ->where('quality_weight', (int)$s['quality_weight'])
  2015. ->where('price_weight', (int)$s['price_weight'])
  2016. ->where('lead_weight', (int)$s['lead_weight'])
  2017. ->where(function ($q) {
  2018. $q->whereNull('name')->whereOr('name', '');
  2019. })
  2020. ->order('id', 'asc')
  2021. ->find();
  2022. }
  2023. $payload = [
  2024. 'name' => $s['name'],
  2025. 'quality_weight' => (int)$s['quality_weight'],
  2026. 'price_weight' => (int)$s['price_weight'],
  2027. 'lead_weight' => (int)$s['lead_weight'],
  2028. 'updatetime' => $now,
  2029. ];
  2030. if (is_array($exist)) {
  2031. // 已存在:只补空名称,不覆盖人工改过的权重
  2032. $existName = trim((string)($exist['name'] ?? ''));
  2033. if ($existName === '') {
  2034. Db::table(self::TABLE_RULE)->where('id', (int)$exist['id'])->update([
  2035. 'name' => $s['name'],
  2036. 'updatetime' => $now,
  2037. ]);
  2038. }
  2039. } else {
  2040. $payload['is_default'] = 0;
  2041. $payload['createtime'] = $now;
  2042. Db::table(self::TABLE_RULE)->insert($payload);
  2043. }
  2044. }
  2045. // 非方案内的旧行直接删除,列表只保留三条
  2046. $names = [];
  2047. foreach ($schemes as $s) {
  2048. $names[] = $s['name'];
  2049. }
  2050. $nameIn = "'" . implode("','", array_map('addslashes', $names)) . "'";
  2051. Db::execute(
  2052. 'DELETE FROM `' . self::TABLE_RULE . '` '
  2053. . 'WHERE `name` NOT IN (' . $nameIn . ') OR `name` IS NULL OR `name`=\'\''
  2054. );
  2055. $hasDefault = Db::table(self::TABLE_RULE)->where('is_default', 1)->find();
  2056. if (!is_array($hasDefault)) {
  2057. $def = Db::table(self::TABLE_RULE)->where('name', '普通订单(价格优先)')->find();
  2058. if (!is_array($def)) {
  2059. $def = Db::table(self::TABLE_RULE)->order('id', 'asc')->find();
  2060. }
  2061. if (is_array($def)) {
  2062. Db::table(self::TABLE_RULE)->where('id', (int)$def['id'])->update([
  2063. 'is_default' => 1,
  2064. 'updatetime' => $now,
  2065. ]);
  2066. }
  2067. }
  2068. $done = true;
  2069. try {
  2070. \think\Cache::set('procuremen_supplier_order_type_rules_ok_v1', 1, 86400);
  2071. } catch (\Throwable $e) {
  2072. }
  2073. } catch (\Throwable $e) {
  2074. Log::write('supplier score ensureOrderTypeRules: ' . $e->getMessage(), 'error');
  2075. }
  2076. }
  2077. /**
  2078. * 下拉用:正常状态的评分规则(订单类型)
  2079. *
  2080. * @return array<int, array{id:int,name:string,label:string,quality_weight:int,price_weight:int,lead_weight:int,is_default:int}>
  2081. */
  2082. public static function listRulesForSelect(): array
  2083. {
  2084. self::ensureSchema();
  2085. $out = [];
  2086. try {
  2087. $rows = Db::table(self::TABLE_RULE)
  2088. ->order('is_default', 'desc')
  2089. ->order('id', 'asc')
  2090. ->select();
  2091. if (!is_array($rows)) {
  2092. return $out;
  2093. }
  2094. foreach ($rows as $row) {
  2095. if (!is_array($row)) {
  2096. continue;
  2097. }
  2098. $name = trim((string)($row['name'] ?? ''));
  2099. if ($name === '') {
  2100. continue;
  2101. }
  2102. $qw = (int)($row['quality_weight'] ?? 0);
  2103. $pw = (int)($row['price_weight'] ?? 0);
  2104. $lw = (int)($row['lead_weight'] ?? 0);
  2105. $out[] = [
  2106. 'id' => (int)($row['id'] ?? 0),
  2107. 'name' => $name,
  2108. 'label' => $name . '|质量' . $qw . '%|价格' . $pw . '%|交期' . $lw . '%',
  2109. 'quality_weight' => $qw,
  2110. 'price_weight' => $pw,
  2111. 'lead_weight' => $lw,
  2112. 'is_default' => !empty($row['is_default']) ? 1 : 0,
  2113. ];
  2114. }
  2115. } catch (\Throwable $e) {
  2116. }
  2117. return $out;
  2118. }
  2119. /**
  2120. * 按订单号解析评分规则:优先下发时写入的权重快照,否则按 score_rule_id 读规则表,再否则默认
  2121. *
  2122. * @return array{id:int,name:string,quality_weight:int,price_weight:int,lead_weight:int,lead_enabled:int}
  2123. */
  2124. public static function resolveRuleForCcydh(string $ccydh, ?array $poHint = null): array
  2125. {
  2126. $ccydh = trim($ccydh);
  2127. if ($ccydh === '' && (!is_array($poHint) || $poHint === [])) {
  2128. return self::getDefaultRule();
  2129. }
  2130. try {
  2131. $po = is_array($poHint) && $poHint !== [] ? $poHint : null;
  2132. if ($po === null && $ccydh !== '') {
  2133. self::ensureSchema();
  2134. $po = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('id', 'desc')->find();
  2135. }
  2136. if (is_array($po)) {
  2137. $ruleId = (int)($po['score_rule_id'] ?? 0);
  2138. $qw = (int)($po['score_quality_weight'] ?? 0);
  2139. $pw = (int)($po['score_price_weight'] ?? 0);
  2140. $lw = (int)($po['score_lead_weight'] ?? 0);
  2141. // 下发时已快照:开标/展示一律用快照,不受后续规则修改影响(无需 ensureSchema)
  2142. if ($ruleId > 0 && ($qw + $pw + $lw) > 0) {
  2143. $name = trim((string)($po['score_rule_name'] ?? ''));
  2144. if ($name === '') {
  2145. $live = self::getRuleById($ruleId);
  2146. $name = (string)($live['name'] ?? '');
  2147. }
  2148. return [
  2149. 'id' => $ruleId,
  2150. 'name' => $name,
  2151. 'quality_weight' => max(0, $qw),
  2152. 'price_weight' => max(0, $pw),
  2153. 'lead_weight' => max(0, $lw),
  2154. 'lead_enabled' => $lw > 0 ? 1 : 0,
  2155. ];
  2156. }
  2157. if ($ruleId > 0) {
  2158. $rule = self::getRuleById($ruleId);
  2159. if ((int)($rule['id'] ?? 0) > 0) {
  2160. return $rule;
  2161. }
  2162. }
  2163. }
  2164. } catch (\Throwable $e) {
  2165. }
  2166. return self::getDefaultRule();
  2167. }
  2168. /**
  2169. * @return array{id:int,name:string,quality_weight:int,price_weight:int,lead_weight:int,lead_enabled:int}
  2170. */
  2171. public static function getRuleById(int $id): array
  2172. {
  2173. if ($id <= 0) {
  2174. return self::getDefaultRule();
  2175. }
  2176. self::ensureSchema();
  2177. try {
  2178. $row = Db::table(self::TABLE_RULE)
  2179. ->where('id', $id)
  2180. ->find();
  2181. if (is_array($row)) {
  2182. $lw = (int)($row['lead_weight'] ?? 0);
  2183. return [
  2184. 'id' => (int)($row['id'] ?? 0),
  2185. 'name' => trim((string)($row['name'] ?? '')),
  2186. 'quality_weight' => (int)($row['quality_weight'] ?? 50),
  2187. 'price_weight' => (int)($row['price_weight'] ?? 50),
  2188. 'lead_weight' => $lw,
  2189. 'lead_enabled' => $lw > 0 ? 1 : 0,
  2190. ];
  2191. }
  2192. } catch (\Throwable $e) {
  2193. }
  2194. return self::getDefaultRule();
  2195. }
  2196. /**
  2197. * @return array{id:int,name:string,quality_weight:int,price_weight:int,lead_weight:int,lead_enabled:int}
  2198. */
  2199. public static function getDefaultRule(): array
  2200. {
  2201. self::ensureSchema();
  2202. try {
  2203. $row = Db::table(self::TABLE_RULE)
  2204. ->where('is_default', 1)
  2205. ->order('id', 'desc')
  2206. ->find();
  2207. if (!is_array($row)) {
  2208. $row = Db::table(self::TABLE_RULE)->order('id', 'asc')->find();
  2209. }
  2210. if (is_array($row)) {
  2211. $lw = (int)($row['lead_weight'] ?? 0);
  2212. return [
  2213. 'id' => (int)($row['id'] ?? 0),
  2214. 'name' => trim((string)($row['name'] ?? '')),
  2215. 'quality_weight' => (int)($row['quality_weight'] ?? 50),
  2216. 'price_weight' => (int)($row['price_weight'] ?? 50),
  2217. 'lead_weight' => $lw,
  2218. 'lead_enabled' => $lw > 0 ? 1 : 0,
  2219. ];
  2220. }
  2221. } catch (\Throwable $e) {
  2222. }
  2223. return [
  2224. 'id' => 0,
  2225. 'name' => '内置默认',
  2226. 'quality_weight' => 50,
  2227. 'price_weight' => 50,
  2228. 'lead_weight' => 0,
  2229. 'lead_enabled' => 0,
  2230. ];
  2231. }
  2232. /**
  2233. * 规范年月;空则取当前月
  2234. */
  2235. public static function normalizeYm(?string $ym): string
  2236. {
  2237. $ym = trim((string)$ym);
  2238. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  2239. return $ym;
  2240. }
  2241. return date('Y-m');
  2242. }
  2243. /**
  2244. * 上一自然月 YYYY-MM
  2245. */
  2246. public static function previousYm(string $ym): string
  2247. {
  2248. $ym = self::normalizeYm($ym);
  2249. $ts = strtotime($ym . '-01');
  2250. if ($ts === false) {
  2251. $ts = time();
  2252. }
  2253. return date('Y-m', strtotime('-1 month', $ts));
  2254. }
  2255. /**
  2256. * 从月度评审表取指定分项:当月按上月起往前查,都没有则默认 40(与月度质量/交货满分一致)
  2257. *
  2258. * @param array<int, string> $companyNames
  2259. * @param 'quality_score'|'delivery_score' $field
  2260. * @return array<string, float> company_name => score
  2261. */
  2262. protected static function loadReviewFieldScoreMap(array $companyNames, string $field, ?string $asOfYm = null): array
  2263. {
  2264. $asOfYm = self::normalizeYm($asOfYm);
  2265. $default = 40.0;
  2266. $map = [];
  2267. $names = [];
  2268. foreach ($companyNames as $n) {
  2269. $n = trim((string)$n);
  2270. if ($n !== '') {
  2271. $names[$n] = true;
  2272. $map[$n] = $default;
  2273. }
  2274. }
  2275. if ($names === [] || !in_array($field, ['quality_score', 'delivery_score'], true)) {
  2276. return $map;
  2277. }
  2278. self::ensureFinalScoreTable();
  2279. try {
  2280. // 当月按上个月起查:ym < asOfYm,且该分项已填写
  2281. $rows = Db::table(self::TABLE_FINAL)
  2282. ->where('company_name', 'in', array_keys($names))
  2283. ->where('ym', '<', $asOfYm)
  2284. ->whereNotNull($field)
  2285. ->field('company_name,ym,' . $field)
  2286. ->order('ym', 'desc')
  2287. ->select();
  2288. } catch (\Throwable $e) {
  2289. return $map;
  2290. }
  2291. if (!is_array($rows)) {
  2292. return $map;
  2293. }
  2294. $seen = [];
  2295. foreach ($rows as $r) {
  2296. if (!is_array($r)) {
  2297. continue;
  2298. }
  2299. $cn = trim((string)($r['company_name'] ?? ''));
  2300. if ($cn === '' || isset($seen[$cn])) {
  2301. continue;
  2302. }
  2303. $score = self::readOptionalScoreValue($r[$field] ?? null);
  2304. if ($score === null) {
  2305. continue;
  2306. }
  2307. $seen[$cn] = true;
  2308. $map[$cn] = round((float)$score, 2);
  2309. }
  2310. return $map;
  2311. }
  2312. /**
  2313. * 从月度评审表取质量得分:当月按上月起往前查,都没有则默认 40
  2314. *
  2315. * @param array<int, string> $companyNames
  2316. * @return array<string, float> company_name => quality_score
  2317. */
  2318. public static function loadReviewQualityScoreMap(array $companyNames, ?string $asOfYm = null): array
  2319. {
  2320. return self::loadReviewFieldScoreMap($companyNames, 'quality_score', $asOfYm);
  2321. }
  2322. /**
  2323. * 从月度评审表取交货得分:当月按上月起往前查,都没有则默认 40(与质量得分口径一致)
  2324. *
  2325. * @param array<int, string> $companyNames
  2326. * @return array<string, float> company_name => delivery_score
  2327. */
  2328. public static function loadReviewDeliveryScoreMap(array $companyNames, ?string $asOfYm = null): array
  2329. {
  2330. return self::loadReviewFieldScoreMap($companyNames, 'delivery_score', $asOfYm);
  2331. }
  2332. /**
  2333. * 日期规范为 Y-m-d;无效/"未填写" 返回空串
  2334. */
  2335. public static function normalizeScoreYmd($value): string
  2336. {
  2337. $s = trim((string)$value);
  2338. if ($s === '' || $s === '未填写' || stripos($s, '0000-00-00') === 0) {
  2339. return '';
  2340. }
  2341. if (preg_match('/开标|验证后|查看/u', $s)) {
  2342. return '';
  2343. }
  2344. if (preg_match('/^(\d{4})[\/\-.](\d{1,2})[\/\-.](\d{1,2})/', $s, $m)) {
  2345. return sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  2346. }
  2347. $ts = strtotime(str_replace('/', '-', $s));
  2348. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  2349. }
  2350. /**
  2351. * 本单报价交期分:满分 40;相对截止日每提前1天+1、滞后1天-1;未填报价交货日或无截止日=0
  2352. */
  2353. public static function calcQuoteDeliveryPartScore(string $deadlineYmd, string $quoteYmd): float
  2354. {
  2355. $deadlineYmd = self::normalizeScoreYmd($deadlineYmd);
  2356. $quoteYmd = self::normalizeScoreYmd($quoteYmd);
  2357. if ($quoteYmd === '' || $deadlineYmd === '') {
  2358. return 0.0;
  2359. }
  2360. $d1 = strtotime($deadlineYmd . ' 00:00:00');
  2361. $d2 = strtotime($quoteYmd . ' 00:00:00');
  2362. if ($d1 === false || $d2 === false) {
  2363. return 0.0;
  2364. }
  2365. $daysEarly = (int)round(($d1 - $d2) / 86400);
  2366. return (float)(40 + $daysEarly);
  2367. }
  2368. /**
  2369. * 订单交货分 = 月度×50% + 报价交期分×50%
  2370. */
  2371. public static function calcOrderDeliveryScore(float $monthlyScore, float $quotePartScore): float
  2372. {
  2373. return round($monthlyScore * 0.5 + $quotePartScore * 0.5, 2);
  2374. }
  2375. /**
  2376. * 从报价行按订单汇总交货得分,一批多订单取平均
  2377. *
  2378. * @param array<int, array<string, mixed>> $lineRows
  2379. */
  2380. public static function calcCompanyDeliveryScoreFromQuoteLines(array $lineRows, float $monthlyScore): float
  2381. {
  2382. $byOrder = [];
  2383. foreach ($lineRows as $ln) {
  2384. if (!is_array($ln)) {
  2385. continue;
  2386. }
  2387. $dh = trim((string)($ln['ccydh'] ?? $ln['CCYDH'] ?? ''));
  2388. if ($dh === '') {
  2389. $dh = '_';
  2390. }
  2391. if (!isset($byOrder[$dh])) {
  2392. $byOrder[$dh] = ['deadline' => '', 'quote' => ''];
  2393. }
  2394. $deadline = self::normalizeScoreYmd(
  2395. $ln['order_delivery_deadline'] ?? $ln['delivery_deadline'] ?? ''
  2396. );
  2397. if ($deadline !== '' && $byOrder[$dh]['deadline'] === '') {
  2398. $byOrder[$dh]['deadline'] = $deadline;
  2399. }
  2400. // 开标前遮罩行不计入报价交期
  2401. if (!empty($ln['delivery_quote_pending']) || !empty($ln['lead_days_quote_pending'])) {
  2402. continue;
  2403. }
  2404. if ($byOrder[$dh]['quote'] !== '') {
  2405. continue;
  2406. }
  2407. $quote = '';
  2408. foreach (['delivery_ymd', 'delivery_show', 'delivery_text', 'delivery'] as $k) {
  2409. if (!array_key_exists($k, $ln) || $ln[$k] === null || $ln[$k] === '') {
  2410. continue;
  2411. }
  2412. $quote = self::normalizeScoreYmd($ln[$k]);
  2413. if ($quote !== '') {
  2414. break;
  2415. }
  2416. }
  2417. if ($quote !== '') {
  2418. $byOrder[$dh]['quote'] = $quote;
  2419. }
  2420. }
  2421. if ($byOrder === []) {
  2422. return self::calcOrderDeliveryScore($monthlyScore, 0.0);
  2423. }
  2424. $sum = 0.0;
  2425. $n = 0;
  2426. foreach ($byOrder as $info) {
  2427. $quotePart = self::calcQuoteDeliveryPartScore(
  2428. (string)($info['deadline'] ?? ''),
  2429. (string)($info['quote'] ?? '')
  2430. );
  2431. $sum += self::calcOrderDeliveryScore($monthlyScore, $quotePart);
  2432. $n++;
  2433. }
  2434. return $n > 0 ? round($sum / $n, 2) : self::calcOrderDeliveryScore($monthlyScore, 0.0);
  2435. }
  2436. /**
  2437. * 按公司名批量取供应商 id(兼容旧调用保留评分字段结构)
  2438. *
  2439. * @param array<int, string> $companyNames
  2440. * @return array<string, array{id:int,score:float,monthly_score:?float,quality_avg:float}>
  2441. */
  2442. public static function loadCustomerScoreMap(array $companyNames): array
  2443. {
  2444. $map = [];
  2445. $names = [];
  2446. foreach ($companyNames as $n) {
  2447. $n = trim((string)$n);
  2448. if ($n !== '') {
  2449. $names[$n] = true;
  2450. }
  2451. }
  2452. if ($names === []) {
  2453. return $map;
  2454. }
  2455. try {
  2456. $rows = Db::table('customer')
  2457. ->where('company_name', 'in', array_keys($names))
  2458. ->field('id,company_name')
  2459. ->select();
  2460. } catch (\Throwable $e) {
  2461. return $map;
  2462. }
  2463. if (!is_array($rows)) {
  2464. return $map;
  2465. }
  2466. foreach ($rows as $r) {
  2467. if (!is_array($r)) {
  2468. continue;
  2469. }
  2470. $cn = trim((string)($r['company_name'] ?? ''));
  2471. if ($cn === '') {
  2472. continue;
  2473. }
  2474. $map[$cn] = [
  2475. 'id' => (int)($r['id'] ?? 0),
  2476. 'score' => 0.0,
  2477. 'monthly_score' => null,
  2478. 'quality_avg' => 50.0,
  2479. ];
  2480. }
  2481. return $map;
  2482. }
  2483. /**
  2484. * 从报价组计算本单各供应商得分(不写库)
  2485. *
  2486. * @param array<int, array<string, mixed>> $quoteGroups loadAuditSupplierQuoteGroups 结构(name/lines[].amount)
  2487. * @param string|null $asOfYm 订单所属月;商务/技术分从该月的上月起往前查评审表
  2488. * @return array<string, array{
  2489. * company_name:string,customer_id:int,quality_score:float,price_sum:float,
  2490. * price_score:float,score:float,rank_no:int,score_text:string,rank_text:string
  2491. * }>
  2492. */
  2493. public static function calculateForQuoteGroups(array $quoteGroups, ?array $rule = null, ?string $asOfYm = null): array
  2494. {
  2495. $rule = $rule ?: self::getDefaultRule();
  2496. $qw = max(0, (float)($rule['quality_weight'] ?? 50));
  2497. $pw = max(0, (float)($rule['price_weight'] ?? 50));
  2498. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  2499. // 填 0 的权重不参与计算
  2500. $leadEnabled = $lw > 0 ? 1 : 0;
  2501. $wSum = $qw + $pw + $lw;
  2502. if ($wSum <= 0) {
  2503. $qw = 50;
  2504. $pw = 50;
  2505. $lw = 0;
  2506. $leadEnabled = 0;
  2507. $wSum = 100;
  2508. }
  2509. $names = [];
  2510. foreach ($quoteGroups as $g) {
  2511. if (!is_array($g)) {
  2512. continue;
  2513. }
  2514. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  2515. if ($cn !== '') {
  2516. $names[] = $cn;
  2517. }
  2518. }
  2519. $custMap = self::loadCustomerScoreMap($names);
  2520. $reviewMap = self::loadReviewQualityScoreMap($names, $asOfYm);
  2521. $deliveryMap = self::loadReviewDeliveryScoreMap($names, $asOfYm);
  2522. $items = [];
  2523. $priceSums = [];
  2524. foreach ($quoteGroups as $g) {
  2525. if (!is_array($g)) {
  2526. continue;
  2527. }
  2528. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  2529. if ($cn === '') {
  2530. continue;
  2531. }
  2532. $priceSum = 0.0;
  2533. $hasPrice = false;
  2534. $leadSum = 0;
  2535. $hasLead = false;
  2536. // 确认页用 lines,审批页用 pick_lines
  2537. $lineRows = $g['lines'] ?? $g['pick_lines'] ?? [];
  2538. if (!is_array($lineRows)) {
  2539. $lineRows = [];
  2540. }
  2541. foreach ($lineRows as $ln) {
  2542. if (!is_array($ln)) {
  2543. continue;
  2544. }
  2545. if (empty($ln['amount_quote_pending'])) {
  2546. $am = self::resolveQuoteLineAmountRaw($ln);
  2547. if ($am !== '' && $am !== '0' && $am !== '0.00' && is_numeric($am)) {
  2548. $priceSum += (float)$am;
  2549. $hasPrice = true;
  2550. }
  2551. }
  2552. if (empty($ln['lead_days_quote_pending'])) {
  2553. $ldRaw = $ln['lead_days'] ?? null;
  2554. if ($ldRaw !== null && $ldRaw !== '' && is_numeric($ldRaw)) {
  2555. $ld = (int)$ldRaw;
  2556. if ($ld > 0) {
  2557. $leadSum += $ld;
  2558. $hasLead = true;
  2559. }
  2560. }
  2561. }
  2562. }
  2563. // 质量得分:月度评审表,当月按上月起往前,默认 40
  2564. $quality = (float)($reviewMap[$cn] ?? 40);
  2565. $monthlyDelivery = (float)($deliveryMap[$cn] ?? 40);
  2566. // 交货得分:月度50% + 本单报价交期50%(按订单算,一批多订单平均)
  2567. $deliveryScore = $leadEnabled
  2568. ? self::calcCompanyDeliveryScoreFromQuoteLines($lineRows, $monthlyDelivery)
  2569. : 0.0;
  2570. $psum = $hasPrice ? round($priceSum, 2) : 0;
  2571. $lsum = $hasLead ? (int)$leadSum : 0;
  2572. $items[$cn] = [
  2573. 'company_name' => $cn,
  2574. 'customer_id' => (int)($custMap[$cn]['id'] ?? 0),
  2575. 'quality_score' => $quality,
  2576. 'quality_score_text' => self::formatScore($quality),
  2577. 'quality_weight' => (int)$qw,
  2578. 'price_sum' => $psum,
  2579. 'price_sum_text' => self::formatScore($psum),
  2580. 'price_weight' => (int)$pw,
  2581. 'has_price' => $hasPrice,
  2582. 'price_score' => 0.0,
  2583. 'price_score_text' => '0',
  2584. 'lead_days_sum' => $lsum,
  2585. 'lead_days_sum_text' => (string)$lsum,
  2586. 'lead_weight' => (int)$lw,
  2587. 'lead_enabled' => $leadEnabled,
  2588. 'has_lead' => $hasLead,
  2589. 'lead_score' => $leadEnabled ? $deliveryScore : 0.0,
  2590. 'lead_score_text' => $leadEnabled ? self::formatScore($deliveryScore) : '0',
  2591. 'score' => 0.0,
  2592. 'rank_no' => 0,
  2593. 'score_text' => '',
  2594. 'rank_text' => '',
  2595. ];
  2596. if ($hasPrice && $priceSum > 0) {
  2597. $priceSums[$cn] = $priceSum;
  2598. }
  2599. }
  2600. $minSum = null;
  2601. foreach ($priceSums as $ps) {
  2602. if ($minSum === null || $ps < $minSum) {
  2603. $minSum = $ps;
  2604. }
  2605. }
  2606. foreach ($items as $cn => &$it) {
  2607. // 单价未填写:价格得分与总分均为 0
  2608. if ($pw > 0 && (empty($it['has_price']) || (float)($it['price_sum'] ?? 0) <= 0)) {
  2609. $it['price_score'] = 0.0;
  2610. $it['price_score_text'] = '0';
  2611. $it['lead_score'] = 0.0;
  2612. $it['lead_score_text'] = self::formatScore(0);
  2613. $it['score'] = 0.0;
  2614. $it['score_text'] = '0';
  2615. continue;
  2616. }
  2617. // 价格得分 = (最低单价合计 / 本供应商单价合计) × 价格权重% × 100
  2618. if ($pw > 0 && !empty($it['has_price']) && $it['price_sum'] > 0 && $minSum !== null && $minSum > 0) {
  2619. $ratio = round($minSum / (float)$it['price_sum'], 4);
  2620. $it['price_score'] = round($ratio * ($pw / 100) * 100, 2);
  2621. } else {
  2622. $it['price_score'] = 0.0;
  2623. }
  2624. $it['price_score_text'] = self::formatScore($it['price_score']);
  2625. // 交货得分已在上方按「月度50%+报价交期50%」算好
  2626. if (!$leadEnabled) {
  2627. $it['lead_score'] = 0.0;
  2628. $it['lead_score_text'] = '0';
  2629. } else {
  2630. $it['lead_score_text'] = self::formatScore($it['lead_score']);
  2631. }
  2632. // 总分 = 质量得分×质量% + 价格得分(已含价格权重) [+ 交货得分×交货%]
  2633. $total = 0.0;
  2634. if ($qw > 0) {
  2635. $total += $it['quality_score'] * ($qw / 100);
  2636. }
  2637. if ($pw > 0) {
  2638. $total += (float)$it['price_score'];
  2639. }
  2640. if ($lw > 0) {
  2641. $total += (float)$it['lead_score'] * ($lw / 100);
  2642. }
  2643. $it['score'] = round($total, 2);
  2644. $it['score_text'] = self::formatScore($it['score']);
  2645. }
  2646. unset($it);
  2647. $sorted = $items;
  2648. uasort($sorted, function ($a, $b) {
  2649. $sa = (float)($a['score'] ?? 0);
  2650. $sb = (float)($b['score'] ?? 0);
  2651. if ($sa !== $sb) {
  2652. return $sb <=> $sa;
  2653. }
  2654. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  2655. });
  2656. $rank = 0;
  2657. foreach ($sorted as $cn => $row) {
  2658. $rank++;
  2659. $items[$cn]['rank_no'] = $rank;
  2660. $items[$cn]['rank_text'] = (string)$rank;
  2661. }
  2662. return $items;
  2663. }
  2664. public static function formatScore($n): string
  2665. {
  2666. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  2667. return $s === '' ? '0' : $s;
  2668. }
  2669. /**
  2670. * 报价行单价原文(兼容确认页 amount、审批页 unit_price_text/amount_text)
  2671. *
  2672. * @param array<string, mixed> $ln
  2673. */
  2674. protected static function resolveQuoteLineAmountRaw(array $ln): string
  2675. {
  2676. foreach (['amount', 'unit_price_text', 'amount_text'] as $k) {
  2677. if (!array_key_exists($k, $ln) || $ln[$k] === null) {
  2678. continue;
  2679. }
  2680. $am = trim((string)$ln[$k]);
  2681. if ($am === '' || $am === '未填写' || $am === '未开标验证' || $am === '开标验证后查看') {
  2682. continue;
  2683. }
  2684. // 去掉千分位等
  2685. $am = str_replace([',', ',', ' '], '', $am);
  2686. if ($am !== '' && is_numeric($am)) {
  2687. return $am;
  2688. }
  2689. }
  2690. return '';
  2691. }
  2692. /**
  2693. * 总分简要文案(仅总分数字;分项见独立字段)
  2694. *
  2695. * @param array<string, mixed> $hit calculate/loadSaved 单项
  2696. */
  2697. public static function formatScoreDetailText(array $hit): string
  2698. {
  2699. return self::formatScore($hit['score'] ?? 0);
  2700. }
  2701. /**
  2702. * 分项得分展示文案(确认/详情表格用)
  2703. *
  2704. * @param array<string, mixed> $hit
  2705. */
  2706. public static function formatScorePartsHtml(array $hit): string
  2707. {
  2708. $qw = (float)($hit['quality_weight'] ?? 0);
  2709. $pw = (float)($hit['price_weight'] ?? 0);
  2710. $lw = (float)($hit['lead_weight'] ?? 0);
  2711. $lines = [];
  2712. if ($qw > 0) {
  2713. $lines[] = '质量得分 ' . self::formatScore($hit['quality_score'] ?? 0);
  2714. }
  2715. if ($pw > 0) {
  2716. $lines[] = '价格得分 ' . self::formatScore($hit['price_score'] ?? 0);
  2717. }
  2718. if ($lw > 0) {
  2719. $lines[] = '交货得分 ' . self::formatScore($hit['lead_score'] ?? 0);
  2720. }
  2721. $lines[] = '总分 ' . self::formatScore($hit['score'] ?? 0);
  2722. return implode("\n", $lines);
  2723. }
  2724. /**
  2725. * 评分规则文案(用于确认页 / 详情展示)
  2726. * 百分比取当前默认规则;权重大于 0 的项才写入公式
  2727. *
  2728. * @param array{quality_weight?:float|int|string,price_weight?:float|int|string,lead_weight?:float|int|string}|null $rule
  2729. */
  2730. public static function formatRuleFormulaText(?array $rule = null): string
  2731. {
  2732. $rule = $rule ?: self::getDefaultRule();
  2733. $qw = (float)($rule['quality_weight'] ?? 50);
  2734. $pw = (float)($rule['price_weight'] ?? 50);
  2735. $lw = (float)($rule['lead_weight'] ?? 0);
  2736. $parts = [];
  2737. if ($qw > 0) {
  2738. $parts[] = '(质量得分×' . self::formatWeightPercent($qw) . '%)';
  2739. }
  2740. if ($pw > 0) {
  2741. $parts[] = '(价格得分)';
  2742. }
  2743. if ($lw > 0) {
  2744. $parts[] = '(交货得分×' . self::formatWeightPercent($lw) . '%)';
  2745. }
  2746. $formula = $parts === []
  2747. ? '(总分)=(质量得分×50%)+(价格得分)'
  2748. : '(总分)=' . implode('+', $parts);
  2749. $formula .= ';质量得分取月度评审(当月按上月起往前查,无则默认40)';
  2750. // 说明顺序与表头一致:价格在前,交货在后
  2751. if ($pw > 0) {
  2752. $formula .= ';价格得分=(最低单价合计/本供应商单价合计)×'
  2753. . self::formatWeightPercent($pw) . '%×100';
  2754. }
  2755. if ($lw > 0) {
  2756. $formula .= ';交货得分=月度交货分×50%+报价交期分×50%(按订单算,一批多订单平均;'
  2757. . '报价交期满分40,相对截止日每提前1天+1、滞后1天-1)';
  2758. }
  2759. return $formula;
  2760. }
  2761. /**
  2762. * 报价组是否展示交货期留痕列(已落库纳入,或尚无落库且当前默认规则交货分>0)
  2763. *
  2764. * @param array<int, array<string, mixed>> $quoteGroups
  2765. */
  2766. public static function detectShowLeadScore(array $quoteGroups = [], ?array $rule = null): bool
  2767. {
  2768. foreach ($quoteGroups as $g) {
  2769. if (!is_array($g)) {
  2770. continue;
  2771. }
  2772. if (!empty($g['show_service_lead_score'])) {
  2773. return true;
  2774. }
  2775. }
  2776. $rule = $rule ?: self::getDefaultRule();
  2777. return (float)($rule['lead_weight'] ?? 0) > 0;
  2778. }
  2779. /**
  2780. * 评分规则提示:优先用传入规则;无则用默认规则
  2781. *
  2782. * @param array<int, array<string, mixed>> $quoteGroups 保留参数兼容调用方
  2783. * @param array{quality_weight?:float|int|string,price_weight?:float|int|string,lead_weight?:float|int|string}|null $rule
  2784. */
  2785. public static function formatRuleFormulaTextForGroups(array $quoteGroups = [], ?array $rule = null): string
  2786. {
  2787. return self::formatRuleFormulaText($rule);
  2788. }
  2789. protected static function formatWeightPercent($n): string
  2790. {
  2791. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  2792. return $s === '' ? '0' : $s;
  2793. }
  2794. /**
  2795. * 开标验证通过后:计算并写入供应商服务评分表
  2796. *
  2797. * @param array<int, array<string, mixed>> $quoteGroups
  2798. */
  2799. public static function saveForOrder(string $ccydh, array $quoteGroups, ?string $ym = null): void
  2800. {
  2801. $ccydh = trim($ccydh);
  2802. if ($ccydh === '') {
  2803. return;
  2804. }
  2805. self::ensureSchema();
  2806. $rule = self::resolveRuleForCcydh($ccydh);
  2807. if ($ym === null || $ym === '') {
  2808. $ym = date('Y-m');
  2809. }
  2810. $ym = self::normalizeYm($ym);
  2811. $calc = self::calculateForQuoteGroups($quoteGroups, $rule, $ym);
  2812. if ($calc === []) {
  2813. return;
  2814. }
  2815. $now = date('Y-m-d H:i:s');
  2816. try {
  2817. Db::table(self::TABLE_SCORE)->where('ccydh', $ccydh)->delete();
  2818. $rows = [];
  2819. foreach ($calc as $it) {
  2820. $rows[] = [
  2821. 'customer_id' => (int)($it['customer_id'] ?? 0),
  2822. 'company_name' => (string)($it['company_name'] ?? ''),
  2823. 'ym' => $ym,
  2824. 'ccydh' => $ccydh,
  2825. 'score' => (float)($it['score'] ?? 0),
  2826. 'rank_no' => (int)($it['rank_no'] ?? 0),
  2827. 'quality_score' => (int)round((float)($it['quality_score'] ?? 0)),
  2828. 'quality_weight' => (int)($rule['quality_weight'] ?? 50),
  2829. 'price_sum' => round((float)($it['price_sum'] ?? 0), 4),
  2830. 'price_weight' => (int)($rule['price_weight'] ?? 50),
  2831. 'price_score' => (float)($it['price_score'] ?? 0),
  2832. 'lead_days_sum' => (int)round((float)($it['lead_days_sum'] ?? 0)),
  2833. 'lead_weight' => (int)($rule['lead_weight'] ?? 0),
  2834. 'lead_enabled' => ((int)($rule['lead_weight'] ?? 0) > 0) ? 1 : 0,
  2835. 'lead_score' => (float)($it['lead_score'] ?? 0),
  2836. 'rule_id' => (int)($rule['id'] ?? 0),
  2837. 'createtime' => $now,
  2838. 'updatetime' => $now,
  2839. ];
  2840. }
  2841. if ($rows !== []) {
  2842. Db::table(self::TABLE_SCORE)->insertAll($rows);
  2843. }
  2844. // 开标后:本月询价供应商名称写入月度评审表(不存在才加空行,已有记录不覆盖)
  2845. $monthNames = [];
  2846. foreach ($quoteGroups as $g) {
  2847. if (!is_array($g)) {
  2848. continue;
  2849. }
  2850. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  2851. if ($cn !== '') {
  2852. $monthNames[] = $cn;
  2853. }
  2854. }
  2855. foreach ($rows as $row) {
  2856. $cn = trim((string)($row['company_name'] ?? ''));
  2857. if ($cn !== '') {
  2858. $monthNames[] = $cn;
  2859. }
  2860. }
  2861. self::ensureMonthlySupplierNames($ym, $monthNames);
  2862. } catch (\Throwable $e) {
  2863. Log::write('supplier service score save: ' . $e->getMessage(), 'error');
  2864. }
  2865. }
  2866. /**
  2867. * 读取某订单已落库评分;无则返回空
  2868. *
  2869. * @return array<string, array<string, mixed>>
  2870. */
  2871. public static function loadSavedByCcydh(string $ccydh): array
  2872. {
  2873. $ccydh = trim($ccydh);
  2874. if ($ccydh === '') {
  2875. return [];
  2876. }
  2877. try {
  2878. $rows = Db::table(self::TABLE_SCORE)->where('ccydh', $ccydh)->select();
  2879. } catch (\Throwable $e) {
  2880. try {
  2881. self::ensureSchema();
  2882. $rows = Db::table(self::TABLE_SCORE)->where('ccydh', $ccydh)->select();
  2883. } catch (\Throwable $e2) {
  2884. return [];
  2885. }
  2886. }
  2887. if (!is_array($rows)) {
  2888. return [];
  2889. }
  2890. $out = [];
  2891. foreach ($rows as $r) {
  2892. if (!is_array($r)) {
  2893. continue;
  2894. }
  2895. $cn = trim((string)($r['company_name'] ?? ''));
  2896. if ($cn === '') {
  2897. continue;
  2898. }
  2899. $qualityScore = (int)round((float)($r['quality_score'] ?? 0));
  2900. $priceSum = round((float)($r['price_sum'] ?? 0), 4);
  2901. $qw = (int)($r['quality_weight'] ?? 50);
  2902. $pw = (int)($r['price_weight'] ?? 50);
  2903. $lw = (int)($r['lead_weight'] ?? 0);
  2904. $leadEnabled = $lw > 0 ? 1 : 0;
  2905. $leadSum = (int)round((float)($r['lead_days_sum'] ?? 0));
  2906. $leadScore = (float)($r['lead_score'] ?? 0);
  2907. $out[$cn] = [
  2908. 'company_name' => $cn,
  2909. 'customer_id' => (int)($r['customer_id'] ?? 0),
  2910. 'quality_score' => $qualityScore,
  2911. 'quality_score_text' => (string)$qualityScore,
  2912. 'quality_weight' => $qw,
  2913. 'price_sum' => $priceSum,
  2914. 'price_sum_text' => self::formatScore($priceSum),
  2915. 'price_weight' => $pw,
  2916. 'price_score' => (float)($r['price_score'] ?? 0),
  2917. 'price_score_text' => self::formatScore($r['price_score'] ?? 0),
  2918. 'lead_days_sum' => $leadSum,
  2919. 'lead_days_sum_text' => $leadEnabled ? (string)$leadSum : '',
  2920. 'lead_weight' => $lw,
  2921. 'lead_enabled' => $leadEnabled,
  2922. 'lead_score' => $leadScore,
  2923. 'lead_score_text' => $leadEnabled ? self::formatScore($leadScore) : '',
  2924. 'score' => (float)($r['score'] ?? 0),
  2925. 'rank_no' => (int)($r['rank_no'] ?? 0),
  2926. 'score_text' => self::formatScore($r['score'] ?? 0),
  2927. 'rank_text' => ((int)($r['rank_no'] ?? 0)) > 0 ? (string)(int)($r['rank_no'] ?? 0) : '',
  2928. '_row_id' => (int)($r['id'] ?? 0),
  2929. ];
  2930. }
  2931. // 按单价合计重算价格得分/总分(兼容历史把权重算进价格得分的数据)
  2932. $minSum = null;
  2933. foreach ($out as $it) {
  2934. $ps = (float)($it['price_sum'] ?? 0);
  2935. if ($ps > 0 && ($minSum === null || $ps < $minSum)) {
  2936. $minSum = $ps;
  2937. }
  2938. }
  2939. foreach ($out as $cn => &$it) {
  2940. $qw = (int)($it['quality_weight'] ?? 50);
  2941. $pw = (int)($it['price_weight'] ?? 50);
  2942. $lw = (int)($it['lead_weight'] ?? 0);
  2943. $priceSum = (float)($it['price_sum'] ?? 0);
  2944. // 单价未填写:总分为 0
  2945. if ($pw > 0 && $priceSum <= 0) {
  2946. $it['price_score'] = 0.0;
  2947. $it['price_score_text'] = '0';
  2948. $it['score'] = 0.0;
  2949. $it['score_text'] = '0';
  2950. continue;
  2951. }
  2952. if ($pw > 0 && $priceSum > 0 && $minSum !== null && $minSum > 0) {
  2953. $ratio = round($minSum / $priceSum, 4);
  2954. $it['price_score'] = round($ratio * ($pw / 100) * 100, 2);
  2955. } else {
  2956. $it['price_score'] = 0.0;
  2957. }
  2958. $it['price_score_text'] = self::formatScore($it['price_score']);
  2959. $total = 0.0;
  2960. if ($qw > 0) {
  2961. $total += (float)$it['quality_score'] * ($qw / 100);
  2962. }
  2963. if ($pw > 0) {
  2964. $total += (float)$it['price_score'];
  2965. }
  2966. if ($lw > 0) {
  2967. $total += (float)$it['lead_score'] * ($lw / 100);
  2968. }
  2969. $it['score'] = round($total, 2);
  2970. $it['score_text'] = self::formatScore($it['score']);
  2971. }
  2972. unset($it);
  2973. $sorted = $out;
  2974. uasort($sorted, static function ($a, $b) {
  2975. $sa = (float)($a['score'] ?? 0);
  2976. $sb = (float)($b['score'] ?? 0);
  2977. if ($sa !== $sb) {
  2978. return $sb <=> $sa;
  2979. }
  2980. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  2981. });
  2982. $rank = 0;
  2983. foreach ($sorted as $cn => $row) {
  2984. $rank++;
  2985. $oldRank = (int)($out[$cn]['rank_no'] ?? 0);
  2986. $out[$cn]['rank_no'] = $rank;
  2987. $out[$cn]['rank_text'] = (string)$rank;
  2988. $rowId = (int)($out[$cn]['_row_id'] ?? 0);
  2989. if ($rowId > 0) {
  2990. $upd = [];
  2991. if ($oldRank !== $rank) {
  2992. $upd['rank_no'] = $rank;
  2993. }
  2994. foreach ($rows as $r) {
  2995. if (!is_array($r) || (int)($r['id'] ?? 0) !== $rowId) {
  2996. continue;
  2997. }
  2998. if (abs((float)($r['price_score'] ?? 0) - (float)$out[$cn]['price_score']) > 0.001) {
  2999. $upd['price_score'] = $out[$cn]['price_score'];
  3000. }
  3001. if (abs((float)($r['score'] ?? 0) - (float)$out[$cn]['score']) > 0.001) {
  3002. $upd['score'] = $out[$cn]['score'];
  3003. }
  3004. break;
  3005. }
  3006. if ($upd !== []) {
  3007. try {
  3008. Db::table(self::TABLE_SCORE)->where('id', $rowId)->update($upd);
  3009. } catch (\Throwable $e) {
  3010. }
  3011. }
  3012. }
  3013. unset($out[$cn]['_row_id']);
  3014. }
  3015. return $out;
  3016. }
  3017. /**
  3018. * 清空报价组上的评分留痕字段
  3019. *
  3020. * @param array<string, mixed> $g
  3021. */
  3022. protected static function clearScoreTrailOnGroup(array &$g, int $showFlag = 0): void
  3023. {
  3024. $g['service_rank'] = '';
  3025. $g['service_score'] = '';
  3026. $g['service_rank_text'] = '';
  3027. $g['service_score_text'] = '';
  3028. $g['service_score_parts_text'] = '';
  3029. $g['service_quality_score'] = '';
  3030. $g['service_quality_score_text'] = '';
  3031. $g['service_price_sum'] = '';
  3032. $g['service_price_sum_text'] = '';
  3033. $g['service_price_score'] = '';
  3034. $g['service_price_score_text'] = '';
  3035. $g['service_lead_days_sum'] = '';
  3036. $g['service_lead_days_sum_text'] = '';
  3037. $g['service_lead_score'] = '';
  3038. $g['service_lead_score_text'] = '';
  3039. $g['service_lead_enabled'] = 0;
  3040. $g['service_quality_weight'] = '';
  3041. $g['service_price_weight'] = '';
  3042. $g['service_lead_weight'] = '';
  3043. $g['show_service_score'] = $showFlag;
  3044. $g['show_service_lead_score'] = 0;
  3045. }
  3046. /**
  3047. * 把排名/评分挂到报价组上(开标后可见)
  3048. * 详情等读路径:优先读已落库评分,避免每次打开重算写库拖慢弹窗
  3049. *
  3050. * @param array<int, array<string, mixed>> $quoteGroups
  3051. * @return array<int, array<string, mixed>>
  3052. */
  3053. public static function attachToQuoteGroups(array $quoteGroups, string $ccydh, bool $quoteVisible): array
  3054. {
  3055. if (!$quoteVisible || $quoteGroups === []) {
  3056. foreach ($quoteGroups as &$g) {
  3057. if (!is_array($g)) {
  3058. continue;
  3059. }
  3060. self::clearScoreTrailOnGroup($g, 0);
  3061. }
  3062. unset($g);
  3063. return $quoteGroups;
  3064. }
  3065. $rule = self::resolveRuleForCcydh($ccydh);
  3066. $ruleQw = (int)($rule['quality_weight'] ?? 0);
  3067. $rulePw = (int)($rule['price_weight'] ?? 0);
  3068. $ruleLw = (int)($rule['lead_weight'] ?? 0);
  3069. $saved = self::loadSavedByCcydh($ccydh);
  3070. $needCalc = ($saved === []);
  3071. if (!$needCalc) {
  3072. $anyHit = false;
  3073. foreach ($quoteGroups as $g) {
  3074. if (!is_array($g)) {
  3075. continue;
  3076. }
  3077. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  3078. if ($cn !== '' && isset($saved[$cn])) {
  3079. $anyHit = true;
  3080. break;
  3081. }
  3082. }
  3083. $needCalc = !$anyHit;
  3084. }
  3085. if (!$needCalc) {
  3086. foreach ($saved as $it) {
  3087. if (!is_array($it)) {
  3088. continue;
  3089. }
  3090. if ((int)($it['quality_weight'] ?? 0) !== $ruleQw
  3091. || (int)($it['price_weight'] ?? 0) !== $rulePw
  3092. || (int)($it['lead_weight'] ?? 0) !== $ruleLw) {
  3093. $needCalc = true;
  3094. break;
  3095. }
  3096. }
  3097. }
  3098. // 无落库或权重与本单规则不一致:按本单规则内存重算展示;落库仍由开标验证 saveForOrder 负责
  3099. if ($needCalc) {
  3100. $saved = self::calculateForQuoteGroups($quoteGroups, $rule, date('Y-m'));
  3101. }
  3102. foreach ($quoteGroups as &$g) {
  3103. if (!is_array($g)) {
  3104. continue;
  3105. }
  3106. $cn = trim((string)($g['name'] ?? $g['company_name'] ?? ''));
  3107. $hit = ($cn !== '' && isset($saved[$cn]) && is_array($saved[$cn])) ? $saved[$cn] : null;
  3108. if (is_array($hit)) {
  3109. $g['service_rank'] = (int)($hit['rank_no'] ?? 0);
  3110. $g['service_score'] = (float)($hit['score'] ?? 0);
  3111. $g['service_rank_text'] = (string)($hit['rank_text'] ?? '');
  3112. $g['service_score_text'] = self::formatScoreDetailText($hit);
  3113. $g['service_score_parts_text'] = self::formatScorePartsHtml($hit);
  3114. $qs = round((float)($hit['quality_score'] ?? 0), 2);
  3115. $ps = (float)($hit['price_score'] ?? 0);
  3116. $psum = round((float)($hit['price_sum'] ?? 0), 2);
  3117. $leadEnabled = ((int)($hit['lead_weight'] ?? 0) > 0) ? 1 : 0;
  3118. $ls = (float)($hit['lead_score'] ?? 0);
  3119. $lsum = (int)round((float)($hit['lead_days_sum'] ?? 0));
  3120. $g['service_quality_score'] = $qs;
  3121. $g['service_quality_score_text'] = (string)($hit['quality_score_text'] ?? self::formatScore($qs));
  3122. $g['service_price_sum'] = $psum;
  3123. $g['service_price_sum_text'] = (string)($hit['price_sum_text'] ?? $psum);
  3124. $g['service_price_score'] = $ps;
  3125. $g['service_price_score_text'] = (string)($hit['price_score_text'] ?? self::formatScore($ps));
  3126. $g['service_lead_enabled'] = $leadEnabled;
  3127. $g['show_service_lead_score'] = $leadEnabled;
  3128. $g['service_lead_days_sum'] = $lsum;
  3129. $g['service_lead_days_sum_text'] = $leadEnabled ? (string)($hit['lead_days_sum_text'] ?? $lsum) : '';
  3130. $g['service_lead_score'] = $ls;
  3131. $g['service_lead_score_text'] = $leadEnabled ? (string)($hit['lead_score_text'] ?? self::formatScore($ls)) : '';
  3132. $g['service_quality_weight'] = (int)($hit['quality_weight'] ?? 50);
  3133. $g['service_price_weight'] = (int)($hit['price_weight'] ?? 50);
  3134. $g['service_lead_weight'] = (int)($hit['lead_weight'] ?? 0);
  3135. $g['show_service_score'] = 1;
  3136. } else {
  3137. self::clearScoreTrailOnGroup($g, 1);
  3138. }
  3139. }
  3140. unset($g);
  3141. // 开标后按排名升序(第1名在最前);无排名的放最后
  3142. usort($quoteGroups, function ($a, $b) {
  3143. $ra = is_array($a) ? (int)($a['service_rank'] ?? 0) : 0;
  3144. $rb = is_array($b) ? (int)($b['service_rank'] ?? 0) : 0;
  3145. $ha = $ra > 0;
  3146. $hb = $rb > 0;
  3147. if ($ha !== $hb) {
  3148. return $ha ? -1 : 1;
  3149. }
  3150. if ($ha && $ra !== $rb) {
  3151. return $ra <=> $rb;
  3152. }
  3153. $sa = is_array($a) ? (float)($a['service_score'] ?? 0) : 0.0;
  3154. $sb = is_array($b) ? (float)($b['service_score'] ?? 0) : 0.0;
  3155. if ($sa !== $sb) {
  3156. return $sb <=> $sa;
  3157. }
  3158. $na = is_array($a) ? trim((string)($a['name'] ?? $a['company_name'] ?? '')) : '';
  3159. $nb = is_array($b) ? trim((string)($b['name'] ?? $b['company_name'] ?? '')) : '';
  3160. return strcmp($na, $nb);
  3161. });
  3162. return $quoteGroups;
  3163. }
  3164. }