ImportService.php 162 KB

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