OrderSuperLoss.php 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\api\service\SuperLossRewardRule;
  5. use think\Cache;
  6. use think\Exception;
  7. use think\Log;
  8. use think\Queue;
  9. use \think\Request;
  10. use \think\Db;
  11. /**
  12. * 工单超节损核算接口
  13. */
  14. class OrderSuperLoss extends Api
  15. {
  16. protected $noNeedLogin = ['*'];
  17. protected $noNeedRight = ['*'];
  18. /**
  19. * 最近一次倍率判定结果(SuperLossRewardRule::resolve 的返回值),落库时直接取用
  20. * @var array|null
  21. */
  22. private $superLossRewardRule = null;
  23. /**
  24. * 首页-已核查成品编号
  25. *
  26. */
  27. public function index()
  28. {
  29. $this->success('请求成功');
  30. }
  31. /**
  32. * 获取左侧菜单栏
  33. * @ApiMethod GET
  34. */
  35. public function getTab()
  36. {
  37. if (Request::instance()->isGet() == false) {
  38. $this->error('非法请求');
  39. }
  40. $sql = "SELECT
  41. DATE_FORMAT(a.jjcp_sj, '%Y-%m') AS date, -- Format the date for grouping
  42. RTRIM(b.`编号`) AS 编号,
  43. RTRIM(b.`名称`) AS 客户名称,
  44. COUNT(DISTINCT a.jjcp_gdbh) AS count
  45. FROM
  46. `成品入仓` a
  47. LEFT JOIN
  48. `物料_存货结构` b
  49. ON (CASE
  50. WHEN LEFT(a.`jjcp_cpdh`, 1) REGEXP '^[A-Za-z]' THEN LEFT(a.`jjcp_cpdh`, 5)
  51. ELSE LEFT(a.`jjcp_cpdh`, 4)
  52. END) = RTRIM(b.`编号`) -- Conditional join based on the first character
  53. WHERE
  54. a.jjcp_sj >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) -- Direct date comparison
  55. AND (a.jjcp_smb IN ('末 板', '末板')) -- Cleaner syntax for conditions
  56. AND a.`成品编码` != ''
  57. AND a.jjcp_sj >= '2025-01-01 00:00:00'
  58. GROUP BY
  59. DATE_FORMAT(a.jjcp_sj, '%Y-%m'), -- Group by formatted date
  60. RTRIM(b.`编号`)
  61. ORDER BY
  62. date DESC,
  63. 编号 ASC;";
  64. $data = Db::query($sql);
  65. // 创建一个新数组来存储整理后的数据
  66. $organizedData = [];
  67. // 遍历原始数据
  68. foreach ($data as $entry) {
  69. $date = date('Ym',strtotime($entry['date']));
  70. // 检查日期是否在已整理数据中存在
  71. if (isset($organizedData[$date])) {
  72. // 如果日期存在,将数据追加到该日期下
  73. $organizedData[$date][] = [
  74. '客户名称' => $entry['客户名称'],
  75. '客户编号' => $entry['编号'],
  76. 'total' => $entry['count'],
  77. ];
  78. // 统计该日期下所有数据的总和
  79. $organizedData[$date]['total_count'] += $entry['count'];
  80. } else {
  81. // 如果日期不存在,创建新的日期项并添加数据
  82. $organizedData[$date] = [
  83. [
  84. '客户名称' => $entry['客户名称'],
  85. '客户编号' => $entry['编号'],
  86. 'total' => $entry['count'],
  87. ]
  88. ];
  89. // 初始化该日期的总和
  90. $organizedData[$date]['total_count'] = $entry['count'];
  91. }
  92. }
  93. // 将整理后的数据调整为以日期和相加的总和为索引的格式
  94. $finalData = [];
  95. foreach ($organizedData as $date => $entries) {
  96. $totalCount = $entries['total_count'];
  97. $index = $date . '-' . $totalCount;
  98. unset($entries['total_count']);
  99. $finalData[$index] = $entries;
  100. }
  101. $this->success('请求成功',$finalData);
  102. }
  103. /**
  104. * 获取工单超节损工艺
  105. * @ApiMethod GET
  106. * @params string order
  107. */
  108. public function getOrderSuperLossGy(){
  109. if (Request::instance()->isGet() == false) {
  110. $this->error('非法请求');
  111. }
  112. $params = Request::instance()->param();
  113. if (!isset($params['order']) || empty($params['order'])) {
  114. $this->error('参数错误');
  115. }
  116. if (!isset($params['yjno']) || empty($params['yjno'])) {
  117. $this->error('参数错误');
  118. }
  119. $sql = "SELECT a.Gy0_gdbh,a.Gy0_yjno,a.Gy0_gxh,rtrim(a.Gy0_gxmc) as Gy0_gxmc,rtrim(a.Add_gxmc) as Add_gxmc,
  120. a.Gy0_ls,a.Gy0_Rate0,a.Gy0_Rate1,a.损耗系数,a.Gy0_ms,a.Gy0_计划接货数*a.Gy0_ls as Gy0_计划接货数,
  121. a.Gy0_计划损耗*a.Gy0_ls as Gy0_计划损耗,sum(b.sczl_cl) as total_cl,sum(b.sczl_zcfp) as total_fp,
  122. sum(c.sczl_cl) as cl,SUM(c.sczl_fp) as fp,rtrim(a.印刷方式) as 印刷方式,rtrim(a.版距) as 版距
  123. FROM `工单_工艺资料` a
  124. LEFT JOIN `设备_产量计酬` b ON a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_gxh = b.sczl_gxh
  125. LEFT JOIN `db_sczl` c ON a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_gxh = c.sczl_gxh
  126. WHERE a.Gy0_gdbh = '{$params['order']}' AND a.Gy0_yjno = '{$params['yjno']}' GROUP BY a.Gy0_gxh";
  127. $data = Db::query($sql);
  128. foreach ($data as $key=>$value){
  129. if (!empty($value['total_cl'])){
  130. $data[$key]['total_cl'] = $value['total_cl'] *$value['Gy0_ls'];
  131. }else{
  132. $data[$key]['total_cl'] =$value['cl'] *$value['Gy0_ls'];
  133. }
  134. if (!empty($value['total_fp'])){
  135. $data[$key]['total_fp'] = $value['total_fp'] *$value['Gy0_ls'];
  136. }else{
  137. $data[$key]['total_fp'] = $value['fp'] *$value['Gy0_ls'];
  138. }
  139. if ($value['印刷方式'] === '卷对卷' && (float)$value['版距'] > 0){
  140. $data[$key]['total_cl'] = ceil($data[$key]['total_cl'] / $value['版距']*1000);
  141. $data[$key]['total_fp'] = ceil($data[$key]['total_fp'] / $value['版距']*1000);
  142. }
  143. unset($data[$key]['cl']);
  144. unset($data[$key]['fp']);
  145. }
  146. $this->success('请求成功',$data);
  147. }
  148. /**
  149. * 工单超节损统计
  150. * @ApiMethod GET
  151. * @params string order
  152. * 节损奖 小盒0.02 大盒0.09
  153. */
  154. public function getOrderSuperLossCount(){
  155. if (Request::instance()->isGet() == false) {
  156. $this->error('非法请求');
  157. }
  158. $params = Request::instance()->param();
  159. if (!isset($params['order']) || empty($params['order'])) {
  160. $this->error('参数错误');
  161. }
  162. $order = $params['order'];
  163. $field = 'a.Gd_gdbh,rtrim(a.成品代号) as 成品代号,rtrim(a.成品名称) as 成品名称,rtrim(a.销售订单号) as 销售订单号,a.订单数量,c.yj_ls as ls,c.yj_ks as ks,SUM(b.st_sl) as 投料';
  164. $data =db('工单_基本资料')
  165. ->alias('a')
  166. ->join('物料_收发记录 b','a.Gd_gdbh = b.st_gdbh AND a.Gd_cpdh = b.cpdh')
  167. ->join('工单_印件资料 c','c.Yj_Gdbh = a.Gd_gdbh AND c.yj_Yjdh = a.Gd_cpdh')
  168. ->where('a.Gd_Gdbh',$order)
  169. ->where('a.行号',$params['yjno'])
  170. ->where('c.yj_Yjno',$params['yjno'])
  171. ->where(function($query) {
  172. $query->where('b.仓库编号', '101')
  173. ->whereOr('b.仓库编号', 'Y101');})
  174. ->field($field)
  175. ->find();
  176. if ($data['ls'] == 0){
  177. $data['ls'] === 1;
  178. }
  179. if ($data['ks'] == 0){
  180. $data['ks'] === 1;
  181. }
  182. $data['实际投料'] = number_format($data['投料'] * $data['ls'] * $data['ks'] / 10000, 4, '.', '');
  183. if($data['实际投料'] == 0){
  184. $this->error('投料数据为 0,请点击超节损页面“修正工单投料”按钮进行修正');
  185. return;
  186. }
  187. //查出成品数量及日期
  188. $cp_sql = "SELECT SUM(jjcp_sl) as cp_sl,MAX(jjcp_sj) as jjcp_sj FROM `成品入仓` WHERE jjcp_gdbh = '{$order}' AND jjcp_yjno = '{$params['yjno']}' GROUP BY jjcp_gdbh,jjcp_yjno";
  189. $cp_data = Db::query($cp_sql);
  190. if (empty($cp_data)){
  191. $this->success('此工单未查询到成品入库信息,请核查该工单是否已进入超节损');
  192. }
  193. $data['warehousing_num'] = $cp_data[0]['cp_sl'];
  194. $data['warehousing_date'] = substr($cp_data[0]['jjcp_sj'],0,10);
  195. $gxh_values = $this->getSuperLossProcessGxhList($order, $params['yjno']);
  196. if (empty($gxh_values)) {
  197. $this->error('未查询到报工工序');
  198. }
  199. $sczlProcessSub = $this->buildSczlProcessAggSubSql();
  200. $gy_data =db('工单_工艺资料')
  201. ->alias('a')
  202. ->field([
  203. 'a.Gy0_yjno', 'a.Gy0_gxh', 'RTRIM(a.Gy0_gxmc) as Gy0_gxmc','RTRIM(a.Add_gxmc) as Add_gxmc','a.Gy0_ks', 'a.Gy0_ls', 'a.Gy0_计划接货数*a.Gy0_ls as Gy0_计划接货数',
  204. 'a.Gy0_计划损耗', 'a.无形损承担比例','a.超节损承担比例','SUM(b.sczl_zcfp) as total_fp','SUM(b.sczl_cl) as total_cl','SUM(c.cl) as cl','SUM(c.fp) as fp',
  205. ])
  206. ->join('设备_产量计酬 b', 'a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh','left')
  207. ->join([$sczlProcessSub => 'c'], 'a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh', 'left')
  208. ->where([
  209. 'a.Gy0_gdbh' => $order,
  210. 'a.Gy0_yjno' => $params['yjno'],
  211. 'a.Gy0_gxh' => ['in', $gxh_values]
  212. ])
  213. ->group('a.Gy0_yjno,a.Gy0_gxh')
  214. ->select();
  215. //目标合格率 = (投料数 - 参与工序计划损耗合计) / 投料数
  216. $target_rate = $this->calcTargetRateBp($order, $params['yjno'], $gxh_values, (float)$data['实际投料'] * 10000) / 100;
  217. $data['target_rate'] = number_format($target_rate, 2) . '%'; //目标合格率
  218. $real_rate = $cp_data[0]['cp_sl'] / ((float)$data['实际投料'] * 10000) *100;
  219. $data['real_rate'] = number_format($real_rate,2) . '%';//实际合格率
  220. //制程废品
  221. $zzfp_data =db('设备_产量计酬')->where('sczl_gdbh',$order)->where('sczl_yjno',$params['yjno'])->value('SUM(sczl_zcfp) as sczl_zcfp');
  222. //联数
  223. $ls =db('工单_工艺资料')->where('Gy0_gdbh',$order)->field('Gy0_ls,Gy0_ks')->find();
  224. //制程废品*ls
  225. $data['zcfp'] = $zzfp_data * $ls['Gy0_ls'] * $ls['Gy0_ks'];
  226. //废品数量
  227. $wasteTotal = db('db_qczl')->where('qczl_gdbh',$order)->where('qczl_yjno',$params['yjno'])->sum('qczl_fp');
  228. if (empty($wasteTotal)){
  229. $wasteTotal = 0;
  230. }
  231. //废品合计
  232. $waste_total = $data['zcfp'] + $wasteTotal;
  233. //工单无形损
  234. $data['intangible_loss'] = (int)((float)$data['实际投料'] *10000 - $cp_data[0]['cp_sl'] - $waste_total);
  235. $out_sql = "SELECT fp_sl1,fp_sl2,fp_sl3,fp_sl4,fp_sl5,fp_sl6,fp_sl7,fp_sl8,fp_sl9,fp_sl10,fp_sl11,fp_sl12,fp_sl13,
  236. fp_lb1,fp_lb2,fp_lb3,fp_lb4,fp_lb5,fp_lb6,fp_lb7,fp_lb8,fp_lb9,fp_lb10,fp_lb11,fp_lb12,fp_lb13,
  237. fp_bh1,fp_bh2,fp_bh3,fp_bh4,fp_bh5,fp_bh6,fp_bh7,fp_bh8,fp_bh9,fp_bh10,fp_bh11,fp_bh12,fp_bh13,
  238. fp_gxmc1,fp_gxmc2,fp_gxmc3,fp_gxmc4,fp_gxmc5,fp_gxmc6,fp_gxmc7,fp_gxmc8,fp_gxmc9,fp_gxmc10,fp_gxmc11,fp_gxmc12,fp_gxmc13,UniqId
  239. FROM db_qczl WHERE qczl_gdbh = '{$order}' AND qczl_yjno = '{$params['yjno']}'";
  240. $waste_out = Db::query($out_sql);
  241. $list = []; //外发废数组
  242. $quality = [];//质检废数组
  243. $material = [];//材料废数组
  244. $change = [];//零头处理数组
  245. $jijian = [];//机检数据
  246. $j = 0;
  247. $m = 0;
  248. $n = 0;
  249. $l = 0;
  250. $s = 0;
  251. foreach ($waste_out as $entry) {
  252. for ($i = 1; $i <= 13; $i++) {
  253. $labelKey = "fp_lb" . $i;
  254. $bhKey = "fp_bh" . $i;
  255. $gxmcKey = "fp_gxmc" . $i;
  256. $slKey = "fp_sl" . $i;
  257. if (!empty($entry[$labelKey])) {
  258. //外发废
  259. if (substr($entry[$labelKey],0,3) == 'M04'){
  260. $list[$j]= $entry[$slKey];
  261. $j++;
  262. }
  263. //材料废
  264. if (substr($entry[$labelKey],0,1) == 'L' ){
  265. $material[$n]= $entry[$slKey];
  266. $n++;
  267. }
  268. //零头处理
  269. if (substr($entry[$labelKey],0,3) == 'M01' ){
  270. $change[$l]= $entry[$slKey];
  271. $l++;
  272. }
  273. //机检数据
  274. if (substr($entry[$labelKey],0,1) == 'K' ){
  275. $jijian[$s]= $entry[$slKey];
  276. $s++;
  277. }
  278. }
  279. $quality[$m]= $entry[$slKey];
  280. $m++;
  281. }
  282. }
  283. $data['材料废'] = array_sum($material); //材料废
  284. $data['零头处理'] = array_sum($change); //零头处理
  285. $data['外发废'] = array_sum($list);//外发废
  286. $data['工单质检废'] = array_sum($quality);//质检废
  287. $data['机检废品'] = array_sum($jijian);
  288. $plan_total = $this->getIntangibleAllocationPlanLossTotal($order, $params['yjno'], $gxh_values);
  289. if ($plan_total == 0) {
  290. $this->error('计划损耗数据为 0,请到工单资料管理页面修改工艺资料中选择正确的工序损耗');
  291. return;
  292. }
  293. //单据列表最后统计
  294. $total = [];
  295. $total['plan_loss'] = 0;
  296. $total['total_fp'] = 0;
  297. $total['waste_quality'] = 0;
  298. $total['waste_intangible'] = 0;
  299. $total['reward'] = 0; //超节损奖励数组
  300. //按工序打印
  301. if ($params['type'] == 1){
  302. $total['total_waste'] = 0;
  303. $total['loss'] = 0;
  304. $processIntangibleShares = $this->buildProcessIntangibleShareMap(
  305. $order,
  306. $params['yjno'],
  307. $gxh_values,
  308. floatval($data['intangible_loss'])
  309. );
  310. foreach ($gy_data as $k=>$item){
  311. $gy_data[$k]['Gy0_计划损耗'] = $item['Gy0_计划损耗']*$item['Gy0_ls']*$item['Gy0_ks'];
  312. $gy_data[$k]['waste_quality'] = 0;
  313. $gy_data[$k]['total_fp'] = $item['total_fp'] * $item['Gy0_ls'];
  314. $gy_data[$k]['total_cl'] = $item['total_cl'] * $item['Gy0_ls'];
  315. $gy_data[$k]['intangible_loss'] = (int)($processIntangibleShares[$this->normalizeGxhKey($item['Gy0_gxh'])] ?? 0);
  316. foreach ($waste_out as $entry) {
  317. for ($i = 1; $i <= 13; $i++) {
  318. $gxmcKey = "fp_gxmc" . $i;
  319. $slKey = "fp_sl" . $i;
  320. if (substr($entry[$gxmcKey], 0, 2) == $item['Gy0_gxh']
  321. && !$this->isMachineInspectionProcess((string)$item['Gy0_gxmc'])) {
  322. $gy_data[$k]['waste_quality'] += $entry[$slKey];
  323. }
  324. }
  325. }
  326. //报废合计
  327. $gy_data[$k]['total_waste'] = $gy_data[$k]['waste_quality'] + $gy_data[$k]['intangible_loss'] + $gy_data[$k]['total_fp'];
  328. //工序节损数
  329. $gy_data[$k]['loss'] = $item['Gy0_计划损耗'] * $item['Gy0_ls'] * $item['Gy0_ks'] - $gy_data[$k]['total_waste'];
  330. $this->applyMachineInspectionProcessLossRules(
  331. (string)$item['Gy0_gxmc'],
  332. (int)$gy_data[$k]['Gy0_计划损耗'],
  333. $gy_data[$k]
  334. );
  335. //占投料报废率
  336. $gy_data[$k]['loss_rate'] = number_format($gy_data[$k]['loss'] / $item['Gy0_计划接货数'],4) * 100 .'%';
  337. //工序目标报废率
  338. $target_loss_rate = floor($item['Gy0_计划损耗'] / $item['Gy0_计划接货数'] * 10000) / 10000;
  339. if ($target_loss_rate == 0){
  340. $target_loss_rate = round($item['Gy0_计划损耗'] / $item['Gy0_计划接货数'] * 10000) / 10000;
  341. }
  342. $gy_data[$k]['target_loss_rate'] = $target_loss_rate * 100 . '%';
  343. //工序实际报废率
  344. $gy_data[$k]['actual_loss_rate'] = number_format($gy_data[$k]['total_waste'] / ($data['实际投料']*10000),4) * 100 .'%';
  345. $gy_data[$k]['超节损承担比例'] = number_format($item['超节损承担比例'],4) * 100 .'%';
  346. $guige = \db('物料_存货编码')
  347. ->where('物料代码',$data['成品代号'])
  348. ->value('rtrim(规格)');
  349. //工序超节损金额
  350. if ($guige === '小盒'){
  351. $moneyRate = 0.02;
  352. }else{
  353. $moneyRate = 0.09;
  354. }
  355. if ($this->isSuperLossRewardExcluded((string)$item['Gy0_gxmc'])) {
  356. $gy_data[$k]['工序超节损金额'] = '0.000000';
  357. } else {
  358. $gy_data[$k]['工序超节损金额'] = number_format($gy_data[$k]['loss'] * $item['超节损承担比例'] * $moneyRate, 4);
  359. }
  360. $total['plan_loss'] += $gy_data[$k]['Gy0_计划损耗'];
  361. $total['total_fp'] += $gy_data[$k]['total_fp'];
  362. $total['waste_quality'] += $gy_data[$k]['waste_quality'];
  363. $total['waste_intangible'] += $gy_data[$k]['intangible_loss'];
  364. $total['total_waste'] += $gy_data[$k]['total_waste'];
  365. $total['loss'] += $gy_data[$k]['loss'];
  366. $total['reward'] += floatval(str_replace(',', '', $gy_data[$k]['工序超节损金额']));
  367. }
  368. $feedQty = floatval($data['实际投料']) * 10000;
  369. $realRateVal = $feedQty > 0 ? (floatval($cp_data[0]['cp_sl']) / $feedQty * 100) : 0;
  370. $rewardMultiplier = $this->resolveSuperLossRewardMultiplier(
  371. floatval($target_rate),
  372. $realRateVal,
  373. floatval($data['材料废'] ?? 0),
  374. $feedQty,
  375. (string)$order,
  376. $params['yjno']
  377. );
  378. $data['reward_rate'] = $this->stringifyRewardMultiplier($rewardMultiplier);
  379. $data['材料废占比'] = $feedQty > 0
  380. ? number_format(floatval($data['材料废'] ?? 0) / $feedQty * 100, 4) . '%'
  381. : null;
  382. if ($rewardMultiplier > 1) {
  383. $total['reward'] = 0;
  384. foreach ($gy_data as $k => $item) {
  385. $baseReward = floatval(str_replace(',', '', (string)$gy_data[$k]['工序超节损金额']));
  386. if ($baseReward != 0.0) {
  387. $gy_data[$k]['工序超节损金额'] = number_format($baseReward * $rewardMultiplier, 4);
  388. }
  389. $total['reward'] += floatval(str_replace(',', '', $gy_data[$k]['工序超节损金额']));
  390. }
  391. }
  392. $total['reward'] = number_format($total['reward'], 2);
  393. $data['gy_data'] = $gy_data;
  394. $data['total'] = $total;
  395. $this->success('请求成功',$data);
  396. }else{ //按班组打印
  397. //总产量数据
  398. $total_cl_data = \db('工单_工艺资料')->alias('a')
  399. ->field(['a.Gy0_yjno', 'a.Gy0_gxh','a.Gy0_ls', 'SUM(b.sczl_cl) as total_cl', 'SUM(c.sczl_cl) as cl'])
  400. ->join('设备_产量计酬 b', 'a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh','left')
  401. ->join('db_sczl c', 'a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh','left')
  402. ->where([
  403. 'a.Gy0_gdbh' => $order,
  404. 'a.Gy0_yjno' => $params['yjno'],
  405. 'a.Gy0_gxh' => ['IN', $gxh_values],
  406. 'b.sczl_cl|c.sczl_cl' => ['>', 0]
  407. ])
  408. ->group('b.sczl_gxh')
  409. ->order('a.Gy0_gxh')
  410. ->select();
  411. $sczlTeamSub = $this->buildSczlTeamAggSubSql();
  412. //按班组分的产量数据
  413. $gy_data =db('工单_工艺资料')
  414. ->alias('a')
  415. ->field([
  416. 'a.Gy0_yjno', 'a.Gy0_gxh', 'a.Gy0_ls', 'a.Gy0_ks' ,'a.Gy0_计划损耗', 'a.无形损承担比例', 'a.超节损承担比例', 'b.sczl_gxmc',
  417. 'rtrim(a.印刷方式) as 印刷方式', 'rtrim(a.版距) as 版距',
  418. 'SUM(b.sczl_zcfp) as sczl_zcfp', 'SUM(b.sczl_cl) as total_cl',
  419. 'b.sczl_bh1', 'b.sczl_bh2', 'b.sczl_bh3', 'b.sczl_bh4', 'b.sczl_bh5', 'b.sczl_bh6',
  420. 'b.sczl_bh7', 'b.sczl_bh8', 'b.sczl_bh9', 'b.sczl_bh10',
  421. 'c.gxmc', 'c.cl', 'c.fp', 'c.sczl_bh1 as sczl_bh'
  422. ])
  423. ->join('设备_产量计酬 b', 'a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh','left')
  424. ->join([$sczlTeamSub => 'c'], 'a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh AND IFNULL(b.sczl_bh1,\'\') = IFNULL(c.sczl_bh1,\'\')', 'left')
  425. ->where([
  426. 'a.Gy0_gdbh' => $order,
  427. 'a.Gy0_yjno' => $params['yjno'],
  428. 'a.Gy0_gxh' => ['in', $gxh_values],
  429. 'b.sczl_cl|c.cl' => ['>', 0]
  430. ])
  431. ->group('b.sczl_gxh, b.sczl_bh1, CASE WHEN b.sczl_bh2 = "000000" THEN "" ELSE b.sczl_bh2 END, b.sczl_bh3,
  432. b.sczl_bh4, b.sczl_bh5, b.sczl_bh6, b.sczl_bh7, b.sczl_bh8, b.sczl_bh9')
  433. ->order('a.Gy0_gxh asc, b.开工时间 asc')
  434. ->select();
  435. //拆片只在 db_sczl 报工,不进产量计酬;上面按计酬班组关联会整道丢掉
  436. $gy_data = $this->mergeChaipianTeamRows($gy_data ?: [], (string)$order, $params['yjno'], $gxh_values);
  437. foreach ($gy_data as $key=>$value){
  438. $gy_data[$key]['Gy0_yjno'] = $value['Gy0_yjno'] > 10 ? $value['Gy0_yjno'] : '0'.$value['Gy0_yjno'];
  439. $rawQty = $value['total_cl'];
  440. if (empty($rawQty)) {
  441. $rawQty = $value['cl'];
  442. }
  443. $gy_data[$key]['total_cl'] = $this->superLossSheetQty(
  444. $rawQty,
  445. $value['Gy0_ls'],
  446. $value['Gy0_ks'],
  447. isset($value['印刷方式']) ? $value['印刷方式'] : '',
  448. isset($value['版距']) ? $value['版距'] : 0
  449. );
  450. $gy_data[$key]['Gy0_计划损耗'] = $value['Gy0_计划损耗'] * $value['Gy0_ls'] * $value['Gy0_ks'];
  451. //每道工序的制程废品(按班组分)
  452. $gy_data[$key]['sczl_zcfp'] = $value['sczl_zcfp'] * $value['Gy0_ls'];
  453. if (empty($value['sczl_zcfp'])){
  454. $gy_data[$key]['sczl_zcfp'] = $value['fp'] * $value['Gy0_ls'];
  455. }
  456. //计算每道工序的质检废(按班组)
  457. $gy_data[$key]['sczl_gxmc'] = $value['sczl_gxmc'];
  458. if (empty($value['sczl_gxmc'])){
  459. $gy_data[$key]['sczl_gxmc'] = $value['gxmc'];
  460. }
  461. if (empty($value['sczl_bh1']) || is_null($value['sczl_bh1'])) {
  462. $value['sczl_bh1'] = $value['sczl_bh'] ?? '';
  463. }
  464. $gy_data[$key]['sczl_bh1'] = $value['sczl_bh1'];
  465. $gy_data[$key]['质检废'] = 0;
  466. foreach ($waste_out as $entry) {
  467. for ($i = 1; $i <= 13; $i++) {
  468. $gxmcKey = "fp_gxmc" . $i;
  469. $slKey = "fp_sl" . $i;
  470. $bhKey = "fp_bh" . $i;
  471. if ((int)substr($entry[$gxmcKey],0,2) == $value['Gy0_gxh'] && $entry[$bhKey] == $value['sczl_bh1']){
  472. $gy_data[$key]['质检废'] += $entry[$slKey];
  473. }
  474. }
  475. }
  476. //班组成员
  477. $nameArr = [];
  478. for ($j = 1; $j <= 10; $j++) {
  479. $bhKey = "sczl_bh" . $j;
  480. if (!empty($value[$bhKey])){
  481. $name = \db('人事_基本资料')->where('员工编号',$value[$bhKey])->value('rtrim(员工姓名)');
  482. array_push($nameArr,$name);
  483. }
  484. }
  485. $gy_data[$key]['member'] = implode(' ',$nameArr);
  486. unset($gy_data[$key]['gxmc']);
  487. unset($gy_data[$key]['cl']);
  488. unset($gy_data[$key]['fp']);
  489. unset($gy_data[$key]['sczl_bh']);
  490. }
  491. $this->allocateSuperLossPlanShare($gy_data, 'total_cl', 'Gy0_计划损耗', '计划损耗', 'Gy0_gxh');
  492. foreach ($gy_data as $key => $value) {
  493. unset($gy_data[$key]['Gy0_计划损耗']);
  494. }
  495. $this->assignIntangibleLossToGyDataRows(
  496. $gy_data,
  497. $order,
  498. $params['yjno'],
  499. $gxh_values,
  500. floatval($data['intangible_loss'])
  501. );
  502. $i = 0;
  503. foreach ($gy_data as &$item) {
  504. $sczl_bh1 = $item['sczl_bh1'];
  505. $total_cl = $item['total_cl'];
  506. //节损数量
  507. if ($item['无形损分摊'] > 0){
  508. $total_waste = $item['质检废'] + $item['sczl_zcfp'] + $item['无形损分摊'];
  509. }else{
  510. $total_waste = $item['质检废'] + $item['sczl_zcfp'];
  511. }
  512. $gy_data[$i]['节损数量'] = $item['计划损耗'] - $total_waste;
  513. //节损奖
  514. $guige = \db('物料_存货编码')
  515. ->where('物料代码',$data['成品代号'])
  516. ->value('rtrim(规格)');
  517. //工序超节损金额
  518. if ($guige === '小盒'){
  519. $moneyRate = 0.02;
  520. }else{
  521. $moneyRate = 0.09;
  522. }
  523. if ($this->isSuperLossRewardExcluded((string)$item['sczl_gxmc'])) {
  524. $gy_data[$i]['节损奖'] = 0;
  525. } else {
  526. $gy_data[$i]['节损奖'] = number_format($gy_data[$i]['节损数量'] * $item['超节损承担比例'] * $moneyRate, 4);
  527. }
  528. $gy_data[$i]['超节损承担比例'] = number_format($item['超节损承担比例'],4) * 100 .'%';
  529. $total['plan_loss'] += $item['计划损耗'];
  530. $total['total_fp'] += $item['sczl_zcfp'];
  531. $total['waste_quality'] += $item['质检废'];
  532. $total['waste_intangible'] += $item['无形损分摊'];
  533. $total['reward'] += floatval(str_replace(',', '', $gy_data[$i]['节损奖']));
  534. $i++;
  535. }
  536. $feedQty = floatval($data['实际投料']) * 10000;
  537. $realRateVal = $feedQty > 0 ? (floatval($cp_data[0]['cp_sl']) / $feedQty * 100) : 0;
  538. $rewardMultiplier = $this->resolveSuperLossRewardMultiplier(
  539. floatval($target_rate),
  540. $realRateVal,
  541. floatval($data['材料废'] ?? 0),
  542. $feedQty,
  543. (string)$order,
  544. $params['yjno']
  545. );
  546. $data['reward_rate'] = $this->stringifyRewardMultiplier($rewardMultiplier);
  547. if ($rewardMultiplier > 1) {
  548. $total['reward'] = 0;
  549. foreach ($gy_data as $idx => $item) {
  550. $baseReward = floatval(str_replace(',', '', (string)$gy_data[$idx]['节损奖']));
  551. if ($baseReward != 0.0) {
  552. $gy_data[$idx]['节损奖'] = number_format($baseReward * $rewardMultiplier, 4);
  553. }
  554. $total['reward'] += floatval(str_replace(',', '', $gy_data[$idx]['节损奖']));
  555. }
  556. }
  557. $total['reward'] = number_format($total['reward'],2);
  558. $data['gy_data'] = $gy_data;
  559. $data['total'] = $total;
  560. $this->success('请求成功',$data);
  561. }
  562. }
  563. /**
  564. * 获取工单工艺
  565. * @ApiMethod GET
  566. * @params string order
  567. */
  568. public function getOrderGy(){
  569. if (Request::instance()->isGet() == false) {
  570. $this->error('非法请求');
  571. }
  572. $params = Request::instance()->param();
  573. if (!isset($params['order']) || empty($params['order'])) {
  574. $this->error('参数错误');
  575. }
  576. $order = $params['order'];
  577. $field = 'Gy0_yjno,Gy0_gxh,rtrim(Gy0_gxmc) as Gy0_gxmc,rtrim(Add_gxmc) as Add_gxmc,Gy0_rate0,Gy0_rate1,损耗系数,无形损承担比例 as loss_one,超节损承担比例 as loss_two,超节损核算单价 as loss_thr,UniqId';
  578. $data =db('工单_工艺资料')->where('Gy0_gdbh',$order)->where('Gy0_yjno',$params['yjno'])->field($field)->select();
  579. $this->success('请求成功',$data);
  580. }
  581. /**
  582. * 更新工单工艺
  583. * @ApiMethod POST
  584. * @params array data
  585. */
  586. public function updateOrderGy(){
  587. if (Request::instance()->isPost() == false) {
  588. $this->error('非法请求');
  589. }
  590. $params = Request::instance()->post();
  591. if (!isset($params) || !isset($params[0]['UniqId'])){
  592. $this->error('参数不能为空');
  593. }
  594. $i = 0;
  595. foreach ($params as $key=>$value){
  596. $data = [];
  597. $data['无形损承担比例'] = $value['loss_one'];
  598. $data['超节损承担比例'] = $value['loss_two'];
  599. $data['超节损核算单价'] = $value['loss_thr'];
  600. $sql =db('工单_工艺资料')->where('UniqId',$value['UniqId'])->fetchSql(true)->update($data);
  601. $res = Db::query($sql);
  602. if ($res !== false){
  603. $i++;
  604. }
  605. }
  606. if ($i !== 0){
  607. $this->success('更新成功');
  608. }else{
  609. $this->error('更新失败');
  610. }
  611. }
  612. /**
  613. * 获取工单印件考核资料
  614. * @ApiMethod GET
  615. * @params string order
  616. */
  617. public function getOrderYj(){
  618. if (Request::instance()->isGet() == false) {
  619. $this->error('非法请求');
  620. }
  621. $params = Request::instance()->request();
  622. if (!isset($params['order']) || empty($params['order'])) {
  623. $this->error('参数错误');
  624. }
  625. if (!isset($params['yjno']) || empty($params['yjno'])) {
  626. $this->error('参数错误');
  627. }
  628. $data =db('工单_印件资料')
  629. ->where('Yj_gdbh',$params['order'])
  630. ->where('Yj_Yjno', $params['yjno'])
  631. ->field('Yj_gdbh,rtrim(yj_Yjdh) as yj_Yjdh,yj_Yjno,rtrim(yj_yjmc) as yj_yjmc,质量考核')->find();
  632. $this->success('请求成功',$data);
  633. }
  634. /**
  635. * 更新工单印件考核资料
  636. * @ApiMethod POST
  637. * @params array data
  638. */
  639. public function updateOrderYj(){
  640. if ($this->request->isGet() === false){
  641. $this->error('请求错误');
  642. }
  643. $params = $this->request->get();
  644. if (!isset($params['order'])){
  645. $this->error('参数不能为空');
  646. }
  647. if (!isset($params['yj_yjno'])){
  648. $this->error('参数不能为空');
  649. }
  650. if (!isset($params['examine'])){
  651. $this->error('参数不能为空');
  652. }
  653. if ($params['examine'] === '参与'){
  654. $examine = 0;
  655. }else{
  656. $examine = 1;
  657. }
  658. $where['Yj_Gdbh'] = $params['order'];
  659. $where['yj_Yjno'] = $params['yj_yjno'];
  660. $sql =db('工单_印件资料')->where($where)->fetchSql(true)->update(['质量考核'=>$examine]);
  661. $res = \db()->query($sql);
  662. $returnData = $this->OneOrderSuperLoss($where['Yj_Gdbh'],$where['yj_Yjno']);
  663. db('工单_质量考核汇总')
  664. ->where('Gy0_gdbh',$where['Yj_Gdbh'])
  665. ->where('印件及工序',$where['yj_Yjno'])
  666. ->delete();
  667. $sql = db('工单_质量考核汇总')->fetchSql(true)->insertAll($returnData);
  668. $result = db()->query($sql);
  669. if($result===false) $this->error('失败');
  670. if ($res !== false){
  671. $this->success('更新成功');
  672. }else{
  673. $this->error('更新失败');
  674. }
  675. }
  676. /**
  677. * 获取修正工单实际投料列表
  678. * @ApiMethod GET
  679. * @params string year
  680. * @params string month
  681. */
  682. public function getOrderFeedList(){
  683. if (Request::instance()->isGet() == false) {
  684. $this->error('非法请求');
  685. }
  686. $params = Request::instance()->request();
  687. if (empty($params['workorder']) || empty($params['yjno'])) {
  688. $this->error('参数错误');
  689. }
  690. $field = "a.Gd_gdbh,rtrim(c.yj_Yjdh) as yj_yjdh,c.yj_Yjno, c.yj_ks,c.yj_ls,rtrim(c.yj_zzdh) as yj_zzdh,
  691. rtrim(b.BOM_物料名称) as BOM_物料名称,rtrim(c.yj_tlgg) as yj_tlgg,rtrim(d.st_dw) as BOM_投料单位,
  692. a.订单数量,c.yj_平张投料, b.BOM_实际用量,d.st_sl as 实际投料,d.st_oldSl as 原投料,a.投料确认,
  693. d.Uniqid as UniqId,d.mod_number";
  694. $data =db('工单_基本资料')->alias('a')
  695. ->join('工单_印件资料 c','a.Gd_gdbh = c.Yj_Gdbh ','left')
  696. ->join('工单_bom资料 b','c.Yj_Gdbh = b.BOM_工单编号 AND c.yj_zzdh = b.BOM_物料编码','left')
  697. ->join('物料_收发记录 d','a.Gd_gdbh = d.st_gdbh AND d.cpdh = c.yj_Yjdh')
  698. ->where('a.Gd_gdbh',$params['workorder'])
  699. ->where('c.yj_Yjno',$params['yjno'])
  700. ->where(function($query) {
  701. $query->where('d.仓库编号', '101')
  702. ->whereOr('d.仓库编号', 'Y101');})
  703. ->field($field)
  704. ->group('a.Gd_gdbh,d.Uniqid')
  705. ->order('b.BOM_投料单位,a.UniqId asc')
  706. ->select();
  707. if (empty($data)){
  708. $this->success('请求成功');
  709. }
  710. foreach ($data as $key=>$value){
  711. $len = stripos($value['yj_tlgg'],'/');
  712. if ($len){
  713. $name = substr($value['yj_tlgg'],0,$len);
  714. $len_two = stripos($value['yj_tlgg'],'(');
  715. if ($len_two){
  716. $name = substr($name,0,$len_two);
  717. }
  718. $data[$key]['yj_tlgg'] = $name;
  719. }
  720. $data[$key]['rate'] = '';
  721. if (empty($value['原投料'])){
  722. $data[$key]['原投料'] = $value['实际投料'];
  723. }
  724. if ($value['mod_number'] === 0){
  725. $data[$key]['实际投料'] = '';
  726. }
  727. }
  728. $this->success('请求成功',$data);
  729. }
  730. /**
  731. * 更新工单实际投料
  732. * @ApiMethod POST
  733. * @params int UniqId
  734. * @params string number
  735. */
  736. public function updateOrderFeed(){
  737. if (Request::instance()->isPost() == false) {
  738. $this->error('非法请求');
  739. }
  740. $params = Request::instance()->post();
  741. if (!isset($params[0]['UniqId']) || empty($params[0]['UniqId'])){
  742. $this->error('参数错误');
  743. }
  744. $i = 0;
  745. $list = \db('物料_收发记录')->where('Uniqid',$params['0']['UniqId'])->find();
  746. foreach ($params as $key=>$value){
  747. $mod_num = \db('物料_收发记录')
  748. ->where('Uniqid',$value['UniqId'])
  749. ->value('mod_number');
  750. $tl_sql = \db('物料_收发记录')
  751. ->where('Uniqid',$value['UniqId'])
  752. ->fetchSql(true)
  753. ->update(['st_sl'=>$value['number'],'st_oldSl'=>$value['old_number'],'mod_number'=>$mod_num+1,'st_dw' => $value['dw']]);
  754. $tlRes = Db::query($tl_sql);
  755. if (!$tlRes){
  756. $i++;
  757. }
  758. }
  759. $total_num = \db('物料_收发记录')
  760. ->alias('a')
  761. ->field('SUM(a.st_sl) as 投料数量,b.yj_ls,b.yj_ks')
  762. ->join('工单_印件资料 b','a.st_gdbh = b.Yj_Gdbh AND a.cpdh = b.yj_yjdh')
  763. ->where('a.st_gdbh',$list['st_gdbh'])
  764. ->where('a.cpdh',$list['cpdh'])
  765. ->where(function($query) {
  766. $query->where('a.仓库编号', '101')
  767. ->whereOr('a.仓库编号', 'Y101');})
  768. ->find();
  769. $number = $total_num['投料数量']/10000*$total_num['yj_ls']*$total_num['yj_ks'];
  770. $res_sql = db('工单_基本资料')->where('Gd_gdbh',$list['st_gdbh'])->where('Gd_cpdh',$list['cpdh'])->fetchSql(true)->setField('实际投料',$number);
  771. $res = Db::query($res_sql);
  772. $data['yj_实际投料'] = $number;
  773. $yj_sql =db('工单_印件资料')->where('Yj_Gdbh',$list['st_gdbh'])->where('yj_Yjdh',$list['cpdh'])->fetchSql(true)->update($data);
  774. $yjRes = Db::query($yj_sql);
  775. $yjno = db('工单_印件资料')->where('Yj_Gdbh',$list['st_gdbh'])->where('yj_Yjdh',$list['cpdh'])->column('yj_Yjno')[0];
  776. /**
  777. * 重新计算工单超节损数据
  778. **/
  779. $result = $this->OneOrderSuperLoss($list['st_gdbh'],$yjno);
  780. //先删除数据
  781. \db('工单_质量考核汇总')
  782. ->where('Gy0_gdbh',$list['st_gdbh'])
  783. ->where('印件及工序',$yjno)
  784. ->delete();
  785. //插入新数据
  786. $lossSql = \db('工单_质量考核汇总')->fetchSql(true)->insertAll($result);
  787. $lossRes = \db()->query($lossSql);
  788. if ($i != 0 && $lossRes !== false){
  789. $this->success('更新成功');
  790. }else{
  791. $this->error('更新失败');
  792. }
  793. }
  794. /**
  795. * 工单工序产量统计
  796. * @ApiMethod GET
  797. * @params string order
  798. */
  799. public function getOrderProcessCount(){
  800. if (Request::instance()->isGet() == false) {
  801. $this->error('非法请求');
  802. }
  803. $params = Request::instance()->request();
  804. if (empty($params['order']) || empty($params['order'])) {
  805. $this->error('参数错误');
  806. }
  807. if (empty($params['yjno']) || empty($params['yjno'])) {
  808. $this->error('参数错误');
  809. }
  810. $order = $params['order'];
  811. $yjno = $params['yjno'];
  812. $sql = "SELECT a.Gy0_yjno,a.Gy0_gxh,rtrim(a.Gy0_gxmc) as Gy0_gxmc,rtrim(a.Add_gxmc) as Add_gxmc,a.Gy0_计划接货数,
  813. a.Gy0_ls,a.Gy0_sbbh,a.PD_WG,SUM(b.sczl_cl) as sczl_cl,SUM(b.sczl_zcfp) as sczl_zcfp,
  814. SUM(b.sczl_来料少数) as 来料异常,COUNT(DISTINCT b.sczl_num) as process_num,b.sczl_Pgcl,
  815. SUM(c.sczl_cl) as cl,b.sczl_rq,MAX(b.sczl_sj2) as sczl_sj2,rtrim(a.印刷方式) as 印刷方式,rtrim(a.版距) as 版距
  816. FROM `工单_工艺资料` a
  817. LEFT JOIN `设备_产量计酬` b ON a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh
  818. LEFT JOIN db_sczl c ON a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh
  819. WHERE a.Gy0_gdbh = '{$order}' and a.GY0_Yjno = '{$yjno}' GROUP BY a.Gy0_yjno, a.Gy0_gxh ORDER BY a.Gy0_yjno, a.Gy0_gxh";
  820. $data = Db::query($sql);
  821. //手检数据
  822. $handData =db('db_手工检验')->where('sczl_gdbh',$order)->field('sum(sczl_cl) as cl,rtrim(sczl_yjgx) as sczl_gxh')->select();
  823. //包装及成品防护数据
  824. $sql = "SELECT sczl_gdbh1,sczl_gdbh2,sczl_gdbh3,sczl_gdbh4,sczl_gdbh5,sczl_gdbh6,rtrim(sczl_gxmc1) as sczl_gxmc1,rtrim(sczl_gxmc2) as sczl_gxmc2,
  825. rtrim(sczl_gxmc3) as sczl_gxmc3,rtrim(sczl_gxmc4) as sczl_gxmc4,rtrim(sczl_gxmc5) as sczl_gxmc5,rtrim(sczl_gxmc6) as sczl_gxmc6,
  826. sczl_cl1,sczl_cl2,sczl_cl3,sczl_cl4,sczl_cl5,sczl_cl6,sczl_PgCl1,sczl_PgCl2,sczl_PgCl3,sczl_PgCl4,sczl_PgCl5,sczl_PgCl6
  827. FROM `db_包装计件` WHERE `sczl_gdbh1` LIKE '%{$order}%' OR `sczl_gdbh2` LIKE '%{$order}%'
  828. OR `sczl_gdbh3` LIKE '%{$order}%' OR `sczl_gdbh4` LIKE '%{$order}%' OR `sczl_gdbh5` LIKE '%{$order}%' OR `sczl_gdbh6` LIKE '%{$order}%'";
  829. $package = Db::query($sql);
  830. $list = [];
  831. $j = 0;
  832. foreach ($package as $value){
  833. for ($i = 1; $i <= 6; $i++) {
  834. $gdbhlKey = "sczl_gdbh" . $i;
  835. $gxmcKey = "sczl_gxmc" . $i;
  836. $clKey = "sczl_cl" . $i;
  837. $pgclKey = "sczl_PgCl" . $i;
  838. if ($value[$gdbhlKey] == '2311743' && $value[$clKey] > 0) {
  839. $list[$j]['sczl_gdbh'] = $value[$gdbhlKey];
  840. $list[$j]['sczl_gxmc'] = $value[$gxmcKey];
  841. $list[$j]['sczl_cl'] = $value[$clKey];
  842. $list[$j]['sczl_PgCl'] = $value[$pgclKey];
  843. $j++;
  844. }
  845. }
  846. }
  847. // 创建一个关联数组,用于存储相同 sczl_gxmc 的值和对应的乘积之和
  848. $sumArray = [];
  849. foreach ($list as $item) {
  850. $key = $item['sczl_gxmc'];
  851. $cl = floatval($item['sczl_cl']);
  852. $pgCl = intval($item['sczl_PgCl']);
  853. $product = $cl * $pgCl;
  854. if (!isset($sumArray[$key])) {
  855. $sumArray[$key] = 0;
  856. }
  857. $sumArray[$key] += $product;
  858. }
  859. $handGxh = substr($handData[0]['sczl_gxh'],-2);
  860. foreach ($data as $key=>$item){
  861. $data[$key]['折算车头产量'] = $item['Gy0_计划接货数'];
  862. $data[$key]['Gy0_计划接货数'] = $item['Gy0_计划接货数']*$item['Gy0_ls'];
  863. $data[$key]['制程废品率'] = '';
  864. if ($item['sczl_zcfp'] > 0 && $item['sczl_cl']){
  865. $data[$key]['制程废品率'] = number_format($item['sczl_zcfp']/$item['sczl_cl']*100,4).'%';
  866. }
  867. if ($item['cl'] > 0){
  868. $data[$key]['sczl_cl'] = $item['cl'];
  869. }
  870. if ($item['sczl_Pgcl'] > 0){
  871. $data[$key]['sczl_cl'] = $item['sczl_cl'] * $item['sczl_Pgcl'];
  872. }
  873. if ($item['Gy0_gxh'] == (int)$handGxh){
  874. $data[$key]['sczl_cl'] = $handData[0]['cl'];
  875. }
  876. foreach ($sumArray as $k=>$v){
  877. if ($item['Gy0_gxmc'] == $k){
  878. $data[$key]['sczl_cl'] = $v;
  879. }
  880. }
  881. if (substr($item['PD_WG'],0,4) == '1900'){
  882. $data[$key]['PD_WG'] = '计划';
  883. }else{
  884. $data[$key]['PD_WG'] = '完工';
  885. }
  886. //印刷方式为卷对卷时:上报产量/版距*1000;卷对张不换算
  887. if ($item['印刷方式'] === '卷对卷' && (float)$item['版距'] > 0){
  888. $data[$key]['sczl_cl'] = ceil($data[$key]['sczl_cl']/$item['版距']*1000);
  889. $data[$key]['sczl_zcfp'] = ceil($data[$key]['sczl_zcfp']/$item['版距']*1000);
  890. $data[$key]['来料异常'] = ceil($data[$key]['来料异常']/$item['版距']*1000);
  891. }
  892. }
  893. $this->success('请求成功',$data);
  894. }
  895. /**
  896. * 月份员工超节损数据汇总
  897. * @return void
  898. * @throws \think\db\exception\DataNotFoundException
  899. * @throws \think\db\exception\ModelNotFoundException
  900. * @throws \think\exception\DbException
  901. */
  902. public function EmployeeDataCollect()
  903. {
  904. if ($this->request->isPost() === false) {
  905. $this->error('请求错误');
  906. }
  907. $params = $this->request->post();
  908. if (empty($params)) {
  909. $this->error('参数错误');
  910. }
  911. $date = date('Ym', strtotime($params['date']));
  912. $list = \db('工单_质量考核汇总')
  913. ->alias('a')
  914. ->join('工单_印件资料 b', 'a.Gy0_gdbh = b.Yj_Gdbh AND a.印件及工序 = b.yj_Yjno')
  915. ->join('成品入仓 c', 'a.Gy0_gdbh = c.jjcp_gdbh AND a.印件及工序 = c.jjcp_yjno')
  916. ->where('a.sys_ny', $date)
  917. ->where(function ($query) {
  918. $query->where('b.质量考核', 0)
  919. ->whereOr('b.质量考核', null);
  920. })
  921. ->where('c.jjcp_smb', 'like', '末%')
  922. ->select();
  923. $data = [];
  924. foreach ($list as $item) {
  925. $workshop = $item["车间名称"] ?? '';
  926. for ($i = 1; $i <= 8; $i++) {
  927. if (!empty($item["sczl_bh{$i}"]) && $item["sczl_bh{$i}"]!== ''){
  928. $bh = $item["sczl_bh{$i}"] ?? '';
  929. $xm = $item["Xm{$i}"] ?? '';
  930. $rateValue = floatval($item["sczl_rate{$i}"]) ?? '';
  931. // 关键优化:如果分配比例为 0 或空,默认为 1
  932. $rate = (empty($rateValue) || (float)$rateValue == 0) ? 1 : (float)$rateValue;
  933. if (!empty($bh) && $bh !== '') {
  934. $je = round((float)$item["CjsJe"] * $rate, 4);
  935. $data[] = [
  936. "bh" => $bh,
  937. "xm" => $xm,
  938. "je" => (float)number_format($je, 4, '.', ''),
  939. "cj" => $workshop
  940. ];
  941. }
  942. }
  943. }
  944. }
  945. $result = [];
  946. foreach ($data as $item) {
  947. $cj = $item['cj'];
  948. $bh = $item['bh'];
  949. $je = round($item['je'], 2); // 保留两位小数
  950. if (!isset($result[$cj])) {
  951. $result[$cj] = [];
  952. }
  953. if (isset($result[$cj][$bh])) {
  954. $result[$cj][$bh]['je'] += (float)$je;
  955. } else {
  956. $result[$cj][$bh] = [
  957. 'bh' => $bh,
  958. 'xm' => $item['xm'],
  959. 'je' => (float)$je,
  960. 'cj' => $cj
  961. ];
  962. }
  963. }
  964. // 将每个车间的子数组转换为索引数组
  965. foreach ($result as $cjName => &$items) {
  966. $items = array_values($items);
  967. }
  968. $this->success('成功', $result);
  969. }
  970. /**
  971. * 员工月度超节损工序明细
  972. * @ApiMethod (GET)
  973. * @param string $month 月份,202611 或 2026-11
  974. * @param string $code 员工编号
  975. */
  976. public function EmployeeMonthDetail()
  977. {
  978. if (!$this->request->isGet() && !$this->request->isPost()) {
  979. $this->error('请求错误');
  980. }
  981. $params = $this->request->param();
  982. $monthRaw = isset($params['month']) ? trim((string)$params['month']) : '';
  983. if ($monthRaw === '' && isset($params['date'])) {
  984. $monthRaw = trim((string)$params['date']);
  985. }
  986. $code = isset($params['code']) ? trim((string)$params['code']) : '';
  987. if ($code === '' && isset($params['员工编号'])) {
  988. $code = trim((string)$params['员工编号']);
  989. }
  990. $month = str_replace(['-', '/', '.'], '', $monthRaw);
  991. if ($code === '' || !preg_match('/^\d{6}$/', $month)) {
  992. $this->error('参数错误');
  993. }
  994. $holders = [];
  995. $binds = [];
  996. for ($i = 1; $i <= 8; $i++) {
  997. $holders[] = "RTRIM(a.`sczl_bh{$i}`) = :emp{$i}";
  998. $binds['emp' . $i] = $code;
  999. }
  1000. $finalPrint = \db('成品入仓')
  1001. ->where('jjcp_smb', 'in', ['末 板', '末板'])
  1002. ->field('jjcp_gdbh, jjcp_yjno')
  1003. ->group('jjcp_gdbh, jjcp_yjno')
  1004. ->buildSql();
  1005. $rows = \db('工单_质量考核汇总')
  1006. ->alias('a')
  1007. ->join('工单_印件资料 b', 'a.Gy0_gdbh = b.Yj_Gdbh AND a.`印件及工序` = b.yj_Yjno', 'LEFT')
  1008. ->join([$finalPrint => 'c'], 'a.Gy0_gdbh = c.jjcp_gdbh AND a.`印件及工序` = c.jjcp_yjno')
  1009. ->where('a.sys_ny', $month)
  1010. ->whereRaw('(' . implode(' OR ', $holders) . ')', $binds)
  1011. ->field('a.Gy0_gdbh,a.`印件及工序`,a.`工序`,a.`工序名称`,a.CjsJe,a.sczl_bzdh,a.`产品代号`,a.`产品名称`,b.`质量考核`,
  1012. a.sczl_bh1,a.sczl_bh2,a.sczl_bh3,a.sczl_bh4,a.sczl_bh5,a.sczl_bh6,a.sczl_bh7,a.sczl_bh8,
  1013. a.sczl_rate1,a.sczl_rate2,a.sczl_rate3,a.sczl_rate4,a.sczl_rate5,a.sczl_rate6,a.sczl_rate7,a.sczl_rate8,
  1014. a.Xm1,a.Xm2,a.Xm3,a.Xm4,a.Xm5,a.Xm6,a.Xm7,a.Xm8')
  1015. ->order('a.Gy0_gdbh asc,a.印件及工序 asc,a.工序 asc')
  1016. ->select();
  1017. $employeeName = '';
  1018. $processAmount = [];
  1019. if (!empty($rows)) {
  1020. $orders = [];
  1021. foreach ($rows as $row) {
  1022. $orders[$row['Gy0_gdbh']] = $row['Gy0_gdbh'];
  1023. if ($employeeName === '') {
  1024. for ($i = 1; $i <= 8; $i++) {
  1025. if (trim((string)$row['sczl_bh' . $i]) === $code && trim((string)$row['Xm' . $i]) !== '') {
  1026. $employeeName = trim((string)$row['Xm' . $i]);
  1027. break;
  1028. }
  1029. }
  1030. }
  1031. }
  1032. $sumRows = \db('工单_质量考核汇总')
  1033. ->where('sys_ny', $month)
  1034. ->where('Gy0_gdbh', 'in', array_values($orders))
  1035. ->field('Gy0_gdbh,`印件及工序`,`工序`,SUM(CjsJe) AS process_je')
  1036. ->group('Gy0_gdbh,`印件及工序`,`工序`')
  1037. ->select();
  1038. foreach ($sumRows as $sumRow) {
  1039. $key = $sumRow['Gy0_gdbh'] . '|' . trim((string)$sumRow['印件及工序']) . '|' . trim((string)$sumRow['工序']);
  1040. $processAmount[$key] = round((float)$sumRow['process_je'], 2);
  1041. }
  1042. }
  1043. if ($employeeName === '') {
  1044. $employeeName = (string)\db('人事_基本资料')->where('员工编号', $code)->value('rtrim(员工姓名)');
  1045. }
  1046. $groups = [
  1047. '参与考核' => [],
  1048. '不参与考核' => [],
  1049. ];
  1050. foreach ($rows as $row) {
  1051. $rate = 0.0;
  1052. for ($i = 1; $i <= 8; $i++) {
  1053. if (trim((string)$row['sczl_bh' . $i]) !== $code) {
  1054. continue;
  1055. }
  1056. $slotRate = (float)$row['sczl_rate' . $i];
  1057. if ($slotRate == 0.0) {
  1058. $slotRate = 1.0;
  1059. }
  1060. $rate += $slotRate;
  1061. }
  1062. $teamAmount = round((float)$row['CjsJe'], 2);
  1063. $personalAmount = round($teamAmount * $rate, 2);
  1064. $processKey = $row['Gy0_gdbh'] . '|' . trim((string)$row['印件及工序']) . '|' . trim((string)$row['工序']);
  1065. $orderKey = $row['Gy0_gdbh'] . '|' . trim((string)$row['印件及工序']);
  1066. $category = ((string)$row['质量考核'] === '1') ? '不参与考核' : '参与考核';
  1067. if (!isset($groups[$category][$orderKey])) {
  1068. $groups[$category][$orderKey] = [
  1069. '工单编号' => trim((string)$row['Gy0_gdbh']),
  1070. '印件号' => trim((string)$row['印件及工序']),
  1071. '产品代号' => trim((string)$row['产品代号']),
  1072. '产品名称' => trim((string)$row['产品名称']),
  1073. '工序明细' => [],
  1074. ];
  1075. }
  1076. $percent = rtrim(rtrim(number_format($rate * 100, 2, '.', ''), '0'), '.');
  1077. $groups[$category][$orderKey]['工序明细'][] = [
  1078. '工序号' => trim((string)$row['工序']),
  1079. '工序名称' => trim((string)$row['工序名称']),
  1080. '班组' => trim((string)$row['sczl_bzdh']),
  1081. '工序节损金额' => isset($processAmount[$processKey]) ? $processAmount[$processKey] : 0,
  1082. '班组节损金额' => $teamAmount,
  1083. '个人承担比例' => $percent . '%',
  1084. '个人节损金额' => $personalAmount,
  1085. ];
  1086. }
  1087. $assessed = $this->summarizeEmployeeSuperLossOrders($groups['参与考核']);
  1088. $excluded = $this->summarizeEmployeeSuperLossOrders($groups['不参与考核']);
  1089. $this->success('成功', [
  1090. '月份' => $month,
  1091. '员工编号' => $code,
  1092. '员工姓名' => trim($employeeName),
  1093. '参与考核' => $assessed,
  1094. '不参与考核' => $excluded,
  1095. ]);
  1096. }
  1097. /**
  1098. * 员工月度明细按工单归类,并在分类结尾汇总
  1099. * @param array $orders
  1100. * @return array
  1101. */
  1102. private function summarizeEmployeeSuperLossOrders(array $orders)
  1103. {
  1104. $list = array_values($orders);
  1105. $orderCount = count($list);
  1106. $processCount = 0;
  1107. $teamAmount = 0.0;
  1108. $personalAmount = 0.0;
  1109. $processKeys = [];
  1110. $processAmount = 0.0;
  1111. foreach ($list as $order) {
  1112. foreach ($order['工序明细'] as $line) {
  1113. $processCount++;
  1114. $teamAmount += (float)$line['班组节损金额'];
  1115. $personalAmount += (float)$line['个人节损金额'];
  1116. $key = $order['工单编号'] . '|' . $order['印件号'] . '|' . $line['工序号'];
  1117. if (!isset($processKeys[$key])) {
  1118. $processKeys[$key] = true;
  1119. $processAmount += (float)$line['工序节损金额'];
  1120. }
  1121. }
  1122. }
  1123. return [
  1124. '工单' => $list,
  1125. '汇总' => [
  1126. '工单数' => $orderCount,
  1127. '工序数' => $processCount,
  1128. '工序节损金额' => round($processAmount, 2),
  1129. '班组节损金额' => round($teamAmount, 2),
  1130. '个人节损金额' => round($personalAmount, 2),
  1131. ],
  1132. ];
  1133. }
  1134. /**
  1135. * 单条工单超节损计算
  1136. * @param $gdbh
  1137. * @param $yjno
  1138. * @return array
  1139. * @throws \think\db\exception\DataNotFoundException
  1140. * @throws \think\db\exception\ModelNotFoundException
  1141. * @throws \think\exception\DbException
  1142. */
  1143. public function OneOrderSuperLoss($gdbh,$yjno)
  1144. {
  1145. $param = [
  1146. 'gdbh' => $gdbh,
  1147. 'yjno' => $yjno
  1148. ];
  1149. //查询工单入仓数据
  1150. $workOrderData = \db('成品入仓')
  1151. ->where('jjcp_gdbh', $param['gdbh'])
  1152. ->where('jjcp_yjno', $param['yjno'])
  1153. ->where('jjcp_smb', '末 板')
  1154. ->find();
  1155. if (empty($workOrderData)) {
  1156. $this->error('工单' . $param['gdbh'] . '-' . $param['yjno'] . '未查询到末板入仓记录');
  1157. }
  1158. //入仓数量
  1159. $total_number = \db('成品入仓')
  1160. ->where('jjcp_gdbh', $param['gdbh'])
  1161. ->where('jjcp_yjno', $param['yjno'])
  1162. ->column('SUM(jjcp_sl)');
  1163. //查询工单资料、投料数据
  1164. $field = 'a.Gd_gdbh,rtrim(a.成品代号) as 成品代号,rtrim(a.成品名称) as 成品名称,rtrim(a.Gd_客户代号) as Gd_客户代号,
  1165. rtrim(a.Gd_客户名称) as Gd_客户名称,rtrim(a.Gd_cpdh) as Gd_cpdh,rtrim(a.Gd_cpmc) as Gd_cpmc,
  1166. rtrim(a.销售订单号) as 销售订单号,a.订单数量,a.投料大箱,rtrim(a.计量单位) as 计量单位,
  1167. c.yj_ls as ls,c.yj_ks as ks,SUM(b.st_sl) as 投料,
  1168. b.st_dw,c.yj_zzmc,c.yj_tlgg,SUM(b.mod_number) as mod_num';
  1169. $data = db('工单_基本资料')
  1170. ->alias('a')
  1171. ->join('物料_收发记录 b', 'a.Gd_gdbh = b.st_gdbh AND a.Gd_cpdh = b.cpdh')
  1172. ->join('工单_印件资料 c', 'c.Yj_Gdbh = a.Gd_gdbh AND c.yj_Yjdh = a.Gd_cpdh')
  1173. ->where('a.Gd_Gdbh', $param['gdbh'])
  1174. ->where('c.yj_Yjno', $param['yjno'])
  1175. ->where(function ($query) {
  1176. $query->where('b.仓库编号', '101')
  1177. ->whereOr('b.仓库编号', 'Y101');
  1178. })
  1179. ->field($field)
  1180. ->find();
  1181. if ($data['投料'] == null){
  1182. return false;
  1183. }
  1184. if (!empty($data['yj_tlgg'])){
  1185. $number1 = (int)substr($data['yj_tlgg'],0,3);
  1186. $number2 = (int)substr($data['yj_tlgg'],4,3);
  1187. if ($number1 !== 0 && $number2 !== 0) {
  1188. preg_match('/(\d+)g/',$data['yj_zzmc'], $matches);
  1189. if ($data['st_dw'] === '吨'){
  1190. $data['投料'] = round(($data['投料']*1000*1000)/$matches[1]/($number1*$number2)*1000000);
  1191. $data['st_dw'] = '张';
  1192. }
  1193. }
  1194. }
  1195. //将开数、联数为0重新赋值
  1196. if ($data['ls'] == 0) {
  1197. $data['ls'] = 1;
  1198. }
  1199. if ($data['ks'] == 0) {
  1200. $data['ks'] = 1;
  1201. }
  1202. //计算工单实际投料
  1203. $data['实际投料'] = str_replace(',', '', number_format($data['投料'] * $data['ls'] * $data['ks'] / 10000, 4));
  1204. new WorkOrder();
  1205. (new WorkOrder)->PlannedProcessYield($param['gdbh'],$param['yjno'],0,$data['实际投料']*10000/$data['ls']);
  1206. //工单入仓数量
  1207. $data['warehousing_num'] = $total_number[0];
  1208. //截取工单末版的入仓时间
  1209. $data['warehousing_date'] = substr($workOrderData['jjcp_sj'], 0, 10);
  1210. $gxh_values = $this->getSuperLossProcessGxhList($workOrderData['jjcp_gdbh'], $workOrderData['jjcp_yjno']);
  1211. if (empty($gxh_values)) {
  1212. $this->error("工单".$workOrderData['jjcp_gdbh']."-".$workOrderData['jjcp_yjno']."未查询到报工信息,请核查该工单是否已进入超节损");
  1213. }
  1214. $feedQty = floatval($data['实际投料']) * 10000;
  1215. $realRateVal = $feedQty > 0 ? (floatval($total_number[0]) / $feedQty * 100) : 0;
  1216. $data['real_rate'] = number_format($realRateVal, 2) . '%';
  1217. $targetRateVal = 100.0;
  1218. //制程废品
  1219. $zzfp_data = db('设备_产量计酬')
  1220. ->where('sczl_gdbh', $workOrderData['jjcp_gdbh'])
  1221. ->where('sczl_yjno', $workOrderData['jjcp_yjno'])
  1222. ->field('SUM(sczl_zcfp) as sczl_zcfp')
  1223. ->select();
  1224. //制程废品*ls*ks
  1225. $data['zcfp'] = $zzfp_data[0]['sczl_zcfp'] * $data['ls'] * $data['ks'];
  1226. //废品数量
  1227. $wasteTotal = db('db_qczl')
  1228. ->where('qczl_gdbh', $workOrderData['jjcp_gdbh'])
  1229. ->where('qczl_yjno', $workOrderData['jjcp_yjno'])
  1230. ->sum('qczl_fp');
  1231. if (empty($wasteTotal)) {
  1232. $wasteTotal = 0;
  1233. }
  1234. //废品合计=制程废品+核检废品
  1235. $waste_total = $data['zcfp'] + $wasteTotal;
  1236. //工单无形损 = 实际投料-入仓数量-废品合计
  1237. $data['intangible_loss'] = (int)($data['实际投料'] * 10000 - $total_number[0] - $waste_total);
  1238. //查询核检单废品上报数据
  1239. $out_sql = "SELECT qczl_num,fp_sl1,fp_sl2,fp_sl3,fp_sl4,fp_sl5,fp_sl6,fp_sl7,fp_sl8,fp_sl9,fp_sl10,fp_sl11,fp_sl12,fp_sl13,
  1240. fp_lb1,fp_lb2,fp_lb3,fp_lb4,fp_lb5,fp_lb6,fp_lb7,fp_lb8,fp_lb9,fp_lb10,fp_lb11,fp_lb12,fp_lb13,
  1241. fp_bh1,fp_bh2,fp_bh3,fp_bh4,fp_bh5,fp_bh6,fp_bh7,fp_bh8,fp_bh9,fp_bh10,fp_bh11,fp_bh12,fp_bh13,
  1242. fp_bz1,fp_bz2,fp_bz3,fp_bz4,fp_bz5,fp_bz6,fp_bz7,fp_bz8,fp_bz9,fp_bz10,fp_bz11,fp_bz12,fp_bz13,
  1243. fp_gxmc1,fp_gxmc2,fp_gxmc3,fp_gxmc4,fp_gxmc5,fp_gxmc6,fp_gxmc7,fp_gxmc8,fp_gxmc9,fp_gxmc10,fp_gxmc11,fp_gxmc12,fp_gxmc13,UniqId
  1244. FROM db_qczl WHERE qczl_gdbh = '{$workOrderData['jjcp_gdbh']}' AND qczl_yjno = '{$workOrderData['jjcp_yjno']}'";
  1245. $waste_out = Db::query($out_sql);
  1246. $list = []; //外发废数组
  1247. $quality = [];//质检废数组
  1248. $material = [];//材料废数组
  1249. $change = [];//零头处理数组
  1250. $machine = [];//机检废品数组
  1251. $j = 0;
  1252. $m = 0;
  1253. $n = 0;
  1254. $l = 0;
  1255. $o = 0;
  1256. foreach ($waste_out as $entry) {
  1257. for ($i = 1; $i <= 13; $i++) {
  1258. $labelKey = "fp_lb" . $i;
  1259. $bhKey = "fp_bh" . $i;
  1260. $gxmcKey = "fp_gxmc" . $i;
  1261. $slKey = "fp_sl" . $i;
  1262. if (!empty($entry[$labelKey])) {
  1263. //外发加工废
  1264. if (substr($entry[$labelKey],0,3) == 'M04'){
  1265. $list[$j]= $entry[$slKey];
  1266. $j++;
  1267. }
  1268. //材料废
  1269. if (substr($entry[$labelKey],0,1) == 'L' ){
  1270. $material[$n]= $entry[$slKey];
  1271. $n++;
  1272. }
  1273. //零头处理
  1274. if (substr($entry[$labelKey],0,3) == 'M01' ){
  1275. $change[$l]= $entry[$slKey];
  1276. $l++;
  1277. }
  1278. //机检废品
  1279. if (substr($entry[$gxmcKey],0,2) == '01' ){
  1280. $machine[$o]= $entry[$slKey];
  1281. $o++;
  1282. }
  1283. }
  1284. $quality[$m]= $entry[$slKey];
  1285. $m++;
  1286. }
  1287. }
  1288. $data['材料废'] = array_sum($material); //材料废
  1289. $data['零头处理'] = array_sum($change); //零头处理
  1290. $data['外发废'] = array_sum($list);//外发废
  1291. $data['工单质检废'] = array_sum($quality);//质检废
  1292. $data['机检废'] = array_sum($machine);//机检废
  1293. $plan_total = $this->getIntangibleAllocationPlanLossTotal(
  1294. $workOrderData['jjcp_gdbh'],
  1295. $workOrderData['jjcp_yjno'],
  1296. $gxh_values
  1297. );
  1298. $targetRateVal = $this->calcSuperLossTargetQualificationRate(
  1299. $workOrderData['jjcp_gdbh'],
  1300. $workOrderData['jjcp_yjno'],
  1301. $gxh_values,
  1302. $feedQty
  1303. );
  1304. $data['target_rate'] = number_format($targetRateVal, 2) . '%';
  1305. //单据列表最后统计/数据汇总
  1306. $total = [];
  1307. $total['plan_loss'] = 0;
  1308. $total['total_fp'] = 0;
  1309. $total['waste_quality'] = 0;
  1310. $total['waste_intangible'] = 0;
  1311. $total['reward'] = 0; //超节损奖励数组
  1312. $sczlProcessSubForCl = $this->buildSczlProcessAggSubSql();
  1313. //工单产量数据详情查询
  1314. $total_cl_data = \db('工单_工艺资料')->alias('a')
  1315. ->field(['a.Gy0_yjno', 'a.Gy0_gxh', 'rtrim(a.Gy0_gxmc) as gxmc', 'a.Gy0_ls', 'SUM(b.sczl_cl) as total_cl', 'MAX(c.cl) as cl','rtrim(a.印刷方式) as 印刷方式','rtrim(a.版距) as 版距'])
  1316. ->join('设备_产量计酬 b', 'a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh', 'left')
  1317. ->join([$sczlProcessSubForCl => 'c'], 'a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh', 'left')
  1318. ->where([
  1319. 'a.Gy0_gdbh' => $workOrderData['jjcp_gdbh'],
  1320. 'a.Gy0_yjno' => $workOrderData['jjcp_yjno'],
  1321. 'a.Gy0_gxh' => ['IN', $gxh_values],
  1322. ])
  1323. ->group('a.Gy0_gxh')
  1324. ->order('a.Gy0_gxh')
  1325. ->select();
  1326. $payrollTeamSub = $this->buildPayrollTeamAggSubSql();
  1327. $sczlTeamSub = $this->buildSczlTeamAggSubSql();
  1328. $gxmcExpr = $this->processGxmcSqlExpr();
  1329. //按班组分的产量数据
  1330. $gy_data = db('工单_工艺资料')
  1331. ->alias('a')
  1332. ->field([
  1333. 'a.Gy0_gdbh', 'a.Gy0_yjno', 'a.Gy0_gxh', 'a.Gy0_ls', 'a.Gy0_ks', 'a.Gy0_计划损耗', 'a.超节损承担比例',
  1334. $gxmcExpr . ' AS sczl_gxmc', 'b.sczl_zcfp', 'b.total_cl',
  1335. 'b.sczl_bh1', 'b.sczl_bh2', 'b.sczl_bh3', 'b.sczl_bh4', 'b.sczl_bh5', 'b.sczl_bh6',
  1336. 'b.sczl_bh7', 'b.sczl_bh8', 'b.sczl_bh9', 'b.sczl_bh10', 'b.流程单',
  1337. 'b.sczl_bzdh', 'b.sczl_rate1', 'b.sczl_rate2', 'b.sczl_rate3', 'b.sczl_rate4', 'b.sczl_rate5',
  1338. 'b.sczl_rate6', 'b.sczl_rate7', 'b.sczl_rate8', 'b.sczl_rate9', 'b.sczl_rate10',
  1339. 'c.gxmc', 'c.cl', 'c.fp', 'c.sczl_bh1 as sczl_bh',
  1340. 'd.使用部门 as 使用部门', 'c.bzdh', 'b.sczl_jtbh', 'a.损耗系数', 'a.Gy0_ms', 'a.Gy0_Rate0',
  1341. 'a.Gy0_Rate1', 'a.无形损承担比例', 'a.Gy0_计划接货数*a.Gy0_ls*a.Gy0_ks as 计划产量',
  1342. 'rtrim(a.Gy0_SITE) as Gy0_SITE',
  1343. 'rtrim(a.印刷方式) as 印刷方式', 'rtrim(a.版距) as 版距',
  1344. ])
  1345. ->join([$payrollTeamSub => 'b'], 'a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh', 'left')
  1346. ->join([$sczlTeamSub => 'c'], 'a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh AND IFNULL(b.sczl_bh1,\'\') = IFNULL(c.sczl_bh1,\'\')', 'left')
  1347. ->join('设备_基本资料 d', 'd.设备编号 = b.sczl_jtbh', 'left')
  1348. ->where([
  1349. 'a.Gy0_gdbh' => $workOrderData['jjcp_gdbh'],
  1350. 'a.Gy0_yjno' => $workOrderData['jjcp_yjno'],
  1351. 'a.Gy0_gxh' => ['in', $gxh_values],
  1352. ])
  1353. ->order('a.Gy0_gxh asc, b.开工时间 asc')
  1354. ->select();
  1355. $gy_data = $this->appendMissingSuperLossProcessRows(
  1356. $gy_data,
  1357. $gxh_values,
  1358. $workOrderData['jjcp_gdbh'],
  1359. $workOrderData['jjcp_yjno']
  1360. );
  1361. $gy_data = $this->expandSczlMultiTeamRows(
  1362. $gy_data,
  1363. $workOrderData['jjcp_gdbh'],
  1364. $workOrderData['jjcp_yjno']
  1365. );
  1366. $sumBz = [];
  1367. foreach ($gy_data as $kk => $vv){
  1368. //每道工序的产量(按班组分)
  1369. $vv['total_cl'] = $vv['total_cl'] * $vv['Gy0_ls'] * $vv['Gy0_ks'];
  1370. if (empty($vv['total_cl'])) {
  1371. $vv['total_cl'] = $vv['cl'] * $vv['Gy0_ls'] * $vv['Gy0_ks'];
  1372. }
  1373. if (empty($vv['sczl_bh1'])) {
  1374. $vv['sczl_bh1'] = $vv['sczl_bh'] ?? '';
  1375. }
  1376. if (isset($sumBz[$vv['sczl_bh1'].'-'.$vv['Gy0_gxh']])){
  1377. $sumBz[$vv['sczl_bh1'].'-'.$vv['Gy0_gxh']] += $vv['total_cl'];
  1378. }else{
  1379. $sumBz[$vv['sczl_bh1'].'-'.$vv['Gy0_gxh']] = $vv['total_cl'];
  1380. }
  1381. }
  1382. foreach ($gy_data as $kk => $vv) {
  1383. $this->fillSczlTeamMemberFields(
  1384. $gy_data[$kk],
  1385. $workOrderData['jjcp_gdbh'],
  1386. $workOrderData['jjcp_yjno']
  1387. );
  1388. $vv = $gy_data[$kk];
  1389. $rawQty = $vv['total_cl'];
  1390. if (empty($rawQty)) {
  1391. $rawQty = $vv['cl'];
  1392. }
  1393. $wasteBase = (float)$rawQty * $vv['Gy0_ls'] * $vv['Gy0_ks'];
  1394. $gy_data[$kk]['total_cl'] = $this->superLossSheetQty(
  1395. $rawQty,
  1396. $vv['Gy0_ls'],
  1397. $vv['Gy0_ks'],
  1398. $vv['印刷方式'],
  1399. $vv['版距']
  1400. );
  1401. $gy_data[$kk]['Gy0_计划损耗'] = $vv['Gy0_计划损耗'] * $vv['Gy0_ls'] * $vv['Gy0_ks'];
  1402. $vv['Gy0_计划损耗'] = $gy_data[$kk]['Gy0_计划损耗'];
  1403. //每道工序的制程废品(按班组分)
  1404. $gy_data[$kk]['sczl_zcfp'] = $vv['sczl_zcfp'] * $vv['Gy0_ls'];
  1405. if (empty($vv['sczl_zcfp'])) {
  1406. $gy_data[$kk]['sczl_zcfp'] = $vv['fp'] * $vv['Gy0_ls'];
  1407. }
  1408. //计算每道工序的质检废(按班组)
  1409. $gy_data[$kk]['sczl_gxmc'] = $vv['sczl_gxmc'];
  1410. if (empty($vv['sczl_gxmc'])) {
  1411. $gy_data[$kk]['sczl_gxmc'] = $vv['gxmc'];
  1412. }
  1413. if (empty($vv['sczl_bh1']) || is_null($vv['sczl_bh1'])) {
  1414. $vv['sczl_bh1'] = $vv['sczl_bh'] ?? '';
  1415. }
  1416. $gy_data[$kk]['sczl_bh1'] = $vv['sczl_bh1'];
  1417. $gy_data[$kk]['质检废'] = 0;
  1418. $gy_data[$kk]['zjfp'] = 0;
  1419. foreach ($waste_out as $entry) {
  1420. for ($i = 1; $i <= 13; $i++) {
  1421. $gxmcKey = "fp_gxmc" . $i;
  1422. $gxlbKey = "fp_lb" . $i;
  1423. $slKey = "fp_sl" . $i;
  1424. $bhKey = "fp_bh" . $i;
  1425. if ((int)substr($entry[$gxmcKey], 0, 2) == $vv['Gy0_gxh'] && $entry[$bhKey] == $vv['sczl_bh1']) {
  1426. $gy_data[$kk]['zjfp'] += $entry[$slKey];
  1427. }
  1428. }
  1429. }
  1430. $teamKey = $vv['sczl_bh1'] . '-' . $vv['Gy0_gxh'];
  1431. $teamTotal = $sumBz[$teamKey] ?? 0;
  1432. if ($teamTotal > 0) {
  1433. $gy_data[$kk]['质检废'] = round($gy_data[$kk]['zjfp'] * ($wasteBase / $teamTotal));
  1434. } else {
  1435. $gy_data[$kk]['质检废'] = (int)$gy_data[$kk]['zjfp'];
  1436. }
  1437. if ($this->isMachineInspectionProcess((string)$gy_data[$kk]['sczl_gxmc'])) {
  1438. $gy_data[$kk]['质检废'] = 0;
  1439. $gy_data[$kk]['zjfp'] = 0;
  1440. $gy_data[$kk]['sczl_zcfp'] = 0;
  1441. }
  1442. //班组成员
  1443. for ($j = 1; $j <= 10; $j++) {
  1444. $bhKey = "sczl_bh" . $j;
  1445. if (!empty($vv[$bhKey])) {
  1446. $name = \db('人事_基本资料')->where('员工编号', $vv[$bhKey])->value('rtrim(员工姓名)');
  1447. $gy_data[$kk]['sczl_name' . $j] = $name;
  1448. } else {
  1449. $gy_data[$kk]['sczl_name' . $j] = '';
  1450. }
  1451. }
  1452. //工序产量
  1453. foreach ($total_cl_data as $k => $v) {
  1454. $banju1 = (float)$v['版距'] / 1000;
  1455. if (trim((string)$v['印刷方式']) === '卷对卷' && $banju1 > 0) {
  1456. $v['total_cl'] = $v['total_cl'] / $banju1;
  1457. }
  1458. if ($v['Gy0_yjno'] === $vv['Gy0_yjno'] && $v['Gy0_gxh'] === $vv['Gy0_gxh']) {
  1459. if (strpos($v['gxmc'], '拆片') !== false) {
  1460. $gy_data[$kk]['工序产量'] = $v['cl'] * $vv['Gy0_ls'] * $vv['Gy0_ks'];
  1461. } else {
  1462. $gy_data[$kk]['工序产量'] = $v['total_cl'] * $vv['Gy0_ls'] * $vv['Gy0_ks'];
  1463. }
  1464. }
  1465. }
  1466. unset($gy_data[$kk]['gxmc']);
  1467. unset($gy_data[$kk]['cl']);
  1468. unset($gy_data[$kk]['fp']);
  1469. unset($gy_data[$kk]['sczl_bh']);
  1470. unset($gy_data[$kk]['bzdh']);
  1471. }
  1472. $this->allocateSuperLossPlanShare($gy_data, 'total_cl', 'Gy0_计划损耗', '计划损耗', 'Gy0_gxh');
  1473. $this->assignIntangibleLossToGyDataRows(
  1474. $gy_data,
  1475. $workOrderData['jjcp_gdbh'],
  1476. $workOrderData['jjcp_yjno'],
  1477. $gxh_values,
  1478. floatval($data['intangible_loss'])
  1479. );
  1480. $guige = \db('物料_存货编码')
  1481. ->where('物料代码', $data['成品代号'])
  1482. ->value('rtrim(规格)');
  1483. $moneyRate = (strpos((string)$guige, '小盒') !== false) ? 0.02 : 0.09;
  1484. //计算超节损金额(工序合计不变,节损数和金额按班组行分摊,尾差补到该工序最后一行)
  1485. foreach ($gy_data as $n => $item) {
  1486. $gy_data[$n]['sys_ny'] = date('Ym', strtotime($workOrderData['jjcp_sj']));
  1487. $gy_data[$n]['超节损核算单价'] = $moneyRate;
  1488. $total['plan_loss'] += $item['计划损耗'];
  1489. $total['total_fp'] += $item['sczl_zcfp'];
  1490. $total['waste_quality'] += $item['质检废'];
  1491. $total['waste_intangible'] += $item['无形损分摊'];
  1492. }
  1493. $processGxSummary = [];
  1494. foreach ($gy_data as $n => $item) {
  1495. $gk = $this->normalizeGxhKey($item['Gy0_gxh']);
  1496. if ($gk === '') {
  1497. continue;
  1498. }
  1499. if (!isset($processGxSummary[$gk])) {
  1500. $processGxSummary[$gk] = [
  1501. 'plan_loss' => (int)$item['Gy0_计划损耗'],
  1502. 'zcfp' => 0,
  1503. 'zj' => 0,
  1504. 'intangible' => 0,
  1505. 'row_indexes' => [],
  1506. 'gxmc' => $item['sczl_gxmc'],
  1507. 'ratio' => $item['超节损承担比例'],
  1508. ];
  1509. }
  1510. $processGxSummary[$gk]['zcfp'] += (int)$item['sczl_zcfp'];
  1511. $processGxSummary[$gk]['zj'] += (int)$item['质检废'];
  1512. $processGxSummary[$gk]['intangible'] += (int)$item['无形损分摊'];
  1513. $processGxSummary[$gk]['row_indexes'][] = $n;
  1514. }
  1515. $rewardMultiplier = $this->resolveSuperLossRewardMultiplier(
  1516. $targetRateVal,
  1517. $realRateVal,
  1518. floatval($data['材料废'] ?? 0),
  1519. $feedQty,
  1520. (string)$workOrderData['jjcp_gdbh'],
  1521. $workOrderData['jjcp_yjno']
  1522. );
  1523. $data['reward_rate'] = $this->stringifyRewardMultiplier($rewardMultiplier);
  1524. $total['reward'] = 0;
  1525. foreach ($processGxSummary as $summary) {
  1526. $machine = $this->isMachineInspectionProcess((string)$summary['gxmc']);
  1527. $excluded = $this->isSuperLossRewardExcluded((string)$summary['gxmc']);
  1528. if ($machine) {
  1529. $processCjsSl = $summary['plan_loss'] - $summary['intangible'];
  1530. } else {
  1531. $totalWaste = $summary['zcfp'] + $summary['zj'] + $summary['intangible'];
  1532. $processCjsSl = $summary['plan_loss'] - $totalWaste;
  1533. }
  1534. if ($excluded) {
  1535. $processCjsJe = 0.0;
  1536. } else {
  1537. $processCjsJe = $processCjsSl * floatval($summary['ratio']) * $moneyRate;
  1538. }
  1539. if ($rewardMultiplier > 1 && $processCjsJe != 0.0) {
  1540. $processCjsJe *= $rewardMultiplier;
  1541. }
  1542. $processCjsJe = round($processCjsJe, 4);
  1543. $indexes = $summary['row_indexes'];
  1544. $last = count($indexes) - 1;
  1545. $rowSl = [];
  1546. $slSum = 0;
  1547. foreach ($indexes as $idx => $n) {
  1548. $item = $gy_data[$n];
  1549. $rowWaste = (int)$item['sczl_zcfp'] + (int)$item['质检废'] + (int)$item['无形损分摊'];
  1550. $rowSl[$idx] = (int)$item['计划损耗'] - $rowWaste;
  1551. $slSum += $rowSl[$idx];
  1552. }
  1553. $rowSl[$last] += $processCjsSl - $slSum;
  1554. $rowJe = [];
  1555. $jeSum = 0.0;
  1556. foreach ($indexes as $idx => $n) {
  1557. if ($excluded) {
  1558. $je = 0.0;
  1559. } else {
  1560. $je = $rowSl[$idx] * floatval($summary['ratio']) * $moneyRate;
  1561. if ($rewardMultiplier > 1 && $je != 0.0) {
  1562. $je *= $rewardMultiplier;
  1563. }
  1564. }
  1565. $rowJe[$idx] = round($je, 4);
  1566. $jeSum += $rowJe[$idx];
  1567. }
  1568. $rowJe[$last] = round($rowJe[$last] + ($processCjsJe - round($jeSum, 4)), 4);
  1569. foreach ($indexes as $idx => $n) {
  1570. $gy_data[$n]['节损数量'] = $rowSl[$idx];
  1571. $gy_data[$n]['节损奖'] = number_format($rowJe[$idx], 4);
  1572. $total['reward'] += $rowJe[$idx];
  1573. }
  1574. }
  1575. //整合数据
  1576. //本次判定的追溯字段快照(表无对应列时为空数组)
  1577. $ruleValues = $this->superLossRuleValues($this->superLossRewardRule);
  1578. $result = [];
  1579. foreach ($gy_data as $key => $value) {
  1580. $result[$key] = [
  1581. 'sys_ny' => $value['sys_ny'],
  1582. 'Gy0_gdbh' => $value['Gy0_gdbh'],
  1583. '印件及工序' => $value['Gy0_yjno'],
  1584. '工序' => $value['Gy0_gxh'],
  1585. '工序名称' => $value['sczl_gxmc'],
  1586. '联数' => $value['Gy0_ls'],
  1587. '基础损耗' => $value['Gy0_Rate0'],
  1588. '损耗率' => $value['Gy0_Rate1'],
  1589. '损耗系数' => $value['损耗系数'],
  1590. '计损色数' => $value['Gy0_ms'],
  1591. '计划产量' => $value['计划产量'],
  1592. '计划损耗' => $value['Gy0_计划损耗'],
  1593. '班组分摊计划损耗' => $value['计划损耗'],
  1594. '印件工序产量' => $value['工序产量'],
  1595. '班组产量' => $value['total_cl'],
  1596. '班组制程废品' => $value['sczl_zcfp'],
  1597. '工单质检废' => $data['工单质检废'],
  1598. '班组质检废品' => $value['zjfp'],
  1599. '班组分摊质检废品' => $value['质检废'],
  1600. '无班组废品' => 0,
  1601. '外发废' => $data['外发废'],
  1602. '材料废' => $data['材料废'],
  1603. '零头处理' => $data['零头处理'],
  1604. '分摊废' => 0,
  1605. '分摊废明细' => 0,
  1606. '印件无形损' => $data['intangible_loss'],
  1607. '班组分摊无形损' => $value['无形损分摊'],
  1608. 'CjsSl' => $value['节损数量'],
  1609. 'CjsJe' => str_replace(",", "", $value['节损奖']),
  1610. '无形损承担比例' => $value['无形损承担比例'],
  1611. '超节损承担比例' => $value['超节损承担比例'],
  1612. '超节损核算单价' => $value['超节损核算单价'],
  1613. 'sczl_jtbh' => $value['sczl_jtbh'],
  1614. 'sczl_bzdh' => $value['sczl_bzdh'],
  1615. 'sczl_bh1' => $value['sczl_bh1'],
  1616. 'sczl_bh2' => $value['sczl_bh2'],
  1617. 'sczl_bh3' => $value['sczl_bh3'],
  1618. 'sczl_bh4' => $value['sczl_bh4'],
  1619. 'sczl_bh5' => $value['sczl_bh5'],
  1620. 'sczl_bh6' => $value['sczl_bh6'],
  1621. 'sczl_bh7' => $value['sczl_bh7'],
  1622. 'sczl_bh8' => $value['sczl_bh8'],
  1623. 'Xm1' => $value['sczl_name1'],
  1624. 'Xm2' => $value['sczl_name2'],
  1625. 'Xm3' => $value['sczl_name3'],
  1626. 'Xm4' => $value['sczl_name4'],
  1627. 'Xm5' => $value['sczl_name5'],
  1628. 'Xm6' => $value['sczl_name6'],
  1629. 'Xm7' => $value['sczl_name7'],
  1630. 'Xm8' => $value['sczl_name8'],
  1631. 'sczl_rate1' => $value['sczl_rate1'],
  1632. 'sczl_rate2' => $value['sczl_rate2'],
  1633. 'sczl_rate3' => $value['sczl_rate3'],
  1634. 'sczl_rate4' => $value['sczl_rate4'],
  1635. 'sczl_rate5' => $value['sczl_rate5'],
  1636. 'sczl_rate6' => $value['sczl_rate6'],
  1637. 'sczl_rate7' => $value['sczl_rate7'],
  1638. 'sczl_rate8' => $value['sczl_rate8'],
  1639. '类型' => '',
  1640. '客户代号' => $data['Gd_客户代号'] ?? '',
  1641. '客户名称' => $data['Gd_客户名称'] ?? '',
  1642. '产品代号' => $data['Gd_cpdh'] ?? $data['成品代号'],
  1643. '产品名称' => $data['Gd_cpmc'] ?? $data['成品名称'],
  1644. '销售订单号' => $data['销售订单号'],
  1645. '订单数量' => $data['订单数量'],
  1646. '计量单位' => $data['计量单位'] ?? '',
  1647. '实际投料' => $data['实际投料'],
  1648. '入仓数量' => $total_number[0],
  1649. '入仓日期' => $workOrderData['jjcp_sj'],
  1650. '大箱数' => $data['投料大箱'] ?? '',
  1651. '废品合计' => $data['工单质检废'] + $data['zcfp'],
  1652. 'sys_id' => '',
  1653. 'sys_rq' => date('Y-m-d H:i:s', time()),
  1654. '车间名称' => $value['Gy0_SITE']
  1655. ];
  1656. //追加倍率追溯字段(reward_multiplier/reward_tier/target_rate_bp/... 仅当表已执行 DDL 时写入)
  1657. if (!empty($ruleValues)) {
  1658. $result[$key] = array_merge($result[$key], $ruleValues);
  1659. }
  1660. }
  1661. return $result;
  1662. }
  1663. /**
  1664. * 写入超节损核算结果(队列 OrderSuperLossJob / OrderLossQueueWorker 等调用)
  1665. *
  1666. * @param string $gdbh 工单编号
  1667. * @param string $yjno 印件号
  1668. * @param array $rows OneOrderSuperLoss 返回的行数据
  1669. * @return bool
  1670. */
  1671. public function saveSuperLossResult($gdbh, $yjno, array $rows)
  1672. {
  1673. $gdbh = trim((string)$gdbh);
  1674. $yjno = trim((string)$yjno);
  1675. if ($gdbh === '' || $yjno === '' || empty($rows)) {
  1676. return false;
  1677. }
  1678. //只保留表里真实存在的列,避免生产未执行 DDL 时写入 reward_* 等新字段报 Unknown column
  1679. $columns = $this->superLossRuleColumns();
  1680. if (!empty($columns)) {
  1681. $allowed = array_flip($columns);
  1682. foreach ($rows as $idx => $row) {
  1683. $rows[$idx] = array_intersect_key($row, $allowed);
  1684. }
  1685. }
  1686. foreach ($rows as $idx => $row) {
  1687. for ($r = 1; $r <= 8; $r++) {
  1688. $key = 'sczl_rate' . $r;
  1689. if (!isset($row[$key]) || $row[$key] === '' || $row[$key] === null) {
  1690. $rows[$idx][$key] = 0;
  1691. }
  1692. }
  1693. }
  1694. //先删后插必须在一个事务内,避免中途失败导致工单核算结果整体丢失
  1695. Db::startTrans();
  1696. try {
  1697. db('工单_质量考核汇总')
  1698. ->where('Gy0_gdbh', $gdbh)
  1699. ->where('印件及工序', $yjno)
  1700. ->delete();
  1701. //分批插入,避免单条 SQL 过大(一个工单可能几十行、几十列)
  1702. foreach (array_chunk($rows, 500) as $chunk) {
  1703. $res = db('工单_质量考核汇总')->insertAll($chunk);
  1704. if ($res === false) {
  1705. throw new \RuntimeException('insertAll 返回 false');
  1706. }
  1707. }
  1708. Db::commit();
  1709. return true;
  1710. } catch (\Throwable $e) {
  1711. Db::rollback();
  1712. Log::error('超节损-写入质量考核汇总失败: ' . $e->getMessage() . '; gdbh=' . $gdbh . ', yjno=' . $yjno);
  1713. return false;
  1714. }
  1715. }
  1716. /**
  1717. * 超节损列表
  1718. * @return void
  1719. * @throws \think\db\exception\DataNotFoundException
  1720. * @throws \think\db\exception\ModelNotFoundException
  1721. * @throws \think\exception\DbException
  1722. */
  1723. public function getList()
  1724. {
  1725. if (!Request::instance()->isGet()) {
  1726. $this->error('非法请求');
  1727. }
  1728. $params = Request::instance()->param();
  1729. $where = [];
  1730. // 设置默认分页和限制
  1731. $limit = empty($params['limit']) ? 15 : intval($params['limit']);
  1732. $pages = empty($params['page']) ? 1 : intval($params['page']);
  1733. // 构建查询条件
  1734. if (!empty($params['code'])) {
  1735. // 根据产品代号是否含有字母确定匹配长度
  1736. $prefixLength = preg_match('/[A-Za-z]/', $params['code']) ? 5 : 4;
  1737. $where['a.jjcp_cpdh'] = ['LIKE', substr($params['code'], 0, $prefixLength) . '%'];
  1738. }
  1739. if (!empty($params['date'])) {
  1740. $year = substr($params['date'], 0, 4); // 取前4位作为年份
  1741. $month = substr($params['date'], 4, 2); // 取后2位作为月份
  1742. // 格式化为需要的值
  1743. $formattedDate = $year . '-' . $month;
  1744. $where['a.jjcp_sj'] = ['like',$formattedDate.'%'];
  1745. }
  1746. if (!empty($params['search'])) {
  1747. if (!empty($params['date']) || !empty($params['code'])) {
  1748. $this->error('参数错误');
  1749. }
  1750. $where['a.jjcp_gdbh|a.jjcp_cpdh|a.jjcp_cpmc'] = ['like', '%' . $params['search'] . '%'];
  1751. }
  1752. // 定义字段
  1753. $field = '
  1754. b.sys_ny,
  1755. a.jjcp_gdbh AS Gd_gdbh,
  1756. a.jjcp_yjno AS jjcp_yjno,
  1757. a.jjcp_yjno AS yj_Yjno,
  1758. c.yj_Yjdh as yjdh,
  1759. c.yj_ls AS yj_ls,
  1760. c.yj_cpdh AS 成品编码,
  1761. c.yj_yjmc AS 成品名称,
  1762. b.`实际投料`,
  1763. b.`计量单位`,
  1764. DATE(a.jjcp_sj) AS warehousing_date,
  1765. total_sl.warehousing_num,
  1766. SUM(DISTINCT b.`计划损耗`) AS `工单计划损耗`,
  1767. b.`废品合计`,
  1768. SUM(b.`CjsJe`) AS reward_money,
  1769. b.`印件无形损` AS 工单无形损,
  1770. b.`材料废`,
  1771. b.`零头处理`,
  1772. b.`外发废`,
  1773. SUM(b.`班组制程废品`) AS zcfp,
  1774. `工单质检废` AS 工单质检废,
  1775. c.质量考核,
  1776. IFNULL(cs.索赔合计, 0) AS 材料索赔
  1777. ';
  1778. //优先读取核算时落库的倍率/目标合格率(表未执行 DDL 时不拼接,自动回退旧口径)
  1779. $ruleFields = $this->superLossRuleFields();
  1780. $extraFields = [];
  1781. if (in_array('reward_multiplier', $ruleFields, true)) {
  1782. $extraFields[] = 'MAX(b.`reward_multiplier`) AS reward_multiplier';
  1783. }
  1784. if (in_array('target_rate_bp', $ruleFields, true)) {
  1785. $extraFields[] = 'MAX(b.`target_rate_bp`) AS target_rate_bp';
  1786. }
  1787. if (!empty($extraFields)) {
  1788. $field = rtrim(trim($field), ',') . ",\n " . implode(",\n ", $extraFields) . ' ';
  1789. }
  1790. // 子查询:计算所有记录的 jjcp_sl 总和(入仓数量)
  1791. $subQuery = \db('成品入仓')
  1792. ->alias('a_sub')
  1793. ->field('
  1794. a_sub.jjcp_gdbh AS Gd_gdbh_sub,
  1795. a_sub.jjcp_yjno AS jjcp_yjno_sub,
  1796. SUM(a_sub.jjcp_sl) AS warehousing_num
  1797. ')
  1798. ->group('a_sub.jjcp_gdbh, a_sub.jjcp_yjno')
  1799. ->buildSql();
  1800. // 子查询:材料索赔合计(按 工单编号+印件号 汇总 工单_索赔记录.num)
  1801. $claimSub = \db('工单_索赔记录')
  1802. ->alias('cl')
  1803. ->field('
  1804. cl.gdbh AS claim_gdbh,
  1805. cl.yjno AS claim_yjno,
  1806. SUM(cl.num) AS 索赔合计
  1807. ')
  1808. ->group('cl.gdbh, cl.yjno')
  1809. ->buildSql();
  1810. $list = \db('成品入仓')
  1811. ->alias('a')
  1812. ->join('工单_质量考核汇总 b','a.jjcp_gdbh = b.Gy0_gdbh AND a.jjcp_yjno = b.印件及工序','left')
  1813. ->join('工单_印件资料 c','a.jjcp_gdbh = c.Yj_Gdbh AND a.jjcp_yjno = c.yj_Yjno')
  1814. ->join([$subQuery => 'total_sl'], 'a.jjcp_gdbh = total_sl.Gd_gdbh_sub AND a.jjcp_yjno = total_sl.jjcp_yjno_sub', 'left')
  1815. ->join([$claimSub => 'cs'], 'a.jjcp_gdbh = cs.claim_gdbh AND a.jjcp_yjno = cs.claim_yjno', 'left')
  1816. ->field($field)
  1817. ->where($where)
  1818. ->where('a.jjcp_smb','like','末%')
  1819. ->group('Gd_gdbh,jjcp_yjno')
  1820. ->order('warehousing_date DESC')
  1821. ->page($pages)
  1822. ->limit($limit)
  1823. ->select();
  1824. // 处理查询结果
  1825. foreach ($list as $key => $value) {
  1826. $status = \db('工单_印件资料')
  1827. ->where('Yj_Gdbh', $value['Gd_gdbh'])
  1828. ->where('yj_Yjno', $value['jjcp_yjno'])
  1829. ->value('质量考核');
  1830. $processDetail = \db('工单_工艺资料')
  1831. ->where('Gy0_gdbh', $value['Gd_gdbh'])
  1832. ->where('Gy0_yjno', $value['jjcp_yjno'])
  1833. ->field('CONCAT(rtrim(Gy0_gxmc),"[",rtrim(Add_gxmc),"]") as 工序名称,Gy0_ls as 联数')
  1834. ->select();
  1835. $number1 = $number2 = 1;
  1836. foreach ($processDetail as $k => $v) {
  1837. if (strpos($v['工序名称'],'分切') !== false) {
  1838. $number1 = $v['联数'];
  1839. }
  1840. if (strpos($v['工序名称'],'分切') === false && $v['联数'] > 1) {
  1841. $number2 = $v['联数'];
  1842. }
  1843. }
  1844. $Multiple = $number1/$number2;
  1845. if (is_int($Multiple) === false) {
  1846. $Multiple = 1;
  1847. }
  1848. $list[$key]['工单质检废'] = $value['废品合计'] - $value['zcfp'];
  1849. $list[$key]['质量考核'] = $status;
  1850. $list[$key]['考核'] = ($status == 1) ? '否' : '是';
  1851. if ($value['实际投料'] !== null){
  1852. $actualMaterial = $value['实际投料'] * 10000;
  1853. $gxhValues = $this->getSuperLossProcessGxhList($value['Gd_gdbh'], $value['jjcp_yjno']);
  1854. $list[$key]['target_rate'] = number_format(
  1855. $this->calcTargetRateBp($value['Gd_gdbh'], $value['jjcp_yjno'], $gxhValues, $actualMaterial) / 100,
  1856. 2
  1857. ) . '%';
  1858. $list[$key]['real_rate'] = $value['warehousing_num']/($value['实际投料']*10000)*100;
  1859. $list[$key]['real_rate'] = number_format($list[$key]['real_rate'], 2).'%';
  1860. }else{
  1861. $list[$key]['target_rate'] = null;
  1862. $list[$key]['real_rate'] = null;
  1863. }
  1864. //倍率读库(未核算过时显示 1)
  1865. $list[$key]['reward_rate'] = isset($value['reward_multiplier']) && $value['reward_multiplier'] !== null
  1866. ? $this->stringifyRewardMultiplier($value['reward_multiplier'])
  1867. : '1';
  1868. }
  1869. if (!empty($list)) {
  1870. $this->success('成功', $list);
  1871. } else {
  1872. $this->error('未找到数据');
  1873. }
  1874. }
  1875. // 计算合格率
  1876. private function calculateRate($actual, $loss)
  1877. {
  1878. if ($actual == 0) {
  1879. return '0.00%'; // 防止除以零
  1880. }
  1881. $rate = ($actual - $loss) / $actual * 100;
  1882. return number_format($rate, 2) . '%';
  1883. }
  1884. /**
  1885. * 工序超节损
  1886. * @return void
  1887. * @throws \think\db\exception\DataNotFoundException
  1888. * @throws \think\db\exception\ModelNotFoundException
  1889. * @throws \think\exception\DbException
  1890. */
  1891. public function ProcessLoss()
  1892. {
  1893. if ($this->request->isGet() === false){
  1894. $this->error('请求错误');
  1895. }
  1896. $param = $this->request->param();
  1897. if (empty($param) || empty($param['order']) || empty($param['yjno'])){
  1898. $this->error('参数错误');
  1899. }
  1900. $where = ['Gy0_gdbh'=>$param['order'],'印件及工序'=>$param['yjno']];
  1901. //查询订单印件数据
  1902. $field = '
  1903. Gy0_gdbh AS Gd_gdbh,
  1904. `印件及工序` AS yjno,
  1905. `联数` AS ls,
  1906. `产品代号` AS `成品代号`,
  1907. `产品名称` AS `成品名称`,
  1908. `实际投料`,
  1909. `计量单位`,
  1910. DATE(`入仓日期`) AS warehousing_date,
  1911. `入仓数量` AS warehousing_num,
  1912. SUM(DISTINCT `计划损耗`) AS `计划损耗`,
  1913. `废品合计`,
  1914. `印件无形损` as intangible_loss,
  1915. `材料废`,
  1916. `零头处理`,
  1917. `外发废`,
  1918. SUM(`班组制程废品`) AS `zcfp`,
  1919. `工单质检废` AS `班组分摊质检废品`,
  1920. `订单数量`,
  1921. `销售订单号`
  1922. ';
  1923. $list = \db('工单_质量考核汇总')
  1924. ->field($field)
  1925. ->where($where)
  1926. ->group('Gy0_gdbh, `印件及工序`')
  1927. ->order('sys_rq DESC')
  1928. ->find();
  1929. $processDetail = \db('工单_工艺资料')
  1930. ->where('Gy0_gdbh', $param['order'])
  1931. ->where('Gy0_yjno', $param['yjno'])
  1932. ->field('CONCAT(rtrim(Gy0_gxmc),"[",rtrim(Add_gxmc),"]") as 工序名称,Gy0_ls as 联数')
  1933. ->select();
  1934. $status = \db('工单_印件资料')
  1935. ->where('Yj_Gdbh', $param['order'])
  1936. ->where('yj_Yjno', $param['yjno'])
  1937. ->value('质量考核');
  1938. // 添加到 $list 数组中
  1939. $list['质量考核'] = $status;
  1940. $list['考核'] = ($status == 1) ? '不参与考核' : '参与考核';
  1941. $list['实际投料'] = $list['实际投料']*10000;
  1942. $feedQty = floatval($list['实际投料']);
  1943. $gxhValues = $this->getSuperLossProcessGxhList($param['order'], $param['yjno']);
  1944. $targetRateVal = $this->calcSuperLossTargetQualificationRate(
  1945. $param['order'],
  1946. $param['yjno'],
  1947. $gxhValues,
  1948. $feedQty
  1949. );
  1950. $realRateVal = $feedQty > 0 ? (floatval($list['warehousing_num']) / $feedQty * 100) : 0.0;
  1951. //倍率:优先用核算时落库的结果,保证明细与列表、工资口径一致;未核算过再按规则实时计算
  1952. $storedRule = $this->getStoredSuperLossRule((string)$param['order'], $param['yjno']);
  1953. $rewardMultiplier = $this->resolveSuperLossRewardMultiplier(
  1954. $targetRateVal,
  1955. $realRateVal,
  1956. floatval($list['材料废'] ?? 0),
  1957. $feedQty,
  1958. (string)$param['order'],
  1959. $param['yjno']
  1960. );
  1961. $list['reward_rate'] = isset($storedRule['reward_multiplier']) && $storedRule['reward_multiplier'] !== null
  1962. ? $this->stringifyRewardMultiplier($storedRule['reward_multiplier'])
  1963. : $this->stringifyRewardMultiplier($rewardMultiplier);
  1964. $list['target_rate'] = number_format($targetRateVal, 2) . '%';
  1965. $list['real_rate'] = number_format($realRateVal, 2) . '%';
  1966. $list['计算规则'] = $this->formatSuperLossRewardRule($this->superLossRewardRule);
  1967. //查询工序数据(字段名与历史 ProcessLoss 一致)
  1968. $gy_field = '
  1969. `工序` AS Gy0_gxh,
  1970. MAX(`工序名称`) AS Gy0_gxmc,
  1971. MAX(`印件及工序`) AS Gy0_yjno,
  1972. MAX(`联数`) AS Gy0_ls,
  1973. MAX(`计划损耗`) AS Gy0_计划损耗,
  1974. MAX(`计划产量`) AS Gy0_计划接货数,
  1975. SUM(`班组分摊无形损`) AS Gy0_无形损,
  1976. MAX(`印件工序产量`) AS total_cl,
  1977. SUM(`班组制程废品`) AS total_fp,
  1978. SUM(`班组分摊质检废品`) AS waste_quality,
  1979. SUM(`CjsSl`) AS loss,
  1980. SUM(`CjsJe`) AS `工序超节损金额`,
  1981. MAX(`超节损承担比例`) AS 超节损承担比例,
  1982. MAX(`无形损承担比例`) AS 无形损承担比例
  1983. ';
  1984. $gy_data = \db('工单_质量考核汇总')
  1985. ->field($gy_field)
  1986. ->where($where)
  1987. ->group('Gy0_gxh')
  1988. ->select();
  1989. foreach ($gy_data as $key => $value) {
  1990. //报废合计取班组行已分摊的制程废、质检废、无形损
  1991. $intangibleLoss = (float)$value['Gy0_无形损'];
  1992. if ($intangibleLoss < 0) {
  1993. $intangibleLoss = 0;
  1994. }
  1995. $gy_data[$key]['total_waste'] = $intangibleLoss + $value['total_fp'] + $value['waste_quality'];
  1996. //节损数、节损金额使用入库时写入的 CjsSl、CjsJe,与班组打印合计一致
  1997. $gy_data[$key]['loss'] = (int)round((float)$value['loss']);
  1998. $gy_data[$key]['工序超节损金额'] = round((float)$value['工序超节损金额'], 4);
  1999. $denom = (float)$value['Gy0_计划接货数'];
  2000. if ($denom <= 0) {
  2001. $denom = 1;
  2002. }
  2003. //工序实际报废率
  2004. $gy_data[$key]['actual_loss_rate'] = ((number_format($gy_data[$key]['total_waste'] / $denom, 4)) * 100) . '%';
  2005. //工序目标报废率
  2006. $gy_data[$key]['target_loss_rate'] = ((number_format($value['Gy0_计划损耗'] / $denom, 4)) * 100) . '%';
  2007. //占投料报废率,分子用已入库的节损数
  2008. $feedForRate = (float)$list['实际投料'];
  2009. $gy_data[$key]['loss_rate'] = ($feedForRate > 0
  2010. ? (number_format($gy_data[$key]['loss'] / $feedForRate, 4) * 100)
  2011. : 0) . '%';
  2012. }
  2013. $list['gy_data'] = $gy_data;
  2014. $total = [
  2015. 'total_waste' => 0,
  2016. 'total_zjfp' => 0,
  2017. 'total_fp' => 0,
  2018. 'plan_loss' => 0,
  2019. 'waste_intangible' => 0,
  2020. 'loss' => 0,
  2021. 'reward' => 0,
  2022. ];
  2023. foreach ($gy_data as $item){
  2024. $total['total_waste'] += $item['total_waste'];
  2025. $total['total_zjfp'] += $item['waste_quality'];
  2026. $total['total_fp'] += $item['total_fp'];
  2027. $total['plan_loss'] += $item['Gy0_计划损耗'];
  2028. $total['waste_intangible'] += $item['Gy0_无形损'];
  2029. $total['loss'] += $item['loss'];
  2030. $total['reward'] += $item['工序超节损金额'];
  2031. }
  2032. $total['reward'] = round($total['reward'],2);
  2033. //查询废品数量
  2034. $out_sql = "SELECT qczl_num,fp_sl1,fp_sl2,fp_sl3,fp_sl4,fp_sl5,fp_sl6,fp_sl7,fp_sl8,fp_sl9,fp_sl10,fp_sl11,fp_sl12,fp_sl13,
  2035. fp_lb1,fp_lb2,fp_lb3,fp_lb4,fp_lb5,fp_lb6,fp_lb7,fp_lb8,fp_lb9,fp_lb10,fp_lb11,fp_lb12,fp_lb13,
  2036. fp_bh1,fp_bh2,fp_bh3,fp_bh4,fp_bh5,fp_bh6,fp_bh7,fp_bh8,fp_bh9,fp_bh10,fp_bh11,fp_bh12,fp_bh13,
  2037. fp_gxmc1,fp_gxmc2,fp_gxmc3,fp_gxmc4,fp_gxmc5,fp_gxmc6,fp_gxmc7,fp_gxmc8,fp_gxmc9,fp_gxmc10,fp_gxmc11,fp_gxmc12,fp_gxmc13,UniqId
  2038. FROM db_qczl WHERE qczl_gdbh = '{$param['order']}' AND qczl_yjno = '{$param['yjno']}'";
  2039. $waste_out = Db::query($out_sql);
  2040. $machine = [];//机检废品数组
  2041. $o = 0;
  2042. foreach ($waste_out as $entry) {
  2043. for ($i = 1; $i <= 13; $i++) {
  2044. $labelKey = "fp_lb" . $i;
  2045. $slKey = "fp_sl" . $i;
  2046. if (!empty($entry[$labelKey])) {
  2047. //机检废品
  2048. if (substr($entry[$labelKey],0,1) == 'K' ){
  2049. $machine[$o]= $entry[$slKey];
  2050. $o++;
  2051. }
  2052. }
  2053. }
  2054. }
  2055. $list['机检废'] = array_sum($machine);//机检废
  2056. $list['total'] = $total;
  2057. $list = $this->formatProcessLossResponse($list);
  2058. $this->success('成功', $list);
  2059. }
  2060. //班组超节损数据
  2061. public function ClassLossData()
  2062. {
  2063. if ($this->request->isGet() === false){
  2064. $this->error('请求错误');
  2065. }
  2066. $param = $this->request->param();
  2067. if (empty($param) || empty($param['order']) || empty($param['yjno'])){
  2068. $this->error('参数错误');
  2069. }
  2070. $where = ['Gy0_gdbh'=>$param['order'],'印件及工序'=>$param['yjno']];
  2071. //查询订单印件数据
  2072. $field = '
  2073. Gy0_gdbh AS Gd_gdbh,
  2074. `印件及工序` AS yjno,
  2075. `联数` AS ls,
  2076. `产品代号` AS `成品代号`,
  2077. `产品名称` AS `成品名称`,
  2078. `实际投料`,
  2079. `计量单位`,
  2080. DATE(`入仓日期`) AS warehousing_date,
  2081. `入仓数量` AS warehousing_num,
  2082. SUM(DISTINCT `计划损耗`) AS `计划损耗`,
  2083. `废品合计`,
  2084. `印件无形损` as intangible_loss,
  2085. `材料废`,
  2086. `零头处理`,
  2087. `外发废`,
  2088. SUM(`班组制程废品`) AS `zcfp`,
  2089. `工单质检废` AS `班组分摊质检废品`,
  2090. `订单数量`,
  2091. `销售订单号`
  2092. ';
  2093. $list = \db('工单_质量考核汇总')
  2094. ->field($field)
  2095. ->where($where)
  2096. ->group('Gy0_gdbh, `印件及工序`')
  2097. ->order('sys_rq DESC')
  2098. ->find();
  2099. $processDetail = \db('工单_工艺资料')
  2100. ->where('Gy0_gdbh', $param['order'])
  2101. ->where('Gy0_yjno', $param['yjno'])
  2102. ->field('CONCAT(rtrim(Gy0_gxmc),"[",rtrim(Add_gxmc),"]") as 工序名称,Gy0_ls as 联数')
  2103. ->select();
  2104. $status = \db('工单_印件资料')
  2105. ->where('Yj_Gdbh', $param['order'])
  2106. ->where('yj_Yjno', $param['yjno'])
  2107. ->value('质量考核');
  2108. // 添加到 $list 数组中
  2109. $list['质量考核'] = $status;
  2110. $list['考核'] = ($status == 1) ? '不参与考核' : '参与考核';
  2111. $list['实际投料'] = $list['实际投料']*10000;
  2112. $classGxhValues = $this->getSuperLossProcessGxhList($param['order'], $param['yjno']);
  2113. $list['target_rate'] = number_format(
  2114. $this->calcTargetRateBp($param['order'], $param['yjno'], $classGxhValues, floatval($list['实际投料'])) / 100,
  2115. 2
  2116. ) . '%';
  2117. //实际合格率
  2118. $list['real_rate'] = $list['warehousing_num']/($list['实际投料'])*100;
  2119. $list['real_rate'] = number_format($list['real_rate'],2);
  2120. $list['real_rate'] = $list['real_rate'].'%';
  2121. //班组数据
  2122. $gy_data = \db('工单_质量考核汇总')
  2123. ->where($where)
  2124. ->select();
  2125. $class_data = [];
  2126. foreach ($gy_data as $item){
  2127. $name = '';
  2128. for ($i=1;$i<9;$i++){
  2129. if ($item['Xm'.$i] !== ''){
  2130. $name = $name.' '.$item['Xm'.$i];
  2131. }
  2132. }
  2133. $data = [
  2134. 'member' => $name,
  2135. 'sczl_gxmc' => $item['工序名称'],
  2136. 'total_cl' => $item['班组产量'],
  2137. '计划损耗' => $item['班组分摊计划损耗'],
  2138. '无形损分摊' => $item['班组分摊无形损'],
  2139. '节损奖' => $item['CjsJe'],
  2140. '节损数量' => $item['CjsSl'],
  2141. 'sczl_zcfp' => $item['班组制程废品'],
  2142. '质检废' => $item['班组分摊质检废品'],
  2143. '超节损承担比例' => ($item['超节损承担比例']*100).'%',
  2144. ];
  2145. array_push($class_data,$data);
  2146. }
  2147. $list['gy_data'] = $class_data;
  2148. //工单节损数据
  2149. $total_field = '
  2150. SUM(`班组分摊质检废品`) as total_waste,
  2151. SUM(`班组质检废品`) as total_zjfp,
  2152. SUM(`班组制程废品`) as total_fp,
  2153. SUM(DISTINCT `计划损耗`) AS plan_loss,
  2154. `材料废`,
  2155. `印件无形损` as waste_intangible,
  2156. SUM(CjsSl) as loss,
  2157. SUM(CjsJe) as reward
  2158. ';
  2159. $total = \db('工单_质量考核汇总')
  2160. ->where($where)
  2161. ->field($total_field)
  2162. ->find();
  2163. if (!empty($total)) {
  2164. $total['loss'] = (int)round((float)$total['loss']);
  2165. $total['reward'] = round((float)$total['reward'], 2);
  2166. }
  2167. //查询废品数量
  2168. $out_sql = "SELECT qczl_num,fp_sl1,fp_sl2,fp_sl3,fp_sl4,fp_sl5,fp_sl6,fp_sl7,fp_sl8,fp_sl9,fp_sl10,fp_sl11,fp_sl12,fp_sl13,
  2169. fp_lb1,fp_lb2,fp_lb3,fp_lb4,fp_lb5,fp_lb6,fp_lb7,fp_lb8,fp_lb9,fp_lb10,fp_lb11,fp_lb12,fp_lb13,
  2170. fp_bh1,fp_bh2,fp_bh3,fp_bh4,fp_bh5,fp_bh6,fp_bh7,fp_bh8,fp_bh9,fp_bh10,fp_bh11,fp_bh12,fp_bh13,
  2171. fp_gxmc1,fp_gxmc2,fp_gxmc3,fp_gxmc4,fp_gxmc5,fp_gxmc6,fp_gxmc7,fp_gxmc8,fp_gxmc9,fp_gxmc10,fp_gxmc11,fp_gxmc12,fp_gxmc13,UniqId
  2172. FROM db_qczl WHERE qczl_gdbh = '{$param['order']}' AND qczl_yjno = '{$param['yjno']}'";
  2173. $waste_out = Db::query($out_sql);
  2174. $machine = [];//机检废品数组
  2175. $o = 0;
  2176. foreach ($waste_out as $entry) {
  2177. for ($i = 1; $i <= 13; $i++) {
  2178. $labelKey = "fp_lb" . $i;
  2179. $slKey = "fp_sl" . $i;
  2180. if (!empty($entry[$labelKey])) {
  2181. //机检废品
  2182. if (substr($entry[$labelKey],0,1) == 'K' ){
  2183. $machine[$o]= $entry[$slKey];
  2184. $o++;
  2185. }
  2186. }
  2187. }
  2188. }
  2189. $list['机检废'] = array_sum($machine);//机检废
  2190. $list['total'] = $total;
  2191. $this->success('成功',$list);
  2192. }
  2193. /**
  2194. * 循环插入超节损数据
  2195. * @return void
  2196. * @throws \think\Exception
  2197. * @throws \think\db\exception\BindParamException
  2198. * @throws \think\db\exception\DataNotFoundException
  2199. * @throws \think\db\exception\ModelNotFoundException
  2200. * @throws \think\exception\DbException
  2201. * @throws \think\exception\PDOException
  2202. */
  2203. public function orderLossData()
  2204. {
  2205. $param = $this->request->param();
  2206. $where = [];
  2207. if (isset($param['gdbh']) && isset($param['yjno']) && !empty($param['gdbh']) && !empty($param['yjno'])){
  2208. $where['a.jjcp_gdbh'] = $param['gdbh'];
  2209. $where['a.jjcp_yjno'] = $param['yjno'];
  2210. }
  2211. if (isset($param['mouth'])){
  2212. $where['a.jjcp_sj'] = ['like',$param['mouth'].'%'];
  2213. }
  2214. $where['a.jjcp_smb'] = ['like','末%'];
  2215. $list = \db('成品入仓')
  2216. ->alias('a')
  2217. ->join('设备_产量计酬 b','a.jjcp_gdbh = b.sczl_gdbh AND a.jjcp_yjno = b.sczl_yjno')
  2218. ->join('物料_收发记录 c','a.jjcp_gdbh = c.st_gdbh AND a.jjcp_cpdh = c.cpdh')
  2219. ->where($where)
  2220. ->where(function ($query) {
  2221. $query->where('c.仓库编号', '101')
  2222. ->whereOr('c.仓库编号', 'Y101');
  2223. })
  2224. ->field('a.jjcp_gdbh,a.jjcp_yjno')
  2225. ->group('a.jjcp_gdbh,a.jjcp_yjno')
  2226. ->select();
  2227. $i = 0;
  2228. if (empty($list)) {
  2229. $this->error('未搜索到工单入仓数据');
  2230. }
  2231. foreach ($list as $item){
  2232. $jobData = [
  2233. 'gdbh' => $item['jjcp_gdbh'],
  2234. 'yjno' => $item['jjcp_yjno'],
  2235. 'created_at' => date('Y-m-d H:i:s'),
  2236. ];
  2237. $res = Queue::push('app\\job\\OrderSuperLossJob', $jobData, 'order_loss_calculation');
  2238. if (!$res) {
  2239. $i++;
  2240. }
  2241. }
  2242. if ($i === 0){
  2243. $this->success('任务已提交,共' . count($list) . '条');
  2244. }else{
  2245. $this->error('提交完成,失败' . $i . '条');
  2246. }
  2247. }
  2248. /**
  2249. * 创建投料数
  2250. * @return void
  2251. */
  2252. public function feedAdd()
  2253. {
  2254. // 1. 请求验证
  2255. if (!$this->request->isPost()) {
  2256. $this->error('请求错误');
  2257. }
  2258. $param = Request::instance()->post();
  2259. if (empty($param)) {
  2260. $this->error('参数错误');
  2261. }
  2262. // 2. 数据验证
  2263. $requiredFields = ['st_gdbh', 'st_sl', 'st_dw', 'sys_id', 'cpdh'];
  2264. foreach ($requiredFields as $field) {
  2265. if (!isset($param[$field]) || $param[$field] === '') {
  2266. $this->error("参数{$field}不能为空");
  2267. }
  2268. }
  2269. try {
  2270. // 3. 数据准备
  2271. $currentTime = date('Y-m-d H:i:s');
  2272. $currentDate = date('Y-m-d');
  2273. // 仓库编号逻辑
  2274. $cangku = preg_match('/[a-zA-Z]/', $param['st_gdbh']) ? 'Y101' : '101';
  2275. // 4. 主数据
  2276. $data = [
  2277. 'st_rq' => $currentDate,
  2278. 'st_jylb' => '生产领料',
  2279. 'st_gdbh' => $param['st_gdbh'],
  2280. 'st_wlbh' => $param['st_wlbh'],
  2281. 'st_sl' => $param['st_sl'],
  2282. 'st_dw' => $param['st_dw'],
  2283. 'sys_id' => $param['sys_id'],
  2284. 'sys_rq' => $currentTime,
  2285. 'cpdh' => $param['cpdh'],
  2286. ];
  2287. // 添加仓库编号(特殊处理)
  2288. $data['`仓库编号`'] = $cangku;
  2289. // 5. 日志数据
  2290. $logData = [
  2291. 'Gd_gdbh' => $param['st_gdbh'],
  2292. 'ModifyUser' => $param['sys_id'],
  2293. 'ModifyTime' => $currentTime,
  2294. 'FieldName' => 'st_sl',
  2295. 'NewValue' => $param['st_sl'],
  2296. 'ModifySource' => '新增物料投料数'
  2297. ];
  2298. // 6. 开启事务
  2299. Db::startTrans();
  2300. // 7. 插入日志
  2301. Db::name('系统操作日志表')->insert($logData);
  2302. // 8. 插入主记录 - 手动构建安全的SQL语句
  2303. $fields = array_keys($data);
  2304. $values = array_values($data);
  2305. // 构建字段名部分
  2306. $fieldList = implode(', ', array_map(function($field) {
  2307. return strpos($field, '`') === 0 ? $field : "`{$field}`";
  2308. }, $fields));
  2309. // 构建占位符
  2310. $placeholders = implode(', ', array_fill(0, count($values), '?'));
  2311. // 执行安全的参数化查询
  2312. $sql = "INSERT INTO `物料_收发记录` ({$fieldList}) VALUES ({$placeholders})";
  2313. $feedResult = Db::execute($sql, $values);
  2314. if ($feedResult === false) {
  2315. throw new Exception('新增物料记录失败');
  2316. }
  2317. // 9. 获取工单信息
  2318. $totalNum = Db::name('工单_印件资料')
  2319. ->field('yj_ls, yj_ks, yj_tlgg, yj_zzmc, yj_Yjno')
  2320. ->where('Yj_Gdbh', $param['st_gdbh'])
  2321. ->where('yj_Yjdh', $param['cpdh'])
  2322. ->find();
  2323. if (!$totalNum) {
  2324. throw new Exception('未找到对应的工单印件资料');
  2325. }
  2326. // 10. 计算投料数量
  2327. $num = $param['st_sl'];
  2328. if (!empty($totalNum['yj_tlgg'])) {
  2329. $dimensions = explode('*', $totalNum['yj_tlgg']);
  2330. $number1 = (int)($dimensions[0] ?? 0);
  2331. $number2 = (int)($dimensions[1] ?? 0);
  2332. preg_match('/(\d+)g/', $totalNum['yj_zzmc'], $matches);
  2333. $paperWeight = $matches[1] ?? 0;
  2334. if ($param['st_dw'] === '吨' && $paperWeight > 0 && $number1 > 0 && $number2 > 0) {
  2335. $num = round(($param['st_sl'] * 1000000) / $paperWeight / ($number1 * $number2) * 1000000);
  2336. }
  2337. }
  2338. // 11. 计算实际投料
  2339. $actualFeed = $num / 10000 * $totalNum['yj_ls'] * $totalNum['yj_ks'];
  2340. // 12. 更新工单基本资料 - 使用原生SQL处理中文字段
  2341. $updateBasicSql = "UPDATE `工单_基本资料` SET `实际投料` = ? WHERE `Gd_gdbh` = ? AND `Gd_cpdh` = ?";
  2342. $basicResult = Db::execute($updateBasicSql, [$actualFeed, $param['st_gdbh'], $param['cpdh']]);
  2343. if ($basicResult === false) {
  2344. throw new Exception('更新工单基本资料失败');
  2345. }
  2346. // 13. 更新工单印件资料 - 使用原生SQL
  2347. $updateYjSql = "UPDATE `工单_印件资料` SET `yj_实际投料` = ? WHERE `Yj_Gdbh` = ? AND `yj_cpdh` = ?";
  2348. $yjResult = Db::execute($updateYjSql, [$actualFeed, $param['st_gdbh'], $param['cpdh']]);
  2349. if ($yjResult === false) {
  2350. throw new Exception('更新工单印件资料失败');
  2351. }
  2352. $yjNo = $totalNum['yj_Yjno'];
  2353. // 14. 重新计算工单超节损数据
  2354. $resultAdd = $this->OneOrderSuperLoss($param['st_gdbh'], $yjNo);
  2355. // 15. 更新质量考核汇总 - 先删除
  2356. $deleteSql = "DELETE FROM `工单_质量考核汇总` WHERE `Gy0_gdbh` = ? AND `印件及工序` = ?";
  2357. Db::execute($deleteSql, [$param['st_gdbh'], $yjNo]);
  2358. // 16. 插入新的质量考核数据
  2359. if (!empty($resultAdd)) {
  2360. foreach ($resultAdd as $item) {
  2361. $fields = array_keys($item);
  2362. $values = array_values($item);
  2363. $fieldList = implode(', ', array_map(function($field) {
  2364. return strpos($field, '`') === 0 ? $field : "`{$field}`";
  2365. }, $fields));
  2366. $placeholders = implode(', ', array_fill(0, count($values), '?'));
  2367. $insertSql = "INSERT INTO `工单_质量考核汇总` ({$fieldList}) VALUES ({$placeholders})";
  2368. Db::execute($insertSql, $values);
  2369. }
  2370. }
  2371. // 17. 提交事务
  2372. Db::commit();
  2373. $this->success('新增成功');
  2374. } catch (Exception $e) {
  2375. // 18. 回滚事务
  2376. Db::rollback();
  2377. $this->error('操作失败: ' . $e->getMessage());
  2378. }
  2379. }
  2380. /**
  2381. * 获取物料信息
  2382. * @return void
  2383. * @throws \think\db\exception\DataNotFoundException
  2384. * @throws \think\db\exception\ModelNotFoundException
  2385. * @throws \think\exception\DbException
  2386. */
  2387. public function getFeedList()
  2388. {
  2389. if (Request::instance()->isGet() == false) {
  2390. $this->error('非法请求');
  2391. }
  2392. $params = Request::instance()->request();
  2393. if (empty($params['workorder']) || empty($params['yjno'])) {
  2394. $this->error('参数错误');
  2395. }
  2396. $field = "a.Gd_gdbh,rtrim(c.yj_Yjdh) as yj_yjdh,c.yj_Yjno, c.yj_ks,c.yj_ls,rtrim(c.yj_zzdh) as yj_zzdh,
  2397. rtrim(b.BOM_物料名称) as BOM_物料名称,rtrim(c.yj_tlgg) as yj_tlgg,
  2398. a.订单数量,c.yj_平张投料, b.BOM_实际用量,a.投料确认";
  2399. $data =db('工单_基本资料')->alias('a')
  2400. ->join('工单_印件资料 c','a.Gd_gdbh = c.Yj_Gdbh ','left')
  2401. ->join('工单_bom资料 b','c.Yj_Gdbh = b.BOM_工单编号 AND c.yj_zzdh = b.BOM_物料编码','left')
  2402. ->where('a.Gd_gdbh',$params['workorder'])
  2403. ->where('c.yj_Yjno',$params['yjno'])
  2404. ->field($field)
  2405. ->group('a.Gd_gdbh')
  2406. ->order('b.BOM_投料单位,a.UniqId asc')
  2407. ->select();
  2408. if (empty($data)){
  2409. $this->success('请求成功');
  2410. }
  2411. foreach ($data as $key=>$value){
  2412. $len = stripos($value['yj_tlgg'],'/');
  2413. if ($len){
  2414. $name = substr($value['yj_tlgg'],0,$len);
  2415. $len_two = stripos($value['yj_tlgg'],'(');
  2416. if ($len_two){
  2417. $name = substr($name,0,$len_two);
  2418. }
  2419. $data[$key]['yj_tlgg'] = $name;
  2420. }
  2421. $data[$key]['rate'] = '';
  2422. }
  2423. $this->success('请求成功',$data);
  2424. }
  2425. /**
  2426. * 获取工单类型
  2427. * @return void
  2428. */
  2429. public function getWorkorderStatus()
  2430. {
  2431. if ($this->request->isGet() == false) {
  2432. $this->error('请求错误');
  2433. }
  2434. $param = $this->request->param();
  2435. if (empty($param['workorder']) || empty($param['yjno'])) {
  2436. $this->error('参数错误');
  2437. }
  2438. $data = \db('工单_印件资料')
  2439. ->where('Yj_Gdbh',$param['workorder'])
  2440. ->where('yj_Yjno',$param['yjno'])
  2441. ->field('Yj_gdbh,rtrim(yj_Yjdh) as yj_Yjdh,yj_Yjno,rtrim(yj_yjmc) as yj_yjmc,工单类型')
  2442. ->find();
  2443. $this->success('成功',$data);
  2444. }
  2445. /**
  2446. * 工序号统一为与 getSuperLossProcessGxhList 一致的两位字符串,避免 9/09 重复补行
  2447. */
  2448. private function normalizeGxhKey($gxh): string
  2449. {
  2450. if ($gxh === null || $gxh === '') {
  2451. return '';
  2452. }
  2453. $n = (int)$gxh;
  2454. return $n < 10 ? sprintf('%02d', $n) : (string)$n;
  2455. }
  2456. /**
  2457. * 工艺资料工序展示名(Add_gxmc 为空时不拼 null)
  2458. */
  2459. private function processGxmcSqlExpr(): string
  2460. {
  2461. return 'CONCAT(rtrim(a.Gy0_gxmc), IF(a.Add_gxmc IS NULL OR rtrim(a.Add_gxmc) = \'\', \'\', CONCAT(\'【\', rtrim(a.Add_gxmc), \'】\')))';
  2462. }
  2463. /** 外发:不参与无形损分摊 */
  2464. private function isSuperLossIntangibleExcluded(string $gxName): bool
  2465. {
  2466. return strpos($gxName, '外发') !== false;
  2467. }
  2468. private function isMachineInspectionProcess(string $gxName): bool
  2469. {
  2470. return strpos($gxName, '机检') !== false;
  2471. }
  2472. /**
  2473. * 机检:制程/质检不计入本行报废;无形损参与分摊并扣减节损数;超节损金额不计
  2474. */
  2475. private function applyMachineInspectionProcessLossRules(string $gxName, int $planLoss, array &$row): void
  2476. {
  2477. if (!$this->isMachineInspectionProcess($gxName)) {
  2478. return;
  2479. }
  2480. if (array_key_exists('total_fp', $row)) {
  2481. $row['total_fp'] = 0;
  2482. }
  2483. if (array_key_exists('waste_quality', $row)) {
  2484. $row['waste_quality'] = 0;
  2485. }
  2486. $intangible = (int)($row['Gy0_无形损'] ?? $row['intangible_loss'] ?? 0);
  2487. $row['total_waste'] = $intangible;
  2488. $row['loss'] = $planLoss - $intangible;
  2489. }
  2490. /** 机检、外发:不计超节损金额 */
  2491. private function isSuperLossRewardExcluded(string $gxName): bool
  2492. {
  2493. return $this->isMachineInspectionProcess($gxName) || $this->isSuperLossIntangibleExcluded($gxName);
  2494. }
  2495. /** 工序号查询兼容 9 / 09 / 9 */
  2496. private function resolveGxhWhereValues($gxh): array
  2497. {
  2498. $values = [(string)$gxh, $this->normalizeGxhKey($gxh), (string)(int)$gxh];
  2499. $n = (int)$gxh;
  2500. if ($n < 10) {
  2501. $values[] = sprintf('%02d', $n);
  2502. }
  2503. return array_values(array_unique(array_filter($values, static function ($v) {
  2504. return $v !== '';
  2505. })));
  2506. }
  2507. /**
  2508. * 按 db_sczl 报工班组拆成多行(拆片等多员工,与历史入库一致)
  2509. */
  2510. private function buildGyRowsFromSczlTeams(string $gdbh, string $yjno, $gxh, array $templateRow): array
  2511. {
  2512. $gxValues = $this->resolveGxhWhereValues($gxh);
  2513. $sczlRows = db('db_sczl')
  2514. ->where('sczl_gdbh', $gdbh)
  2515. ->where('sczl_yjno', $yjno)
  2516. ->where('sczl_gxh', 'in', $gxValues)
  2517. ->order('sczl_rq asc')
  2518. ->select();
  2519. if (count($sczlRows) <= 1) {
  2520. return [];
  2521. }
  2522. $groups = [];
  2523. foreach ($sczlRows as $sr) {
  2524. $bh1 = trim((string)($sr['sczl_bh1'] ?? ''));
  2525. if ($bh1 === '000000') {
  2526. $bh1 = '';
  2527. }
  2528. $key = $bh1 !== '' ? ('bh:' . $bh1) : ('id:' . ($sr['UniqId'] ?? md5(json_encode($sr))));
  2529. if (!isset($groups[$key])) {
  2530. $groups[$key] = ['sczl' => $sr, 'cl' => 0.0, 'fp' => 0.0];
  2531. }
  2532. $groups[$key]['cl'] += floatval($sr['sczl_cl'] ?? 0);
  2533. $groups[$key]['fp'] += floatval($sr['sczl_fp'] ?? 0);
  2534. }
  2535. if (count($groups) <= 1) {
  2536. return [];
  2537. }
  2538. $rows = [];
  2539. foreach ($groups as $g) {
  2540. $sr = $g['sczl'];
  2541. $row = $templateRow;
  2542. $row['total_cl'] = $g['cl'];
  2543. $row['cl'] = $g['cl'];
  2544. $row['fp'] = $g['fp'];
  2545. $row['sczl_zcfp'] = 0;
  2546. $row['sczl_jtbh'] = $sr['sczl_jtbh'] ?? ($row['sczl_jtbh'] ?? '');
  2547. $row['sczl_bzdh'] = $sr['sczl_bzdh'] ?? '';
  2548. $row['sczl_bh'] = $sr['sczl_bh1'] ?? '';
  2549. for ($j = 1; $j <= 10; $j++) {
  2550. $bhKey = 'sczl_bh' . $j;
  2551. $rateKey = 'sczl_rate' . $j;
  2552. $val = isset($sr[$bhKey]) ? trim((string)$sr[$bhKey]) : '';
  2553. if ($val === '000000') {
  2554. $val = '';
  2555. }
  2556. $row[$bhKey] = $val;
  2557. $row[$rateKey] = (isset($sr[$rateKey]) && $sr[$rateKey] !== '') ? $sr[$rateKey] : 0;
  2558. }
  2559. $rows[] = $row;
  2560. }
  2561. return $rows;
  2562. }
  2563. /**
  2564. * 仅 db_sczl 报工、无产量计酬时:若某工序只有一行且无计酬班组,按 sczl 多员工展开
  2565. */
  2566. private function expandSczlMultiTeamRows(array $gyData, string $gdbh, string $yjno): array
  2567. {
  2568. $byGx = [];
  2569. foreach ($gyData as $idx => $row) {
  2570. $gk = $this->normalizeGxhKey($row['Gy0_gxh'] ?? '');
  2571. if ($gk === '') {
  2572. continue;
  2573. }
  2574. $byGx[$gk][] = $idx;
  2575. }
  2576. $replaceGx = [];
  2577. foreach ($byGx as $gk => $indexes) {
  2578. if (count($indexes) !== 1) {
  2579. continue;
  2580. }
  2581. $row = $gyData[$indexes[0]];
  2582. $gxValues = $this->resolveGxhWhereValues($row['Gy0_gxh']);
  2583. $payrollCnt = (int)db('设备_产量计酬')
  2584. ->where('sczl_gdbh', $gdbh)
  2585. ->where('sczl_yjno', $yjno)
  2586. ->where('sczl_gxh', 'in', $gxValues)
  2587. ->count();
  2588. if ($payrollCnt > 0) {
  2589. continue;
  2590. }
  2591. $teams = $this->buildGyRowsFromSczlTeams($gdbh, $yjno, $row['Gy0_gxh'], $row);
  2592. if (count($teams) > 1) {
  2593. $replaceGx[$gk] = $teams;
  2594. }
  2595. }
  2596. if (empty($replaceGx)) {
  2597. return $gyData;
  2598. }
  2599. $out = [];
  2600. $doneGx = [];
  2601. foreach ($gyData as $row) {
  2602. $gk = $this->normalizeGxhKey($row['Gy0_gxh'] ?? '');
  2603. if (isset($replaceGx[$gk]) && !isset($doneGx[$gk])) {
  2604. foreach ($replaceGx[$gk] as $teamRow) {
  2605. $out[] = $teamRow;
  2606. }
  2607. $doneGx[$gk] = true;
  2608. continue;
  2609. }
  2610. if (isset($doneGx[$gk])) {
  2611. continue;
  2612. }
  2613. $out[] = $row;
  2614. }
  2615. return $out;
  2616. }
  2617. /**
  2618. * 仅 db_sczl 报工、无产量计酬时,从最新一条报工补班组编号/分配比例(拆片等)
  2619. */
  2620. private function fillSczlTeamMemberFields(array &$row, string $gdbh, string $yjno): void
  2621. {
  2622. if (!empty($row['sczl_bh1'])) {
  2623. return;
  2624. }
  2625. $gxh = $row['Gy0_gxh'] ?? '';
  2626. if ($gxh === '') {
  2627. return;
  2628. }
  2629. $sczl = db('db_sczl')
  2630. ->where('sczl_gdbh', $gdbh)
  2631. ->where('sczl_yjno', $yjno)
  2632. ->where('sczl_gxh', $gxh)
  2633. ->order('sczl_rq desc')
  2634. ->find();
  2635. if (empty($sczl)) {
  2636. $sczl = db('db_sczl')
  2637. ->where('sczl_gdbh', $gdbh)
  2638. ->where('sczl_yjno', $yjno)
  2639. ->where('sczl_gxh', (int)$gxh)
  2640. ->order('sczl_rq desc')
  2641. ->find();
  2642. }
  2643. if (empty($sczl)) {
  2644. return;
  2645. }
  2646. for ($j = 1; $j <= 10; $j++) {
  2647. $bhKey = 'sczl_bh' . $j;
  2648. $rateKey = 'sczl_rate' . $j;
  2649. if (!empty($sczl[$bhKey])) {
  2650. $row[$bhKey] = $sczl[$bhKey];
  2651. }
  2652. if (isset($sczl[$rateKey]) && $sczl[$rateKey] !== '') {
  2653. $row[$rateKey] = $sczl[$rateKey];
  2654. }
  2655. }
  2656. if (!empty($sczl['sczl_bzdh'])) {
  2657. $row['sczl_bzdh'] = $sczl['sczl_bzdh'];
  2658. }
  2659. }
  2660. /**
  2661. * ProcessLoss 接口返回结构与历史前端一致(多数数值为字符串,total/部分汇总为数字)
  2662. */
  2663. private function formatProcessLossResponse(array $list): array
  2664. {
  2665. $strFields = [
  2666. 'Gd_gdbh', 'yjno', 'ls', '成品代号', '成品名称', '计量单位', 'warehousing_date',
  2667. 'warehousing_num', '计划损耗', '废品合计', 'intangible_loss', '材料废', '零头处理',
  2668. '外发废', 'zcfp', '班组分摊质检废品', '订单数量', '销售订单号', 'target_rate', 'real_rate', 'reward_rate', '计算规则', '考核',
  2669. ];
  2670. foreach ($strFields as $f) {
  2671. if (array_key_exists($f, $list)) {
  2672. $list[$f] = $list[$f] === null ? '' : (string)$list[$f];
  2673. }
  2674. }
  2675. if (array_key_exists('订单数量', $list) && $list['订单数量'] !== '') {
  2676. $list['订单数量'] = number_format((float)$list['订单数量'], 6, '.', '');
  2677. }
  2678. if (!array_key_exists('质量考核', $list) || $list['质量考核'] === '') {
  2679. $list['质量考核'] = null;
  2680. }
  2681. $list['实际投料'] = $list['实际投料'] === null || $list['实际投料'] === ''
  2682. ? 0
  2683. : (float)$list['实际投料'];
  2684. $list['机检废'] = isset($list['机检废']) ? (int)$list['机检废'] : 0;
  2685. if (!empty($list['gy_data']) && is_array($list['gy_data'])) {
  2686. foreach ($list['gy_data'] as $i => $row) {
  2687. $list['gy_data'][$i]['Gy0_gxh'] = (string)($row['Gy0_gxh'] ?? '');
  2688. $list['gy_data'][$i]['Gy0_gxmc'] = (string)($row['Gy0_gxmc'] ?? '');
  2689. $list['gy_data'][$i]['Gy0_yjno'] = (string)($row['Gy0_yjno'] ?? '');
  2690. $list['gy_data'][$i]['Gy0_ls'] = (string)($row['Gy0_ls'] ?? '');
  2691. $list['gy_data'][$i]['Gy0_无形损'] = (string)(int)($row['Gy0_无形损'] ?? 0);
  2692. $list['gy_data'][$i]['Gy0_计划损耗'] = (string)(int)($row['Gy0_计划损耗'] ?? 0);
  2693. $list['gy_data'][$i]['Gy0_计划接货数'] = (string)(int)($row['Gy0_计划接货数'] ?? 0);
  2694. $list['gy_data'][$i]['total_cl'] = (string)(int)($row['total_cl'] ?? 0);
  2695. $list['gy_data'][$i]['total_fp'] = (string)(int)($row['total_fp'] ?? 0);
  2696. $list['gy_data'][$i]['waste_quality'] = (string)(int)($row['waste_quality'] ?? 0);
  2697. $list['gy_data'][$i]['loss'] = (string)(int)($row['loss'] ?? 0);
  2698. $list['gy_data'][$i]['total_waste'] = (int)($row['total_waste'] ?? 0);
  2699. $list['gy_data'][$i]['actual_loss_rate'] = (string)($row['actual_loss_rate'] ?? '');
  2700. $list['gy_data'][$i]['target_loss_rate'] = (string)($row['target_loss_rate'] ?? '');
  2701. $list['gy_data'][$i]['loss_rate'] = (string)($row['loss_rate'] ?? '');
  2702. $list['gy_data'][$i]['工序超节损金额'] = number_format((float)($row['工序超节损金额'] ?? 0), 2, '.', '');
  2703. $list['gy_data'][$i]['超节损承担比例'] = number_format((float)($row['超节损承担比例'] ?? 0), 3, '.', '');
  2704. $list['gy_data'][$i]['无形损承担比例'] = number_format((float)($row['无形损承担比例'] ?? 0), 3, '.', '');
  2705. }
  2706. }
  2707. if (!empty($list['total']) && is_array($list['total'])) {
  2708. $t = &$list['total'];
  2709. $t['total_waste'] = (int)($t['total_waste'] ?? 0);
  2710. $t['total_zjfp'] = (int)($t['total_zjfp'] ?? 0);
  2711. $t['total_fp'] = (int)($t['total_fp'] ?? 0);
  2712. $t['plan_loss'] = (int)($t['plan_loss'] ?? 0);
  2713. $t['waste_intangible'] = (int)($t['waste_intangible'] ?? 0);
  2714. $t['loss'] = (int)($t['loss'] ?? 0);
  2715. $t['reward'] = round((float)($t['reward'] ?? 0), 2);
  2716. }
  2717. return $list;
  2718. }
  2719. /**
  2720. * 产量计酬按班组聚合,避免与工单基本资料等 JOIN 时 SUM(sczl_zcfp) 被放大
  2721. */
  2722. private function buildPayrollTeamAggSubSql(): string
  2723. {
  2724. return db('设备_产量计酬')
  2725. ->field([
  2726. 'sczl_gdbh',
  2727. 'sczl_yjno',
  2728. 'sczl_gxh',
  2729. 'sczl_jtbh',
  2730. 'sczl_bh1',
  2731. 'sczl_bh2',
  2732. 'sczl_bh3',
  2733. 'sczl_bh4',
  2734. 'sczl_bh5',
  2735. 'sczl_bh6',
  2736. 'sczl_bh7',
  2737. 'sczl_bh8',
  2738. 'sczl_bh9',
  2739. 'sczl_bh10',
  2740. 'MAX(sczl_bzdh) as sczl_bzdh',
  2741. 'MAX(sczl_gxmc) as sczl_gxmc',
  2742. 'MAX(sczl_rate1) as sczl_rate1',
  2743. 'MAX(sczl_rate2) as sczl_rate2',
  2744. 'MAX(sczl_rate3) as sczl_rate3',
  2745. 'MAX(sczl_rate4) as sczl_rate4',
  2746. 'MAX(sczl_rate5) as sczl_rate5',
  2747. 'MAX(sczl_rate6) as sczl_rate6',
  2748. 'MAX(sczl_rate7) as sczl_rate7',
  2749. 'MAX(sczl_rate8) as sczl_rate8',
  2750. 'MAX(sczl_rate9) as sczl_rate9',
  2751. 'MAX(sczl_rate10) as sczl_rate10',
  2752. 'SUM(sczl_zcfp) as sczl_zcfp',
  2753. 'SUM(sczl_cl) as total_cl',
  2754. 'GROUP_CONCAT(DISTINCT sczl_num SEPARATOR ",") AS 流程单',
  2755. 'MIN(开工时间) as 开工时间',
  2756. ])
  2757. ->group('sczl_gdbh, sczl_yjno, sczl_gxh, sczl_jtbh, sczl_bh1, CASE WHEN sczl_bh2 = "000000" THEN "" ELSE sczl_bh2 END, sczl_bh3, sczl_bh4, sczl_bh5, sczl_bh6, sczl_bh7, sczl_bh8, sczl_bh9')
  2758. ->buildSql();
  2759. }
  2760. /**
  2761. * db_sczl 按工序聚合,避免与产量计酬 JOIN 时 SUM 被放大
  2762. */
  2763. private function buildSczlProcessAggSubSql(): string
  2764. {
  2765. return db('db_sczl')
  2766. ->field('sczl_gdbh, sczl_yjno, sczl_gxh, SUM(sczl_cl) as cl, SUM(sczl_fp) as fp')
  2767. ->group('sczl_gdbh, sczl_yjno, sczl_gxh')
  2768. ->buildSql();
  2769. }
  2770. /**
  2771. * db_sczl 按工序+班组聚合(与产量计酬 sczl_bh1 对齐)
  2772. */
  2773. private function buildSczlTeamAggSubSql(): string
  2774. {
  2775. return db('db_sczl')
  2776. ->field([
  2777. 'sczl_gdbh',
  2778. 'sczl_yjno',
  2779. 'sczl_gxh',
  2780. 'sczl_bh1',
  2781. 'SUM(sczl_cl) as cl',
  2782. 'SUM(sczl_fp) as fp',
  2783. 'MAX(rtrim(sczl_gxmc)) as gxmc',
  2784. 'MAX(sczl_bzdh) as bzdh',
  2785. ])
  2786. ->group('sczl_gdbh, sczl_yjno, sczl_gxh, sczl_bh1')
  2787. ->buildSql();
  2788. }
  2789. /**
  2790. * 进入超节损的工序号(产量计酬 + 拆片报工),与 getOrderSuperLossCount 一致
  2791. */
  2792. private function getSuperLossProcessGxhList(string $gdbh, string $yjno): array
  2793. {
  2794. $sql = "SELECT sczl_gxh FROM (
  2795. SELECT sczl_gxh FROM 设备_产量计酬 WHERE sczl_gdbh = ? AND sczl_yjno = ?
  2796. UNION
  2797. SELECT sczl_gxh FROM db_sczl WHERE sczl_gdbh = ? AND sczl_yjno = ? AND sczl_gxmc LIKE '%拆片%'
  2798. UNION
  2799. SELECT Gy0_gxh AS sczl_gxh FROM 工单_工艺资料
  2800. WHERE Gy0_gdbh = ? AND Gy0_yjno = ?
  2801. AND (Gy0_gxmc LIKE '%外发%' OR IFNULL(Add_gxmc, '') LIKE '%外发%')
  2802. UNION
  2803. SELECT Gy0_gxh AS sczl_gxh FROM 工单_工艺资料
  2804. WHERE Gy0_gdbh = ? AND Gy0_yjno = ?
  2805. AND (Gy0_gxmc LIKE '%拆片%' OR IFNULL(Add_gxmc, '') LIKE '%拆片%')
  2806. ) AS combined_result";
  2807. $gxhArr = Db::query($sql, [$gdbh, $yjno, $gdbh, $yjno, $gdbh, $yjno, $gdbh, $yjno]);
  2808. $gxhValues = array_column($gxhArr, 'sczl_gxh');
  2809. foreach ($gxhValues as $k => $v) {
  2810. if ((int)$v < 10) {
  2811. $gxhValues[$k] = '0' . $v;
  2812. }
  2813. }
  2814. return array_values(array_unique(array_filter($gxhValues)));
  2815. }
  2816. /**
  2817. * 无形损分摊分母:参与超节损工序的计划损耗合计(含机检/拆片等;外发不参与)
  2818. */
  2819. private function getIntangibleAllocationPlanLossTotal(string $gdbh, string $yjno, array $gxhValues): float
  2820. {
  2821. if (empty($gxhValues)) {
  2822. return 0.0;
  2823. }
  2824. return floatval(db('工单_工艺资料')
  2825. ->where(['Gy0_gdbh' => $gdbh, 'Gy0_yjno' => $yjno, 'Gy0_gxh' => ['in', $gxhValues]])
  2826. ->where('Gy0_gxmc', 'NOT LIKE', '%外发%')
  2827. ->whereRaw("(Add_gxmc IS NULL OR rtrim(Add_gxmc) = '' OR Add_gxmc NOT LIKE '%外发%')")
  2828. ->value('SUM(Gy0_计划损耗 * Gy0_ls * Gy0_ks)'));
  2829. }
  2830. /**
  2831. * 按工序/班组计划损耗占比分摊印件无形损
  2832. */
  2833. private function calcIntangibleLossShareByPlanLoss(
  2834. float $planLoss,
  2835. float $planLossTotal,
  2836. float $intangibleLoss,
  2837. float $intangibleRate = 0.0
  2838. ): int {
  2839. if ($planLossTotal <= 0 || $intangibleLoss == 0.0 || $planLoss <= 0) {
  2840. return 0;
  2841. }
  2842. $share = ($planLoss / $planLossTotal) * $intangibleLoss;
  2843. if ($intangibleRate > 0) {
  2844. $share *= $intangibleRate;
  2845. }
  2846. return (int)round($share);
  2847. }
  2848. /**
  2849. * 按权重分配整数数量(最大余数法,保证合计等于 totalAmount)
  2850. */
  2851. private function allocateIntegerByWeights(int $totalAmount, array $weightsByKey): array
  2852. {
  2853. if ($totalAmount <= 0 || empty($weightsByKey)) {
  2854. return array_fill_keys(array_keys($weightsByKey), 0);
  2855. }
  2856. $sum = array_sum($weightsByKey);
  2857. if ($sum <= 0) {
  2858. return array_fill_keys(array_keys($weightsByKey), 0);
  2859. }
  2860. $result = [];
  2861. $fractions = [];
  2862. $assigned = 0;
  2863. foreach ($weightsByKey as $key => $weight) {
  2864. if ($weight <= 0) {
  2865. $result[$key] = 0;
  2866. $fractions[$key] = 0.0;
  2867. continue;
  2868. }
  2869. $exact = $totalAmount * $weight / $sum;
  2870. $result[$key] = (int)floor($exact);
  2871. $fractions[$key] = $exact - $result[$key];
  2872. $assigned += $result[$key];
  2873. }
  2874. $remain = $totalAmount - $assigned;
  2875. if ($remain > 0) {
  2876. arsort($fractions);
  2877. foreach (array_keys($fractions) as $key) {
  2878. if ($remain <= 0) {
  2879. break;
  2880. }
  2881. if (($weightsByKey[$key] ?? 0) <= 0) {
  2882. continue;
  2883. }
  2884. $result[$key]++;
  2885. $remain--;
  2886. }
  2887. }
  2888. return $result;
  2889. }
  2890. /**
  2891. * 印件无形损 → 各工序:按 Gy0_计划损耗×联数×开数 占比分摊(外发不参与;可叠加无形损承担比例)
  2892. */
  2893. private function buildProcessIntangibleShareMap(
  2894. string $gdbh,
  2895. string $yjno,
  2896. array $gxhValues,
  2897. float $intangibleLoss
  2898. ): array {
  2899. if ($intangibleLoss <= 0 || empty($gxhValues)) {
  2900. return [];
  2901. }
  2902. $planTotal = $this->getIntangibleAllocationPlanLossTotal($gdbh, $yjno, $gxhValues);
  2903. if ($planTotal <= 0) {
  2904. return [];
  2905. }
  2906. $rows = db('工单_工艺资料')
  2907. ->field([
  2908. 'Gy0_gxh', 'Gy0_计划损耗', 'Gy0_ls', 'Gy0_ks',
  2909. 'rtrim(Gy0_gxmc) as gxmc', 'rtrim(Add_gxmc) as add_gxmc', '无形损承担比例',
  2910. ])
  2911. ->where(['Gy0_gdbh' => $gdbh, 'Gy0_yjno' => $yjno, 'Gy0_gxh' => ['in', $gxhValues]])
  2912. ->select();
  2913. $weights = [];
  2914. foreach ($rows as $row) {
  2915. $gxName = (string)($row['gxmc'] ?? '');
  2916. if (!empty($row['add_gxmc'])) {
  2917. $gxName .= '【' . $row['add_gxmc'] . '】';
  2918. }
  2919. if ($this->isSuperLossIntangibleExcluded($gxName)) {
  2920. continue;
  2921. }
  2922. $plan = floatval($row['Gy0_计划损耗']) * floatval($row['Gy0_ls']) * floatval($row['Gy0_ks']);
  2923. if ($plan <= 0) {
  2924. continue;
  2925. }
  2926. $rate = floatval($row['无形损承担比例'] ?? 0);
  2927. $weight = $plan * ($rate > 0 ? $rate : 1.0);
  2928. $gk = $this->normalizeGxhKey($row['Gy0_gxh']);
  2929. $weights[$gk] = ($weights[$gk] ?? 0.0) + $weight;
  2930. }
  2931. return $this->allocateIntegerByWeights((int)round($intangibleLoss), $weights);
  2932. }
  2933. /**
  2934. * 班组行无形损:先按工序计划损耗得工序份额,再按班组分摊计划损耗拆分到各行
  2935. */
  2936. private function assignIntangibleLossToGyDataRows(
  2937. array &$gyData,
  2938. string $gdbh,
  2939. string $yjno,
  2940. array $gxhValues,
  2941. float $intangibleLoss
  2942. ): void {
  2943. $processShares = $this->buildProcessIntangibleShareMap($gdbh, $yjno, $gxhValues, $intangibleLoss);
  2944. $indexesByGx = [];
  2945. foreach ($gyData as $idx => $row) {
  2946. $gk = $this->normalizeGxhKey($row['Gy0_gxh'] ?? '');
  2947. if ($gk === '') {
  2948. $gyData[$idx]['无形损分摊'] = 0;
  2949. continue;
  2950. }
  2951. $indexesByGx[$gk][] = $idx;
  2952. }
  2953. foreach ($indexesByGx as $gk => $indexes) {
  2954. $processShare = (int)($processShares[$gk] ?? 0);
  2955. if ($processShare <= 0) {
  2956. foreach ($indexes as $idx) {
  2957. $gyData[$idx]['无形损分摊'] = 0;
  2958. }
  2959. continue;
  2960. }
  2961. $weights = [];
  2962. foreach ($indexes as $idx) {
  2963. $weights[$idx] = max(0.0, floatval($gyData[$idx]['计划损耗'] ?? 0));
  2964. }
  2965. if (array_sum($weights) <= 0) {
  2966. foreach ($indexes as $idx) {
  2967. $weights[$idx] = 1.0;
  2968. }
  2969. }
  2970. $teamShares = $this->allocateIntegerByWeights($processShare, $weights);
  2971. foreach ($indexes as $idx) {
  2972. $gyData[$idx]['无形损分摊'] = (int)($teamShares[$idx] ?? 0);
  2973. }
  2974. }
  2975. }
  2976. /**
  2977. * 计酬产量换成张数。卷对卷按版距换算,版距为空或 0 时不除;卷对张不换算。
  2978. */
  2979. private function superLossSheetQty($rawQty, $ls, $ks, $printMode, $banju): int
  2980. {
  2981. $qty = (float)$rawQty;
  2982. if (trim((string)$printMode) === '卷对卷') {
  2983. $pitch = (float)$banju / 1000;
  2984. if ($pitch > 0) {
  2985. $qty = $qty / $pitch;
  2986. }
  2987. }
  2988. return (int)round($qty * (float)$ls * (float)$ks);
  2989. }
  2990. /**
  2991. * 按班组张数分摊工序计划损耗,尾差补到该工序最后一个有产量的班组
  2992. */
  2993. private function allocateSuperLossPlanShare(array &$rows, $sheetKey, $planKey, $shareKey, $gxhKey)
  2994. {
  2995. $groups = [];
  2996. foreach ($rows as $idx => $row) {
  2997. $gk = $this->normalizeGxhKey(isset($row[$gxhKey]) ? $row[$gxhKey] : '');
  2998. if ($gk === '') {
  2999. $rows[$idx][$shareKey] = 0;
  3000. continue;
  3001. }
  3002. $groups[$gk][] = $idx;
  3003. }
  3004. foreach ($groups as $indexes) {
  3005. $sheetSum = 0.0;
  3006. $plan = 0.0;
  3007. foreach ($indexes as $idx) {
  3008. $sheetSum += (float)$rows[$idx][$sheetKey];
  3009. $plan = (float)$rows[$idx][$planKey];
  3010. }
  3011. $allocated = 0;
  3012. $lastWithOutput = null;
  3013. foreach ($indexes as $idx) {
  3014. $sheet = (float)$rows[$idx][$sheetKey];
  3015. if ($sheetSum > 0 && $sheet > 0) {
  3016. $share = (int)round($sheet / $sheetSum * $plan);
  3017. $lastWithOutput = $idx;
  3018. } else {
  3019. $share = 0;
  3020. }
  3021. $rows[$idx][$shareKey] = $share;
  3022. $allocated += $share;
  3023. }
  3024. if ($lastWithOutput !== null) {
  3025. $rows[$lastWithOutput][$shareKey] += (int)round($plan) - $allocated;
  3026. }
  3027. }
  3028. }
  3029. /**
  3030. * 参与超节损的工序计划损耗合计:每道工序 Gy0_计划损耗 × 联数 × 开数,按工序号只计一次
  3031. */
  3032. private function sumSuperLossPlanLoss(string $gdbh, string $yjno, array $gxhValues): float
  3033. {
  3034. if (empty($gxhValues)) {
  3035. return 0.0;
  3036. }
  3037. $rows = db('工单_工艺资料')
  3038. ->where(['Gy0_gdbh' => $gdbh, 'Gy0_yjno' => $yjno, 'Gy0_gxh' => ['in', $gxhValues]])
  3039. ->field('Gy0_gxh, MAX(Gy0_计划损耗 * Gy0_ls * Gy0_ks) AS plan_loss')
  3040. ->group('Gy0_gxh')
  3041. ->select();
  3042. $sum = 0.0;
  3043. foreach ($rows as $row) {
  3044. $sum += floatval($row['plan_loss']);
  3045. }
  3046. return $sum;
  3047. }
  3048. /**
  3049. * 目标合格率(整数基点):(投料数 - 参与工序计划损耗合计) / 投料数
  3050. * 投料数与实际投料同一单位,调用方传入 实际投料 × 10000。
  3051. */
  3052. private function calcTargetRateBp(string $gdbh, string $yjno, array $gxhValues, float $feedQty): int
  3053. {
  3054. if ($feedQty <= 0) {
  3055. return 0;
  3056. }
  3057. $planLoss = $this->sumSuperLossPlanLoss($gdbh, $yjno, $gxhValues);
  3058. $bp = (int)round(($feedQty - $planLoss) / $feedQty * SuperLossRewardRule::BP_BASE);
  3059. if ($bp < 0) {
  3060. return 0;
  3061. }
  3062. if ($bp > SuperLossRewardRule::BP_BASE) {
  3063. return SuperLossRewardRule::BP_BASE;
  3064. }
  3065. return $bp;
  3066. }
  3067. /**
  3068. * 目标合格率(百分数,保留两位)
  3069. */
  3070. private function calcSuperLossTargetQualificationRate(string $gdbh, string $yjno, array $gxhValues, float $feedQty): float
  3071. {
  3072. return $this->calcTargetRateBp($gdbh, $yjno, $gxhValues, $feedQty) / 100;
  3073. }
  3074. /**
  3075. * 班组无形损分摊:印件无形损 ×(本班组计划损耗 / 全部工序计划损耗合计)
  3076. */
  3077. private function calcTeamIntangibleLossShare(
  3078. array $processRow,
  3079. float $teamPlanLoss,
  3080. float $processPlanLoss,
  3081. float $planLossTotal,
  3082. float $intangibleLoss
  3083. ): int {
  3084. $gxName = (string)($processRow['sczl_gxmc'] ?? $processRow['gxmc'] ?? '');
  3085. if ($this->isSuperLossIntangibleExcluded($gxName)) {
  3086. return 0;
  3087. }
  3088. $planBase = $teamPlanLoss > 0 ? $teamPlanLoss : $processPlanLoss;
  3089. return $this->calcIntangibleLossShareByPlanLoss(
  3090. $planBase,
  3091. $planLossTotal,
  3092. $intangibleLoss,
  3093. floatval($processRow['无形损承担比例'] ?? 0)
  3094. );
  3095. }
  3096. /**
  3097. * 班组打印补上只在 db_sczl 报工的拆片,并按工序号插回原位置。
  3098. * 拆片不进产量计酬,按计酬班组关联时对不上主手,整道工序不会出现在结果里。
  3099. */
  3100. private function mergeChaipianTeamRows(array $gyData, string $gdbh, $yjno, array $gxhValues): array
  3101. {
  3102. if ($gdbh === '' || $yjno === '' || empty($gxhValues)) {
  3103. return $gyData;
  3104. }
  3105. $chaipianGxh = db('工单_工艺资料')
  3106. ->where('Gy0_gdbh', $gdbh)
  3107. ->where('Gy0_yjno', $yjno)
  3108. ->where('Gy0_gxh', 'in', $gxhValues)
  3109. ->where(function ($query) {
  3110. $query->where('Gy0_gxmc', 'like', '%拆片%')
  3111. ->whereOr('Add_gxmc', 'like', '%拆片%');
  3112. })
  3113. ->column('Gy0_gxh');
  3114. if (empty($chaipianGxh)) {
  3115. return $gyData;
  3116. }
  3117. $before = count($gyData);
  3118. $gyData = $this->appendMissingSuperLossProcessRows(
  3119. $gyData,
  3120. array_values($chaipianGxh),
  3121. $gdbh,
  3122. (string)$yjno
  3123. );
  3124. if (count($gyData) <= $before) {
  3125. return $gyData;
  3126. }
  3127. $added = array_splice($gyData, $before);
  3128. foreach ($added as $row) {
  3129. $g = (int)($row['Gy0_gxh'] ?? 0);
  3130. $pos = count($gyData);
  3131. foreach ($gyData as $i => $exist) {
  3132. if ((int)($exist['Gy0_gxh'] ?? 0) > $g) {
  3133. $pos = $i;
  3134. break;
  3135. }
  3136. }
  3137. array_splice($gyData, $pos, 0, [$row]);
  3138. }
  3139. return $gyData;
  3140. }
  3141. /**
  3142. * 补全无产量报工、但应参与核算的工序(如外发、拆片等)的单行汇总
  3143. */
  3144. private function appendMissingSuperLossProcessRows(
  3145. array $gyData,
  3146. array $gxhValues,
  3147. string $gdbh,
  3148. string $yjno
  3149. ): array {
  3150. $present = [];
  3151. foreach ($gyData as $row) {
  3152. $present[$this->normalizeGxhKey($row['Gy0_gxh'])] = true;
  3153. }
  3154. $missing = [];
  3155. foreach ($gxhValues as $gv) {
  3156. if (!isset($present[$this->normalizeGxhKey($gv)])) {
  3157. $missing[] = $gv;
  3158. }
  3159. }
  3160. if (empty($missing)) {
  3161. return $gyData;
  3162. }
  3163. $payrollProcessSub = db('设备_产量计酬')
  3164. ->field('sczl_gdbh, sczl_yjno, sczl_gxh, SUM(sczl_zcfp) as sczl_zcfp, SUM(sczl_cl) as total_cl')
  3165. ->group('sczl_gdbh, sczl_yjno, sczl_gxh')
  3166. ->buildSql();
  3167. $sczlProcessSub = $this->buildSczlProcessAggSubSql();
  3168. $gxmcExpr = $this->processGxmcSqlExpr();
  3169. $processRows = db('工单_工艺资料')
  3170. ->alias('a')
  3171. ->field([
  3172. 'a.Gy0_gdbh', 'a.Gy0_yjno', 'a.Gy0_gxh', 'a.Gy0_ls', 'a.Gy0_ks', 'a.Gy0_计划损耗', 'a.超节损承担比例',
  3173. $gxmcExpr . ' AS sczl_gxmc',
  3174. 'b.sczl_zcfp', 'b.total_cl',
  3175. 'c.cl', 'c.fp',
  3176. 'a.无形损承担比例', 'a.Gy0_Rate0', 'a.Gy0_Rate1', 'a.损耗系数', 'a.Gy0_ms',
  3177. 'a.Gy0_计划接货数*a.Gy0_ls*a.Gy0_ks as 计划产量',
  3178. 'rtrim(a.Gy0_SITE) as Gy0_SITE', 'rtrim(a.印刷方式) as 印刷方式', 'rtrim(a.版距) as 版距',
  3179. ])
  3180. ->join([$payrollProcessSub => 'b'], 'a.Gy0_gdbh = b.sczl_gdbh AND a.Gy0_yjno = b.sczl_yjno AND a.Gy0_gxh = b.sczl_gxh', 'left')
  3181. ->join([$sczlProcessSub => 'c'], 'a.Gy0_gdbh = c.sczl_gdbh AND a.Gy0_yjno = c.sczl_yjno AND a.Gy0_gxh = c.sczl_gxh', 'left')
  3182. ->where(['a.Gy0_gdbh' => $gdbh, 'a.Gy0_yjno' => $yjno, 'a.Gy0_gxh' => ['in', $missing]])
  3183. ->select();
  3184. foreach ($processRows as $item) {
  3185. $item['sczl_bh1'] = '';
  3186. $item['sczl_bh'] = '';
  3187. $item['gxmc'] = '';
  3188. $item['sczl_jtbh'] = '';
  3189. $item['sczl_bzdh'] = '';
  3190. for ($j = 1; $j <= 10; $j++) {
  3191. $item['sczl_bh' . $j] = '';
  3192. $item['sczl_rate' . $j] = 0;
  3193. }
  3194. $teams = $this->buildGyRowsFromSczlTeams($gdbh, $yjno, $item['Gy0_gxh'], $item);
  3195. if (!empty($teams)) {
  3196. foreach ($teams as $teamRow) {
  3197. $gyData[] = $teamRow;
  3198. }
  3199. } else {
  3200. $this->fillSczlTeamMemberFields($item, $gdbh, $yjno);
  3201. $gyData[] = $item;
  3202. }
  3203. }
  3204. return $gyData;
  3205. }
  3206. /**
  3207. * 按需求 5.5.6 / 表 2 计算超节损奖罚倍率。
  3208. *
  3209. * 规则见 app\api\service\SuperLossRewardRule:
  3210. * - 材料原因报废率超过 1.5% 且没有索赔时豁免(不加大奖罚);
  3211. * - 其余按目标合格率分档、按实际与目标的偏差点数决定是否放大;
  3212. * - 端点包含(>= / <=),全部以整数基点计算,避免浮点边界误差。
  3213. *
  3214. * 结果同时缓存在 $this->superLossRewardRule 中,供落库写入追溯字段。
  3215. */
  3216. private function resolveSuperLossRewardMultiplier(
  3217. float $targetRate,
  3218. float $realRate,
  3219. float $materialWaste,
  3220. float $feedQty,
  3221. string $gdbh = '',
  3222. $yjno = ''
  3223. ): float {
  3224. $hasClaim = ($gdbh !== '' && $yjno !== '') ? $this->orderHasClaim($gdbh, $yjno) : false;
  3225. $rule = SuperLossRewardRule::resolve(
  3226. SuperLossRewardRule::toBp($targetRate),
  3227. SuperLossRewardRule::toBp($realRate),
  3228. $materialWaste,
  3229. $feedQty,
  3230. $hasClaim
  3231. );
  3232. $this->superLossRewardRule = $rule;
  3233. return (float)$rule['multiplier_rate'];
  3234. }
  3235. /**
  3236. * 工单是否存在材料索赔记录(决定 5.5.6 例外是否成立)
  3237. */
  3238. private function orderHasClaim(string $gdbh, $yjno): bool
  3239. {
  3240. try {
  3241. $count = db('工单_索赔记录')
  3242. ->where('gdbh', $gdbh)
  3243. ->where('yjno', intval($yjno))
  3244. ->count();
  3245. return $count > 0;
  3246. } catch (\Throwable $e) {
  3247. Log::error('超节损-查询索赔记录失败: ' . $e->getMessage());
  3248. return false;
  3249. }
  3250. }
  3251. /**
  3252. * 工单_质量考核汇总 的列清单(进程内缓存;表不存在或探测失败时返回空数组)
  3253. */
  3254. private function superLossRuleColumns(): array
  3255. {
  3256. static $columns = null;
  3257. if ($columns !== null) {
  3258. return $columns;
  3259. }
  3260. $columns = [];
  3261. try {
  3262. $rows = Db::query('SHOW COLUMNS FROM `工单_质量考核汇总`');
  3263. foreach ($rows as $row) {
  3264. if (!empty($row['Field'])) {
  3265. $columns[] = $row['Field'];
  3266. }
  3267. }
  3268. } catch (\Throwable $e) {
  3269. $columns = [];
  3270. Log::error('超节损-探测质量考核汇总表结构失败: ' . $e->getMessage());
  3271. }
  3272. return $columns;
  3273. }
  3274. /**
  3275. * 当前表结构中已存在的追溯字段(未执行 DDL 时为空数组,落库自动跳过,避免 Unknown column)
  3276. */
  3277. private function superLossRuleFields(): array
  3278. {
  3279. static $fields = null;
  3280. if ($fields !== null) {
  3281. return $fields;
  3282. }
  3283. $all = [
  3284. 'reward_multiplier', 'reward_tier', 'target_rate_bp', 'real_rate_bp',
  3285. 'material_waste_rate_bp', 'claim_exempt', 'rule_version',
  3286. ];
  3287. $columns = $this->superLossRuleColumns();
  3288. $fields = empty($columns) ? [] : array_values(array_intersect($all, $columns));
  3289. return $fields;
  3290. }
  3291. /**
  3292. * 从核算结果生成追溯字段(仅保留表里存在的列)
  3293. */
  3294. private function superLossRuleValues(?array $rule): array
  3295. {
  3296. if (empty($rule)) {
  3297. return [];
  3298. }
  3299. $fields = $this->superLossRuleFields();
  3300. if (empty($fields)) {
  3301. return [];
  3302. }
  3303. $map = [
  3304. 'reward_multiplier' => $rule['multiplier_rate'] ?? 1.0,
  3305. 'reward_tier' => (string)($rule['tier'] ?? ''),
  3306. 'target_rate_bp' => (int)($rule['target_rate_bp'] ?? 0),
  3307. 'real_rate_bp' => (int)($rule['real_rate_bp'] ?? 0),
  3308. 'material_waste_rate_bp' => (int)($rule['material_waste_rate_bp'] ?? 0),
  3309. 'claim_exempt' => (int)($rule['claim_exempt'] ?? 0),
  3310. 'rule_version' => (string)($rule['rule_version'] ?? ''),
  3311. ];
  3312. $values = [];
  3313. foreach ($fields as $field) {
  3314. $values[$field] = $map[$field];
  3315. }
  3316. return $values;
  3317. }
  3318. /**
  3319. * 读取某工单已落库的倍率追溯信息(表无新列或未核算过时返回 null)
  3320. */
  3321. private function getStoredSuperLossRule(string $gdbh, $yjno): ?array
  3322. {
  3323. if (empty($this->superLossRuleFields())) {
  3324. return null;
  3325. }
  3326. try {
  3327. $row = db('工单_质量考核汇总')
  3328. ->where('Gy0_gdbh', $gdbh)
  3329. ->where('印件及工序', $yjno)
  3330. ->field('MAX(reward_multiplier) AS reward_multiplier, MAX(target_rate_bp) AS target_rate_bp, MAX(rule_version) AS rule_version')
  3331. ->find();
  3332. return empty($row) ? null : $row;
  3333. } catch (\Throwable $e) {
  3334. return null;
  3335. }
  3336. }
  3337. /**
  3338. * 本工单命中的表2奖罚规则。材料报废率超过1.5%且没有索赔时返回例外说明。
  3339. */
  3340. private function formatSuperLossRewardRule(?array $rule): string
  3341. {
  3342. if (empty($rule)) {
  3343. return '';
  3344. }
  3345. if (!empty($rule['claim_exempt'])) {
  3346. return '材料原因报废率超过1.5%且没有索赔,不加大奖罚';
  3347. }
  3348. $tierCode = (string)($rule['tier'] ?? '');
  3349. if ($tierCode === '') {
  3350. return '奖罚1倍';
  3351. }
  3352. $labels = [
  3353. '>=97' => '≥97%',
  3354. '95-97' => '95%–97%',
  3355. '90-95' => '90%–95%',
  3356. '80-90' => '80%–90%',
  3357. '<=80' => '≤80%',
  3358. ];
  3359. $label = isset($labels[$tierCode]) ? $labels[$tierCode] : $tierCode;
  3360. $multiplierBp = (int)($rule['multiplier_bp'] ?? 100);
  3361. if (empty($rule['hit'])) {
  3362. $conf = SuperLossRewardRule::config();
  3363. foreach ($conf['tiers'] as $tier) {
  3364. if ((string)$tier['tier'] === $tierCode) {
  3365. $multiplierBp = (int)$tier['multiplier_bp'];
  3366. break;
  3367. }
  3368. }
  3369. }
  3370. $high = $this->formatRewardPoint((int)($rule['high_bp'] ?? 0));
  3371. $low = $this->formatRewardPoint((int)($rule['low_bp'] ?? 0));
  3372. $multiplier = $this->stringifyRewardMultiplier($multiplierBp / 100);
  3373. return '目标合格率' . $label . ',超出目标合格率' . $high . '个点,低于目标合格率' . $low . '个点,奖罚' . $multiplier . '倍';
  3374. }
  3375. /**
  3376. * 基点换算成表2里的“个点”:150 -> 1.5,200 -> 2.0,300 -> 3
  3377. */
  3378. private function formatRewardPoint(int $bp): string
  3379. {
  3380. if ($bp % 100 === 0 && $bp >= 300) {
  3381. return (string)(int)($bp / 100);
  3382. }
  3383. return number_format($bp / 100, 1, '.', '');
  3384. }
  3385. /**
  3386. * 倍率统一格式化为 1 / 1.3 / 1.6,避免 1.30 这类展示差异
  3387. */
  3388. private function stringifyRewardMultiplier($rate): string
  3389. {
  3390. $rate = (float)$rate;
  3391. if (abs($rate - 1.0) < 1e-9) {
  3392. return '1';
  3393. }
  3394. $text = number_format($rate, 2, '.', '');
  3395. return rtrim(rtrim($text, '0'), '.');
  3396. }
  3397. /**
  3398. * 索赔变更后重新核算该工单(异步,失败不影响索赔主流程)
  3399. */
  3400. private function enqueueSuperLossRecalc(string $gdbh, $yjno): void
  3401. {
  3402. try {
  3403. if ($gdbh === '' || $yjno === '') {
  3404. return;
  3405. }
  3406. Queue::push('app\\job\\OrderSuperLossJob', [
  3407. 'gdbh' => $gdbh,
  3408. 'yjno' => (string)$yjno,
  3409. ], 'order_loss_calculation');
  3410. } catch (\Throwable $e) {
  3411. Log::error('超节损-索赔变更后入队重算失败: ' . $e->getMessage() . '; gdbh=' . $gdbh . ', yjno=' . $yjno);
  3412. }
  3413. }
  3414. public function updateWorkorderStatus()
  3415. {
  3416. if ($this->request->isGet() == false) {
  3417. $this->error('请求错误');
  3418. }
  3419. $param = $this->request->param();
  3420. if (empty($param['workorder']) || empty($param['yjno']) || empty($param['status'])) {
  3421. $this->error('参数错误');
  3422. }
  3423. $sql = \db('工单_印件资料')
  3424. ->where('Yj_Gdbh',$param['workorder'])
  3425. ->where('yj_Yjno',$param['yjno'])
  3426. ->fetchSql(true)
  3427. ->update(['工单类型'=>$param['status']]);
  3428. $result = db()->query($sql);
  3429. if ($result !== false) {
  3430. $this->success('修改成功');
  3431. }else{
  3432. $this->error('修改失败');
  3433. }
  3434. }
  3435. // ============ 工单索赔记录(工单_索赔记录 表) ============
  3436. /**
  3437. * 获取索赔记录列表
  3438. * @ApiMethod GET
  3439. * @params string gdbh 工单编号
  3440. * @params int yjno 印件号
  3441. */
  3442. public function getClaimList()
  3443. {
  3444. if (!$this->request->isGet()) {
  3445. $this->error('非法请求');
  3446. }
  3447. $params = $this->request->param();
  3448. if (empty($params['gdbh']) || empty($params['yjno'])) {
  3449. $this->error('参数错误');
  3450. }
  3451. $list = \db('工单_索赔记录')
  3452. ->where('gdbh', $params['gdbh'])
  3453. ->where('yjno', intval($params['yjno']))
  3454. ->order('sys_rq desc, Uniqid desc')
  3455. ->select();
  3456. $this->success('成功', $list);
  3457. }
  3458. /**
  3459. * 新增索赔记录
  3460. * @ApiMethod POST
  3461. */
  3462. public function addClaim()
  3463. {
  3464. if (!$this->request->isPost()) {
  3465. $this->error('请求错误');
  3466. }
  3467. $param = $this->request->post();
  3468. $required = ['gdbh', 'yjno', 'wlbh', 'wl_name', 'num', 'sys_id'];
  3469. foreach ($required as $f) {
  3470. if (!isset($param[$f]) || $param[$f] === '' || $param[$f] === null) {
  3471. $this->error("参数 {$f} 不能为空");
  3472. }
  3473. }
  3474. $data = [
  3475. 'gdbh' => $param['gdbh'],
  3476. 'yjno' => intval($param['yjno']),
  3477. 'wlbh' => $param['wlbh'],
  3478. '物料名称' => $param['wl_name'],
  3479. 'num' => intval($param['num']),
  3480. 'sys_id' => $param['sys_id'],
  3481. 'sys_rq' => date('Y-m-d'),
  3482. ];
  3483. $sql = \db('工单_索赔记录')->fetchSql(true)->insert($data);
  3484. $res = Db::execute($sql);
  3485. if ($res) {
  3486. //索赔出现/变化会影响 5.5.6 例外判定,异步重算该工单
  3487. $this->enqueueSuperLossRecalc((string)$data['gdbh'], $data['yjno']);
  3488. $this->success('新增成功');
  3489. } else {
  3490. $this->error('新增失败');
  3491. }
  3492. }
  3493. /**
  3494. * 修改索赔记录(只允许修改 num;wlbh/物料名称 如需改也允许)
  3495. * @ApiMethod POST
  3496. */
  3497. public function updateClaim()
  3498. {
  3499. if (!$this->request->isPost()) {
  3500. $this->error('请求错误');
  3501. }
  3502. $param = $this->request->post();
  3503. if (empty($param['Uniqid'])) {
  3504. $this->error('参数 Uniqid 不能为空');
  3505. }
  3506. $update = [];
  3507. if (isset($param['num'])) {
  3508. $update['num'] = intval($param['num']);
  3509. }
  3510. if (isset($param['sys_id']) && $param['sys_id'] !== '') {
  3511. $update['sys_id'] = $param['sys_id'];
  3512. }
  3513. if (empty($update)) {
  3514. $this->error('没有需要更新的字段');
  3515. }
  3516. $sql = \db('工单_索赔记录')
  3517. ->where('Uniqid', intval($param['Uniqid']))
  3518. ->fetchSql(true)
  3519. ->update($update);
  3520. $res = Db::execute($sql);
  3521. if ($res !== false) {
  3522. $claim = \db('工单_索赔记录')->where('Uniqid', intval($param['Uniqid']))->find();
  3523. if (!empty($claim)) {
  3524. $this->enqueueSuperLossRecalc((string)$claim['gdbh'], $claim['yjno']);
  3525. }
  3526. $this->success('修改成功');
  3527. } else {
  3528. $this->error('修改失败');
  3529. }
  3530. }
  3531. /**
  3532. * 删除索赔记录
  3533. * @ApiMethod POST
  3534. */
  3535. public function deleteClaim()
  3536. {
  3537. if (!$this->request->isPost()) {
  3538. $this->error('请求错误');
  3539. }
  3540. $param = $this->request->post();
  3541. if (empty($param['Uniqid'])) {
  3542. $this->error('参数 Uniqid 不能为空');
  3543. }
  3544. //删除前先取工单信息,删除后用于触发重算
  3545. $claim = \db('工单_索赔记录')->where('Uniqid', intval($param['Uniqid']))->find();
  3546. $sql = \db('工单_索赔记录')->where('Uniqid', intval($param['Uniqid']))->fetchSql(true)->delete();
  3547. $res = Db::execute($sql);
  3548. if ($res !== false) {
  3549. if (!empty($claim)) {
  3550. $this->enqueueSuperLossRecalc((string)$claim['gdbh'], $claim['yjno']);
  3551. }
  3552. $this->success('删除成功');
  3553. } else {
  3554. $this->error('删除失败');
  3555. }
  3556. }
  3557. /**
  3558. * 产品质量改善措施管理 —— 工序质量缺陷明细
  3559. * 根据工单编号 + 印件号,从 db_qczl 汇总 fp_lb1-13 / fp_sl1-13,
  3560. * 相同类别的数量求和 → 每行一个"工序质量缺陷"类别。
  3561. * 占比 = 废品合计 / waste_ref(上方主表的"工单质检废"值)× 100,保留两位小数。
  3562. * @ApiMethod GET
  3563. * @Param string order 工单编号
  3564. * @Param string yjno 印件号
  3565. * @Param number waste_ref 可选,上方主表对应行的"工单质检废"值,用于计算占比
  3566. */
  3567. public function getOrderQuality()
  3568. {
  3569. if ($this->request->isGet() === false) {
  3570. $this->error('非法请求');
  3571. }
  3572. $params = $this->request->param();
  3573. if (empty($params['order']) || empty($params['yjno'])) {
  3574. $this->error('参数错误');
  3575. }
  3576. $order = trim($params['order']);
  3577. $yjno = trim($params['yjno']);
  3578. $wasteRef = isset($params['waste_ref']) ? floatval($params['waste_ref']) : 0;
  3579. // 从 db_qczl 取 fp_lb1-13 / fp_sl1-13 / sys_id(品质量员)
  3580. $sql = "SELECT
  3581. fp_lb1,fp_lb2,fp_lb3,fp_lb4,fp_lb5,fp_lb6,fp_lb7,fp_lb8,fp_lb9,fp_lb10,fp_lb11,fp_lb12,fp_lb13,
  3582. fp_sl1,fp_sl2,fp_sl3,fp_sl4,fp_sl5,fp_sl6,fp_sl7,fp_sl8,fp_sl9,fp_sl10,fp_sl11,fp_sl12,fp_sl13,
  3583. rtrim(sys_id) as sys_id
  3584. FROM db_qczl
  3585. WHERE qczl_gdbh = '{$order}' AND qczl_yjno = '{$yjno}'";
  3586. $rows = Db::query($sql);
  3587. // 废品分类字典校验:只有与 erp_常用字典(分类=废品分类)对得上的缺陷才保留
  3588. // 字典名称格式:废品分类_A-卷凹_A01-色差_ → 有效值为 A01-色差
  3589. $allowMap = [];
  3590. $dictNames = db('erp_常用字典')->where('分类', '废品分类')->column('名称');
  3591. foreach ($dictNames as $dictName) {
  3592. $dictName = trim($dictName);
  3593. if ($dictName === '') {
  3594. continue;
  3595. }
  3596. $parts = array_values(array_filter(explode('_', $dictName), function ($v) {
  3597. return trim($v) !== '';
  3598. }));
  3599. if (empty($parts)) {
  3600. continue;
  3601. }
  3602. $code = trim(end($parts));
  3603. if ($code === '') {
  3604. continue;
  3605. }
  3606. $allowMap[$code] = true;
  3607. // 兼容缺陷表只存中文名的情况(如 色差)
  3608. $pos = strpos($code, '-');
  3609. if ($pos !== false) {
  3610. $suffix = trim(substr($code, $pos + 1));
  3611. if ($suffix !== '') {
  3612. $allowMap[$suffix] = true;
  3613. }
  3614. }
  3615. }
  3616. // 按类别汇总数量:key = 类别名,value = 累计数量
  3617. $aggMap = [];
  3618. foreach ($rows as $entry) {
  3619. for ($i = 1; $i <= 13; $i++) {
  3620. $label = trim($entry['fp_lb' . $i] ?? '');
  3621. if ($label === '' || $label === null) continue;
  3622. // 字典中不存在该缺陷类别 → 不显示
  3623. if (!isset($allowMap[$label])) continue;
  3624. $sl = floatval($entry['fp_sl' . $i] ?? 0);
  3625. if (!isset($aggMap[$label])) {
  3626. $aggMap[$label] = 0;
  3627. }
  3628. $aggMap[$label] += $sl;
  3629. }
  3630. }
  3631. // 品质量员(取非空的第一个 sys_id)
  3632. $sysIds = array_values(array_unique(array_filter(array_column($rows, 'sys_id'))));
  3633. $qualityStaff = !empty($sysIds) ? $sysIds[0] : '';
  3634. // 印件名称
  3635. $productName = db('工单_基本资料')
  3636. ->where('Gd_gdbh', $order)
  3637. ->where('行号', $yjno)
  3638. ->value('成品名称');
  3639. if (empty($productName)) {
  3640. $productName = db('工单_基本资料')
  3641. ->where('Gd_gdbh', $order)
  3642. ->value('成品名称');
  3643. }
  3644. $productName = rtrim($productName ?: '');
  3645. // 组装返回
  3646. $list = [];
  3647. foreach ($aggMap as $label => $total) {
  3648. $rate = '';
  3649. if ($wasteRef > 0) {
  3650. $rate = number_format(($total / $wasteRef) * 100, 2) . '%';
  3651. } else {
  3652. $rate = '0.00%';
  3653. }
  3654. $list[] = [
  3655. '工序质量缺陷' => $label,
  3656. '废品合计' => $total,
  3657. '占比' => $rate,
  3658. '品质量员' => $qualityStaff,
  3659. '印件号' => $yjno,
  3660. '印件名称' => $productName,
  3661. ];
  3662. }
  3663. // 按废品合计倒序
  3664. usort($list, function ($a, $b) {
  3665. return $b['废品合计'] <=> $a['废品合计'];
  3666. });
  3667. $this->success('成功', $list);
  3668. }
  3669. /**
  3670. * 产品品质统计 —— 左侧树(年 → 月 → 厂商/客户)
  3671. * 数据源:成品入仓(末板完工工单)
  3672. * @ApiMethod GET
  3673. */
  3674. public function getProductQualityTab()
  3675. {
  3676. if (Request::instance()->isGet() == false) {
  3677. $this->error('非法请求');
  3678. }
  3679. $sql = "SELECT
  3680. DATE_FORMAT(a.jjcp_sj, '%Y') AS y,
  3681. DATE_FORMAT(a.jjcp_sj, '%m') AS m,
  3682. RTRIM(b.`编号`) AS 客户编号,
  3683. RTRIM(b.`名称`) AS 客户名称,
  3684. COUNT(DISTINCT a.jjcp_gdbh) AS cnt
  3685. FROM `成品入仓` a
  3686. LEFT JOIN `物料_存货结构` b
  3687. ON (CASE WHEN LEFT(a.jjcp_cpdh, 1) REGEXP '^[A-Za-z]' THEN LEFT(a.jjcp_cpdh, 5) ELSE LEFT(a.jjcp_cpdh, 4) END) = RTRIM(b.`编号`)
  3688. WHERE a.jjcp_smb IN ('末 板', '末板')
  3689. AND a.`成品编码` != ''
  3690. AND a.jjcp_sj >= DATE_SUB(CURDATE(), INTERVAL 24 MONTH)
  3691. GROUP BY y, m, 客户编号
  3692. ORDER BY y DESC, m DESC, 客户编号 ASC";
  3693. $rows = Db::query($sql);
  3694. $years = [];
  3695. foreach ($rows as $r) {
  3696. $y = $r['y'];
  3697. $m = $r['m'];
  3698. $custCode = $r['客户编号'] ?: '';
  3699. $custName = $r['客户名称'] ?: '(未匹配客户)';
  3700. $cnt = intval($r['cnt']);
  3701. if (!isset($years[$y])) {
  3702. $years[$y] = ['year' => $y, 'total' => 0, 'months' => []];
  3703. }
  3704. if (!isset($years[$y]['months'][$m])) {
  3705. $years[$y]['months'][$m] = ['month' => $m, 'total' => 0, 'customers' => []];
  3706. }
  3707. $years[$y]['months'][$m]['customers'][] = [
  3708. '客户编号' => $custCode,
  3709. '客户名称' => $custName,
  3710. 'total' => $cnt,
  3711. ];
  3712. $years[$y]['months'][$m]['total'] += $cnt;
  3713. $years[$y]['total'] += $cnt;
  3714. }
  3715. $result = [];
  3716. foreach ($years as $year) {
  3717. krsort($year['months']);
  3718. $months = [];
  3719. foreach ($year['months'] as $month) {
  3720. $months[] = $month;
  3721. }
  3722. $year['months'] = $months;
  3723. $result[] = $year;
  3724. }
  3725. $this->success('请求成功', $result);
  3726. }
  3727. /**
  3728. * 产品品质统计 —— 按产品合计 / 单产品工单明细
  3729. * @ApiMethod GET
  3730. * @Param string year 年份,如 2026
  3731. * @Param string month 月份,如 11(可选,不传则为整年)
  3732. * @Param string customer 客户编号(可选)
  3733. * @Param string cpdh 产品代号(可选,传值时返回该产品的工单明细)
  3734. */
  3735. public function getProductQualityList()
  3736. {
  3737. if (Request::instance()->isGet() == false) {
  3738. $this->error('非法请求');
  3739. }
  3740. $params = Request::instance()->param();
  3741. $year = trim($params['year'] ?? '');
  3742. $month = trim($params['month'] ?? '');
  3743. $customer = trim($params['customer'] ?? '');
  3744. $cpdh = trim($params['cpdh'] ?? '');
  3745. if ($year === '') {
  3746. $this->error('参数错误');
  3747. }
  3748. $dateLike = $month !== ''
  3749. ? $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '%'
  3750. : $year . '-%';
  3751. $rows = $this->queryProductQualityRows($dateLike);
  3752. // 按客户编号过滤(客户编号由产品代号前缀推导,与左侧树口径一致)
  3753. $filtered = [];
  3754. foreach ($rows as $r) {
  3755. $custCode = $this->productCustomerCode($r['产品代号']);
  3756. if ($customer === '__NONE__') {
  3757. // 左侧树的"未匹配客户"节点
  3758. if ($custCode !== '') {
  3759. continue;
  3760. }
  3761. } elseif ($customer !== '' && $custCode !== $customer) {
  3762. continue;
  3763. }
  3764. $r['客户编号'] = $custCode;
  3765. $filtered[] = $r;
  3766. }
  3767. // 工单明细
  3768. if ($cpdh !== '') {
  3769. $detail = [];
  3770. foreach ($filtered as $r) {
  3771. if (trim($r['产品代号']) !== $cpdh) {
  3772. continue;
  3773. }
  3774. $feed = floatval($r['实际投料']) * 10000;
  3775. $in = floatval($r['入仓数量']);
  3776. $loss = floatval($r['计划损耗']);
  3777. $fp = floatval($r['废品合计']);
  3778. $zcfp = floatval($r['制程废']);
  3779. $detail[] = [
  3780. '工单编号' => $r['Gd_gdbh'],
  3781. '印件号' => $r['yjno'],
  3782. '产品代号' => $r['产品代号'],
  3783. '产品名称' => $r['产品名称'],
  3784. '入仓日期' => $r['入仓日期'],
  3785. '入仓数量' => $in,
  3786. '实际投料' => $feed / 10000,
  3787. '废品合计' => $fp,
  3788. '工单制程废' => $zcfp,
  3789. '工单检验废' => $fp - $zcfp,
  3790. '目标合格率' => $feed > 0 ? number_format(($feed - $loss) / $feed * 100, 2) . '%' : '',
  3791. '实际合格率' => $feed > 0 ? number_format($in / $feed * 100, 2) . '%' : '',
  3792. ];
  3793. }
  3794. $this->success('成功', ['summary' => [], 'detail' => $detail]);
  3795. return;
  3796. }
  3797. // 按产品代号合计
  3798. $agg = [];
  3799. foreach ($filtered as $r) {
  3800. $code = trim($r['产品代号']);
  3801. if (!isset($agg[$code])) {
  3802. $agg[$code] = [
  3803. '产品代号' => $code,
  3804. '产品名称' => $r['产品名称'],
  3805. '工单数' => 0,
  3806. '入仓数量' => 0,
  3807. '实际投料' => 0,
  3808. '废品合计' => 0,
  3809. '工单制程废' => 0,
  3810. '计划损耗' => 0,
  3811. '工单集合' => [],
  3812. ];
  3813. }
  3814. $agg[$code]['工单集合'][$r['Gd_gdbh']] = true;
  3815. $agg[$code]['入仓数量'] += floatval($r['入仓数量']);
  3816. $agg[$code]['实际投料'] += floatval($r['实际投料']);
  3817. $agg[$code]['废品合计'] += floatval($r['废品合计']);
  3818. $agg[$code]['工单制程废'] += floatval($r['制程废']);
  3819. $agg[$code]['计划损耗'] += floatval($r['计划损耗']);
  3820. }
  3821. $summary = [];
  3822. foreach ($agg as $item) {
  3823. $feed = $item['实际投料'] * 10000;
  3824. $in = $item['入仓数量'];
  3825. $loss = $item['计划损耗'];
  3826. $fp = $item['废品合计'];
  3827. $zcfp = $item['工单制程废'];
  3828. $summary[] = [
  3829. '产品代号' => $item['产品代号'],
  3830. '产品名称' => $item['产品名称'],
  3831. '工单数' => count($item['工单集合']),
  3832. '入仓数量' => $in,
  3833. '实际投料' => $item['实际投料'],
  3834. '废品合计' => $fp,
  3835. '工单制程废' => $zcfp,
  3836. '工单检验废' => $fp - $zcfp,
  3837. '目标合格率' => $feed > 0 ? number_format(($feed - $loss) / $feed * 100, 2) . '%' : '',
  3838. '实际合格率' => $feed > 0 ? number_format($in / $feed * 100, 2) . '%' : '',
  3839. ];
  3840. }
  3841. // 按废品合计倒序
  3842. usort($summary, function ($a, $b) {
  3843. return $b['废品合计'] <=> $a['废品合计'];
  3844. });
  3845. $this->success('成功', ['summary' => $summary, 'detail' => []]);
  3846. }
  3847. /**
  3848. * 产品品质统计 —— 基础数据(按 工单编号+印件号 一行)
  3849. */
  3850. private function queryProductQualityRows($dateLike)
  3851. {
  3852. $subQuery = \db('成品入仓')
  3853. ->alias('a_sub')
  3854. ->field('
  3855. a_sub.jjcp_gdbh AS Gd_gdbh_sub,
  3856. a_sub.jjcp_yjno AS jjcp_yjno_sub,
  3857. SUM(a_sub.jjcp_sl) AS warehousing_num
  3858. ')
  3859. ->group('a_sub.jjcp_gdbh, a_sub.jjcp_yjno')
  3860. ->buildSql();
  3861. $field = '
  3862. a.jjcp_gdbh AS Gd_gdbh,
  3863. a.jjcp_yjno AS yjno,
  3864. RTRIM(a.jjcp_cpdh) AS 产品代号,
  3865. RTRIM(c.yj_yjmc) AS 产品名称,
  3866. DATE(a.jjcp_sj) AS 入仓日期,
  3867. total_sl.warehousing_num AS 入仓数量,
  3868. b.`实际投料` AS 实际投料,
  3869. b.`废品合计` AS 废品合计,
  3870. SUM(b.`班组制程废品`) AS 制程废,
  3871. SUM(DISTINCT b.`计划损耗`) AS 计划损耗
  3872. ';
  3873. return \db('成品入仓')
  3874. ->alias('a')
  3875. ->join('工单_质量考核汇总 b', 'a.jjcp_gdbh = b.Gy0_gdbh AND a.jjcp_yjno = b.印件及工序', 'left')
  3876. ->join('工单_印件资料 c', 'a.jjcp_gdbh = c.Yj_Gdbh AND a.jjcp_yjno = c.yj_Yjno', 'left')
  3877. ->join([$subQuery => 'total_sl'], 'a.jjcp_gdbh = total_sl.Gd_gdbh_sub AND a.jjcp_yjno = total_sl.jjcp_yjno_sub', 'left')
  3878. ->field($field)
  3879. ->where('a.jjcp_smb', 'in', ['末 板', '末板'])
  3880. ->where('a.成品编码', '<>', '')
  3881. ->where('a.jjcp_sj', 'like', $dateLike)
  3882. ->group('a.jjcp_gdbh, a.jjcp_yjno')
  3883. ->order('a.jjcp_sj DESC')
  3884. ->select();
  3885. }
  3886. /**
  3887. * 产品代号 → 客户编号(与左侧树 SQL 的 CASE 口径保持一致)
  3888. */
  3889. private function productCustomerCode($cpdh)
  3890. {
  3891. $cpdh = trim((string)$cpdh);
  3892. if ($cpdh === '') {
  3893. return '';
  3894. }
  3895. return preg_match('/^[A-Za-z]/', $cpdh) ? substr($cpdh, 0, 5) : substr($cpdh, 0, 4);
  3896. }
  3897. }