OrderSuperLoss.php 168 KB

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