ImportService.php 137 KB

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