ImportService.php 148 KB

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