ImportService.php 132 KB

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