ImportService.php 164 KB

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