ImportService.php 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\DailyDwOrder;
  6. use App\Model\DailyPwOrder;
  7. use App\Model\Depart;
  8. use App\Model\Device;
  9. use App\Model\Employee;
  10. use App\Model\EmployeeDepartPermission;
  11. use App\Model\Fee;
  12. use App\Model\Item;
  13. use App\Model\ItemDetails;
  14. use App\Model\MonthlyDdOrder;
  15. use App\Model\MonthlyPsOrder;
  16. use App\Model\MonthlyPwOrder;
  17. use App\Model\PLeaveOverOrder;
  18. use App\Model\RuleSet;
  19. use App\Model\RuleSetDetails;
  20. use Illuminate\Support\Facades\DB;
  21. use Maatwebsite\Excel\Facades\Excel;
  22. use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
  23. use PhpOffice\PhpSpreadsheet\IOFactory;
  24. use PhpOffice\PhpSpreadsheet\Shared\Date;
  25. class ImportService extends Service
  26. {
  27. public static $type = [
  28. 'depart', // 部门
  29. 'employee', // 用户
  30. 'device', // 设备
  31. 'item', // 项目
  32. 'fee', // 费用
  33. 'monthPwOrder', // 人员月度研发工时单
  34. 'monthDwOrder', // 设备月度研发工时单
  35. 'monthPsOrder', // 人员月度工资单
  36. 'monthDdOrder', // 设备月度折旧单
  37. 'ruleSet', // 规则配置单
  38. 'dailyPwOrder', // 人员日工时单
  39. 'dailyDwOrder', // 设备日工时单
  40. 'leaveOrder', // 请假单
  41. 'overtimeOrder', // 加班单
  42. 'feeOrder', // 费用项目单
  43. 'RDOrder', // 研发支出辅助帐
  44. ];
  45. public function getTableTitleXls($data,$user){
  46. if(empty($data['type'])) return [false,'缺少类型'];
  47. //获取配置文件
  48. // $fuc = $data['type'];
  49. // if (! method_exists(self::class, $fuc)) return [false, "导入文件方法获取不存在,请联系开发"];
  50. list($status,$return) = $this->title($data,$user);
  51. list($msg,$filename) = $return;
  52. if(! $status) return [false, $msg];
  53. $headers = array_column($msg,'value');
  54. $comments = $enums = [];
  55. foreach ($msg as $value){
  56. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  57. if(! empty($value['enums'])) $enums[$value['value']] = $value['enums'];
  58. }
  59. Excel::store(new TableHeadExport([], $headers, $comments, $enums),"/public/export/{$filename}", null, 'Xlsx', []);
  60. return [true, ['file' => $filename]];
  61. }
  62. private function getTableConfig($type = ""){
  63. if(empty($type)) return [];
  64. //获取配置文件
  65. $config = "excel." . $type;
  66. return config($config) ?? [];
  67. }
  68. private function title($data,$user){
  69. $config = $this->getTableConfig($data['type']);
  70. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  71. $config_array = $config['array'] ?? [];
  72. //生成下载文件
  73. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  74. return [true, [$config_array, $filename]];
  75. }
  76. //导入入口
  77. public function importAll($data,$user){
  78. // //不超时
  79. // ini_set('max_execution_time', 0);
  80. // //内存设置
  81. // ini_set('memory_limit', -1);
  82. // $reader = IOFactory::createReader('Xlsx');
  83. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  84. // $spreadsheet = $reader->load($data['file']);
  85. // dd($spreadsheet);
  86. // // 创建一个Reader对象
  87. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  88. //
  89. //// 加载Excel文件
  90. // $spreadsheet = $reader->load($data['file']);
  91. //
  92. //// 获取第一个工作表
  93. // $worksheet = $spreadsheet->getActiveSheet();
  94. //
  95. //// 获取总行数
  96. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  97. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  98. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  99. if(empty($data['file'])) return [false,'导入文件不能为空'];
  100. try {
  101. $import = new ImportAll();
  102. //设置导入人id
  103. $import->setCrt($user['id']);
  104. $import->setUser($user);
  105. $import->setType($data['type']);
  106. $other = $data;
  107. unset($other['file']);
  108. $import->setOtherParam($other);
  109. //导入
  110. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  111. if($import->getMsg()) {
  112. $bool = $import->getIsLongText();
  113. if($bool) {
  114. return [0, $import->getMsg()];
  115. }else{
  116. return [false, $import->getMsg()];
  117. }
  118. }
  119. }catch (\Throwable $exception) {
  120. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  121. }
  122. return [true, ''];
  123. }
  124. // 人 -----------------------------------
  125. public function employeeImport($array, $user, $other_param)
  126. {
  127. $upload = $array[0];
  128. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  129. if (!$status) return [false, $msg];
  130. $table_config = $msg;
  131. unset($array[0]);
  132. if (empty($array)) return [false, '导入数据不能为空'];
  133. // 1. 公共校验 (必填、唯一性等)
  134. list($array, $error) = $this->checkCommon($array, $table_config);
  135. if (!empty($error)) return [0, $error];
  136. // 2. 业务详细校验 (获取更新映射及明细数据)
  137. list($error, $update_map, $detail_data_map) = $this->employeeCheck($array, $user, $table_config);
  138. if (!empty($error)) return [0, $error];
  139. $time = time();
  140. $insert_data = [];
  141. $update_data = [];
  142. $all_detail_insert = []; // 用于聚合所有部门权限
  143. $update_main_ids = [];
  144. // 获取工号在配置中的索引
  145. $keys = array_column($table_config, 'key');
  146. $codeIdx = array_search('number', $keys);
  147. // 3. 数据分拣与聚合
  148. foreach ($array as $key => $value) {
  149. $empNumber = trim((string)$value[$codeIdx]);
  150. if ($empNumber === '') continue;
  151. $main_tmp = [];
  152. foreach ($value as $k => $val) {
  153. // 只要 is_main 为 true,就记录到主表。
  154. // 配置单中 depart_code 为 false,会自动被此处跳过
  155. if (!empty($table_config[$k]['is_main'])) {
  156. $main_tmp[$table_config[$k]['key']] = $val;
  157. }
  158. }
  159. if (isset($update_map[$key])) {
  160. // 更新逻辑:以 ID 为键去重
  161. $empId = $update_map[$key];
  162. $update_main_ids[$empId] = $empId;
  163. $update_data[$empId] = array_merge($main_tmp, ['id' => $empId]);
  164. // 收集部门明细
  165. if (isset($detail_data_map[$key])) {
  166. foreach ($detail_data_map[$key] as $d) {
  167. // 使用 工号_部门ID 确保明细不重复
  168. $all_detail_insert[$empNumber . '_' . $d['depart_id']] = [
  169. 'employee_id' => $empId,
  170. 'depart_id' => $d['depart_id'],
  171. 'top_depart_id' => $user['top_depart_id']
  172. ];
  173. }
  174. }
  175. } else {
  176. // 新增逻辑:以工号为键去重
  177. if (!isset($insert_data[$empNumber])) {
  178. $main_tmp['account'] = $user['top_depart_code'] . "_" . $empNumber;
  179. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  180. $main_tmp['crt_id'] = $user['id'];
  181. $main_tmp['crt_time'] = $time;
  182. $insert_data[$empNumber] = $main_tmp;
  183. }
  184. // 收集部门明细 (待回填主表 ID)
  185. if (isset($detail_data_map[$key])) {
  186. foreach ($detail_data_map[$key] as $d) {
  187. $all_detail_insert[$empNumber . '_' . $d['depart_id']] = [
  188. '_number' => $empNumber, // 临时标记
  189. 'depart_id' => $d['depart_id'],
  190. 'top_depart_id' => $user['top_depart_id']
  191. ];
  192. }
  193. }
  194. }
  195. }
  196. DB::beginTransaction();
  197. try {
  198. // 4. 执行新增主表
  199. $new_item_maps = [];
  200. if (!empty($insert_data)) {
  201. // 使用 array_values 将关联数组转为索引数组
  202. foreach (array_chunk(array_values($insert_data), 500) as $chunk) {
  203. Employee::insert($chunk);
  204. }
  205. // 获取新插入数据的 ID 映射
  206. $new_item_maps = Employee::whereIn('number', array_keys($insert_data))
  207. ->where('del_time', 0)
  208. ->where('top_depart_id', $user['top_depart_id'])
  209. ->pluck('id', 'number')->toArray();
  210. }
  211. // 5. 执行更新主表 (分批更新)
  212. if (!empty($update_data)) {
  213. foreach ($update_data as $uItem) {
  214. $id = $uItem['id'];
  215. unset($uItem['id']);
  216. Employee::where('id', $id)->update($uItem);
  217. }
  218. }
  219. // 6. 处理明细表 (先删后插策略)
  220. // 注意:分行模式下,更新人员的所有旧权限都要先清空
  221. if (!empty($update_main_ids)) {
  222. EmployeeDepartPermission::whereIn('employee_id', array_values($update_main_ids))->delete();
  223. }
  224. // 组装最终插入的明细数组并回填 ID
  225. $final_detail_insert = [];
  226. foreach ($all_detail_insert as $di) {
  227. if (isset($di['_number'])) {
  228. $di['employee_id'] = $new_item_maps[$di['_number']] ?? 0;
  229. unset($di['_number']);
  230. }
  231. if ($di['employee_id'] > 0) {
  232. $final_detail_insert[] = $di;
  233. }
  234. }
  235. // 批量插入所有明细
  236. if (!empty($final_detail_insert)) {
  237. foreach (array_chunk($final_detail_insert, 500) as $chunk) {
  238. EmployeeDepartPermission::insert($chunk);
  239. }
  240. }
  241. DB::commit();
  242. } catch (\Exception $e) {
  243. DB::rollBack();
  244. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  245. }
  246. return [true, ''];
  247. }
  248. private function getEmployeeList($array, $user, $index){
  249. //查找设备
  250. $codes = array_unique(array_filter(array_column($array,$index)));
  251. return Employee::where('del_time', 0)
  252. ->where('top_depart_id', $user['top_depart_id'])
  253. ->whereIn('number', $codes)
  254. ->pluck('id','number')
  255. ->toArray();
  256. }
  257. private function employeeCheck(&$array, $user, $table_config)
  258. {
  259. $keys = array_column($table_config, 'key');
  260. $codeIdx = array_search('number', $keys);
  261. $sexIdx = array_search('sex', $keys);
  262. $eductionIdx = array_search('education', $keys);
  263. $stateIdx = array_search('state', $keys);
  264. $manIdx = array_search('man_type', $keys);
  265. $entrustIdx = array_search('entrust_type', $keys);
  266. $depIdx = array_search('depart_code', $keys);
  267. $code_map = $this->getEmployeeList($array, $user, $codeIdx);
  268. $dep_map = $this->getEDataList($array, $user, $depIdx);
  269. $errors = [];
  270. $update_mapping = [];
  271. $detail_storage = [];
  272. $mainDataConsistency = []; // 用于存放工号对应的主表数据备份
  273. $sex_map = array_flip(Employee::SEX_TYPE);
  274. $e_map = array_flip(Employee::Education);
  275. $state_map = array_flip(Employee::State_Type);
  276. $man_map = array_flip(Employee::Man_Type);
  277. $wt_map = array_flip(Employee::WT_Type);
  278. // 获取所有标记为 is_main 的列索引,用于一致性对比
  279. $mainColIndices = [];
  280. foreach ($table_config as $index => $conf) {
  281. if (!empty($conf['is_main'])) $mainColIndices[$index] = $conf['value'];
  282. }
  283. foreach ($array as $rowIndex => $rowValue) {
  284. $displayLine = $rowIndex + 1;
  285. $valCode = trim($rowValue[$codeIdx] ?? '');
  286. if ($valCode === '') continue;
  287. // --- 核心:一致性校验 ---
  288. if (!isset($mainDataConsistency[$valCode])) {
  289. // 第一次遇见该工号,记录其所有主表字段的值
  290. foreach ($mainColIndices as $idx => $label) {
  291. $mainDataConsistency[$valCode][$idx] = trim($rowValue[$idx] ?? '');
  292. }
  293. } else {
  294. // 再次遇见该工号,对比主表字段是否一致
  295. foreach ($mainColIndices as $idx => $label) {
  296. $currentVal = trim($rowValue[$idx] ?? '');
  297. if ($currentVal !== $mainDataConsistency[$valCode][$idx]) {
  298. $errors[] = "第{$displayLine}行:工号[{$valCode}]的主表数据[{$label}]与前文不一致";
  299. }
  300. }
  301. }
  302. // 1. 判定更新还是新增
  303. if (isset($code_map[$valCode])) {
  304. $update_mapping[$rowIndex] = $code_map[$valCode];
  305. }
  306. // 2. 校验(性别、学历、状态映射转换)
  307. // 性别
  308. $sex_text = trim($rowValue[$sexIdx] ?? '');
  309. if (!empty($sex_text)) {
  310. if (!isset($sex_map[$sex_text])) {
  311. $errors[] = "第{$displayLine}行:性别[{$sex_text}]无效";
  312. } else {
  313. $array[$rowIndex][$sexIdx] = $sex_map[$sex_text];
  314. }
  315. }
  316. // 学历
  317. $e_text = trim($rowValue[$eductionIdx] ?? '');
  318. if (!empty($e_text)) {
  319. if (!isset($e_map[$e_text])) {
  320. $errors[] = "第{$displayLine}行:学历[{$e_text}]无效";
  321. } else {
  322. $array[$rowIndex][$eductionIdx] = $e_map[$e_text];
  323. }
  324. }
  325. // 状态
  326. $state_text = trim($rowValue[$stateIdx] ?? '');
  327. if (!isset($state_map[$state_text])) {
  328. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  329. } else {
  330. $array[$rowIndex][$stateIdx] = $state_map[$state_text];
  331. }
  332. //人员类别
  333. $man_text = trim($rowValue[$manIdx] ?? '');
  334. if (!isset($man_map[$man_text])) {
  335. $errors[] = "第{$displayLine}行:人员类别[{$man_text}]无效";
  336. } else {
  337. $array[$rowIndex][$manIdx] = $man_map[$man_text];
  338. }
  339. //委托类型
  340. $wt_text = trim($rowValue[$entrustIdx] ?? '');
  341. if (!isset($wt_map[$wt_text])) {
  342. $errors[] = "第{$displayLine}行:委托方式[{$wt_text}]无效";
  343. } else {
  344. $array[$rowIndex][$entrustIdx] = $wt_map[$wt_text];
  345. }
  346. // 4. 解析部门 (分行模式)
  347. if ($depIdx !== false && !empty($rowValue[$depIdx])) {
  348. $mNum = trim($rowValue[$depIdx]);
  349. if (!isset($dep_map[$mNum])) {
  350. $errors[] = "第{$displayLine}行:部门编码[{$mNum}]不存在";
  351. } else {
  352. $detail_storage[$rowIndex][] = ['depart_id' => $dep_map[$mNum]];
  353. }
  354. }
  355. }
  356. $error_str = !empty($errors) ? implode('|', $errors) : "";
  357. return [$error_str, $update_mapping, $detail_storage];
  358. }
  359. private function getEDataList($array, $user, $index1)
  360. {
  361. $depNums = [];
  362. // 去重收集
  363. foreach ($array as $row) {
  364. if (!empty($row[$index1])) {
  365. foreach (explode(',', $row[$index1]) as $v) $depNums[trim($v)] = true;
  366. }
  367. }
  368. return Depart::where('del_time', 0)
  369. ->where('top_depart_id', $user['top_depart_id'])
  370. ->whereIn('code', array_keys($depNums))
  371. ->pluck('id', 'code')->toArray();
  372. }
  373. // 部门 ----------------------------------
  374. public function departImport($array, $user, $other_param)
  375. {
  376. $upload = $array[0];
  377. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  378. if (!$status) return [false, $msg];
  379. $table_config = $msg;
  380. unset($array[0]);
  381. if (empty($array)) return [false, '导入数据不能为空'];
  382. list($array, $error) = $this->checkCommon($array, $table_config);
  383. if (!empty($error)) return [0, $error];
  384. // 2. 详细校验
  385. list($error, $update_map, $parent_code_map) = $this->departCheck($array, $user, $table_config);
  386. if (!empty($error)) return [0, $error];
  387. $time = time();
  388. $insert = [];
  389. $update = [];
  390. $all_codes = [];
  391. $all_parent_codes = [];
  392. // --- 修正点 1: 必须确保索引提取准确 ---
  393. $keys = array_column($table_config, 'key');
  394. $codeIdx = array_search('code', $keys);
  395. // ------------------------------------
  396. $ignoreKeys = ['parent_id', 'parent_title'];
  397. foreach ($array as $key => $value) {
  398. $cCode = trim($value[$codeIdx] ?? '');
  399. if($cCode === '') continue;
  400. $all_codes[] = $cCode;
  401. if (isset($parent_code_map[$key])) {
  402. $all_parent_codes[] = $parent_code_map[$key];
  403. }
  404. $main_tmp = [];
  405. foreach ($value as $k => $val){
  406. if(!empty($table_config[$k]['is_main'])){
  407. if (!in_array($table_config[$k]['key'], $ignoreKeys)) {
  408. $main_tmp[$table_config[$k]['key']] = $val;
  409. }
  410. }
  411. }
  412. if (isset($update_map[$key])) {
  413. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  414. } else {
  415. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  416. $main_tmp['crt_time'] = $time;
  417. $main_tmp['parent_id'] = 0;
  418. $insert[] = $main_tmp;
  419. }
  420. }
  421. $searchCodes = array_unique(array_merge($all_codes, $all_parent_codes));
  422. DB::beginTransaction();
  423. try {
  424. if (!empty($insert)) {
  425. foreach (array_chunk($insert, 500) as $chunk) {
  426. Depart::insert($chunk);
  427. }
  428. }
  429. if (!empty($update)) {
  430. foreach ($update as $item) {
  431. $uId = $item['id']; unset($item['id']);
  432. Depart::where('id', $uId)->update($item);
  433. }
  434. }
  435. // --- 修正点 2: 核心回填逻辑 ---
  436. $newCodeToIdMap = Depart::where('del_time', 0)
  437. ->where('top_depart_id', $user['top_depart_id'])
  438. ->whereIn('code', $searchCodes)
  439. ->pluck('id', 'code')
  440. ->toArray();
  441. foreach ($parent_code_map as $rowIndex => $pCode) {
  442. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  443. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  444. $pCode = trim($pCode);
  445. if ($currentCode === '' || $pCode === '') continue;
  446. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  447. $parentId = $newCodeToIdMap[$pCode] ?? null;
  448. if($pCode == $user['top_depart_code']) $parentId = $user['top_depart_id'];
  449. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  450. if ($currentId && $parentId && $currentId != $parentId) {
  451. Depart::where('id', $currentId)->update(['parent_id' => $parentId]);
  452. }
  453. }
  454. DB::commit();
  455. } catch (\Exception $e) {
  456. DB::rollBack();
  457. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  458. }
  459. return [true, ''];
  460. }
  461. private function departCheck(&$array, $user, $table_config)
  462. {
  463. $keys = array_column($table_config, 'key');
  464. $codeIdx = array_search('code', $keys);
  465. $parentIdx = array_search('parent_id', $keys);
  466. // 1. 获取基础数据
  467. list($dbFeeMap, $excelCodesMap) = $this->getDepartList($array, $user, $codeIdx);
  468. $errors = [];
  469. $update = [];
  470. $parent_code_map = [];
  471. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  472. $currentExcelMap = [];
  473. foreach ($array as $row) {
  474. $c = trim($row[$codeIdx] ?? '');
  475. $p = trim($row[$parentIdx] ?? '');
  476. if ($c !== '') $currentExcelMap[$c] = $p ?: $user['top_depart_code'] ;
  477. }
  478. // 3. 逐行校验
  479. foreach ($array as $rowIndex => $value) {
  480. $displayLine = $rowIndex + 1;
  481. $valCode = trim($value[$codeIdx] ?? '');
  482. $valParentCode = trim($value[$parentIdx] ?? '');
  483. if ($valCode === '') continue;
  484. // 更新状态记录
  485. if (isset($dbFeeMap[$valCode])) {
  486. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  487. }
  488. if ($valParentCode !== '') {
  489. // --- A. 存在性校验 ---
  490. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  491. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  492. $errors[] = "第{$displayLine}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  493. continue;
  494. }
  495. // --- B. 自引用校验 ---
  496. if ($valCode === $valParentCode) {
  497. $errors[] = "第{$displayLine}行:上级编码不能是自身";
  498. continue;
  499. }
  500. // --- C. 环路追溯 ---
  501. $visited = [];
  502. $res = $this->findDLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  503. if ($res !== false) {
  504. if ($res['type'] === 'LOOP_SELF') {
  505. $errors[] = "第{$displayLine}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  506. } else {
  507. $errors[] = "第{$displayLine}行:上级[{$valParentCode}]的溯源链条已成环";
  508. }
  509. continue;
  510. }
  511. // 记录有效的父级关系
  512. $parent_code_map[$rowIndex] = $valParentCode;
  513. }else{
  514. $parent_code_map[$rowIndex] = $user['top_depart_code'];
  515. }
  516. }
  517. $error_string = !empty($errors) ? implode('|', $errors) : "";
  518. return [$error_string, $update, $parent_code_map];
  519. }
  520. private function getDepartList($array, $user, $index)
  521. {
  522. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  523. $codesInExcel = [];
  524. foreach ($array as $row) {
  525. $c = trim($row[$index] ?? '');
  526. if ($c !== '') {
  527. $codesInExcel[$c] = true;
  528. }
  529. }
  530. $allFees = Depart::where('del_time', 0)
  531. ->where('top_depart_id', $user['top_depart_id'])
  532. ->select('id', 'code', 'parent_id')
  533. ->get();
  534. $dbFeeMap = [];
  535. foreach ($allFees as $fee) {
  536. $dbFeeMap[$fee->code] = [
  537. 'id' => $fee->id,
  538. 'code' => $fee->code,
  539. 'parent_id' => $fee->parent_id
  540. ];
  541. }
  542. // 返回数据库映射和 Excel 编码映射
  543. return [$dbFeeMap, $codesInExcel];
  544. }
  545. private function findDLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  546. {
  547. $current = $startParentCode;
  548. while ($current !== '' && $current !== 0) {
  549. if ($current === $targetCode) {
  550. return ['type' => 'LOOP_SELF', 'code' => $current];
  551. }
  552. if (isset($visited[$current])) {
  553. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  554. }
  555. $visited[$current] = true;
  556. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  557. $current = $excelMap[$current];
  558. } elseif (isset($dbFeeMap[$current])) {
  559. $parentId = $dbFeeMap[$current]['parent_id'];
  560. $parentCode = '';
  561. foreach ($dbFeeMap as $item) {
  562. if ($item['id'] == $parentId) {
  563. $parentCode = $item['code'];
  564. break;
  565. }
  566. }
  567. $current = $parentCode;
  568. } else {
  569. break;
  570. }
  571. }
  572. return false;
  573. }
  574. // 设备 ------------------------------------
  575. public function deviceImport($array, $user, $other_param){
  576. $upload = $array[0];
  577. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  578. if(!$status) return [false, $msg];
  579. $table_config = $msg;
  580. unset($array[0]);
  581. if(empty($array)) return [false, '导入数据不能为空'];
  582. // 公共校验
  583. list($array, $error) = $this->checkCommon($array, $table_config);
  584. if(!empty($error)) return [0, $error];
  585. // 详细校验 (这里 $array 传引用,内部会转换日期)
  586. list($error, $update_map) = $this->deviceCheck($array, $user, $table_config);
  587. if(!empty($error)) return [0, $error];
  588. $time = time();
  589. $insert = [];
  590. $update = [];
  591. foreach ($array as $key => $value){
  592. $main_tmp = [];
  593. foreach ($value as $k => $val){
  594. if(!empty($table_config[$k]['is_main'])){
  595. $main_tmp[$table_config[$k]['key']] = $val;
  596. }
  597. }
  598. if(isset($update_map[$key])){
  599. // 存入待更新数组
  600. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  601. } else {
  602. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  603. $main_tmp['crt_id'] = $user['id'];
  604. $main_tmp['crt_time'] = $time;
  605. $insert[] = $main_tmp;
  606. }
  607. }
  608. DB::beginTransaction();
  609. try {
  610. // 1. 批量新增
  611. if(!empty($insert)){
  612. foreach(array_chunk($insert, 500) as $chunkInsert){
  613. Device::insert($chunkInsert);
  614. }
  615. }
  616. // 批量更新
  617. foreach (array_chunk($update, 100) as $chunk) {
  618. foreach ($chunk as $item) {
  619. $id = $item['id'];
  620. unset($item['id']);
  621. Device::where('id', $id)->update($item);
  622. }
  623. }
  624. DB::commit();
  625. } catch (\Exception $e) {
  626. DB::rollBack();
  627. return [false, "错误:" . $e->getMessage() . " 行:" . $e->getLine()];
  628. }
  629. return [true, ''];
  630. }
  631. private function deviceCheck(&$array, $user, $table_config)
  632. {
  633. // 动态获取关键列的索引
  634. $codeIdx = array_search('code', array_column($table_config, 'key'));
  635. $dateIdx = array_search('in_time', array_column($table_config, 'key'));
  636. $typeIdx = array_search('type', array_column($table_config, 'key'));
  637. $type2Idx = array_search('is_use', array_column($table_config, 'key'));
  638. $code_map = $this->getDeviceList($array, $user, $codeIdx);
  639. $errors = [];
  640. $update = [];
  641. $map_type = array_flip(Device::$type);
  642. $map_type_2 = array_flip(Device::Use);
  643. foreach ($array as $rowIndex => $value) {
  644. $displayLine = $rowIndex + 1;
  645. $valCode = $value[$codeIdx] ?? '';
  646. // 记录更新 ID
  647. if(isset($code_map[$valCode])){
  648. $update[$rowIndex] = $code_map[$valCode];
  649. }
  650. if(empty($map_type[$value[$typeIdx]])){
  651. $errors[] = "第{$displayLine}行固定资产类型错误";
  652. }else{
  653. $array[$rowIndex][$typeIdx] = $map_type[$value[$typeIdx]];
  654. }
  655. if(empty($map_type_2[$value[$type2Idx]])){
  656. $errors[] = "第{$displayLine}行是否启用错误";
  657. }else{
  658. $array[$rowIndex][$type2Idx] = $map_type_2[$value[$type2Idx]];
  659. }
  660. // 日期处理
  661. if($dateIdx !== false && !empty($value[$dateIdx])){
  662. list($status, $msg) = $this->convertExcelCellToDate($value[$dateIdx]);
  663. if(!$status) {
  664. $errors[] = "第{$displayLine}行日期格式错误";
  665. } else {
  666. $array[$rowIndex][$dateIdx] = $msg;
  667. }
  668. }
  669. }
  670. $error_string = "";
  671. if(! empty($errors)) $error_string = implode('|', $errors);
  672. return [$error_string, $update];
  673. }
  674. private function getDeviceList($array, $user, $index){
  675. //查找设备
  676. $codes = array_unique(array_filter(array_column($array,$index)));
  677. return Device::where('del_time', 0)
  678. ->where('top_depart_id', $user['top_depart_id'])
  679. ->whereIn('code', $codes)
  680. ->pluck('id','code')
  681. ->toArray();
  682. }
  683. // 项目 -----------------------------------
  684. private function getItemList($array, $user, $index){
  685. //查找设备
  686. $codes = array_unique(array_filter(array_column($array,$index)));
  687. return Item::where('del_time', 0)
  688. ->where('top_depart_id', $user['top_depart_id'])
  689. ->whereIn('code', $codes)
  690. ->pluck('id','code')
  691. ->toArray();
  692. }
  693. public function itemImport($array, $user, $other_param)
  694. {
  695. $upload = $array[0];
  696. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  697. if (!$status) return [false, $msg];
  698. $table_config = $msg;
  699. unset($array[0]);
  700. if (empty($array)) return [false, '导入数据不能为空'];
  701. // 1. 公共校验 (必填、唯一性等)
  702. list($array, $error) = $this->checkCommon($array, $table_config);
  703. if (!empty($error)) return [0, $error];
  704. // 2. 业务详细校验 (包含一致性校验、明细解析)
  705. list($error, $update_map, $detail_data_map) = $this->itemCheck($array, $user, $table_config);
  706. if (!empty($error)) return [0, $error];
  707. $time = time();
  708. $insert_data = [];
  709. $update_data = [];
  710. $all_detail_insert = [];
  711. $update_main_ids = [];
  712. $keys = array_column($table_config, 'key');
  713. $codeIdx = array_search('code', $keys);
  714. // 3. 数据分拣(聚合平铺数据)
  715. foreach ($array as $key => $value) {
  716. $itemCode = trim($value[$codeIdx]);
  717. $main_tmp = [];
  718. foreach ($value as $k => $val) {
  719. if (!empty($table_config[$k]['is_main'])) {
  720. if ($table_config[$k]['key'] == 'employee_title') continue;
  721. $main_tmp[$table_config[$k]['key']] = $val;
  722. }
  723. }
  724. if (isset($update_map[$key])) {
  725. // 更新逻辑:以 ID 为键去重
  726. $itemId = $update_map[$key];
  727. $update_main_ids[$itemId] = $itemId;
  728. $update_data[$itemId] = array_merge($main_tmp, ['id' => $itemId]);
  729. if (isset($detail_data_map[$key])) {
  730. foreach ($detail_data_map[$key] as $d) {
  731. $all_detail_insert[] = array_merge($d, [
  732. 'item_id' => $itemId,
  733. 'crt_time' => $time,
  734. 'top_depart_id' => $user['top_depart_id']
  735. ]);
  736. }
  737. }
  738. } else {
  739. // 新增逻辑:以项目编码为键去重
  740. if (!isset($insert_data[$itemCode])) {
  741. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  742. $main_tmp['crt_id'] = $user['id'];
  743. $main_tmp['crt_time'] = $time;
  744. $insert_data[$itemCode] = $main_tmp;
  745. }
  746. if (isset($detail_data_map[$key])) {
  747. foreach ($detail_data_map[$key] as $d) {
  748. $all_detail_insert[] = array_merge($d, [
  749. '_code' => $itemCode,
  750. 'crt_time' => $time,
  751. 'top_depart_id' => $user['top_depart_id']
  752. ]);
  753. }
  754. }
  755. }
  756. }
  757. DB::beginTransaction();
  758. try {
  759. // 4. 执行新增主表
  760. $new_item_maps = [];
  761. if (!empty($insert_data)) {
  762. foreach (array_chunk(array_values($insert_data), 500) as $chunk) {
  763. Item::insert($chunk);
  764. }
  765. $new_item_maps = Item::whereIn('code', array_keys($insert_data))
  766. ->where('del_time', 0)
  767. ->where('top_depart_id', $user['top_depart_id'])
  768. ->pluck('id', 'code')->toArray();
  769. }
  770. // 5. 执行更新主表
  771. if (!empty($update_data)) {
  772. foreach ($update_data as $id => $uItem) {
  773. unset($uItem['id']);
  774. Item::where('id', $id)->update($uItem);
  775. }
  776. }
  777. // 6. 处理明细表 (先全删后插)
  778. if (!empty($update_main_ids)) {
  779. ItemDetails::whereIn('item_id', array_values($update_main_ids))
  780. ->where('del_time', 0)
  781. ->update(['del_time' => $time]);
  782. }
  783. foreach ($all_detail_insert as &$di) {
  784. if (isset($di['_code'])) {
  785. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  786. unset($di['_code']);
  787. }
  788. }
  789. unset($di);
  790. if (!empty($all_detail_insert)) {
  791. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  792. ItemDetails::insert($chunk);
  793. }
  794. }
  795. DB::commit();
  796. } catch (\Exception $e) {
  797. DB::rollBack();
  798. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  799. }
  800. return [true, ''];
  801. }
  802. private function itemCheck(&$array, $user, $table_config)
  803. {
  804. $keys = array_column($table_config, 'key');
  805. $codeIdx = array_search('code', $keys);
  806. $stateIdx = array_search('state', $keys);
  807. $attrIdx = array_search('item_attribute', $keys);
  808. $budgetIdx = array_search('budget', $keys);
  809. $typeIdx = array_search('type', $keys); // 明细类型列
  810. $code2Idx = array_search('code_2', $keys); // 资产/工号列
  811. $dateIdx = array_search('start_time', $keys);
  812. $date2Idx = array_search('end_time', $keys);
  813. $empIdx = array_search('charge_id', $keys);
  814. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  815. $dbEmps = Employee::where('del_time', 0)
  816. ->whereIn('number', $allEmpNumbers)
  817. ->where('top_depart_id', $user['top_depart_id'])
  818. ->pluck('id', 'number')->toArray();
  819. $code_map = $this->getItemList($array, $user, $codeIdx);
  820. // 这里的 getDataList 需要适配平铺后的 code_2 列
  821. list($man_map, $device_map) = $this->getFlatDataList($array, $user, $typeIdx, $code2Idx);
  822. $errors = [];
  823. $update_mapping = [];
  824. $detail_storage = [];
  825. $mainDataConsistency = []; // 一致性校验
  826. $state_type_map = array_flip(Item::State_Type);
  827. $attr_map = array_flip(Item::Item_Attribute);
  828. $detail_type_map = array_flip(ItemDetails::$type_name);
  829. // 识别主表字段列索引
  830. $mainColIndices = [];
  831. foreach ($table_config as $index => $conf) {
  832. if (!empty($conf['is_main'])) $mainColIndices[$index] = $conf['value'];
  833. }
  834. foreach ($array as $rowIndex => $rowValue) {
  835. $displayLine = $rowIndex + 1;
  836. $valCode = trim($rowValue[$codeIdx] ?? '');
  837. $valEmp = trim($rowValue[$empIdx] ?? '');
  838. if ($valCode === '') continue;
  839. // --- A. 主表一致性校验 ---
  840. if (!isset($mainDataConsistency[$valCode])) {
  841. $mainDataConsistency[$valCode] = array_intersect_key($rowValue, $mainColIndices);
  842. } else {
  843. foreach ($mainColIndices as $idx => $label) {
  844. if (trim($rowValue[$idx] ?? '') != trim($mainDataConsistency[$valCode][$idx] ?? '')) {
  845. $errors[] = "第{$displayLine}行:项目[{$valCode}]的主表信息[{$label}]与前文不一致";
  846. }
  847. }
  848. }
  849. // --- B. 基础校验 ---
  850. if (isset($code_map[$valCode])) {
  851. $update_mapping[$rowIndex] = $code_map[$valCode];
  852. }
  853. // 状态
  854. $state_text = $rowValue[$stateIdx] ?? '';
  855. if (!isset($state_type_map[$state_text])) {
  856. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  857. } else {
  858. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  859. }
  860. $attr_text = $rowValue[$attrIdx] ?? '';
  861. if (!isset($attr_map[$attr_text])) {
  862. $errors[] = "第{$displayLine}行:项目属性[{$attr_text}]无效";
  863. } else {
  864. $array[$rowIndex][$attrIdx] = $attr_map[$attr_text];
  865. }
  866. $budget_text = $rowValue[$budgetIdx] ?? 0;
  867. if(! empty($budget_text)){
  868. $res = $this->checkNumber($budget_text, 2, 'non-negative');
  869. if (!$res['valid']) $errors[] = "第{$displayLine}行预算:" . $res['error'];
  870. }
  871. // D. 人员校验
  872. if(! empty($valEmp)){
  873. if (!isset($dbEmps[$valEmp])) {
  874. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  875. } else {
  876. $array[$rowIndex][$empIdx] = $dbEmps[$valEmp];
  877. }
  878. }
  879. // 日期转换
  880. foreach ([$dateIdx, $date2Idx] as $dIdx) {
  881. if ($dIdx !== false && !empty($rowValue[$dIdx])) {
  882. list($s, $m) = $this->convertExcelCellToDate($rowValue[$dIdx]);
  883. if (!$s) $errors[] = "第{$displayLine}行:日期格式非法";
  884. else $array[$rowIndex][$dIdx] = $m;
  885. }
  886. }
  887. // --- C. 解析明细 (一行一个明细) ---
  888. $typeName = trim($rowValue[$typeIdx] ?? '');
  889. $subCode = trim($rowValue[$code2Idx] ?? '');
  890. if ($typeName !== '' && $subCode !== '') {
  891. $typeVal = $detail_type_map[$typeName] ?? 0;
  892. if (!$typeVal) {
  893. $errors[] = "第{$displayLine}行:明细类型[{$typeName}]无效";
  894. } else {
  895. if ($typeVal == ItemDetails::type_one) {
  896. if (!isset($man_map[$subCode])) {
  897. $errors[] = "第{$displayLine}行:人员工号[{$subCode}]不存在";
  898. } else {
  899. $detail_storage[$rowIndex][] = ['type' => $typeVal, 'data_id' => $man_map[$subCode]];
  900. }
  901. } else {
  902. if (!isset($device_map[$subCode])) {
  903. $errors[] = "第{$displayLine}行:设备编码[{$subCode}]不存在";
  904. } else {
  905. $detail_storage[$rowIndex][] = ['type' => $typeVal, 'data_id' => $device_map[$subCode]];
  906. }
  907. }
  908. }
  909. }
  910. }
  911. $error_str = !empty($errors) ? implode('|', $errors) : "";
  912. return [$error_str, $update_mapping, $detail_storage];
  913. }
  914. private function getFlatDataList($array, $user, $typeIdx, $code2Idx)
  915. {
  916. $manNums = [];
  917. $devCodes = [];
  918. $detail_type_map = array_flip(ItemDetails::$type_name);
  919. foreach ($array as $row) {
  920. $typeName = trim($row[$typeIdx] ?? '');
  921. $val = trim($row[$code2Idx] ?? '');
  922. if ($val === '') continue;
  923. $typeVal = $detail_type_map[$typeName] ?? 0;
  924. if ($typeVal == ItemDetails::type_one) {
  925. $manNums[$val] = true;
  926. } elseif ($typeVal == ItemDetails::type_two) {
  927. $devCodes[$val] = true;
  928. }
  929. }
  930. $manMap = Employee::where('del_time', 0)
  931. ->where('top_depart_id', $user['top_depart_id'])
  932. ->whereIn('number', array_keys($manNums))
  933. ->pluck('id', 'number')->toArray();
  934. $devMap = Device::where('del_time', 0)
  935. ->where('top_depart_id', $user['top_depart_id'])
  936. ->whereIn('code', array_keys($devCodes))
  937. ->pluck('id', 'code')->toArray();
  938. return [$manMap, $devMap];
  939. }
  940. // 费用 ----------------------------------
  941. public function feeImport($array, $user, $other_param)
  942. {
  943. $upload = $array[0];
  944. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  945. if (!$status) return [false, $msg];
  946. $table_config = $msg;
  947. unset($array[0]);
  948. if (empty($array)) return [false, '导入数据不能为空'];
  949. list($array, $error) = $this->checkCommon($array, $table_config);
  950. if (!empty($error)) return [0, $error];
  951. // 2. 详细校验
  952. list($error, $update_map, $parent_code_map) = $this->feeCheck($array, $user, $table_config);
  953. if (!empty($error)) return [0, $error];
  954. $time = time();
  955. $insert = [];
  956. $update = [];
  957. $all_codes = [];
  958. // --- 修正点 1: 必须确保索引提取准确 ---
  959. $keys = array_column($table_config, 'key');
  960. $codeIdx = array_search('code', $keys);
  961. // ------------------------------------
  962. $ignoreKeys = ['parent_id', 'parent_title'];
  963. foreach ($array as $key => $value) {
  964. $cCode = trim($value[$codeIdx] ?? '');
  965. if($cCode === '') continue;
  966. $all_codes[] = $cCode;
  967. $main_tmp = [];
  968. foreach ($value as $k => $val){
  969. if(!empty($table_config[$k]['is_main'])){
  970. if (!in_array($table_config[$k]['key'], $ignoreKeys)) {
  971. $main_tmp[$table_config[$k]['key']] = $val;
  972. }
  973. }
  974. }
  975. if (isset($update_map[$key])) {
  976. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  977. } else {
  978. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  979. $main_tmp['crt_time'] = $time;
  980. $main_tmp['parent_id'] = 0;
  981. $insert[] = $main_tmp;
  982. }
  983. }
  984. $all_parent_codes = array_values($parent_code_map);
  985. $searchCodes = array_unique(array_merge($all_codes, $all_parent_codes));
  986. DB::beginTransaction();
  987. try {
  988. if (!empty($insert)) {
  989. foreach (array_chunk($insert, 500) as $chunk) {
  990. Fee::insert($chunk);
  991. }
  992. }
  993. if (!empty($update)) {
  994. foreach ($update as $item) {
  995. $uId = $item['id']; unset($item['id']);
  996. Fee::where('id', $uId)->update($item);
  997. }
  998. }
  999. // --- 修正点 2: 核心回填逻辑 ---
  1000. $newCodeToIdMap = Fee::where('del_time', 0)
  1001. ->where('top_depart_id', $user['top_depart_id'])
  1002. ->whereIn('code', $searchCodes)
  1003. ->pluck('id', 'code')
  1004. ->toArray();
  1005. foreach ($parent_code_map as $rowIndex => $pCode) {
  1006. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  1007. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  1008. $pCode = trim($pCode);
  1009. if ($currentCode === '' || $pCode === '') continue;
  1010. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  1011. $parentId = $newCodeToIdMap[$pCode] ?? null;
  1012. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  1013. if ($currentId && $parentId && $currentId != $parentId) {
  1014. Fee::where('id', $currentId)->update(['parent_id' => $parentId]);
  1015. }
  1016. }
  1017. DB::commit();
  1018. } catch (\Exception $e) {
  1019. DB::rollBack();
  1020. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1021. }
  1022. return [true, ''];
  1023. }
  1024. private function feeCheck(&$array, $user, $table_config)
  1025. {
  1026. $keys = array_column($table_config, 'key');
  1027. $codeIdx = array_search('code', $keys);
  1028. $parentIdx = array_search('parent_id', $keys);
  1029. $isOtherIdx = array_search('is_other', $keys);
  1030. // 1. 获取基础数据
  1031. list($dbFeeMap, $excelCodesMap) = $this->getFeeList($array, $user, $codeIdx);
  1032. $errors = [];
  1033. $update = [];
  1034. $parent_code_map = [];
  1035. $is_other_map = array_flip(Fee::IS_OTHER);
  1036. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  1037. $currentExcelMap = [];
  1038. foreach ($array as $row) {
  1039. $c = trim($row[$codeIdx] ?? '');
  1040. $p = trim($row[$parentIdx] ?? '');
  1041. if ($c !== '') $currentExcelMap[$c] = $p;
  1042. }
  1043. // 3. 逐行校验
  1044. foreach ($array as $rowIndex => $value) {
  1045. $displayLine = $rowIndex + 1;
  1046. $valCode = trim($value[$codeIdx] ?? '');
  1047. $valParentCode = trim($value[$parentIdx] ?? '');
  1048. if ($valCode === '') continue;
  1049. // 更新状态记录
  1050. if (isset($dbFeeMap[$valCode])) {
  1051. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  1052. }
  1053. // 其他费用
  1054. $is_other_text = $value[$isOtherIdx] ?? '';
  1055. if (!isset($is_other_map[$is_other_text])) {
  1056. $errors[] = "第{$displayLine}行:是否其他费用[{$is_other_text}]无效";
  1057. } else {
  1058. $array[$rowIndex][$isOtherIdx] = $is_other_map[$is_other_text];
  1059. }
  1060. if ($valParentCode !== '') {
  1061. // --- A. 存在性校验 ---
  1062. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  1063. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  1064. $errors[] = "第{$displayLine}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  1065. continue;
  1066. }
  1067. // --- B. 自引用校验 ---
  1068. if ($valCode === $valParentCode) {
  1069. $errors[] = "第{$displayLine}行:上级编码不能是自身";
  1070. continue;
  1071. }
  1072. // --- C. 环路追溯 ---
  1073. $visited = [];
  1074. $res = $this->findLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  1075. if ($res !== false) {
  1076. if ($res['type'] === 'LOOP_SELF') {
  1077. $errors[] = "第{$displayLine}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  1078. } else {
  1079. $errors[] = "第{$displayLine}行:上级[{$valParentCode}]的溯源链条已成环";
  1080. }
  1081. continue;
  1082. }
  1083. // 记录有效的父级关系
  1084. $parent_code_map[$rowIndex] = $valParentCode;
  1085. }
  1086. }
  1087. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1088. return [$error_string, $update, $parent_code_map];
  1089. }
  1090. private function getFeeList($array, $user, $index)
  1091. {
  1092. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  1093. $codesInExcel = [];
  1094. foreach ($array as $row) {
  1095. $c = trim($row[$index] ?? '');
  1096. if ($c !== '') {
  1097. $codesInExcel[$c] = true;
  1098. }
  1099. }
  1100. $allFees = Fee::where('del_time', 0)
  1101. ->where('top_depart_id', $user['top_depart_id'])
  1102. ->select('id', 'code', 'parent_id')
  1103. ->get();
  1104. $dbFeeMap = [];
  1105. foreach ($allFees as $fee) {
  1106. $dbFeeMap[$fee->code] = [
  1107. 'id' => $fee->id,
  1108. 'code' => $fee->code,
  1109. 'parent_id' => $fee->parent_id
  1110. ];
  1111. }
  1112. // 返回数据库映射和 Excel 编码映射
  1113. return [$dbFeeMap, $codesInExcel];
  1114. }
  1115. private function findLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  1116. {
  1117. $current = $startParentCode;
  1118. while ($current !== '' && $current !== 0) {
  1119. if ($current === $targetCode) {
  1120. return ['type' => 'LOOP_SELF', 'code' => $current];
  1121. }
  1122. if (isset($visited[$current])) {
  1123. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  1124. }
  1125. $visited[$current] = true;
  1126. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  1127. $current = $excelMap[$current];
  1128. } elseif (isset($dbFeeMap[$current])) {
  1129. $parentId = $dbFeeMap[$current]['parent_id'];
  1130. $parentCode = '';
  1131. foreach ($dbFeeMap as $item) {
  1132. if ($item['id'] == $parentId) {
  1133. $parentCode = $item['code'];
  1134. break;
  1135. }
  1136. }
  1137. $current = $parentCode;
  1138. } else {
  1139. break;
  1140. }
  1141. }
  1142. return false;
  1143. }
  1144. // 人员月度工时单 ------------------------------
  1145. public function monthPwOrderImport($array, $user, $other_param)
  1146. {
  1147. $upload = $array[0];
  1148. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1149. if (!$status) return [false, $msg];
  1150. $table_config = $msg;
  1151. unset($array[0]);
  1152. if (empty($array)) return [false, '导入数据不能为空'];
  1153. list($array, $error) = $this->checkCommon($array, $table_config);
  1154. if (!empty($error)) return [0, $error];
  1155. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1156. list($error, $update_map, $dbEmps) = $this->monthPwOrderCheck($array, $user, $table_config);
  1157. if (!empty($error)) return [0, $error];
  1158. $keys = array_column($table_config, 'key');
  1159. $codeIdx = array_search('code', $keys);
  1160. $monthIdx = array_search('month', $keys);
  1161. $empIdx = array_search('employee_id', $keys);
  1162. // --- 步骤 1: 数据聚合分组 ---
  1163. // 将 Excel 数据按“单据”维度归类
  1164. $groups = [];
  1165. foreach ($array as $rowIndex => $row) {
  1166. $cCode = trim($row[$codeIdx] ?? '');
  1167. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1168. // 聚合 Key:有编码用编码,没编码用月份标记
  1169. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1170. if (!isset($groups[$aggKey])) {
  1171. $groups[$aggKey] = [
  1172. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1173. 'code' => $cCode,
  1174. 'month' => $cMonthTs,
  1175. 'details' => []
  1176. ];
  1177. }
  1178. // 准备详情行数据
  1179. $detailTmp = [];
  1180. foreach ($table_config as $k => $conf) {
  1181. if (!$conf['is_main']) {
  1182. $fieldKey = $conf['key'];
  1183. if ($fieldKey == 'employee_title') continue;
  1184. $fieldVal = $row[$k];
  1185. // 如果是人员,转换为 ID
  1186. if ($fieldKey == 'employee_id') {
  1187. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1188. }
  1189. $detailTmp[$fieldKey] = $fieldVal;
  1190. }
  1191. }
  1192. $groups[$aggKey]['details'][] = $detailTmp;
  1193. }
  1194. // --- 步骤 2: 开启事务写入 ---
  1195. DB::beginTransaction();
  1196. try {
  1197. $time = time();
  1198. foreach ($groups as $aggKey => $group) {
  1199. $mainId = $group['main_id'];
  1200. if ($mainId > 0) {
  1201. // 删除旧详情
  1202. DB::table('monthly_pw_order_details')->where('del_time',0)
  1203. ->where('main_id', $mainId)
  1204. ->update(['del_time' => $time]);
  1205. } else {
  1206. // B. 新增逻辑
  1207. $newCode = $this->generateBillNo([
  1208. 'top_depart_id' => $user['top_depart_id'],
  1209. 'type' => MonthlyPwOrder::Order_type,
  1210. 'period' => date("Ym", $group['month'])
  1211. ]);
  1212. $mainId = DB::table('monthly_pw_order')->insertGetId([
  1213. 'code' => $newCode,
  1214. 'month' => $group['month'],
  1215. 'top_depart_id' => $user['top_depart_id'],
  1216. 'crt_id' => $user['id'],
  1217. 'crt_time' => $time,
  1218. 'upd_time' => $time,
  1219. 'del_time' => 0
  1220. ]);
  1221. }
  1222. // C. 批量插入详情
  1223. $insertDetails = [];
  1224. foreach ($group['details'] as $detail) {
  1225. $detail['main_id'] = $mainId;
  1226. $detail['top_depart_id']= $user['top_depart_id'];
  1227. $detail['crt_time'] = $time;
  1228. $detail['del_time'] = 0;
  1229. $insertDetails[] = $detail;
  1230. }
  1231. if (!empty($insertDetails)) {
  1232. DB::table('monthly_pw_order_details')->insert($insertDetails);
  1233. }
  1234. }
  1235. DB::commit();
  1236. } catch (\Exception $e) {
  1237. DB::rollBack();
  1238. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1239. }
  1240. return [true, ''];
  1241. }
  1242. private function monthPwOrderCheck(&$array, $user, $table_config)
  1243. {
  1244. $keys = array_column($table_config, 'key');
  1245. $codeIdx = array_search('code', $keys);
  1246. $monthIdx = array_search('month', $keys);
  1247. $empIdx = array_search('employee_id', $keys);
  1248. $numIdx = array_search('total_days', $keys);
  1249. $num2Idx = array_search('rd_total_days', $keys);
  1250. $num3Idx = array_search('total_hours', $keys);
  1251. $num4Idx = array_search('rd_total_hours', $keys);
  1252. $topDepartId = $user['top_depart_id'];
  1253. $errors = [];
  1254. // --- 1. 预处理月份与工号 ---
  1255. $allEmpNumbers = [];
  1256. $allMonthsTs = [];
  1257. foreach ($array as $rowIndex => $row) {
  1258. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1259. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1260. if (!$mStatus) {
  1261. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误";
  1262. continue;
  1263. }
  1264. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1265. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1266. $allMonthsTs[] = $valMonthTs;
  1267. if (!empty($row[$empIdx])) $allEmpNumbers[] = trim($row[$empIdx]);
  1268. }
  1269. if (!empty($errors)) return [implode('|', $errors), [], []];
  1270. $allMonthsTs = array_unique($allMonthsTs);
  1271. $allEmpNumbers = array_unique($allEmpNumbers);
  1272. //归档
  1273. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1274. if(! $status) return [$msg, [], []];
  1275. // --- 2. 批量预加载 ---
  1276. // A. 人员档案
  1277. $empModels = Employee::where('del_time', 0)->whereIn('number', $allEmpNumbers)
  1278. ->where('top_depart_id', $topDepartId)->get(['id', 'number', 'title'])->keyBy('number');
  1279. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  1280. // B. 系统考勤基准 (按月获取)
  1281. $systemStatsMap = [];
  1282. $service = new EmployeeService();
  1283. foreach ($allMonthsTs as $ts) {
  1284. list($sStatus, $stats) = $service->getEmployeesMonthStats(array_values($dbEmps), $ts, $user);
  1285. if (!$sStatus) {
  1286. $errors[] = "月份[" . date('Y-m', $ts) . "]:" . $stats;
  1287. continue;
  1288. }
  1289. $systemStatsMap[$ts] = $stats;
  1290. }
  1291. if (!empty($errors)) return [implode('|', $errors), [], []];
  1292. // C. 核心修正:单据查重(建立 月份 -> 单号 的映射,避免循环内查询)
  1293. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1294. // 1) 所有的 Excel 涉及月份在数据库中已有的单据映射
  1295. $existingMonthsMap = DB::table('monthly_pw_order')
  1296. ->where('top_depart_id', $topDepartId)
  1297. ->where('del_time', 0)
  1298. ->whereIn('month', $allMonthsTs)
  1299. ->pluck('code', 'month') // 注意:这里直接查出 month => code
  1300. ->toArray();
  1301. // 2) 用户填写的单据号对应的数据库记录
  1302. $dbOrdersByCode = DB::table('monthly_pw_order')
  1303. ->whereIn('code', $allCodes)
  1304. ->where('top_depart_id', $topDepartId)
  1305. ->where('del_time', 0)
  1306. ->get()
  1307. ->keyBy('code');
  1308. // --- 3. 业务逻辑全量检查 ---
  1309. $excelAggregator = [];
  1310. $update_map = [];
  1311. foreach ($array as $rowIndex => $row) {
  1312. $line = $rowIndex + 1;
  1313. $valCode = trim($row[$codeIdx] ?? '');
  1314. $valMonthTs = $row[$monthIdx];
  1315. $valEmpNum = trim($row[$empIdx] ?? '');
  1316. $monthStr = date('Y-m', $valMonthTs);
  1317. if (!isset($empModels[$valEmpNum])) {
  1318. $errors[] = "第{$line}行:工号[{$valEmpNum}]不存在";
  1319. continue;
  1320. }
  1321. $empId = $empModels[$valEmpNum]->id;
  1322. $empTitle = "[{$valEmpNum}]" . $empModels[$valEmpNum]->title;
  1323. // --- 核心修正:单据单号提示逻辑 ---
  1324. if ($valCode !== '') {
  1325. if (isset($dbOrdersByCode[$valCode])) {
  1326. if ($dbOrdersByCode[$valCode]->month != $valMonthTs) {
  1327. $errors[] = "第{$line}行:单据[{$valCode}]月份应为" . date('Y-m', $dbOrdersByCode[$valCode]->month) . ",请核实";
  1328. }
  1329. $update_map[$rowIndex] = $dbOrdersByCode[$valCode]->id;
  1330. } else {
  1331. $errors[] = "第{$line}行:填写的单据编号[{$valCode}]在系统中不存在";
  1332. }
  1333. } else {
  1334. // 如果没填单号,但该月已存在单据,从预加载的 existingMonthsMap 中获取正确单号
  1335. if (isset($existingMonthsMap[$valMonthTs])) {
  1336. $correctCode = $existingMonthsMap[$valMonthTs];
  1337. $errors[] = "第{$line}行:月份[{$monthStr}]已存在研发单,单号为:[{$correctCode}],请填写该单号进行编辑";
  1338. }
  1339. }
  1340. // --- 考勤上限校验 ---
  1341. $sysEmpData = $systemStatsMap[$valMonthTs][$empId] ?? null;
  1342. if ($sysEmpData) {
  1343. $inTotalDays = (float)($row[$numIdx] ?? 0);
  1344. $inRdDays = (float)($row[$num2Idx] ?? 0);
  1345. $inTotalHours= (float)($row[$num3Idx] ?? 0);
  1346. $inRdHours = (float)($row[$num4Idx] ?? 0);
  1347. // 使用误差范围比较,避免浮点数精度问题
  1348. if (abs($inTotalDays - $sysEmpData['attendance_days']) > 0.01) {
  1349. $errors[] = "第{$line}行:{$empTitle}出勤总天数({$inTotalDays})与核算({$sysEmpData['attendance_days']})不符";
  1350. }
  1351. if (abs($inTotalHours - $sysEmpData['final_work_hour']) > 0.01) {
  1352. $errors[] = "第{$line}行:{$empTitle}出勤总工时({$inTotalHours})与核算({$sysEmpData['final_work_hour']})不符";
  1353. }
  1354. if ($inRdDays > $inTotalDays + 0.01) $errors[] = "第{$line}行:{$empTitle}研发天数超过总天数";
  1355. if ($inRdHours > $inTotalHours + 0.01) $errors[] = "第{$line}行:{$empTitle}研发工时超过总工时";
  1356. }
  1357. if (isset($excelAggregator[$valCode ?: $valMonthTs]['emps'][$valEmpNum])) {
  1358. $errors[] = "第{$line}行:人员在同单据内重复";
  1359. }
  1360. $excelAggregator[$valCode ?: $valMonthTs]['emps'][$valEmpNum] = true;
  1361. }
  1362. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  1363. }
  1364. // 设备月度工时单
  1365. public function monthDwOrderImport($array, $user, $other_param)
  1366. {
  1367. $upload = $array[0];
  1368. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1369. if (!$status) return [false, $msg];
  1370. $table_config = $msg;
  1371. unset($array[0]);
  1372. if (empty($array)) return [false, '导入数据不能为空'];
  1373. list($array, $error) = $this->checkCommon($array, $table_config);
  1374. if (!empty($error)) return [0, $error];
  1375. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1376. list($error, $update_map, $dbDevs) = $this->monthDwOrderCheck($array, $user, $table_config);
  1377. if (!empty($error)) return [0, $error];
  1378. $keys = array_column($table_config, 'key');
  1379. $codeIdx = array_search('code', $keys);
  1380. $monthIdx = array_search('month', $keys);
  1381. $empIdx = array_search('device_id', $keys);
  1382. // --- 步骤 1: 数据聚合分组 ---
  1383. // 将 Excel 数据按“单据”维度归类
  1384. $groups = [];
  1385. foreach ($array as $rowIndex => $row) {
  1386. $cCode = trim($row[$codeIdx] ?? '');
  1387. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1388. // 聚合 Key:有编码用编码,没编码用月份标记
  1389. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1390. if (!isset($groups[$aggKey])) {
  1391. $groups[$aggKey] = [
  1392. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1393. 'code' => $cCode,
  1394. 'month' => $cMonthTs,
  1395. 'details' => []
  1396. ];
  1397. }
  1398. // 准备详情行数据
  1399. $detailTmp = [];
  1400. foreach ($table_config as $k => $conf) {
  1401. if (!$conf['is_main']) {
  1402. $fieldKey = $conf['key'];
  1403. if ($fieldKey == 'device_title') continue;
  1404. $fieldVal = $row[$k];
  1405. // 如果是人员,转换为 ID
  1406. if ($fieldKey == 'device_id') {
  1407. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1408. }
  1409. $detailTmp[$fieldKey] = $fieldVal;
  1410. }
  1411. }
  1412. $groups[$aggKey]['details'][] = $detailTmp;
  1413. }
  1414. // --- 步骤 2: 开启事务写入 ---
  1415. DB::beginTransaction();
  1416. try {
  1417. $time = time();
  1418. foreach ($groups as $aggKey => $group) {
  1419. $mainId = $group['main_id'];
  1420. if ($mainId > 0) {
  1421. // 删除旧详情
  1422. DB::table('monthly_dw_order_details')->where('del_time',0)
  1423. ->where('main_id', $mainId)
  1424. ->update(['del_time' => $time]);
  1425. } else {
  1426. // B. 新增逻辑
  1427. $newCode = $this->generateBillNo([
  1428. 'top_depart_id' => $user['top_depart_id'],
  1429. 'type' => MonthlyPwOrder::Order_type,
  1430. 'period' => date("Ym", $group['month'])
  1431. ]);
  1432. $mainId = DB::table('monthly_dw_order')->insertGetId([
  1433. 'code' => $newCode,
  1434. 'month' => $group['month'],
  1435. 'top_depart_id' => $user['top_depart_id'],
  1436. 'crt_id' => $user['id'],
  1437. 'crt_time' => $time,
  1438. 'upd_time' => $time,
  1439. 'del_time' => 0
  1440. ]);
  1441. }
  1442. // C. 批量插入详情
  1443. $insertDetails = [];
  1444. foreach ($group['details'] as $detail) {
  1445. $detail['main_id'] = $mainId;
  1446. $detail['top_depart_id']= $user['top_depart_id'];
  1447. $detail['crt_time'] = $time;
  1448. $detail['del_time'] = 0;
  1449. $insertDetails[] = $detail;
  1450. }
  1451. if (!empty($insertDetails)) {
  1452. DB::table('monthly_dw_order_details')->insert($insertDetails);
  1453. }
  1454. }
  1455. DB::commit();
  1456. } catch (\Exception $e) {
  1457. DB::rollBack();
  1458. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1459. }
  1460. return [true, ''];
  1461. }
  1462. private function monthDwOrderCheck(&$array, $user, $table_config)
  1463. {
  1464. $keys = array_column($table_config, 'key');
  1465. $codeIdx = array_search('code', $keys);
  1466. $monthIdx = array_search('month', $keys);
  1467. $devIdx = array_search('device_id', $keys);
  1468. $numIdx = array_search('total_days', $keys);
  1469. $num2Idx = array_search('rd_total_days', $keys);
  1470. $num3Idx = array_search('total_hours', $keys);
  1471. $num4Idx = array_search('rd_total_hours', $keys);
  1472. $topDepartId = $user['top_depart_id'];
  1473. $errors = [];
  1474. // --- 1. 提取月份和资产编码 ---
  1475. $allDevCodes = [];
  1476. $allMonthsTs = [];
  1477. foreach ($array as $rowIndex => $row) {
  1478. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($row[$monthIdx] ?? '');
  1479. if (!$mStatus) {
  1480. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误";
  1481. continue;
  1482. }
  1483. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1484. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1485. $allMonthsTs[] = $valMonthTs;
  1486. if (!empty($row[$devIdx])) $allDevCodes[] = trim($row[$devIdx]);
  1487. }
  1488. if (!empty($errors)) return [implode('|', $errors), [], []];
  1489. $allMonthsTs = array_unique($allMonthsTs);
  1490. //归档
  1491. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1492. if(! $status) return [$msg, [], []];
  1493. // --- 2. 预加载档案与基准 ---
  1494. $devModels = Device::where('del_time', 0)
  1495. ->whereIn('code', $allDevCodes)
  1496. ->where('top_depart_id', $topDepartId)
  1497. ->get(['id', 'code', 'title'])
  1498. ->keyBy('code');
  1499. $dbDevs = $devModels->pluck('id', 'code')->toArray();
  1500. $systemStatsMap = [];
  1501. $allDeviceIds = array_values($dbDevs);
  1502. $service = new DeviceService();
  1503. foreach ($allMonthsTs as $ts) {
  1504. list($sStatus, $stats) = $service->getDevicesMonthStats($allDeviceIds, $ts, $user);
  1505. if (!$sStatus) {
  1506. $errors[] = "月份[" . date('Y-m', $ts) . "]解析失败:{$stats}";
  1507. $systemStatsMap[$ts] = null;
  1508. } else {
  1509. $systemStatsMap[$ts] = $stats;
  1510. }
  1511. }
  1512. // 如果基准获取有误(如日历未设),直接返回错误,不执行后续逻辑
  1513. if (!empty($errors)) return [implode('|', $errors), [], []];
  1514. // --- 3. 核心修正:单据查重与单号映射 (避免循环内查询) ---
  1515. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1516. // 获取该租户相关月份已存在的单据映射 (Month => Code)
  1517. $existingMonthsMap = DB::table('monthly_dw_order')
  1518. ->where('top_depart_id', $topDepartId)
  1519. ->where('del_time', 0)
  1520. ->whereIn('month', $allMonthsTs)
  1521. ->pluck('code', 'month')
  1522. ->toArray();
  1523. // 获取 Excel 中填写的单号对应的数据库记录 (Code => Object)
  1524. $dbOrdersByCode = DB::table('monthly_dw_order')
  1525. ->whereIn('code', $allCodes)
  1526. ->where('top_depart_id', $topDepartId)
  1527. ->where('del_time', 0)
  1528. ->get()
  1529. ->keyBy('code');
  1530. $excelAggregator = [];
  1531. $update_map = [];
  1532. // --- 4. 循环校验 ---
  1533. foreach ($array as $rowIndex => $row) {
  1534. $line = $rowIndex + 1;
  1535. $valMonthTs = $row[$monthIdx];
  1536. $monthStr = date('Y-m', $valMonthTs);
  1537. $valDevCode = trim($row[$devIdx] ?? '');
  1538. $valCode = trim($row[$codeIdx] ?? '');
  1539. // A. 设备档案检查
  1540. if (!isset($devModels[$valDevCode])) {
  1541. $errors[] = "第{$line}行:设备编码[{$valDevCode}]不存在";
  1542. continue;
  1543. }
  1544. $deviceId = $devModels[$valDevCode]->id;
  1545. $devTitle = "[{$valDevCode}]" . $devModels[$valDevCode]->title;
  1546. // B. 单据号存在性与意图校验
  1547. if ($valCode !== '') {
  1548. // 意图:编辑已存在的单据
  1549. if (isset($dbOrdersByCode[$valCode])) {
  1550. $dbOrder = $dbOrdersByCode[$valCode];
  1551. if ($dbOrder->month != $valMonthTs) {
  1552. $errors[] = "第{$line}行:单据[{$valCode}]所属月份为" . date('Y-m', $dbOrder->month) . ",与当前月份不符";
  1553. }
  1554. $update_map[$rowIndex] = $dbOrder->id;
  1555. } else {
  1556. // 填了单号但库里没有
  1557. $errors[] = "第{$line}行:单据编号[{$valCode}]无效或不存在";
  1558. }
  1559. } else {
  1560. // 意图:新增。校验是否该月已有单据
  1561. if (isset($existingMonthsMap[$valMonthTs])) {
  1562. $correctCode = $existingMonthsMap[$valMonthTs];
  1563. $errors[] = "第{$line}行:月份[{$monthStr}]已存在研发单,单号为:[{$correctCode}],请填写该单号进行更新";
  1564. }
  1565. }
  1566. // C. 考勤基准对比
  1567. $sysData = $systemStatsMap[$valMonthTs][$deviceId] ?? null;
  1568. if ($sysData) {
  1569. $inTotalDays = (float)($row[$numIdx] ?? 0);
  1570. $inRdDays = (float)($row[$num2Idx] ?? 0);
  1571. $inTotalHours= (float)($row[$num3Idx] ?? 0);
  1572. $inRdHours = (float)($row[$num4Idx] ?? 0);
  1573. // 1. 内部逻辑:研发 <= 总额
  1574. if ($inRdDays > $inTotalDays + 0.01) $errors[] = "第{$line}行:{$devTitle}研发天数大于总天数";
  1575. if ($inRdHours > $inTotalHours + 0.01) $errors[] = "第{$line}行:{$devTitle}研发工时大于总工时";
  1576. // 2. 外部逻辑:总额 == 系统核算
  1577. if (abs($inTotalDays - $sysData['attendance_days']) > 0.01) {
  1578. $errors[] = "第{$line}行:{$devTitle}总天数({$inTotalDays})不等于系统核算({$sysData['attendance_days']})";
  1579. }
  1580. if (abs($inTotalHours - $sysData['final_work_hour']) > 0.01) {
  1581. $errors[] = "第{$line}行:{$devTitle}总工时({$inTotalHours})不等于系统核算({$sysData['final_work_hour']})";
  1582. }
  1583. }
  1584. // D. 组内查重 (单号或月份作为聚合维度)
  1585. $aggKey = $valCode ?: "NEW_" . $valMonthTs;
  1586. if (isset($excelAggregator[$aggKey]['devs'][$valDevCode])) {
  1587. $errors[] = "第{$line}行:资产编码[{$valDevCode}]在同单据中重复";
  1588. }
  1589. $excelAggregator[$aggKey]['devs'][$valDevCode] = true;
  1590. }
  1591. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1592. return [$error_string, $update_map, $dbDevs];
  1593. }
  1594. // 人员月度工资单
  1595. public function monthPsOrderImport($array, $user, $other_param)
  1596. {
  1597. $upload = $array[0];
  1598. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1599. if (!$status) return [false, $msg];
  1600. $table_config = $msg;
  1601. unset($array[0]);
  1602. if (empty($array)) return [false, '导入数据不能为空'];
  1603. list($array, $error) = $this->checkCommon($array, $table_config);
  1604. if (!empty($error)) return [0, $error];
  1605. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1606. list($error, $update_map, $dbEmps) = $this->monthPsOrderCheck($array, $user, $table_config);
  1607. if (!empty($error)) return [0, $error];
  1608. $keys = array_column($table_config, 'key');
  1609. $codeIdx = array_search('code', $keys);
  1610. $monthIdx = array_search('month', $keys);
  1611. $empIdx = array_search('employee_id', $keys);
  1612. // --- 步骤 1: 数据聚合分组 ---
  1613. // 将 Excel 数据按“单据”维度归类
  1614. $groups = [];
  1615. foreach ($array as $rowIndex => $row) {
  1616. $cCode = trim($row[$codeIdx] ?? '');
  1617. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1618. // 聚合 Key:有编码用编码,没编码用月份标记
  1619. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1620. if (!isset($groups[$aggKey])) {
  1621. $groups[$aggKey] = [
  1622. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1623. 'code' => $cCode,
  1624. 'month' => $cMonthTs,
  1625. 'details' => []
  1626. ];
  1627. }
  1628. // 准备详情行数据
  1629. $detailTmp = [];
  1630. foreach ($table_config as $k => $conf) {
  1631. if (!$conf['is_main']) {
  1632. $fieldKey = $conf['key'];
  1633. if ($fieldKey == 'employee_title') continue;
  1634. $fieldVal = $row[$k];
  1635. // 如果是人员,转换为 ID
  1636. if ($fieldKey == 'employee_id') {
  1637. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1638. }
  1639. $detailTmp[$fieldKey] = $fieldVal;
  1640. }
  1641. }
  1642. $groups[$aggKey]['details'][] = $detailTmp;
  1643. }
  1644. // --- 步骤 2: 开启事务写入 ---
  1645. DB::beginTransaction();
  1646. try {
  1647. $time = time();
  1648. foreach ($groups as $aggKey => $group) {
  1649. $mainId = $group['main_id'];
  1650. if ($mainId > 0) {
  1651. // 删除旧详情
  1652. DB::table('monthly_ps_order_details')->where('del_time',0)
  1653. ->where('main_id', $mainId)
  1654. ->update(['del_time' => $time]);
  1655. } else {
  1656. // B. 新增逻辑
  1657. $newCode = $this->generateBillNo([
  1658. 'top_depart_id' => $user['top_depart_id'],
  1659. 'type' => MonthlyPsOrder::Order_type,
  1660. 'period' => date("Ym", $group['month'])
  1661. ]);
  1662. $mainId = DB::table('monthly_ps_order')->insertGetId([
  1663. 'code' => $newCode,
  1664. 'month' => $group['month'],
  1665. 'top_depart_id' => $user['top_depart_id'],
  1666. 'crt_id' => $user['id'],
  1667. 'crt_time' => $time,
  1668. 'upd_time' => $time,
  1669. 'del_time' => 0
  1670. ]);
  1671. }
  1672. // C. 批量插入详情
  1673. $insertDetails = [];
  1674. foreach ($group['details'] as $detail) {
  1675. $detail['main_id'] = $mainId;
  1676. $detail['top_depart_id']= $user['top_depart_id'];
  1677. $detail['crt_time'] = $time;
  1678. $detail['del_time'] = 0;
  1679. $insertDetails[] = $detail;
  1680. }
  1681. if (!empty($insertDetails)) {
  1682. DB::table('monthly_ps_order_details')->insert($insertDetails);
  1683. }
  1684. }
  1685. DB::commit();
  1686. } catch (\Exception $e) {
  1687. DB::rollBack();
  1688. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1689. }
  1690. return [true, ''];
  1691. }
  1692. private function monthPsOrderCheck(&$array, $user, $table_config)
  1693. {
  1694. $keys = array_column($table_config, 'key');
  1695. $codeIdx = array_search('code', $keys);
  1696. $monthIdx = array_search('month', $keys);
  1697. $empIdx = array_search('employee_id', $keys);
  1698. $numIdx = array_search('base_salary', $keys);
  1699. $num2Idx = array_search('social_insurance', $keys);
  1700. $num3Idx = array_search('public_housing_fund', $keys);
  1701. $num4Idx = array_search('performance_salary', $keys);
  1702. $num5Idx = array_search('bonus', $keys);
  1703. $num6Idx = array_search('other', $keys);
  1704. // 1. 预加载基础数据
  1705. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  1706. $dbEmps = Employee::where('del_time', 0)
  1707. ->whereIn('number', $allEmpNumbers)
  1708. ->where('top_depart_id', $user['top_depart_id'])
  1709. ->pluck('id', 'number')->toArray();
  1710. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1711. $dbOrders = DB::table('monthly_ps_order')
  1712. ->whereIn('code', $allCodes)
  1713. ->where('top_depart_id', $user['top_depart_id'])
  1714. ->where('del_time', 0) // 必须确保没删除
  1715. ->get()->keyBy('code');
  1716. $errors = [];
  1717. $uniqueMonths = [];
  1718. // --- 步骤 1:月份标准化预处理 ---
  1719. foreach ($array as $rowIndex => $row) {
  1720. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1721. if ($valMonthRaw === '') continue;
  1722. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1723. if (!$mStatus) {
  1724. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1725. continue;
  1726. }
  1727. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1728. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1729. $uniqueMonths[] = $valMonthTs;
  1730. }
  1731. if (!empty($errors)) return [implode('|', $errors), [], []];
  1732. $allMonthsTs = array_unique($uniqueMonths);
  1733. //归档
  1734. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1735. if(! $status) return [$msg, [], []];
  1736. // 查询数据库中已存在的月份单据
  1737. $existingMonths = DB::table('monthly_ps_order')
  1738. ->where('top_depart_id', $user['top_depart_id'])
  1739. ->where('del_time', 0)
  1740. ->whereIn('month', $allMonthsTs)
  1741. ->pluck('month')
  1742. ->toArray();
  1743. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1744. $excelAggregator = [];
  1745. $update_map = [];
  1746. $monthToKeyMap = []; // 校验 Excel 内部月份是否冲突
  1747. // --- 步骤 2:全量业务校验 ---
  1748. foreach ($array as $rowIndex => $row) {
  1749. $displayLine = $rowIndex + 1;
  1750. $valCode = trim($row[$codeIdx] ?? '');
  1751. $valMonthTs = $row[$monthIdx] ?? '';
  1752. $valEmp = trim($row[$empIdx] ?? '');
  1753. if (!is_numeric($valMonthTs)) continue;
  1754. // 确定单据组 AggKey
  1755. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1756. // A. 校验单据存在性 & 匹配 ID
  1757. if ($valCode) {
  1758. if (isset($dbOrders[$valCode])) {
  1759. $dbOrder = $dbOrders[$valCode];
  1760. if ($dbOrder->month != $valMonthTs) {
  1761. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  1762. }
  1763. $update_map[$rowIndex] = $dbOrder->id;
  1764. }
  1765. // 乱填编码的情况,不会进 update_map,将由下方的查重逻辑拦截
  1766. }
  1767. // B. 【核心修正】月份唯一单据校验
  1768. // 如果系统最终认为这行是“新增”,则必须检查该月份是否已有数据
  1769. if (!isset($update_map[$rowIndex])) {
  1770. if (isset($existingMonthsMap[$valMonthTs])) {
  1771. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据,请填写正确的单据编码进行编辑";
  1772. }
  1773. }
  1774. // C. Excel 内部逻辑一致性
  1775. if (!isset($monthToKeyMap[$valMonthTs])) {
  1776. $monthToKeyMap[$valMonthTs] = $aggKey;
  1777. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  1778. $errors[] = "第{$displayLine}行:同一个月份[" . date('Y-m', $valMonthTs) . "]在 Excel 中指向了不同的单据组";
  1779. }
  1780. // D. 人员校验与单据内查重
  1781. if (!isset($dbEmps[$valEmp])) {
  1782. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  1783. } else {
  1784. if (isset($excelAggregator[$aggKey]['emps'][$valEmp])) {
  1785. $errors[] = "第{$displayLine}行:人员[{$valEmp}]在同一单据中重复";
  1786. }
  1787. $excelAggregator[$aggKey]['emps'][$valEmp] = true;
  1788. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1789. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1790. }
  1791. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1792. }
  1793. // E. 数字格式校验
  1794. $numChecks = [
  1795. $numIdx => '基本工资',
  1796. $num2Idx => '社保',
  1797. $num3Idx => '公积金',
  1798. $num4Idx => '绩效工资',
  1799. $num5Idx => '奖金',
  1800. $num6Idx => '其他',
  1801. ];
  1802. foreach ($numChecks as $idx => $label) {
  1803. $res = $this->checkNumber($row[$idx] ?? 0, 2, 'non-negative');
  1804. if (!$res['valid']) $errors[] = "第{$displayLine}行{$label}:" . $res['error'];
  1805. }
  1806. }
  1807. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1808. return [$error_string, $update_map, $dbEmps];
  1809. }
  1810. // 设备月度折旧单
  1811. public function monthDdOrderImport($array, $user, $other_param)
  1812. {
  1813. $upload = $array[0];
  1814. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1815. if (!$status) return [false, $msg];
  1816. $table_config = $msg;
  1817. unset($array[0]);
  1818. if (empty($array)) return [false, '导入数据不能为空'];
  1819. list($array, $error) = $this->checkCommon($array, $table_config);
  1820. if (!empty($error)) return [0, $error];
  1821. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1822. list($error, $update_map, $dbDevs) = $this->monthDdOrderCheck($array, $user, $table_config);
  1823. if (!empty($error)) return [0, $error];
  1824. $keys = array_column($table_config, 'key');
  1825. $codeIdx = array_search('code', $keys);
  1826. $monthIdx = array_search('month', $keys);
  1827. $empIdx = array_search('device_id', $keys);
  1828. // --- 步骤 1: 数据聚合分组 ---
  1829. // 将 Excel 数据按“单据”维度归类
  1830. $groups = [];
  1831. foreach ($array as $rowIndex => $row) {
  1832. $cCode = trim($row[$codeIdx] ?? '');
  1833. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1834. // 聚合 Key:有编码用编码,没编码用月份标记
  1835. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1836. if (!isset($groups[$aggKey])) {
  1837. $groups[$aggKey] = [
  1838. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1839. 'code' => $cCode,
  1840. 'month' => $cMonthTs,
  1841. 'details' => []
  1842. ];
  1843. }
  1844. // 准备详情行数据
  1845. $detailTmp = [];
  1846. foreach ($table_config as $k => $conf) {
  1847. if (!$conf['is_main']) {
  1848. $fieldKey = $conf['key'];
  1849. if ($fieldKey == 'device_title') continue;
  1850. $fieldVal = $row[$k];
  1851. // 如果是人员,转换为 ID
  1852. if ($fieldKey == 'device_id') {
  1853. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1854. }
  1855. $detailTmp[$fieldKey] = $fieldVal;
  1856. }
  1857. }
  1858. $groups[$aggKey]['details'][] = $detailTmp;
  1859. }
  1860. // --- 步骤 2: 开启事务写入 ---
  1861. DB::beginTransaction();
  1862. try {
  1863. $time = time();
  1864. foreach ($groups as $aggKey => $group) {
  1865. $mainId = $group['main_id'];
  1866. if ($mainId > 0) {
  1867. // 删除旧详情
  1868. DB::table('monthly_dd_order_details')->where('del_time',0)
  1869. ->where('main_id', $mainId)
  1870. ->update(['del_time' => $time]);
  1871. } else {
  1872. // B. 新增逻辑
  1873. $newCode = $this->generateBillNo([
  1874. 'top_depart_id' => $user['top_depart_id'],
  1875. 'type' => MonthlyDdOrder::Order_type,
  1876. 'period' => date("Ym", $group['month'])
  1877. ]);
  1878. $mainId = DB::table('monthly_dd_order')->insertGetId([
  1879. 'code' => $newCode,
  1880. 'month' => $group['month'],
  1881. 'top_depart_id' => $user['top_depart_id'],
  1882. 'crt_id' => $user['id'],
  1883. 'crt_time' => $time,
  1884. 'upd_time' => $time,
  1885. 'del_time' => 0
  1886. ]);
  1887. }
  1888. // C. 批量插入详情
  1889. $insertDetails = [];
  1890. foreach ($group['details'] as $detail) {
  1891. $detail['main_id'] = $mainId;
  1892. $detail['top_depart_id']= $user['top_depart_id'];
  1893. $detail['crt_time'] = $time;
  1894. $detail['del_time'] = 0;
  1895. $insertDetails[] = $detail;
  1896. }
  1897. if (!empty($insertDetails)) {
  1898. DB::table('monthly_dd_order_details')->insert($insertDetails);
  1899. }
  1900. }
  1901. DB::commit();
  1902. } catch (\Exception $e) {
  1903. DB::rollBack();
  1904. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1905. }
  1906. return [true, ''];
  1907. }
  1908. private function monthDdOrderCheck(&$array, $user, $table_config)
  1909. {
  1910. $keys = array_column($table_config, 'key');
  1911. $codeIdx = array_search('code', $keys);
  1912. $monthIdx = array_search('month', $keys);
  1913. $devIdx = array_search('device_id', $keys);
  1914. $numIdx = array_search('depreciation_amount', $keys);
  1915. // 1. 预加载基础数据
  1916. $allDevNumbers = array_filter(array_unique(array_column($array, $devIdx)));
  1917. $dbDevs = Device::where('del_time', 0)
  1918. ->whereIn('code', $allDevNumbers)
  1919. ->where('top_depart_id', $user['top_depart_id'])
  1920. ->pluck('id', 'code')->toArray();
  1921. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1922. $dbOrders = DB::table('monthly_dd_order')
  1923. ->whereIn('code', $allCodes)
  1924. ->where('top_depart_id', $user['top_depart_id'])
  1925. ->where('del_time', 0)
  1926. ->get()->keyBy('code');
  1927. $errors = [];
  1928. $uniqueMonths = [];
  1929. // --- 步骤 1:月份标准化 ---
  1930. foreach ($array as $rowIndex => $row) {
  1931. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1932. if ($valMonthRaw === '') continue;
  1933. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1934. if (!$mStatus) {
  1935. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1936. continue;
  1937. }
  1938. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1939. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1940. $uniqueMonths[] = $valMonthTs;
  1941. }
  1942. if (!empty($errors)) return [implode('|', $errors), [], []];
  1943. $allMonthsTs = array_unique($uniqueMonths);
  1944. //归档
  1945. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1946. if(! $status) return [$msg, [], []];
  1947. // 预查数据库已存在的月份
  1948. $existingMonths = DB::table('monthly_dd_order')
  1949. ->where('top_depart_id', $user['top_depart_id'])
  1950. ->where('del_time', 0)
  1951. ->whereIn('month', $allMonthsTs)
  1952. ->pluck('month')
  1953. ->toArray();
  1954. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1955. $excelAggregator = [];
  1956. $update_map = [];
  1957. $monthToKeyMap = []; // 校验同一月份在 Excel 内部是否产生了多个单据组
  1958. // --- 步骤 2:全量校验 ---
  1959. foreach ($array as $rowIndex => $row) {
  1960. $displayLine = $rowIndex + 1;
  1961. $valCode = trim($row[$codeIdx] ?? '');
  1962. $valMonthTs = $row[$monthIdx] ?? '';
  1963. $valDev = trim($row[$devIdx] ?? '');
  1964. $valNumRaw = $row[$numIdx] ?? 0;
  1965. if (!is_numeric($valMonthTs)) continue;
  1966. // 确定单据聚合 Key
  1967. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1968. // A. 匹配更新 ID
  1969. if ($valCode) {
  1970. if (isset($dbOrders[$valCode])) {
  1971. $dbOrder = $dbOrders[$valCode];
  1972. if ($dbOrder->month != $valMonthTs) {
  1973. $errors[] = "第{$displayLine}行:单据[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入不符";
  1974. }
  1975. $update_map[$rowIndex] = $dbOrder->id;
  1976. }
  1977. // 乱填编码的情况不进 update_map,将被视为“新增”由下方逻辑拦截
  1978. }
  1979. // B. 【核心修正】月份唯一性拦截
  1980. // 只要不是更新已有单据,且月份已存在,就报错
  1981. if (!isset($update_map[$rowIndex])) {
  1982. if (isset($existingMonthsMap[$valMonthTs])) {
  1983. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在折旧单,请填正确编码编辑";
  1984. }
  1985. }
  1986. // C. Excel 内部逻辑一致性
  1987. if (!isset($monthToKeyMap[$valMonthTs])) {
  1988. $monthToKeyMap[$valMonthTs] = $aggKey;
  1989. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  1990. $errors[] = "第{$displayLine}行:同月份[" . date('Y-m', $valMonthTs) . "]存在多组单据定义";
  1991. }
  1992. // D. 设备校验
  1993. if (!isset($dbDevs[$valDev])) {
  1994. $errors[] = "第{$displayLine}行:资产编码[{$valDev}]不存在";
  1995. } else {
  1996. if (isset($excelAggregator[$aggKey]['devs'][$valDev])) {
  1997. $errors[] = "第{$displayLine}行:资产编码[{$valDev}]在同单据中重复";
  1998. }
  1999. $excelAggregator[$aggKey]['devs'][$valDev] = true;
  2000. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  2001. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  2002. }
  2003. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  2004. }
  2005. // E. 数字校验
  2006. $res = $this->checkNumber($valNumRaw, 2, 'non-negative');
  2007. if (!$res['valid']) {
  2008. $errors[] = "第{$displayLine}行月折旧额:" . $res['error'];
  2009. }
  2010. }
  2011. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2012. return [$error_string, $update_map, $dbDevs];
  2013. }
  2014. // 规则配置单
  2015. public function ruleSetImport($array, $user, $other_param){
  2016. $upload = $array[0];
  2017. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2018. if (!$status) return [false, $msg];
  2019. $table_config = $msg;
  2020. unset($array[0]);
  2021. if (empty($array)) return [false, '导入数据不能为空'];
  2022. list($array, $error) = $this->checkCommon($array, $table_config);
  2023. if (!empty($error)) return [0, $error];
  2024. // 2. 详细校验
  2025. list($error, $update_map, $dbDevs) = $this->ruleSetCheck($array, $user, $table_config);
  2026. if (!empty($error)) return [0, $error];
  2027. $keys = array_column($table_config, 'key');
  2028. $codeIdx = array_search('code', $keys);
  2029. $monthIdx = array_search('month', $keys);
  2030. $rateIdx = array_search('rate', $keys);
  2031. $groups = [];
  2032. foreach ($array as $rowIndex => $row) {
  2033. $mCode = trim($row[$codeIdx] ?? '');
  2034. $month = $row[$monthIdx];
  2035. $aggKey = $mCode ?: "NEW_" . $month;
  2036. if (!isset($groups[$aggKey])) {
  2037. $groups[$aggKey] = [
  2038. 'id' => $update_map[$rowIndex] ?? 0,
  2039. 'month' => $month,
  2040. 'details' => []
  2041. ];
  2042. }
  2043. $groups[$aggKey]['details'][] = [
  2044. 'item_id' => $row['parsed_item_id'],
  2045. 'data_id' => $row['parsed_data_id'],
  2046. 'type' => $row['parsed_type'],
  2047. 'rate' => $row[$rateIdx],
  2048. ];
  2049. }
  2050. $time = time();
  2051. DB::beginTransaction();
  2052. try {
  2053. foreach ($groups as $group) {
  2054. $mainId = $group['id'];
  2055. if ($mainId) {
  2056. DB::table('rule_set_details')
  2057. ->where('del_time',0)
  2058. ->where('main_id', $mainId)->update(['del_time' => $time]);
  2059. } else {
  2060. $newCode = $this->generateBillNo([
  2061. 'top_depart_id' => $user['top_depart_id'],
  2062. 'type' => RuleSet::Order_type,
  2063. 'period' => date("Ym", $group['month'])
  2064. ]);
  2065. $mainId = DB::table('rule_set')->insertGetId([
  2066. 'code' => $newCode,
  2067. 'month' => $group['month'],
  2068. 'top_depart_id' => $user['top_depart_id'],
  2069. 'crt_id' => $user['id'],
  2070. 'crt_time' => $time
  2071. ]);
  2072. }
  2073. foreach ($group['details'] as &$d) {
  2074. $d['main_id'] = $mainId;
  2075. $d['top_depart_id'] = $user['top_depart_id'];
  2076. $d['crt_time'] = $time;
  2077. }
  2078. DB::table('rule_set_details')->insert($group['details']);
  2079. }
  2080. DB::commit();
  2081. } catch (\Exception $e) {
  2082. DB::rollBack();
  2083. return [false, "失败: " . $e->getMessage()];
  2084. }
  2085. return [true, ''];
  2086. }
  2087. private function ruleSetCheck(&$array, $user, $table_config)
  2088. {
  2089. $keys = array_column($table_config, 'key');
  2090. // 1. 索引提取
  2091. $mCodeIdx = array_search('code', $keys);
  2092. $monthIdx = array_search('month', $keys);
  2093. $typeIdx = array_search('type', $keys);
  2094. $dCodeIdx = array_search('code_2', $keys);
  2095. $itemIdIdx = array_search('item_id', $keys);
  2096. $rateIdx = array_search('rate', $keys);
  2097. $uniqueMonths = [];
  2098. $empCodes = [];
  2099. $devCodes = [];
  2100. $itemCodes = [];
  2101. $type_map = array_flip(RuleSetDetails::$type_name);
  2102. // --- 步骤 1: 预处理扫描 ---
  2103. foreach ($array as $rowIndex => $row) {
  2104. $valMonthRaw = trim($row[$monthIdx] ?? '');
  2105. if ($valMonthRaw === '') continue;
  2106. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  2107. if (!$mStatus) {
  2108. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  2109. continue;
  2110. }
  2111. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  2112. $array[$rowIndex][$monthIdx] = $valMonthTs;
  2113. $uniqueMonths[] = $valMonthTs;
  2114. $type = $type_map[$row[$typeIdx] ?? ''] ?? 0;
  2115. $dCode = trim($row[$dCodeIdx] ?? '');
  2116. $iCode = trim($row[$itemIdIdx] ?? '');
  2117. if ($type == RuleSetDetails::type_one && $dCode !== '') $empCodes[] = $dCode;
  2118. if ($type == RuleSetDetails::type_two && $dCode !== '') $devCodes[] = $dCode;
  2119. if ($iCode !== '') $itemCodes[] = $iCode;
  2120. }
  2121. if (!empty($errors)) return [implode('|', $errors), [], []];
  2122. $allMonthsTs = array_unique($uniqueMonths);
  2123. //归档
  2124. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  2125. if(! $status) return [$msg, [], []];
  2126. // --- 步骤 2: 批量预加载 ---
  2127. $dbEmps = Employee::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2128. ->whereIn('number', array_unique($empCodes))->pluck('id', 'number')->toArray();
  2129. $dbDevs = Device::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2130. ->whereIn('code', array_unique($devCodes))->pluck('id', 'code')->toArray();
  2131. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2132. ->whereIn('code', array_unique($itemCodes))->pluck('id', 'code')->toArray();
  2133. $allMCodes = array_filter(array_unique(array_column($array, $mCodeIdx)));
  2134. $dbOrders = DB::table('rule_set')->where('top_depart_id', $user['top_depart_id'])
  2135. ->where('del_time', 0)->whereIn('code', $allMCodes)->get()->keyBy('code');
  2136. $existingMonthsMap = DB::table('rule_set')->where('top_depart_id', $user['top_depart_id'])
  2137. ->where('del_time', 0)->whereIn('month', array_unique($uniqueMonths))->pluck('id', 'month')->toArray();
  2138. $errors = [];
  2139. $update_map = [];
  2140. $aggregator = [];
  2141. $uniqueCheck = [];
  2142. $monthToKeyMap = []; // 校验 Excel 内部月份与单号组的唯一性
  2143. // --- 步骤 3: 详细校验循环 ---
  2144. foreach ($array as $rowIndex => $row) {
  2145. $displayLine = $rowIndex + 1;
  2146. $valMCode = trim($row[$mCodeIdx] ?? '');
  2147. $valMonthTs = $row[$monthIdx] ?? '';
  2148. $typeTitle = trim($row[$typeIdx] ?? '');
  2149. $type = $type_map[$typeTitle] ?? 0;
  2150. $valDCode = trim($row[$dCodeIdx] ?? '');
  2151. $valICode = trim($row[$itemIdIdx] ?? '');
  2152. $valRate = $row[$rateIdx] ?? 0;
  2153. // A. 编辑/新增逻辑判定 (核心修正)
  2154. if ($valMCode !== '' && isset($dbOrders[$valMCode])) {
  2155. $dbOrder = $dbOrders[$valMCode];
  2156. if ($dbOrder->month != $valMonthTs) {
  2157. $errors[] = "第{$displayLine}行:单号[{$valMCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],不允许修改";
  2158. }
  2159. $update_map[$rowIndex] = $dbOrder->id;
  2160. }
  2161. // 月份唯一性拦截:只要没进入 update_map (无论是乱填单号还是没填),就查重
  2162. if (!isset($update_map[$rowIndex])) {
  2163. if (isset($existingMonthsMap[$valMonthTs])) {
  2164. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据,请填写正确的单号编辑";
  2165. }
  2166. }
  2167. // B. Excel 内部一致性拦截
  2168. $aggKey = $valMCode ?: "NEW_ORDER_" . $valMonthTs;
  2169. if (!isset($monthToKeyMap[$valMonthTs])) {
  2170. $monthToKeyMap[$valMonthTs] = $aggKey;
  2171. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  2172. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]在表格中对应了不同的单据编号,请确保同一月份的单号一致";
  2173. }
  2174. // C. 人员/设备/项目存在性校验
  2175. $dataId = 0;
  2176. if ($type == RuleSetDetails::type_one) {
  2177. $dataId = $dbEmps[$valDCode] ?? 0;
  2178. if (!$dataId) $errors[] = "第{$displayLine}行:工号[{$valDCode}]不存在";
  2179. } elseif ($type == RuleSetDetails::type_two) {
  2180. $dataId = $dbDevs[$valDCode] ?? 0;
  2181. if (!$dataId) $errors[] = "第{$displayLine}行:资产编码[{$valDCode}]不存在";
  2182. } else {
  2183. $errors[] = "第{$displayLine}行:明细类型[{$typeTitle}]非法";
  2184. }
  2185. $itemId = $dbItems[$valICode] ?? 0;
  2186. if (!$itemId) $errors[] = "第{$displayLine}行:项目编码[{$valICode}]不存在";
  2187. // D. 比例与唯一性聚合
  2188. if ($dataId && $itemId) {
  2189. // 同一单据+项目内 人/设备唯一
  2190. $rowUniqueKey = $aggKey . '_' . $itemId . '_' . $type . '_' . $dataId;
  2191. if (isset($uniqueCheck[$rowUniqueKey])) {
  2192. $errors[] = "第{$displayLine}行:项目[{$valICode}]下[{$valDCode}]重复录入";
  2193. }
  2194. $uniqueCheck[$rowUniqueKey] = true;
  2195. // 比例和校验聚合
  2196. $totalRateKey = $aggKey . '_' . $type . '_' . $dataId;
  2197. $aggregator[$totalRateKey]['total_rate'] = ($aggregator[$totalRateKey]['total_rate'] ?? 0) + $valRate;
  2198. $aggregator[$totalRateKey]['title'] = $valDCode;
  2199. $aggregator[$totalRateKey]['type_name'] = $typeTitle;
  2200. $aggregator[$totalRateKey]['month_str'] = date('Y-m', $valMonthTs);
  2201. }
  2202. $array[$rowIndex]['parsed_data_id'] = $dataId;
  2203. $array[$rowIndex]['parsed_item_id'] = $itemId;
  2204. $array[$rowIndex]['parsed_type'] = $type;
  2205. }
  2206. // --- 步骤 4: 比例汇总校验 ---
  2207. foreach ($aggregator as $key => $info) {
  2208. if (abs($info['total_rate'] - 100) > 0.0001) {
  2209. $errors[] = "汇总错误:月份[{$info['month_str']}]下,{$info['type_name']}[{$info['title']}]的总分摊比例为 {$info['total_rate']}%,不等于 100%";
  2210. }
  2211. }
  2212. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2213. return [$error_string, $update_map, $dbItems];
  2214. }
  2215. // 人员日工时单 ------------------------------
  2216. public function dailyPwOrderImport($array, $user, $other_param)
  2217. {
  2218. $upload = $array[0];
  2219. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2220. if (!$status) return [false, $msg];
  2221. $table_config = $msg;
  2222. unset($array[0]);
  2223. if (empty($array)) return [false, '导入数据不能为空'];
  2224. // 1. 基础格式检查
  2225. list($array, $error) = $this->checkCommon($array, $table_config);
  2226. if (!empty($error)) return [0, $error];
  2227. // 2. 详细业务校验 (返回 update_map, 人员映射, 项目映射)
  2228. list($error, $update_map, $dbEmps, $dbItems) = $this->dailyPwOrderCheck($array, $user, $table_config);
  2229. if (!empty($error)) return [0, $error];
  2230. $keys = array_column($table_config, 'key');
  2231. $codeIdx = array_search('code', $keys);
  2232. $timeIdx = array_search('order_time', $keys);
  2233. $itemIdx = array_search('item_id', $keys);
  2234. $empIdx = array_search('employee_id', $keys);
  2235. $startIdx = array_search('start_time', $keys);
  2236. $endIdx = array_search('end_time', $keys);
  2237. // 3. 数据聚合分组
  2238. $groups = [];
  2239. foreach ($array as $rowIndex => $row) {
  2240. $cCode = trim($row[$codeIdx] ?? '');
  2241. $cTimeTs = $row[$timeIdx];
  2242. $cItemCode = trim($row[$itemIdx] ?? '');
  2243. $cItemId = $dbItems[$cItemCode] ?? 0;
  2244. // 聚合 Key:如果是更新则按主表ID聚类;如果是新增则按 日期+项目 聚类
  2245. $aggKey = ($update_map[$rowIndex] ?? 0) > 0
  2246. ? "UPDATE_" . $update_map[$rowIndex]
  2247. : "NEW_" . $cTimeTs . "_" . $cItemId;
  2248. if (!isset($groups[$aggKey])) {
  2249. $groups[$aggKey] = [
  2250. 'main_id' => $update_map[$rowIndex] ?? 0,
  2251. 'code' => $cCode,
  2252. 'order_time' => $cTimeTs,
  2253. 'item_id' => $cItemId,
  2254. 'details' => []
  2255. ];
  2256. }
  2257. // 解析时间
  2258. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2259. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2260. $groups[$aggKey]['details'][] = [
  2261. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2262. 'start_time_hour' => $sH,
  2263. 'start_time_min' => $sM,
  2264. 'end_time_hour' => $eH,
  2265. 'end_time_min' => $eM,
  2266. 'total_work_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM), // 计算分钟差
  2267. ];
  2268. }
  2269. // 4. 执行写入
  2270. DB::beginTransaction();
  2271. try {
  2272. $time = time();
  2273. foreach ($groups as $group) {
  2274. $mainId = $group['main_id'];
  2275. if ($mainId > 0) {
  2276. // 编辑:更新主表(允许改项目)
  2277. DB::table('daily_pw_order')->where('id', $mainId)->update([
  2278. 'item_id' => $group['item_id'],
  2279. 'upd_time' => $time
  2280. ]);
  2281. // 逻辑删除旧明细
  2282. DB::table('daily_pw_order_details')->where('main_id', $mainId)
  2283. ->where('del_time', 0)
  2284. ->update(['del_time' => $time]);
  2285. } else {
  2286. // 新增:自动生成单号
  2287. $newCode = $this->generateBillNo([
  2288. 'top_depart_id' => $user['top_depart_id'],
  2289. 'type' => DailyPwOrder::Order_type,
  2290. 'period' => date("Ym", $group['order_time'])
  2291. ]);
  2292. $mainId = DB::table('daily_pw_order')->insertGetId([
  2293. 'code' => $newCode,
  2294. 'order_time' => $group['order_time'],
  2295. 'item_id' => $group['item_id'],
  2296. 'top_depart_id' => $user['top_depart_id'],
  2297. 'crt_id' => $user['id'],
  2298. 'crt_time' => $time,
  2299. ]);
  2300. }
  2301. // 批量插入明细
  2302. $insertDetails = [];
  2303. foreach ($group['details'] as $detail) {
  2304. $detail['main_id'] = $mainId;
  2305. $detail['top_depart_id'] = $user['top_depart_id'];
  2306. $detail['crt_time'] = $time;
  2307. $detail['crt_id'] = $user['id'];
  2308. $insertDetails[] = $detail;
  2309. }
  2310. if (!empty($insertDetails)) {
  2311. DB::table('daily_pw_order_details')->insert($insertDetails);
  2312. }
  2313. }
  2314. DB::commit();
  2315. } catch (\Exception $e) {
  2316. DB::rollBack();
  2317. return [false, "失败:" . $e->getMessage()];
  2318. }
  2319. return [true, ''];
  2320. }
  2321. private function dailyPwOrderCheck(&$array, $user, $table_config)
  2322. {
  2323. $keys = array_column($table_config, 'key');
  2324. $codeIdx = array_search('code', $keys);
  2325. $timeIdx = array_search('order_time', $keys);
  2326. $itemIdx = array_search('item_id', $keys);
  2327. $empIdx = array_search('employee_id', $keys);
  2328. $startIdx = array_search('start_time', $keys);
  2329. $endIdx = array_search('end_time', $keys);
  2330. $topDepartId = $user['top_depart_id'];
  2331. // 1. 批量预加载基础档案
  2332. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  2333. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2334. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  2335. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  2336. $empDisplayMap = $empModels->mapWithKeys(function($item){
  2337. return [$item->id => "[{$item->number}]{$item->title}"];
  2338. })->toArray();
  2339. $itemCodes = array_filter(array_unique(array_column($array, $itemIdx)));
  2340. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2341. ->whereIn('code', $itemCodes)->pluck('id', 'code')->toArray();
  2342. // 2. 预加载已有单据
  2343. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2344. $dbOrders = DB::table('daily_pw_order')->where('top_depart_id', $topDepartId)
  2345. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2346. // --- 跨单据预查:提前解析日期并检索库内已存在的工时区间 ---
  2347. $allDates = [];
  2348. foreach ($array as $rowIndex => $row) {
  2349. $valMonthRaw = $row[$timeIdx] ?? '';
  2350. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2351. if(! $status) {
  2352. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2353. continue;
  2354. }
  2355. $d = strtotime(date('Y-m-d', $ts));
  2356. $array[$rowIndex][$timeIdx] = $d;
  2357. $allDates[] = $d;
  2358. }
  2359. if (!empty($errors)) return [implode('|', $errors), [], [], []];
  2360. $allDates = array_unique($allDates);
  2361. //归档
  2362. list($status, $msg) = ArchiveService::isArchive($allDates, $user);
  2363. if(! $status) return [$msg, [], [], []];
  2364. // 查询数据库:同公司、同日期、同项目、同人员的已有工时 (排除本次 Excel 涉及到的单号)
  2365. $dbExistingWork = DB::table('daily_pw_order_details as d')
  2366. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  2367. ->where('m.top_depart_id', $topDepartId) // 核心:公司数据隔离
  2368. ->whereIn('m.order_time', $allDates)
  2369. ->whereIn('m.item_id', array_values($dbItems))
  2370. ->whereIn('d.employee_id', array_values($dbEmps))
  2371. ->where('m.del_time', 0)
  2372. ->where('d.del_time', 0)
  2373. ->whereNotIn('m.code', $allCodes) // 排除掉当前正在编辑的单据本身,避免自冲突
  2374. ->select('m.order_time', 'm.item_id', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2375. ->get()
  2376. ->groupBy(function($item) {
  2377. return $item->order_time . '_' . $item->item_id . '_' . $item->employee_id;
  2378. });
  2379. $errors = [];
  2380. $update_map = [];
  2381. $excelBillMap = [];
  2382. $timeOverlapMap = []; // 内部记录器:$date_$item_$emp => [ ['s'=>min, 'e'=>min], ... ]
  2383. // 3. 全量循环检查
  2384. foreach ($array as $rowIndex => $row) {
  2385. $displayLine = $rowIndex + 1;
  2386. $ts = $row[$timeIdx];
  2387. $valCode = trim($row[$codeIdx] ?? '');
  2388. $valItemCode = trim($row[$itemIdx] ?? '');
  2389. $itemId = $dbItems[$valItemCode] ?? 0;
  2390. $valEmpCode = trim($row[$empIdx] ?? '');
  2391. $empId = $dbEmps[$valEmpCode] ?? 0;
  2392. $empName = $empDisplayMap[$empId] ?? "工号:{$valEmpCode}";
  2393. // B. 基础档案存在性校验
  2394. if (!$itemId) $errors[] = "第{$displayLine}行:项目编号[{$valItemCode}]不存在";
  2395. if (!$empId) $errors[] = "第{$displayLine}行:人员工号[{$valEmpCode}]不存在";
  2396. if (!$itemId || !$empId) continue;
  2397. // C. 单号与编辑逻辑判定
  2398. if ($valCode !== '') {
  2399. if (isset($dbOrders[$valCode])) {
  2400. $dbOrder = $dbOrders[$valCode];
  2401. if ($dbOrder->order_time != $ts) {
  2402. $errors[] = "第{$displayLine}行:单据[{$valCode}]原日期为[" . date('Y-m-d', $dbOrder->order_time) . "],不允许跨日期编辑";
  2403. }
  2404. $update_map[$rowIndex] = $dbOrder->id;
  2405. } else {
  2406. $errors[] = "第{$displayLine}行:单据编号[{$valCode}]不存在,若要新增请清空该列";
  2407. }
  2408. }
  2409. // D. 时间合法性校验
  2410. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2411. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2412. if ($sH === null || $sM === null || $eH === null || $eM === null) {
  2413. $errors[] = "第{$displayLine}行:时间格式非法或超出00:00-23:59范围";
  2414. continue;
  2415. }
  2416. $currentStart = $sH * 60 + $sM;
  2417. $currentEnd = $eH * 60 + $eM;
  2418. if ($currentStart >= $currentEnd) {
  2419. $errors[] = "第{$displayLine}行:人员{$empName}的开始时间需早于结束时间";
  2420. continue;
  2421. }
  2422. // --- E. 三位一体冲突校验 ---
  2423. $checkKey = $ts . "_" . $itemId . "_" . $empId;
  2424. // 1. 校验:数据库已有记录 (跨单据)
  2425. if (isset($dbExistingWork[$checkKey])) {
  2426. foreach ($dbExistingWork[$checkKey] as $p) {
  2427. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  2428. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  2429. // 重叠判定公式: (StartA < EndB) && (StartB < EndA)
  2430. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  2431. $errors[] = "第{$displayLine}行:人员{$empName}与已存在该时间重叠的工时单";
  2432. break;
  2433. }
  2434. }
  2435. }
  2436. // 2. 校验:Excel内上方行记录 (内部重叠)
  2437. if (isset($timeOverlapMap[$checkKey])) {
  2438. foreach ($timeOverlapMap[$checkKey] as $period) {
  2439. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  2440. $errors[] = "第{$displayLine}行:人员{$empName}与表格内其他行时间重叠";
  2441. break;
  2442. }
  2443. }
  2444. }
  2445. // 3. 校验通过,记录到内部记录器
  2446. $timeOverlapMap[$checkKey][] = ['s' => $currentStart, 'e' => $currentEnd];
  2447. }
  2448. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2449. return [$error_string, $update_map, $dbEmps, $dbItems];
  2450. }
  2451. // 设备日工时单 ------------------------------
  2452. public function dailyDwOrderImport($array, $user, $other_param)
  2453. {
  2454. $upload = $array[0];
  2455. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2456. if (!$status) return [false, $msg];
  2457. $table_config = $msg;
  2458. unset($array[0]);
  2459. if (empty($array)) return [false, '导入数据不能为空'];
  2460. // 1. 基础格式检查
  2461. list($array, $error) = $this->checkCommon($array, $table_config);
  2462. if (!empty($error)) return [0, $error];
  2463. // 2. 详细业务校验 (改为设备校验)
  2464. list($error, $update_map, $dbDevices, $dbItems) = $this->dailyDwOrderCheck($array, $user, $table_config);
  2465. if (!empty($error)) return [0, $error];
  2466. $keys = array_column($table_config, 'key');
  2467. $codeIdx = array_search('code', $keys);
  2468. $timeIdx = array_search('order_time', $keys);
  2469. $itemIdx = array_search('item_id', $keys);
  2470. $devIdx = array_search('device_id', $keys); // 对应配置中的 device_id
  2471. $startIdx = array_search('start_time', $keys);
  2472. $endIdx = array_search('end_time', $keys);
  2473. // 3. 数据聚合分组
  2474. $groups = [];
  2475. foreach ($array as $rowIndex => $row) {
  2476. $cCode = trim($row[$codeIdx] ?? '');
  2477. $cTimeTs = $row[$timeIdx];
  2478. $cItemCode = trim($row[$itemIdx] ?? '');
  2479. $cItemId = $dbItems[$cItemCode] ?? 0;
  2480. $aggKey = ($update_map[$rowIndex] ?? 0) > 0
  2481. ? "UPDATE_" . $update_map[$rowIndex]
  2482. : "NEW_" . $cTimeTs . "_" . $cItemId;
  2483. if (!isset($groups[$aggKey])) {
  2484. $groups[$aggKey] = [
  2485. 'main_id' => $update_map[$rowIndex] ?? 0,
  2486. 'code' => $cCode,
  2487. 'order_time' => $cTimeTs,
  2488. 'item_id' => $cItemId,
  2489. 'details' => []
  2490. ];
  2491. }
  2492. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2493. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2494. $groups[$aggKey]['details'][] = [
  2495. 'device_id' => $dbDevices[trim($row[$devIdx])] ?? 0, // 改为设备ID
  2496. 'start_time_hour' => $sH,
  2497. 'start_time_min' => $sM,
  2498. 'end_time_hour' => $eH,
  2499. 'end_time_min' => $eM,
  2500. 'total_work_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2501. ];
  2502. }
  2503. // 4. 执行写入
  2504. DB::beginTransaction();
  2505. try {
  2506. $time = time();
  2507. foreach ($groups as $group) {
  2508. $mainId = $group['main_id'];
  2509. if ($mainId > 0) {
  2510. // 编辑:更新设备工时主表
  2511. DB::table('daily_dw_order')->where('id', $mainId)->update([
  2512. 'item_id' => $group['item_id'],
  2513. 'upd_time' => $time
  2514. ]);
  2515. DB::table('daily_dw_order_details')->where('main_id', $mainId)
  2516. ->where('del_time', 0)
  2517. ->update(['del_time' => $time]);
  2518. } else {
  2519. // 新增
  2520. $newCode = $this->generateBillNo([
  2521. 'top_depart_id' => $user['top_depart_id'],
  2522. 'type' => DailyDwOrder::Order_type,
  2523. 'period' => date("Ym", $group['order_time'])
  2524. ]);
  2525. $mainId = DB::table('daily_dw_order')->insertGetId([
  2526. 'code' => $newCode,
  2527. 'order_time' => $group['order_time'],
  2528. 'item_id' => $group['item_id'],
  2529. 'top_depart_id' => $user['top_depart_id'],
  2530. 'crt_id' => $user['id'],
  2531. 'crt_time' => $time,
  2532. ]);
  2533. }
  2534. $insertDetails = [];
  2535. foreach ($group['details'] as $detail) {
  2536. $detail['main_id'] = $mainId;
  2537. $detail['top_depart_id'] = $user['top_depart_id'];
  2538. $detail['crt_time'] = $time;
  2539. $detail['crt_id'] = $user['id'];
  2540. $insertDetails[] = $detail;
  2541. }
  2542. if (!empty($insertDetails)) {
  2543. DB::table('daily_dw_order_details')->insert($insertDetails);
  2544. }
  2545. }
  2546. DB::commit();
  2547. } catch (\Exception $e) {
  2548. DB::rollBack();
  2549. return [false, "失败:" . $e->getMessage()];
  2550. }
  2551. return [true, ''];
  2552. }
  2553. private function dailyDwOrderCheck(&$array, $user, $table_config)
  2554. {
  2555. $keys = array_column($table_config, 'key');
  2556. $codeIdx = array_search('code', $keys);
  2557. $timeIdx = array_search('order_time', $keys);
  2558. $itemIdx = array_search('item_id', $keys);
  2559. $devIdx = array_search('device_id', $keys); // 设备编码索引
  2560. $startIdx = array_search('start_time', $keys);
  2561. $endIdx = array_search('end_time', $keys);
  2562. $topDepartId = $user['top_depart_id'];
  2563. // 1. 批量预加载设备档案 (替换原本的人员逻辑)
  2564. $devCodes = array_filter(array_unique(array_column($array, $devIdx)));
  2565. $devModels = Device::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2566. ->whereIn('code', $devCodes)->get(['id', 'code', 'title']);
  2567. $dbDevices = $devModels->pluck('id', 'code')->toArray(); // 以编号为Key查找ID
  2568. $devDisplayMap = $devModels->mapWithKeys(function($item){
  2569. return [$item->id => "[{$item->code}]{$item->title}"];
  2570. })->toArray();
  2571. $itemCodes = array_filter(array_unique(array_column($array, $itemIdx)));
  2572. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2573. ->whereIn('code', $itemCodes)->pluck('id', 'code')->toArray();
  2574. // 2. 预加载设备已有单据
  2575. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2576. $dbOrders = DB::table('daily_dw_order')->where('top_depart_id', $topDepartId)
  2577. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2578. // 3. 跨单据预查
  2579. $allDates = [];
  2580. foreach ($array as $rowIndex => $row) {
  2581. $valMonthRaw = $row[$timeIdx] ?? '';
  2582. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2583. if(! $status) {
  2584. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2585. continue;
  2586. }
  2587. $d = strtotime(date('Y-m-d', $ts));
  2588. $array[$rowIndex][$timeIdx] = $d;
  2589. $allDates[] = $d;
  2590. }
  2591. if (!empty($errors)) return [implode('|', $errors), [], [], []];
  2592. $allDates = array_unique($allDates);
  2593. //归档
  2594. list($status, $msg) = ArchiveService::isArchive($allDates, $user);
  2595. if(! $status) return [$msg, [], [], []];
  2596. $dbExistingWork = DB::table('daily_dw_order_details as d')
  2597. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  2598. ->where('m.top_depart_id', $topDepartId)
  2599. ->whereIn('m.order_time', $allDates)
  2600. ->whereIn('m.item_id', array_values($dbItems))
  2601. ->whereIn('d.device_id', array_values($dbDevices)) // 改为 device_id
  2602. ->where('m.del_time', 0)
  2603. ->where('d.del_time', 0)
  2604. ->whereNotIn('m.code', $allCodes)
  2605. ->select('m.order_time', 'm.item_id', 'd.device_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2606. ->get()
  2607. ->groupBy(function($item) {
  2608. return $item->order_time . '_' . $item->item_id . '_' . $item->device_id;
  2609. });
  2610. $errors = [];
  2611. $update_map = [];
  2612. $timeOverlapMap = [];
  2613. // 4. 全量循环检查
  2614. foreach ($array as $rowIndex => $row) {
  2615. $displayLine = $rowIndex + 1;
  2616. $ts = $row[$timeIdx];
  2617. $valCode = trim($row[$codeIdx] ?? '');
  2618. $valItemCode = trim($row[$itemIdx] ?? '');
  2619. $itemId = $dbItems[$valItemCode] ?? 0;
  2620. $valDevCode = trim($row[$devIdx] ?? '');
  2621. $devId = $dbDevices[$valDevCode] ?? 0;
  2622. $devName = $devDisplayMap[$devId] ?? "设备编号:{$valDevCode}";
  2623. if (!$itemId) $errors[] = "第{$displayLine}行:项目编号[{$valItemCode}]不存在";
  2624. if (!$devId) $errors[] = "第{$displayLine}行:设备编码[{$valDevCode}]不存在";
  2625. if (!$itemId || !$devId) continue;
  2626. if ($valCode !== '') {
  2627. if (isset($dbOrders[$valCode])) {
  2628. $dbOrder = $dbOrders[$valCode];
  2629. if ($dbOrder->order_time != $ts) {
  2630. $errors[] = "第{$displayLine}行:单据[{$valCode}]原日期不符,编辑模式不允许修改日期";
  2631. }
  2632. $update_map[$rowIndex] = $dbOrder->id;
  2633. } else {
  2634. $errors[] = "第{$displayLine}行:单据编号[{$valCode}]不存在";
  2635. }
  2636. }
  2637. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2638. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2639. if ($sH === null || $sM === null || $eH === null || $eM === null) {
  2640. $errors[] = "第{$displayLine}行:时间段格式非法";
  2641. continue;
  2642. }
  2643. $currentStart = $sH * 60 + $sM;
  2644. $currentEnd = $eH * 60 + $eM;
  2645. if ($currentStart >= $currentEnd) {
  2646. $errors[] = "第{$displayLine}行:设备{$devName}开始时间需早于结束时间";
  2647. continue;
  2648. }
  2649. $checkKey = $ts . "_" . $itemId . "_" . $devId;
  2650. // 跨单据检查
  2651. if (isset($dbExistingWork[$checkKey])) {
  2652. foreach ($dbExistingWork[$checkKey] as $p) {
  2653. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  2654. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  2655. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  2656. $errors[] = "第{$displayLine}行:设备{$devName}在该项目当日已有记录重叠";
  2657. break;
  2658. }
  2659. }
  2660. }
  2661. // Excel内部检查
  2662. if (isset($timeOverlapMap[$checkKey])) {
  2663. foreach ($timeOverlapMap[$checkKey] as $period) {
  2664. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  2665. $errors[] = "第{$displayLine}行:设备{$devName}与表格内其他行重叠";
  2666. break;
  2667. }
  2668. }
  2669. }
  2670. $timeOverlapMap[$checkKey][] = ['s' => $currentStart, 'e' => $currentEnd];
  2671. }
  2672. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2673. return [$error_string, $update_map, $dbDevices, $dbItems];
  2674. }
  2675. // 人员请假单 --------------------------------
  2676. public function leaveOrderImport($array, $user, $other_param)
  2677. {
  2678. $upload = $array[0];
  2679. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2680. if (!$status) return [false, $msg];
  2681. $table_config = $msg;
  2682. unset($array[0]);
  2683. if (empty($array)) return [false, '导入数据不能为空'];
  2684. // 1. 基础格式检查
  2685. list($array, $error) = $this->checkCommon($array, $table_config);
  2686. if (!empty($error)) return [0, $error];
  2687. // 2. 详细业务校验 (固定为请假单校验)
  2688. list($error, $update_map, $dbEmps) = $this->leaveOrderCheck($array, $user, $table_config);
  2689. if (!empty($error)) return [0, $error];
  2690. $keys = array_column($table_config, 'key');
  2691. $codeIdx = array_search('code', $keys);
  2692. $timeIdx = array_search('order_time', $keys);
  2693. $empIdx = array_search('employee_id', $keys);
  2694. $startIdx = array_search('start_time', $keys);
  2695. $endIdx = array_search('end_time', $keys);
  2696. // 3. 数据聚合分组 (按日期聚合)
  2697. $groups = [];
  2698. foreach ($array as $rowIndex => $row) {
  2699. $cTimeTs = $row[$timeIdx];
  2700. $mainId = $update_map[$rowIndex] ?? 0;
  2701. // 聚合Key:如果是更新则按主表ID;如果是新增则按日期
  2702. $aggKey = $mainId > 0 ? "ID_" . $mainId : "DATE_" . $cTimeTs;
  2703. if (!isset($groups[$aggKey])) {
  2704. $groups[$aggKey] = [
  2705. 'main_id' => $mainId,
  2706. 'order_time' => $cTimeTs,
  2707. 'details' => []
  2708. ];
  2709. }
  2710. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2711. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2712. $groups[$aggKey]['details'][] = [
  2713. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2714. 'start_time_hour' => $sH,
  2715. 'start_time_min' => $sM,
  2716. 'end_time_hour' => $eH,
  2717. 'end_time_min' => $eM,
  2718. 'total_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2719. 'type' => PLeaveOverOrder::TYPE_ONE, // 固定请假类型
  2720. ];
  2721. }
  2722. // 4. 执行写入
  2723. DB::beginTransaction();
  2724. try {
  2725. $time = time();
  2726. foreach ($groups as $group) {
  2727. if ($group['main_id'] > 0) {
  2728. $mainId = $group['main_id'];
  2729. // 删除旧明细准备覆盖
  2730. DB::table('p_leave_over_order_details')->where('main_id', $mainId)->update(['del_time' => $time]);
  2731. } else {
  2732. // 生成请假单号
  2733. $newCode = $this->generateBillNo([
  2734. 'top_depart_id' => $user['top_depart_id'],
  2735. 'type' => PLeaveOverOrder::Order_type,
  2736. 'period' => date("Ym", $group['order_time'])
  2737. ]);
  2738. $mainId = DB::table('p_leave_over_order')->insertGetId([
  2739. 'code' => $newCode,
  2740. 'order_time' => $group['order_time'],
  2741. 'type' => PLeaveOverOrder::TYPE_ONE,
  2742. 'top_depart_id' => $user['top_depart_id'],
  2743. 'crt_id' => $user['id'],
  2744. 'crt_time' => $time,
  2745. ]);
  2746. }
  2747. foreach ($group['details'] as &$d) {
  2748. $d['main_id'] = $mainId;
  2749. $d['top_depart_id'] = $user['top_depart_id'];
  2750. $d['crt_time'] = $time;
  2751. }
  2752. DB::table('p_leave_over_order_details')->insert($group['details']);
  2753. }
  2754. DB::commit();
  2755. } catch (\Exception $e) {
  2756. DB::rollBack();
  2757. return [false, "失败:" . $e->getMessage()];
  2758. }
  2759. return [true, ''];
  2760. }
  2761. private function leaveOrderCheck(&$array, $user, $table_config)
  2762. {
  2763. $keys = array_column($table_config, 'key');
  2764. $codeIdx = array_search('code', $keys);
  2765. $timeIdx = array_search('order_time', $keys);
  2766. $empIdx = array_search('employee_id', $keys);
  2767. $startIdx = array_search('start_time', $keys);
  2768. $endIdx = array_search('end_time', $keys);
  2769. $topDepartId = $user['top_depart_id'];
  2770. $errors = [];
  2771. $update_map = [];
  2772. // --- 1. 基础档案预加载 (代码省略,保持原样) ---
  2773. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  2774. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2775. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  2776. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  2777. $empDisplayMap = $empModels->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  2778. // --- 2. 日历 & 主表预查 (代码省略,保持原样) ---
  2779. $allDateTs = [];
  2780. foreach ($array as $rowIndex => $row) {
  2781. $valMonthRaw = $row[$timeIdx] ?? '';
  2782. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2783. if(! $status) {
  2784. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2785. continue;
  2786. }
  2787. $d = strtotime(date('Y-m-d', $ts));
  2788. $array[$rowIndex][$timeIdx] = $d;
  2789. $allDateTs[] = $d;
  2790. }
  2791. if (!empty($errors)) return [implode('|', $errors), [], []];
  2792. $allDateTs = array_unique($allDateTs);
  2793. //归档
  2794. list($status, $msg) = ArchiveService::isArchive($allDateTs, $user);
  2795. if(! $status) return [$msg, [], []];
  2796. $calendarMap = DB::table('calendar_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  2797. ->whereIn('time', $allDateTs)->pluck('is_work', 'time')->toArray();
  2798. $existMainOrders = DB::table('p_leave_over_order')
  2799. ->where('top_depart_id', $topDepartId)
  2800. ->whereIn('order_time', $allDateTs)
  2801. ->where('type', PLeaveOverOrder::TYPE_ONE)
  2802. ->where('del_time', 0)->get()->keyBy('order_time');
  2803. // --- 3. 工时设置 (代码省略,保持原样) ---
  2804. $specialWorkMap = DB::table('employee_work_range')->whereIn('employee_id', array_values($dbEmps))
  2805. ->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  2806. $commonWorkRanges = DB::table('work_range_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)->get();
  2807. $commonPeriods = [];
  2808. foreach ($commonWorkRanges as $wr) {
  2809. $commonPeriods[] = ['s' => $wr->start_time_hour * 60 + $wr->start_time_min, 'e' => $wr->end_time_hour * 60 + $wr->end_time_min];
  2810. }
  2811. // --- 4. 库内明细校验数据 (代码省略,保持原样) ---
  2812. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2813. $dbExistingWork = DB::table('p_leave_over_order_details as d')
  2814. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  2815. ->where('m.top_depart_id', $topDepartId)
  2816. ->whereIn('m.order_time', $allDateTs)
  2817. ->where('m.type', PLeaveOverOrder::TYPE_ONE)
  2818. ->where('m.del_time', 0)->where('d.del_time', 0)
  2819. ->whereNotIn('m.code', $allCodes)
  2820. ->select('m.order_time', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2821. ->get()->groupBy(fn($item) => $item->order_time . '_' . $item->employee_id);
  2822. $dbOrders = DB::table('p_leave_over_order')->where('top_depart_id', $topDepartId)
  2823. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2824. $internalOverlapMap = [];
  2825. // --- 5. 循环校验 (全量提示版) ---
  2826. foreach ($array as $rowIndex => $row) {
  2827. $line = $rowIndex + 1;
  2828. $rowErrors = []; // 临时收集本行的所有错误
  2829. $ts = $row[$timeIdx];
  2830. // 1. 单据与编辑逻辑检查
  2831. $valCode = trim($row[$codeIdx] ?? '');
  2832. if ($valCode === '') {
  2833. if (isset($existMainOrders[$ts])) {
  2834. $rowErrors[] = date('Y-m-d', $ts) . "已存在请假单[{$existMainOrders[$ts]->code}],请填写单号进行编辑";
  2835. }
  2836. } else {
  2837. if (isset($dbOrders[$valCode])) {
  2838. if ($dbOrders[$valCode]->order_time != $ts) {
  2839. $rowErrors[] = "单据[{$valCode}]原日期不符,不允许跨日期编辑";
  2840. }
  2841. $update_map[$rowIndex] = $dbOrders[$valCode]->id;
  2842. } else {
  2843. $rowErrors[] = "单据号[{$valCode}]不存在";
  2844. }
  2845. }
  2846. // 2. 日历检查
  2847. if (!isset($calendarMap[$ts]) || (int)$calendarMap[$ts] !== 1) {
  2848. $rowErrors[] = "该日期非工作日,无需请假";
  2849. }
  2850. // 3. 人员检查
  2851. $empId = $dbEmps[trim($row[$empIdx])] ?? 0;
  2852. $empName = $empDisplayMap[$empId] ?? "工号:".$row[$empIdx];
  2853. if (!$empId) {
  2854. $rowErrors[] = "人员不存在";
  2855. // 如果人都不存在,后面的时间校验没意义,报错合并
  2856. $errors[] = "第{$line}行:" . implode(';', $rowErrors);
  2857. continue;
  2858. }
  2859. // 4. 时间段合法性检查
  2860. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2861. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2862. $curS = $sH * 60 + $sM; $curE = $eH * 60 + $eM;
  2863. if ($curS >= $curE) {
  2864. $rowErrors[] = "结束时间需晚于开始时间";
  2865. } else {
  2866. // 只有在时间段本身合法的情况下,才检查范围和重叠
  2867. // A. 工作范围检查
  2868. $empPeriods = isset($specialWorkMap[$empId]) ? [] : $commonPeriods;
  2869. if (isset($specialWorkMap[$empId])) {
  2870. foreach ($specialWorkMap[$empId] as $sw) {
  2871. $empPeriods[] = ['s' => $sw->start_time_hour * 60 + $sw->start_time_min, 'e' => $sw->end_time_hour * 60 + $sw->end_time_min];
  2872. }
  2873. }
  2874. $inRange = false;
  2875. foreach ($empPeriods as $p) { if ($curS >= $p['s'] && $curE <= $p['e']) { $inRange = true; break; } }
  2876. if (!$inRange) {
  2877. $rowErrors[] = "请假需在规定的工作时间内";
  2878. }
  2879. // B. 重叠检查 (不再 continue,两个都查)
  2880. $checkKey = $ts . "_" . $empId;
  2881. // 表内
  2882. if (isset($internalOverlapMap[$checkKey])) {
  2883. foreach ($internalOverlapMap[$checkKey] as $p) {
  2884. if ($curS < $p['e'] && $p['s'] < $curE) {
  2885. $rowErrors[] = "在表内存在时间重叠";
  2886. break; // 同一行的“表内重叠”只提示一次
  2887. }
  2888. }
  2889. }
  2890. // 库内
  2891. if (isset($dbExistingWork[$checkKey])) {
  2892. foreach ($dbExistingWork[$checkKey] as $p) {
  2893. $exS = $p->start_time_hour * 60 + $p->start_time_min;
  2894. $exE = $p->end_time_hour * 60 + $p->end_time_min;
  2895. if ($curS < $exE && $exS < $curE) {
  2896. $rowErrors[] = "与已有的请假单时间重叠";
  2897. break; // 同一行的“库内重叠”只提示一次
  2898. }
  2899. }
  2900. }
  2901. }
  2902. // 收集汇总错误
  2903. if (!empty($rowErrors)) {
  2904. $errors[] = "第{$line}行:{$empName}" . implode(',', $rowErrors);
  2905. } else {
  2906. // 只有完全没错误的数据,才放入 internalOverlapMap 供后续行比对
  2907. // 这样可以防止第2行报错了,第3行又提示跟第2行重叠,造成提示混乱
  2908. $checkKey = $ts . "_" . $empId;
  2909. $internalOverlapMap[$checkKey][] = ['s' => $curS, 'e' => $curE];
  2910. }
  2911. }
  2912. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  2913. }
  2914. // 人员加班单
  2915. public function overtimeOrderImport($array, $user, $other_param)
  2916. {
  2917. $upload = $array[0];
  2918. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2919. if (!$status) return [false, $msg];
  2920. $table_config = $msg;
  2921. unset($array[0]);
  2922. if (empty($array)) return [false, '导入数据不能为空'];
  2923. // 1. 基础格式检查
  2924. list($array, $error) = $this->checkCommon($array, $table_config);
  2925. if (!empty($error)) return [0, $error];
  2926. // 2. 业务逻辑校验 (专用于加班)
  2927. list($error, $update_map, $dbEmps) = $this->overtimeOrderCheck($array, $user, $table_config);
  2928. if (!empty($error)) return [0, $error];
  2929. $keys = array_column($table_config, 'key');
  2930. $codeIdx = array_search('code', $keys);
  2931. $timeIdx = array_search('order_time', $keys);
  2932. $empIdx = array_search('employee_id', $keys);
  2933. $startIdx = array_search('start_time', $keys);
  2934. $endIdx = array_search('end_time', $keys);
  2935. // 3. 数据聚合分组 (按日期聚合)
  2936. $groups = [];
  2937. foreach ($array as $rowIndex => $row) {
  2938. $cTimeTs = $row[$timeIdx];
  2939. $mainId = $update_map[$rowIndex] ?? 0;
  2940. $aggKey = $mainId > 0 ? "ID_" . $mainId : "DATE_" . $cTimeTs;
  2941. if (!isset($groups[$aggKey])) {
  2942. $groups[$aggKey] = [
  2943. 'main_id' => $mainId,
  2944. 'order_time' => $cTimeTs,
  2945. 'details' => []
  2946. ];
  2947. }
  2948. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2949. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2950. $groups[$aggKey]['details'][] = [
  2951. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2952. 'start_time_hour' => $sH,
  2953. 'start_time_min' => $sM,
  2954. 'end_time_hour' => $eH,
  2955. 'end_time_min' => $eM,
  2956. 'total_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2957. 'type' => PLeaveOverOrder::TYPE_TWO, // 加班类型
  2958. ];
  2959. }
  2960. // 4. 执行写入
  2961. DB::beginTransaction();
  2962. try {
  2963. $time = time();
  2964. foreach ($groups as $group) {
  2965. if ($group['main_id'] > 0) {
  2966. $mainId = $group['main_id'];
  2967. DB::table('p_leave_over_order_details')->where('main_id', $mainId)->update(['del_time' => $time]);
  2968. } else {
  2969. $newCode = $this->generateBillNo([
  2970. 'top_depart_id' => $user['top_depart_id'],
  2971. 'type' => PLeaveOverOrder::Order_type,
  2972. 'period' => date("Ym", $group['order_time'])
  2973. ]);
  2974. $mainId = DB::table('p_leave_over_order')->insertGetId([
  2975. 'code' => $newCode,
  2976. 'order_time' => $group['order_time'],
  2977. 'type' => PLeaveOverOrder::TYPE_TWO,
  2978. 'top_depart_id' => $user['top_depart_id'],
  2979. 'crt_id' => $user['id'],
  2980. 'crt_time' => $time,
  2981. ]);
  2982. }
  2983. foreach ($group['details'] as &$d) {
  2984. $d['main_id'] = $mainId;
  2985. $d['top_depart_id'] = $user['top_depart_id'];
  2986. $d['crt_time'] = $time;
  2987. }
  2988. DB::table('p_leave_over_order_details')->insert($group['details']);
  2989. }
  2990. DB::commit();
  2991. } catch (\Exception $e) {
  2992. DB::rollBack();
  2993. return [false, "失败:" . $e->getMessage()];
  2994. }
  2995. return [true, ''];
  2996. }
  2997. private function overtimeOrderCheck(&$array, $user, $table_config)
  2998. {
  2999. $keys = array_column($table_config, 'key');
  3000. $codeIdx = array_search('code', $keys);
  3001. $timeIdx = array_search('order_time', $keys);
  3002. $empIdx = array_search('employee_id', $keys);
  3003. $startIdx = array_search('start_time', $keys);
  3004. $endIdx = array_search('end_time', $keys);
  3005. $topDepartId = $user['top_depart_id'];
  3006. $errors = [];
  3007. $update_map = [];
  3008. // 1. 档案预加载
  3009. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  3010. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  3011. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  3012. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  3013. $empDisplayMap = $empModels->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  3014. // 2. 日期、日历、主表预查
  3015. $allDateTs = [];
  3016. foreach ($array as $rowIndex => $row) {
  3017. $valMonthRaw = $row[$timeIdx] ?? '';
  3018. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  3019. if(! $status) {
  3020. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  3021. continue;
  3022. }
  3023. $d = strtotime(date('Y-m-d', $ts));
  3024. $array[$rowIndex][$timeIdx] = $d;
  3025. $allDateTs[] = $d;
  3026. }
  3027. if (!empty($errors)) return [implode('|', $errors), [], []];
  3028. $allDateTs = array_unique($allDateTs);
  3029. //归档
  3030. list($status, $msg) = ArchiveService::isArchive($allDateTs, $user);
  3031. if(! $status) return [$msg, [], []];
  3032. $calendarMap = DB::table('calendar_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3033. ->whereIn('time', $allDateTs)->pluck('is_work', 'time')->toArray();
  3034. $existMainOrders = DB::table('p_leave_over_order')
  3035. ->where('top_depart_id', $topDepartId)
  3036. ->whereIn('order_time', $allDateTs)
  3037. ->where('type', PLeaveOverOrder::TYPE_TWO)
  3038. ->where('del_time', 0)->get()->keyBy('order_time');
  3039. // 3. 工时设置预加载
  3040. $specialWorkMap = DB::table('employee_work_range')->whereIn('employee_id', array_values($dbEmps))
  3041. ->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  3042. $commonWorkRanges = DB::table('work_range_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)->get();
  3043. $commonPeriods = [];
  3044. foreach ($commonWorkRanges as $wr) {
  3045. $commonPeriods[] = ['s' => $wr->start_time_hour * 60 + $wr->start_time_min, 'e' => $wr->end_time_hour * 60 + $wr->end_time_min];
  3046. }
  3047. // 4. 库内明细预查 (跨单重叠校验)
  3048. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  3049. $dbExistingWork = DB::table('p_leave_over_order_details as d')
  3050. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  3051. ->where('m.top_depart_id', $topDepartId)
  3052. ->whereIn('m.order_time', $allDateTs)
  3053. ->where('m.type', PLeaveOverOrder::TYPE_TWO)
  3054. ->where('m.del_time', 0)->where('d.del_time', 0)
  3055. ->whereNotIn('m.code', $allCodes)
  3056. ->select('m.order_time', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  3057. ->get()->groupBy(fn($item) => $item->order_time . '_' . $item->employee_id);
  3058. $dbOrders = DB::table('p_leave_over_order')->where('top_depart_id', $topDepartId)
  3059. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  3060. $internalOverlapMap = [];
  3061. // 5. 全量循环检查
  3062. foreach ($array as $rowIndex => $row) {
  3063. $line = $rowIndex + 1;
  3064. $rowErrors = [];
  3065. $ts = $row[$timeIdx];
  3066. // A. 单据存在性逻辑
  3067. $valCode = trim($row[$codeIdx] ?? '');
  3068. if ($valCode === '') {
  3069. if (isset($existMainOrders[$ts])) {
  3070. $rowErrors[] = date('Y-m-d', $ts) . "已存在加班单[{$existMainOrders[$ts]->code}],请填写单号进行编辑";
  3071. }
  3072. } else {
  3073. if (isset($dbOrders[$valCode])) {
  3074. if ($dbOrders[$valCode]->order_time != $ts) $rowErrors[] = "单据[{$valCode}]原日期不符";
  3075. $update_map[$rowIndex] = $dbOrders[$valCode]->id;
  3076. } else { $rowErrors[] = "单据号[{$valCode}]不存在"; }
  3077. }
  3078. // B. 人员校验
  3079. $empId = $dbEmps[trim($row[$empIdx])] ?? 0;
  3080. $empName = $empDisplayMap[$empId] ?? "工号:".$row[$empIdx];
  3081. if (!$empId) {
  3082. $errors[] = "第{$line}行:人员不存在"; continue;
  3083. }
  3084. // C. 时间格式校验
  3085. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  3086. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  3087. $curS = $sH * 60 + $sM; $curE = $eH * 60 + $eM;
  3088. if ($curS >= $curE) {
  3089. $rowErrors[] = "结束时间需晚于开始时间";
  3090. } else {
  3091. // D. 加班规则校验 (核心逻辑)
  3092. $isWorkDay = (int)($calendarMap[$ts] ?? 0) === 1;
  3093. if ($isWorkDay) {
  3094. // 如果是工作日,加班不能在工作时间内
  3095. $empPeriods = isset($specialWorkMap[$empId]) ? [] : $commonPeriods;
  3096. if (isset($specialWorkMap[$empId])) {
  3097. foreach ($specialWorkMap[$empId] as $sw) {
  3098. $empPeriods[] = ['s' => $sw->start_time_hour * 60 + $sw->start_time_min, 'e' => $sw->end_time_hour * 60 + $sw->end_time_min];
  3099. }
  3100. }
  3101. foreach ($empPeriods as $p) {
  3102. if ($curS < $p['e'] && $p['s'] < $curE) {
  3103. $rowErrors[] = "加班时间不能与正常工作时间重叠";
  3104. break;
  3105. }
  3106. }
  3107. }
  3108. // E. 重叠校验
  3109. $checkKey = $ts . "_" . $empId;
  3110. // 表内重叠
  3111. if (isset($internalOverlapMap[$checkKey])) {
  3112. foreach ($internalOverlapMap[$checkKey] as $p) {
  3113. if ($curS < $p['e'] && $p['s'] < $curE) { $rowErrors[] = "在表内存在时间重叠"; break; }
  3114. }
  3115. }
  3116. // 库内重叠
  3117. if (isset($dbExistingWork[$checkKey])) {
  3118. foreach ($dbExistingWork[$checkKey] as $p) {
  3119. $exS = $p->start_time_hour * 60 + $p->start_time_min; $exE = $p->end_time_hour * 60 + $p->end_time_min;
  3120. if ($curS < $exE && $exS < $curE) { $rowErrors[] = "与已有的加班单时间重叠"; break; }
  3121. }
  3122. }
  3123. }
  3124. if (!empty($rowErrors)) {
  3125. $errors[] = "第{$line}行:{$empName} " . implode(',', $rowErrors);
  3126. } else {
  3127. $internalOverlapMap[$ts . "_" . $empId][] = ['s' => $curS, 'e' => $curE];
  3128. }
  3129. }
  3130. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  3131. }
  3132. // 费用项目单月度导入 ------------------------------
  3133. public function feeOrderImport($array, $user, $other_param)
  3134. {
  3135. $upload = $array[0];
  3136. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3137. if (!$status) return [false, $msg];
  3138. $table_config = $msg;
  3139. unset($array[0]);
  3140. if (empty($array)) return [false, '导入数据不能为空'];
  3141. // 1. 基础校验(格式、必填项等)
  3142. list($array, $error) = $this->checkCommon($array, $table_config);
  3143. if (!empty($error)) return [0, $error];
  3144. // 2. 业务详细校验 (获取 update_map 和 基础档案映射)
  3145. // 此时 claim_date 会在 check 方法内部被转换为时间戳并校验月份归属
  3146. list($error, $update_map, $maps) = $this->feeOrderCheck($array, $user, $table_config);
  3147. if (!empty($error)) return [0, $error];
  3148. $keys = array_column($table_config, 'key');
  3149. $codeIdx = array_search('code', $keys);
  3150. $monthIdx = array_search('month', $keys);
  3151. // --- 步骤 1: 数据聚合分组 ---
  3152. $groups = [];
  3153. foreach ($array as $rowIndex => $row) {
  3154. $cCode = trim($row[$codeIdx] ?? '');
  3155. $cMonthTs = $row[$monthIdx];
  3156. // 聚合 Key:有编码用编码,没编码用月份
  3157. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  3158. if (!isset($groups[$aggKey])) {
  3159. $groups[$aggKey] = [
  3160. 'main_id' => $update_map[$rowIndex] ?? 0,
  3161. 'code' => $cCode,
  3162. 'month' => $cMonthTs,
  3163. 'details' => []
  3164. ];
  3165. }
  3166. // 准备详情行数据
  3167. $detailTmp = [];
  3168. foreach ($table_config as $k => $conf) {
  3169. if (!$conf['is_main']) {
  3170. $fieldKey = $conf['key'];
  3171. // 跳过仅用于展示的名称字段
  3172. if (in_array($fieldKey, ['employee_title', 'item_title', 'fee_title'])) continue;
  3173. $fieldVal = $row[$k];
  3174. // 转换编号为 ID
  3175. if ($fieldKey == 'employee_id') $fieldVal = $maps['emps'][$fieldVal] ?? 0;
  3176. if ($fieldKey == 'item_id') $fieldVal = $maps['items'][$fieldVal] ?? 0;
  3177. if ($fieldKey == 'fee_id') $fieldVal = $maps['fees'][$fieldVal] ?? 0;
  3178. // 转换枚举值(委托方式、是否定位到人)
  3179. if ($fieldKey == 'entrust_type') {
  3180. $fieldVal = array_search($fieldVal, \App\Model\ExpenseClaimsDetails::State_Type) ?: 0;
  3181. }
  3182. if ($fieldKey == 'expense_type') {
  3183. $fieldVal = array_search($fieldVal, \App\Model\ExpenseClaimsDetails::State_Type_2) ?: 0;
  3184. }
  3185. // 注意:claim_date 已经在 check 方法里转成了时间戳,这里直接赋值即可
  3186. $detailTmp[$fieldKey] = $fieldVal;
  3187. }
  3188. }
  3189. $groups[$aggKey]['details'][] = $detailTmp;
  3190. }
  3191. // --- 步骤 2: 事务写入 ---
  3192. DB::beginTransaction();
  3193. try {
  3194. $time = time();
  3195. foreach ($groups as $group) {
  3196. $mainId = $group['main_id'];
  3197. if ($mainId > 0) {
  3198. // 编辑:逻辑删除旧明细
  3199. DB::table('expense_claims_details')->where('del_time', 0)
  3200. ->where('expense_claims_id', $mainId)
  3201. ->update(['del_time' => $time]);
  3202. // 更新主表更新时间
  3203. DB::table('expense_claims')->where('id', $mainId)->update(['upd_time' => $time]);
  3204. } else {
  3205. // 新增:生成单号
  3206. $newCode = $this->generateBillNo([
  3207. 'top_depart_id' => $user['top_depart_id'],
  3208. 'type' => \App\Model\ExpenseClaims::Order_type,
  3209. 'period' => date("Ym", $group['month'])
  3210. ]);
  3211. $mainId = DB::table('expense_claims')->insertGetId([
  3212. 'code' => $newCode,
  3213. 'month' => $group['month'],
  3214. 'top_depart_id' => $user['top_depart_id'],
  3215. 'crt_id' => $user['id'],
  3216. 'crt_time' => $time,
  3217. 'upd_time' => $time,
  3218. 'del_time' => 0
  3219. ]);
  3220. }
  3221. // 批量插入详情
  3222. $insertDetails = [];
  3223. foreach ($group['details'] as $detail) {
  3224. $detail['expense_claims_id'] = $mainId;
  3225. $detail['top_depart_id'] = $user['top_depart_id'];
  3226. $detail['crt_id'] = $user['id'];
  3227. $detail['crt_time'] = $time;
  3228. $detail['upd_time'] = $time;
  3229. $detail['del_time'] = 0;
  3230. $insertDetails[] = $detail;
  3231. }
  3232. if (!empty($insertDetails)) {
  3233. DB::table('expense_claims_details')->insert($insertDetails);
  3234. }
  3235. }
  3236. DB::commit();
  3237. } catch (\Exception $e) {
  3238. DB::rollBack();
  3239. return [false, "写入失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  3240. }
  3241. return [true, ''];
  3242. }
  3243. private function feeOrderCheck(&$array, $user, $table_config)
  3244. {
  3245. $keys = array_column($table_config, 'key');
  3246. $codeIdx = array_search('code', $keys);
  3247. $monthIdx = array_search('month', $keys);
  3248. $empIdx = array_search('employee_id', $keys);
  3249. $itemIdx = array_search('item_id', $keys);
  3250. $feeIdx = array_search('fee_id', $keys);
  3251. $claimDateIdx = array_search('claim_date', $keys);
  3252. $topDepartId = $user['top_depart_id'];
  3253. $errors = [];
  3254. $allEmpNos = []; $allItemCodes = []; $allFeeCodes = []; $allMonthsTs = []; $allCodes = [];
  3255. // --- 1. 预处理:日期转换与基础编号提取 ---
  3256. foreach ($array as $rowIndex => $row) {
  3257. $line = $rowIndex + 1;
  3258. // A. 报销主月份处理
  3259. $valMonthRaw = trim($row[$monthIdx] ?? '');
  3260. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  3261. if (!$mStatus) {
  3262. $errors[] = "第{$line}行:月份格式错误";
  3263. continue;
  3264. }
  3265. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  3266. $array[$rowIndex][$monthIdx] = $valMonthTs; // 回写转换后的时间戳
  3267. $allMonthsTs[] = $valMonthTs;
  3268. // B. 费用产生日期校验 (claim_date)
  3269. $valClaimDateRaw = trim($row[$claimDateIdx] ?? '');
  3270. if (empty($valClaimDateRaw)) {
  3271. $errors[] = "第{$line}行:费用产生日期不能为空";
  3272. } else {
  3273. list($dStatus, $dTs) = $this->convertExcelCellToDate($valClaimDateRaw);
  3274. if (!$dStatus) {
  3275. $errors[] = "第{$line}行:费用产生日期格式错误";
  3276. } else {
  3277. // 核心逻辑:判断产生日期是否在主月份内
  3278. $monthStr = date('Y-m', $valMonthTs);
  3279. $claimMonthStr = date('Y-m', $dTs);
  3280. if ($monthStr !== $claimMonthStr) {
  3281. $errors[] = "第{$line}行:产生日期[{$claimMonthStr}]与报销月份[{$monthStr}]不符";
  3282. }
  3283. $array[$rowIndex][$claimDateIdx] = $dTs; // 回写转换后的时间戳
  3284. }
  3285. }
  3286. // C. 提取其他编号
  3287. if (!empty($row[$empIdx])) $allEmpNos[] = trim($row[$empIdx]);
  3288. if (!empty($row[$itemIdx])) $allItemCodes[] = trim($row[$itemIdx]);
  3289. if (!empty($row[$feeIdx])) $allFeeCodes[] = trim($row[$feeIdx]);
  3290. if (!empty($row[$codeIdx])) $allCodes[] = trim($row[$codeIdx]);
  3291. }
  3292. if (!empty($errors)) return [implode('|', $errors), [], []];
  3293. $allMonthsTs = array_unique($allMonthsTs);
  3294. //归档
  3295. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  3296. if(! $status) return [$msg, [], []];
  3297. // --- 2. 批量预加载档案映射 ---
  3298. $dbEmps = DB::table('employee')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3299. ->whereIn('number', array_unique($allEmpNos))->pluck('id', 'number')->toArray();
  3300. $dbItems = DB::table('item')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3301. ->whereIn('code', array_unique($allItemCodes))->pluck('id', 'code')->toArray();
  3302. $dbFees = DB::table('fee')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3303. ->whereIn('code', array_unique($allFeeCodes))->pluck('id', 'code')->toArray();
  3304. $existingMonthsMap = DB::table('expense_claims')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3305. ->whereIn('month', $allMonthsTs)->pluck('code', 'month')->toArray();
  3306. $dbOrdersByCode = DB::table('expense_claims')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3307. ->whereIn('code', array_unique($allCodes))->get()->keyBy('code');
  3308. // --- 3. 逐行校验档案存在性与单据逻辑 ---
  3309. $update_map = [];
  3310. foreach ($array as $rowIndex => $row) {
  3311. $line = $rowIndex + 1;
  3312. $valCode = trim($row[$codeIdx] ?? '');
  3313. $valMonthTs = $row[$monthIdx];
  3314. if (!empty($row[$empIdx]) && !isset($dbEmps[trim($row[$empIdx])])) {
  3315. $errors[] = "第{$line}行:工号[{$row[$empIdx]}]不存在";
  3316. }
  3317. if (!isset($dbItems[trim($row[$itemIdx])])) {
  3318. $errors[] = "第{$line}行:项目编号[{$row[$itemIdx]}]不存在";
  3319. }
  3320. if (!isset($dbFees[trim($row[$feeIdx])])) {
  3321. $errors[] = "第{$line}行:费用类型编号[{$row[$feeIdx]}]不存在";
  3322. }
  3323. if ($valCode !== '') {
  3324. if (isset($dbOrdersByCode[$valCode])) {
  3325. if ($dbOrdersByCode[$valCode]->month != $valMonthTs) {
  3326. $errors[] = "第{$line}行:单据[{$valCode}]对应月份为" . date('Y-m', $dbOrdersByCode[$valCode]->month) . ",Excel中月份不符";
  3327. }
  3328. $update_map[$rowIndex] = $dbOrdersByCode[$valCode]->id;
  3329. } else {
  3330. $errors[] = "第{$line}行:填写的单据编码[{$valCode}]系统中不存在";
  3331. }
  3332. } else {
  3333. if (isset($existingMonthsMap[$valMonthTs])) {
  3334. $errors[] = "第{$line}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据[{$existingMonthsMap[$valMonthTs]}],请填写该单号进行编辑";
  3335. }
  3336. }
  3337. }
  3338. $maps = ['emps' => $dbEmps, 'items' => $dbItems, 'fees' => $dbFees];
  3339. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $maps];
  3340. }
  3341. /**
  3342. * 解析并校验时间
  3343. */
  3344. private function parseTimeHourMin($val)
  3345. {
  3346. $h = -1; $m = -1;
  3347. if (strpos($val, ':') !== false) {
  3348. $parts = explode(':', $val);
  3349. $h = isset($parts[0]) ? (int)$parts[0] : -1;
  3350. $m = isset($parts[1]) ? (int)$parts[1] : -1;
  3351. } elseif (is_numeric($val)) {
  3352. $totalMinutes = (int)round($val * 1440);
  3353. $h = (int)floor($totalMinutes / 60);
  3354. $m = (int)($totalMinutes % 60);
  3355. }
  3356. if ($h < 0 || $h > 23 || $m < 0 || $m > 59) {
  3357. return [null, null];
  3358. }
  3359. return [$h, $m];
  3360. }
  3361. //公共校验 -----------------------------------------
  3362. private function checkCommon($array, $table_config) {
  3363. $error = [];
  3364. $uniqueCheck = [];
  3365. foreach ($array as $line => $row) {
  3366. // 如果整行都是空的(包括 null),直接剔除
  3367. if (empty(array_filter($row))) {
  3368. unset($array[$line]);
  3369. continue;
  3370. }
  3371. // --- 核心修正点:遍历配置,而不是遍历原始行数据 ---
  3372. // 这样即便 Excel 有 100 列,我们也只校验配置里的那 4 列
  3373. $newRow = [];
  3374. foreach ($table_config as $colIndex => $config) {
  3375. $value = isset($row[$colIndex]) ? trim($row[$colIndex]) : '';
  3376. $fieldName = $config['value'];
  3377. // 1. 必填校验
  3378. if (!empty($config['required']) && $value === '') {
  3379. $error[] = "第{$line}行:[{$fieldName}] 必填";
  3380. }
  3381. // 2. 默认值填充
  3382. if ($value === '' && isset($config['default'])) {
  3383. $value = $config['default'];
  3384. }
  3385. // 3. 唯一性校验
  3386. if (!empty($config['unique']) && $value !== '') {
  3387. if (isset($uniqueCheck[$colIndex][$value])) {
  3388. $prevLine = $uniqueCheck[$colIndex][$value];
  3389. $error[] = "第{$line}行:[{$fieldName}] 与第{$prevLine}行重复,重复值:{$value}";
  3390. } else {
  3391. $uniqueCheck[$colIndex][$value] = $line;
  3392. }
  3393. }
  3394. $newRow[$colIndex] = $value;
  3395. }
  3396. // 只保留校验过的数据列,多余的列(第4列之后)被自动丢弃
  3397. $array[$line] = $newRow;
  3398. }
  3399. $error_string = !empty($error) ? implode('|', $error) : "";
  3400. return [$array, $error_string];
  3401. }
  3402. //模板校验 -----------------------------------------
  3403. private function compareTableAndReturn($upload, $param){
  3404. if(empty($upload)) return [false, '表头不能为空'];
  3405. $config = $this->getTableConfig($param['type']);
  3406. $config_array = $config['array'];
  3407. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  3408. foreach ($config_array as $key => $value){
  3409. $key_position = $key + 1;
  3410. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  3411. $tmp_v = trim($upload[$key]);
  3412. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  3413. }
  3414. return [true, $config_array];
  3415. }
  3416. //转换日期 ------------------------------------------
  3417. function convertExcelCellToDate($cellValue) {
  3418. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  3419. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  3420. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  3421. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  3422. try {
  3423. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  3424. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  3425. // // 如果是,则将时间设置为 '23:59:00'
  3426. // $dateTimeObject->setTime(23, 59);
  3427. // }
  3428. // 现在你可以格式化这个日期了
  3429. $formattedDate = $dateTimeObject->format('Y-m-d');
  3430. if(! strtotime($formattedDate)) return [false, ''];
  3431. return [true, strtotime($formattedDate)];
  3432. } catch (\Exception $e) {
  3433. // 处理转换失败的情况
  3434. return [false, '单元格日期格式转换时间戳失败'];
  3435. }
  3436. }
  3437. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  3438. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  3439. return [true, strtotime($cellValue)];
  3440. }
  3441. }