ImportService.php 160 KB

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