EmployeeService.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. <?php
  2. namespace App\Service;
  3. use App\Model\CalendarDetails;
  4. use App\Model\Depart;
  5. use App\Model\Employee;
  6. use App\Model\EmployeeDepartPermission;
  7. use App\Model\EmployeeFile;
  8. use App\Model\EmployeeRole;
  9. use App\Model\EmployeeWorkRange;
  10. use App\Model\Role;
  11. use App\Model\RoleMenu;
  12. use App\Model\RoleMenuButton;
  13. use App\Model\SysMenu;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Hash;
  16. use Mockery\Exception;
  17. class EmployeeService extends Service
  18. {
  19. public function employeeEditOther($data,$user){
  20. list($status,$msg) = $this->employeeOtherRule($data,$user);
  21. if(!$status) return [$status,$msg];
  22. try {
  23. DB::beginTransaction();
  24. $model = new Employee();
  25. $model = $model->where('id',$user['id'])->first();
  26. $model->password = Hash::make($data['new_password']);
  27. $model->p_version = $model->p_version + 1;
  28. $model->save();
  29. DB::commit();
  30. }catch (\Exception $exception){
  31. DB::rollBack();
  32. return [false, $exception->getMessage()];
  33. }
  34. return [true,''];
  35. }
  36. public function employeeOtherRule($data,$user){
  37. if(! isset($data['old_password'])) return [false,'请输入原密码'];
  38. if($data['old_password'] == "") return [false,'原密码不能为空'];
  39. if(! isset($data['new_password'])) return [false,'请输入新密码'];
  40. if($data['new_password'] == "") return [false,'新密码不能为空'];
  41. if(! isset($data['re_password'])) return [false,'请输入确认密码'];
  42. if($data['re_password'] == "") return [false,'确认密码不能为空'];
  43. if(! Hash::check($data['old_password'], $user['password'])) return [false,'原密码错误'];
  44. if($data['new_password'] == $data['old_password']) return [false,'原密码与新密码一致'];
  45. if($data['new_password'] !== $data['re_password']) return [false,'新密码与确认密码不一致'];
  46. return [true,''];
  47. }
  48. public function employeeEdit($data,$user){
  49. list($status,$msg) = $this->employeeRule($data,$user,false);
  50. if(!$status) return [$status,$msg];
  51. try {
  52. DB::beginTransaction();
  53. $model = new Employee();
  54. $model = $model->where('id',$data['id'])->first();
  55. $model->number = $data['number'] ?? "";
  56. $model->title = $data['title'] ?? "";
  57. $model->mobile = $data['mobile'] ?? "";
  58. $model->sex = $data['sex'] ?? 0;
  59. $model->education = $data['education'] ?? "";
  60. $model->id_card = $data['id_card'] ?? "";
  61. $model->major = $data['major'] ?? "";
  62. $model->position = $data['position'] ?? "";
  63. $model->p_title = $data['p_title'] ?? "";
  64. $model->state = $data['state'] ?? 0;
  65. $model->is_admin = $data['is_admin'] ?? 0;
  66. $model->entrust_type = $data['entrust_type'] ?? 0;
  67. $model->man_type = $data['man_type'] ?? 0;
  68. if($model->is_admin && $data['password'] !== '******') {
  69. $model->password = Hash::make($data['password']);
  70. $model->p_version = $model->p_version + 1;
  71. }
  72. $model->save();
  73. $time = time();
  74. EmployeeDepartPermission::where('employee_id',$data['id'])->delete();
  75. if(isset($data['depart'])){
  76. $insert = [];
  77. foreach ($data['depart'] as $value){
  78. $insert[] = [
  79. 'employee_id' => $model->id,
  80. 'depart_id' => $value,
  81. 'top_depart_id' => $user['top_depart_id'],
  82. ];
  83. }
  84. EmployeeDepartPermission::insert($insert);
  85. }
  86. EmployeeRole::where('employee_id',$data['id'])->update([
  87. 'del_time' => $time
  88. ]);
  89. if(isset($data['role'])){
  90. $insert = [];
  91. foreach ($data['role'] as $value){
  92. $insert[] = [
  93. 'employee_id' => $model->id,
  94. 'role_id' => $value,
  95. 'crt_time' => $time,
  96. ];
  97. }
  98. EmployeeRole::insert($insert);
  99. }
  100. EmployeeWorkRange::where('employee_id',$data['id'])->delete();
  101. if(isset($data['work_range'])){
  102. $insert = [];
  103. foreach ($data['work_range'] as $value){
  104. $insert[] = [
  105. 'employee_id' => $model->id,
  106. 'start_time_hour' => $value['start_time_hour'],
  107. 'start_time_min' => $value['start_time_min'],
  108. 'end_time_hour' => $value['end_time_hour'],
  109. 'end_time_min' => $value['end_time_min'],
  110. 'total_work_min' => $value['total_work_min'],
  111. 'top_depart_id' => $value['top_depart_id'],
  112. 'crt_time' => time(),
  113. ];
  114. }
  115. EmployeeWorkRange::insert($insert);
  116. }
  117. $old = EmployeeFile::where('del_time',0)
  118. ->where('employee_id',$model->id)
  119. ->pluck('file')
  120. ->toArray();
  121. EmployeeFile::where('del_time',0)
  122. ->where('employee_id',$model->id)
  123. ->update(['del_time' => $time]);
  124. $new = [];
  125. $insert = [];
  126. if(! empty($data['img_url'])){
  127. $insert[] = [
  128. 'employee_id' => $model->id,
  129. 'file' => $data['img_url'],
  130. 'crt_time' => $time,
  131. 'top_depart_id' => $user['top_depart_id'],
  132. ];
  133. EmployeeFile::insert($insert);
  134. $new[] = $data['img_url'];
  135. }
  136. DB::commit();
  137. }catch (\Exception $exception){
  138. DB::rollBack();
  139. return [false, $exception->getMessage()];
  140. }
  141. return [true, ['file' => ['new' => $new, 'old' => $old]]];
  142. }
  143. public function employeeAdd($data,$user){
  144. list($status,$msg) = $this->employeeRule($data, $user);
  145. if(!$status) return [$status,$msg];
  146. try{
  147. DB::beginTransaction();
  148. $model = new Employee();
  149. $model->number = $data['number'] ?? "";
  150. $model->title = $data['title'] ?? "";
  151. $model->mobile = $data['mobile'] ?? "";
  152. $model->sex = $data['sex'] ?? 0;
  153. $model->education = $data['education'] ?? "";
  154. $model->id_card = $data['id_card'] ?? "";
  155. $model->major = $data['major'] ?? "";
  156. $model->position = $data['position'] ?? "";
  157. $model->p_title = $data['p_title'] ?? "";
  158. $model->state = $data['state'] ?? 0;
  159. $model->crt_id = $user['id'];
  160. $model->is_admin = $data['is_admin'] ?? 0;
  161. $model->account = $data['account'] ?? "";
  162. $model->entrust_type = $data['entrust_type'] ?? 0;
  163. $model->man_type = $data['man_type'] ?? 0;
  164. if($model->is_admin) $model->password = Hash::make($data['password']);
  165. $model->top_depart_id = $data['top_depart_id'];
  166. $model->save();
  167. $time = time();
  168. if(isset($data['depart'])){
  169. $insert = [];
  170. foreach ($data['depart'] as $value){
  171. $insert[] = [
  172. 'employee_id' => $model->id,
  173. 'depart_id' => $value,
  174. 'top_depart_id' => $user['top_depart_id'],
  175. ];
  176. }
  177. EmployeeDepartPermission::insert($insert);
  178. }
  179. if(isset($data['role'])){
  180. $insert = [];
  181. foreach ($data['role'] as $value){
  182. $insert[] = [
  183. 'employee_id' => $model->id,
  184. 'role_id' => $value,
  185. 'crt_time' => $time,
  186. ];
  187. }
  188. EmployeeRole::insert($insert);
  189. }
  190. if(isset($data['work_range'])){
  191. $insert = [];
  192. foreach ($data['work_range'] as $value){
  193. $insert[] = [
  194. 'employee_id' => $model->id,
  195. 'start_time_hour' => $value['start_time_hour'],
  196. 'start_time_min' => $value['start_time_min'],
  197. 'end_time_hour' => $value['end_time_hour'],
  198. 'end_time_min' => $value['end_time_min'],
  199. 'total_work_min' => $value['total_work_min'],
  200. 'top_depart_id' => $value['top_depart_id'],
  201. 'crt_time' => $time,
  202. ];
  203. }
  204. EmployeeWorkRange::insert($insert);
  205. }
  206. $new = [];
  207. $insert = [];
  208. if(! empty($data['img_url'])){
  209. $insert[] = [
  210. 'employee_id' => $model->id,
  211. 'file' => $data['img_url'],
  212. 'top_depart_id' => $value['top_depart_id'],
  213. 'crt_time' => $time,
  214. ];
  215. EmployeeFile::insert($insert);
  216. $new[] = $data['img_url'];
  217. }
  218. DB::commit();
  219. }catch (Exception $e){
  220. DB::rollBack();
  221. return [false, $e->getMessage()];
  222. }
  223. return [true, ['file' => ['new' => $new]]];
  224. }
  225. public function employeeDel($data){
  226. if($this->isEmpty($data,'id')) return [false,'请选择删除的数据!'];
  227. try {
  228. DB::beginTransaction();
  229. $time = time();
  230. Employee::whereIn('id',$data['id'])->update([
  231. 'del_time'=>$time
  232. ]);
  233. EmployeeRole::where('del_time',0)->whereIn('employee_id',$data['id'])->update([
  234. 'del_time'=>$time
  235. ]);
  236. EmployeeDepartPermission::whereIn('employee_id',$data['id'])->delete();
  237. EmployeeWorkRange::whereIn('employee_id',$data['id'])->delete();
  238. $old = EmployeeFile::where('del_time',0)
  239. ->whereIn('employee_id',$data['id'])
  240. ->pluck('file')
  241. ->toArray();
  242. DB::commit();
  243. }catch (\Exception $exception){
  244. DB::rollBack();
  245. return [false,$exception->getMessage()];
  246. }
  247. return [true, ['file' => ['old' => $old]]];
  248. }
  249. public function employeeDetail($data, $user){
  250. if(empty($data['id'])) return [false,'人员id不能为空'];
  251. list($status, $return) = $this->employeeList(['id' => [$data['id']]], $user);
  252. $user = $return['data'][0] ?? [];
  253. list($img, $img2) = $this->showUserImg($data['id']);
  254. $user['img_url'] = $img;
  255. $user['img_url_show'] = $img2;
  256. return [true, $user];
  257. }
  258. public function getEmployeeImg($data, $user){
  259. list($img, $img_str) = $this->showUserImg($user['id']);
  260. return [true, ['img_url' => $img_str]];
  261. }
  262. private function showUserImg($id){
  263. $file = EmployeeFile::where('del_time',0)
  264. ->where('employee_id',$id)
  265. ->pluck('file')
  266. ->toArray();
  267. $file = $file[0] ?? "";
  268. $img_str = "";
  269. $timeStamp = 86400;
  270. if(! empty($file)){
  271. $fileUploadService = new FileUploadService();
  272. $img_str = $fileUploadService->getFileShow($file, $timeStamp);
  273. }
  274. return [$file, $img_str];
  275. }
  276. public function employeeCommon($data,$user, $field = []){
  277. if(empty($field)) $field = Employee::$field;
  278. $model = Employee::TopClear($user,$data);
  279. $model = $model->where('del_time',0)
  280. ->where('is_admin', '<>', Employee::IS_ADMIN_TWO)
  281. ->select($field)
  282. ->orderBy('id','desc');
  283. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  284. if(! empty($data['number'])) $model->where('number', 'LIKE', '%'.$data['number'].'%');
  285. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  286. if(! empty($data['mobile'])) $model->where('mobile', 'LIKE', '%'.$data['mobile'].'%');
  287. if(isset($data['is_admin'])) $model->where('is_admin', $data['is_admin']);
  288. if(! empty($data['state'])) $model->where('state', $data['state']);
  289. if(isset($data['education'])) $model->where('education', $data['education']);
  290. if(! empty($data['role'])) {
  291. $emp = EmployeeRole::where('role_id',$data['role'])
  292. ->where('del_time',0)
  293. ->select('employee_id')->get()->toArray();
  294. $model->whereIn('id',array_column($emp,'employee_id'));
  295. }
  296. if(! empty($data['depart'])) {
  297. // 1. 获取所有子部门 ID(包含自身)
  298. $allDeparts = Depart::where('del_time', 0)->select('id', 'parent_id')->get();
  299. $departIds = array_merge($this->getAllDescendants($allDeparts->toArray(), $data['depart']), [$data['depart']]);
  300. // 2. 优化:直接使用子查询,避免拉取巨大的 $employee_id 数组到内存
  301. $model->whereIn('id', function ($query) use ($departIds) {
  302. $query->select('employee_id')
  303. ->from('employee_depart_permission')
  304. ->whereIn('depart_id', $departIds);
  305. });
  306. }
  307. return $model;
  308. }
  309. /**
  310. * 产品列表
  311. * @param $data
  312. * @param $user
  313. * @return array
  314. */
  315. public function employeeList($data,$user){
  316. $model = $this->employeeCommon($data, $user);
  317. $list = $this->limit($model,'',$data);
  318. $list = $this->organizationEmployeeData($list, $data, $user);
  319. return [true, $list];
  320. }
  321. public function organizationEmployeeData($data, $ergs, $user)
  322. {
  323. if (empty($data['data'])) return $data;
  324. // 获取员工ID并查询扩展数据
  325. $employee_ids = array_column($data['data'], 'id');
  326. list($status, $extraMap) = $this->getEmployee($employee_ids);
  327. $map = [];
  328. if(isset($ergs['search_for_month_work'])) list($status, $map) = $this->getEmployeesMonthStats($employee_ids, $ergs['search_for_month_work'], $user);
  329. foreach ($data['data'] as &$item) {
  330. $id = $item['id'];
  331. $extra = $extraMap[$id] ?? null;
  332. $item['role'] = $extra['role_ids'] ?? [];
  333. $item['role_name'] = isset($extra['role_names']) ? implode(',', $extra['role_names']) : '';
  334. $item['depart'] = $extra['depart_ids'] ?? [];
  335. $item['depart_title'] = isset($extra['depart_names']) ? implode(',', $extra['depart_names']) : '';
  336. // 业务状态字段
  337. $item['is_admin_title'] = Employee::IS_ADMIN_TITLE[$item['is_admin']] ?? "";
  338. $item['state_title'] = Employee::State_Type[$item['state']] ?? "";
  339. $item['sex_title'] = Employee::SEX_TYPE[$item['sex']] ?? "";
  340. $item['man_type_title'] = Employee::Man_Type[$item['man_type']] ?? "";
  341. $item['entrust_type_title'] = Employee::WT_Type[$item['entrust_type']] ?? "";
  342. $item['education_title'] = Employee::Education[$item['education']] ?? "";
  343. $item['crt_time'] = !empty($item['crt_time']) ? date("Y-m-d", $item['crt_time']) : "";
  344. if (isset($ergs['search_for_month_work'])) {
  345. $item['month_pw'] = []; // 默认空数组
  346. if ($status) {
  347. $item['month_pw'] = $map[$item['id']] ?? [];
  348. }
  349. }
  350. }
  351. return $data;
  352. }
  353. public function getEmployeesMonthStats($employee_ids, $month, $user)
  354. {
  355. $topDepartId = $user['top_depart_id'];
  356. // 1. 月份初始化
  357. if(is_numeric($month)){
  358. $monthStart = $month;
  359. }else{
  360. $monthStart = $this->changeDateToDate($month);
  361. $monthStr = date("Y-m", $monthStart);
  362. }
  363. $endTime = strtotime("+1 month", $monthStart) - 1;
  364. // 2. 获取当月标准工作日天数 (基数)
  365. $standardWorkDays = DB::table('calendar_details')
  366. ->where('top_depart_id', $topDepartId)
  367. ->where('del_time', 0)
  368. ->where('time', '>=', $monthStart)
  369. ->where('time', '<=', $endTime)
  370. ->where('is_work', CalendarDetails::TYPE_ONE)
  371. ->count();
  372. if ($standardWorkDays <= 0) return [false, '工作日信息未设置'];
  373. // 3. 批量获取个性化工时设置
  374. $empWorkRanges = DB::table('employee_work_range')
  375. ->whereIn('employee_id', $employee_ids)
  376. ->where('top_depart_id', $topDepartId)
  377. ->select('employee_id', DB::raw('SUM(total_work_min) as total_min'))
  378. ->groupBy('employee_id')
  379. ->pluck('total_min', 'employee_id')
  380. ->toArray();
  381. // 4. 获取公司通用工时设置
  382. $commonWorkMin = DB::table('work_range_details')
  383. ->where('top_depart_id', $topDepartId)
  384. ->where('del_time', 0)
  385. ->sum('total_work_min');
  386. if(empty($commonWorkMin)) return [false, '公司工作时段未设置'];
  387. // 5. 批量获取请假与加班汇总
  388. $actualStats = DB::table('p_leave_over_order_details as d')
  389. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  390. ->whereIn('d.employee_id', $employee_ids)
  391. ->where('m.order_time', '>=', $monthStart)
  392. ->where('m.order_time', '<=', $endTime)
  393. ->where('m.del_time', 0)
  394. ->where('d.del_time', 0)
  395. ->select(
  396. 'd.employee_id',
  397. DB::raw("SUM(CASE WHEN m.type = 1 THEN d.total_min ELSE 0 END) as leave_min"),
  398. DB::raw("SUM(CASE WHEN m.type = 2 THEN d.total_min ELSE 0 END) as overtime_min")
  399. )
  400. ->groupBy('d.employee_id')
  401. ->get()
  402. ->keyBy('employee_id');
  403. // 6. 核心逻辑汇总
  404. $result = [];
  405. foreach ($employee_ids as $empId) {
  406. // A. 确定该人员每日标准时长 (基数)
  407. $dailyStandardMin = isset($empWorkRanges[$empId]) ? (float)$empWorkRanges[$empId] : (float)$commonWorkMin;
  408. // 如果每日标准时长没设置,跳过该人防止除以0错误
  409. if ($dailyStandardMin <= 0) continue;
  410. // B. 获取加班和请假数据
  411. $empActual = $actualStats->get($empId);
  412. $leaveMin = $empActual ? (float)$empActual->leave_min : 0;
  413. $overtimeMin = $empActual ? (float)$empActual->overtime_min : 0;
  414. // 净增减工时(分)
  415. $netDiffMin = $overtimeMin - $leaveMin;
  416. // C. 计算出勤总工时 (标准总分钟 + 净增减)
  417. $standardMonthMin = $standardWorkDays * $dailyStandardMin;
  418. $finalWorkMin = $standardMonthMin + $netDiffMin;
  419. // D. 计算出勤总天数 (标准天数 + 净增减折算天数)
  420. // 计算公式:出勤天数 = (标准总分钟 + 加班分钟 - 请假分钟) / 每日标准分钟
  421. $finalAttendanceDays = round($finalWorkMin / $dailyStandardMin, 2);
  422. $result[$empId] = [
  423. // 'standard_days' => $standardWorkDays, // 标准工作天数
  424. 'attendance_days' => $finalAttendanceDays, // 出勤总天数 * (结算后)
  425. // 'standard_month_min' => $standardMonthMin, // 标准总工时 (分钟)
  426. // 'final_work_min' => $finalWorkMin, // 出勤总工时 * (结算后分钟)
  427. 'final_work_hour' => round($finalWorkMin / 60, 2), // 出勤总工时 * (结算后小时)
  428. // 'leave_min' => $leaveMin,
  429. // 'overtime_min' => $overtimeMin,
  430. // 'daily_standard_min' => $dailyStandardMin
  431. ];
  432. }
  433. return [true, $result];
  434. }
  435. public function getEmployee(array $employee_ids)
  436. {
  437. if (empty($employee_ids)) return [false, []];
  438. // 1. 一次性获取所有角色
  439. $roles = DB::table('employee_role as a')
  440. ->join('role as b', 'a.role_id', '=', 'b.id')
  441. ->where('a.del_time', 0)
  442. ->where('b.del_time', 0)
  443. ->whereIn("a.employee_id", $employee_ids)
  444. ->select('a.employee_id', 'b.title', 'b.id')
  445. ->get();
  446. // 2. 一次性获取所有部门
  447. $departs = DB::table('employee_depart_permission as a')
  448. ->join('depart as b', 'a.depart_id', '=', 'b.id')
  449. ->whereIn("a.employee_id", $employee_ids)
  450. ->select('a.employee_id', 'b.title', 'b.id')
  451. ->orderBy('b.id')
  452. ->get();
  453. $work_range = DB::table('employee_work_range as a')
  454. ->whereIn("employee_id", $employee_ids)
  455. ->select('employee_id','start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min')
  456. ->get();
  457. // 3. 结果按员工ID分组归纳
  458. $resultMap = [];
  459. foreach ($employee_ids as $id) {
  460. $resultMap[$id] = [
  461. 'role_ids' => [],
  462. 'role_names' => [],
  463. 'depart_ids' => [],
  464. 'depart_names' => [],
  465. 'work_range' => [],
  466. ];
  467. }
  468. foreach ($roles as $r) {
  469. $resultMap[$r->employee_id]['role_ids'][] = $r->id;
  470. $resultMap[$r->employee_id]['role_names'][] = $r->title;
  471. }
  472. foreach ($departs as $d) {
  473. $resultMap[$d->employee_id]['depart_ids'][] = $d->id;
  474. $resultMap[$d->employee_id]['depart_names'][] = $d->title;
  475. }
  476. foreach ($work_range as $d) {
  477. $resultMap[$d->employee_id]['work_range'][] = $d;
  478. }
  479. return [true, $resultMap];
  480. }
  481. public function fillDataForExport($data, $column, $user, &$return)
  482. {
  483. if (empty($data)) return;
  484. $dataArray = is_array($data) ? $data : $data->toArray();
  485. $mainIds = array_column($dataArray, 'id');
  486. // 1. 获取详情映射 [员工ID => [ [部门编码, 部门名称], [部门编码, 部门名称] ]]
  487. $detailsMap = $this->getEmployeeDetailsMap($mainIds, $user);
  488. // 枚举映射
  489. $sexMap = Employee::SEX_TYPE;
  490. $eduMap = Employee::Education;
  491. $stateMap = Employee::State_Type;
  492. foreach ($dataArray as $main) {
  493. $empId = $main['id'];
  494. $details = $detailsMap[$empId] ?? [];
  495. // 2. 格式化主表信息(这些是这一人所有行共有的内容)
  496. $mainInfo = $main;
  497. $mainInfo['sex_title'] = $sexMap[$main['sex']] ?? '';
  498. $mainInfo['education_title'] = $eduMap[$main['education']] ?? '';
  499. $mainInfo['state_title'] = $stateMap[$main['state']] ?? '';
  500. if (empty($details)) {
  501. // 如果没部门,保底出一行
  502. $tempRow = [];
  503. foreach ($column as $col) {
  504. $tempRow[] = $mainInfo[$col] ?? '';
  505. }
  506. $return[] = $tempRow;
  507. } else {
  508. // 3. 核心拆分点:遍历部门明细,每一个部门都产生一个新的 $tempRow
  509. foreach ($details as $sub) {
  510. // 将员工基本信息与“当前这一个”部门信息合并
  511. $fullRowData = array_merge($mainInfo, $sub);
  512. $tempRow = [];
  513. // 严格按配置顺序取值
  514. foreach ($column as $col) {
  515. $tempRow[] = $fullRowData[$col] ?? '';
  516. }
  517. // 【重点】这里是追加,不是覆盖!
  518. // 如果张三有2个部门,这里会先后 push 两次,Excel 就会多出两行
  519. $return[] = $tempRow;
  520. }
  521. }
  522. }
  523. }
  524. public function getEmployeeDetailsMap($empIds, $user)
  525. {
  526. // 关联查询权限表和部门档案
  527. $list = DB::table('employee_depart_permission as p')
  528. ->join('depart as d', 'p.depart_id', '=', 'd.id')
  529. ->whereIn('p.employee_id', $empIds)
  530. ->where('p.top_depart_id', $user['top_depart_id'])
  531. ->where('d.del_time', 0)
  532. ->select('p.employee_id', 'd.code as depart_code', 'd.title as depart_title')
  533. ->get();
  534. $res = [];
  535. foreach ($list as $item) {
  536. // 【重点】注意这里的 [],它保证了同一个 employee_id 下可以挂载多个部门数组
  537. $res[$item->employee_id][] = [
  538. 'depart_code' => $item->depart_code,
  539. 'depart_title' => $item->depart_title,
  540. ];
  541. }
  542. return $res;
  543. }
  544. public function employeeRule(&$data, $user,$is_add = true){
  545. if(empty($data['number'])) return [false,'工号不存在'];
  546. if(empty($data['title'])) return [false,'姓名不存在'];
  547. if(! empty($data['sex']) && ! isset(Employee::SEX_TYPE[$data['sex']])) return [false, '性别不存在'];
  548. if(empty($data['mobile'])) return [false,'联系电话不能为空'];
  549. // if(! $this->isValidPhone($data['mobile'])) return [false, '手机号码格式错误'];
  550. if(empty($data['major'])) return [false, '专业领域不能为空'];
  551. if(! empty($data['education']) && ! isset(Employee::Education[$data['education']])) return [false, '学历不存在'];
  552. if(empty($data['id_card'])) return [false, '身份证号不能为空'];
  553. if(empty($data['depart'])) return [false,'部门不能为空'];
  554. if(empty($data['state'])) return [false,'状态不能为空'];
  555. if(! isset(Employee::State_Type[$data['state']])) return [false,'状态不存在'];
  556. if(! empty($data['is_admin'])){
  557. if(! isset(Employee::IS_ADMIN_TITLE_SIMPLE[$data['is_admin']])) return [false, 'is_admin类型不存在'];
  558. if(empty($data['password'])) return [false, '密码不能为空'];
  559. if(mb_strlen($data['password']) < 6) return [false, '密码长度不得小于6位长度'];
  560. if(empty($data['role'])) return [false, '角色不能为空'];
  561. }
  562. if(empty($data['man_type'])) return [false,'是否为技术研究人员不能为空'];
  563. if(! isset(Employee::Man_Type[$data['man_type']])) return [false,'是否为技术研究人员不存在'];
  564. if(! isset($data['entrust_type'])) return [false,'委托方式不能为空'];
  565. if(! isset(Employee::WT_Type[$data['entrust_type']])) return [false,'委托方式不存在'];
  566. $data['top_depart_id'] = $user['top_depart_id'];
  567. if(! empty($data['work_range'])){
  568. foreach ($data['work_range'] as $key => $value){
  569. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  570. if(!$res['valid']) return [false, "开始点:" . $res['error']];
  571. if($value['start_time_hour'] > 23) return [false, false, "开始点不合法"];
  572. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  573. if(!$res['valid']) return [false, "开始分:" . $res['error']];
  574. if($value['start_time_min'] > 60) return [false, false, "开始点不合法"];
  575. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  576. if(!$res['valid']) return [false, "结束点:" . $res['error']];
  577. if($value['end_time_hour'] > 24) return [false, false, "结束点不合法"];
  578. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  579. if(!$res['valid']) return [false, "结束分:" . $res['error']];
  580. if($value['end_time_min'] > 60) return [false, false, "结束分不合法"];
  581. $data['work_range'][$key]['total_work_min'] = ($value['end_time_hour'] * 60 + $value['end_time_min']) - ($value['start_time_hour'] * 60 + $value['start_time_min']);
  582. $data['work_range'][$key]['top_depart_id'] = $data['top_depart_id'];
  583. }
  584. }
  585. if(! $is_add){
  586. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  587. $bool = Employee::where('del_time',0)
  588. ->where('id','<>',$data['id'])
  589. ->where('top_depart_id', $data['top_depart_id'])
  590. ->where('number', $data['number'])
  591. ->exists();
  592. }else{
  593. $code = Depart::where('id', $user['top_depart_id'])->value('code');
  594. $data['account'] = $code . "_" . $data['number'];
  595. $bool = Employee::where('del_time',0)
  596. ->where('top_depart_id', $data['top_depart_id'])
  597. ->where('number', $data['number'])
  598. ->exists();
  599. }
  600. if($bool) return [false,'人员工号已存在'];
  601. return [true,''];
  602. }
  603. public function roleEdit($data,$user){
  604. list($status,$msg) = $this->roleRule($data,$user, false);
  605. if(!$status) return [$status,$msg];
  606. $model = new Role();
  607. $model = $model->where('id',$data['id'])->first();
  608. $model->title = $data['title'];
  609. $model->save();
  610. return [true,''];
  611. }
  612. public function roleAdd($data,$user){
  613. list($status,$msg) = $this->roleRule($data,$user);
  614. if(!$status) return [$status,$msg];
  615. $model = new Role();
  616. $model->title = $data['title'] ;
  617. $model->top_depart_id = $data['top_depart_id'];
  618. $model->save();
  619. return [true,''];
  620. }
  621. public function roleDel($data){
  622. if($this->isEmpty($data,'id')) return [false,'ID必须!'];
  623. $bool = EmployeeRole::where('del_time',0)
  624. ->whereIn('role_id',$data['id'])
  625. ->exists();
  626. if($bool) return [false,'角色已绑定人员'];
  627. try {
  628. DB::beginTransaction();
  629. $time = time();
  630. Role::where('id',$data['id'])->update([
  631. 'del_time' => $time
  632. ]);
  633. RoleMenu::where('del_time',0)->where('role_id',$data['id'])->update([
  634. 'del_time' => $time
  635. ]);
  636. RoleMenuButton::where('del_time',0)->where('role_id',$data['id'])->update([
  637. 'del_time' => $time
  638. ]);
  639. DB::commit();
  640. }catch (\Exception $exception){
  641. DB::rollBack();
  642. return [false,$exception->getMessage()];
  643. }
  644. return [true, ''];
  645. }
  646. public function roleList($data,$user){
  647. $model = Role::TopClear($user,$data);
  648. $model = $model->where('del_time',0)
  649. ->select('title','crt_time','id','upd_time')
  650. ->orderBy('id','desc');
  651. if(! empty($data['title'])) $model->where('title', 'LIKE', '%' . $data['title'] . '%');
  652. $list = $this->limit($model,'',$data);
  653. return [true, $list];
  654. }
  655. public function roleRule(&$data,$user, $is_check = true){
  656. if($this->isEmpty($data,'title')) return [false,'名称不能为空'];
  657. $data['top_depart_id'] = $user['top_depart_id'];
  658. if($is_check){
  659. $bool = Role::where('title',$data['title'])
  660. ->where('top_depart_id', $data['top_depart_id'])
  661. ->where('del_time',0)
  662. ->exists();
  663. if($bool) return [false,'角色名称已存在'];
  664. }else{
  665. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  666. $top_depart_id = Role::where('id',$data['id'])->value('top_depart_id');
  667. $bool = Role::where('title',$data['title'])
  668. ->where('top_depart_id',$top_depart_id)
  669. ->where('id','<>',$data['id'])
  670. ->where('del_time',0)
  671. ->exists();
  672. if($bool) return [false,'角色名称已存在'];
  673. }
  674. return [true, ''];
  675. }
  676. public function roleMenu($data){
  677. if(empty($data['role_id'])) return [false,'角色不能为空!'];
  678. if(empty($data['menu'])) return [false,'菜单数据不能为空!'];
  679. DB::beginTransaction();
  680. try {
  681. RoleMenu::where('del_time',0)->where('role_id',$data['role_id'])->update(['del_time' => time()]);
  682. RoleMenuButton::where('del_time',0)->where('role_id',$data['role_id'])->update(['del_time' => time()]);
  683. $insert = $insert2 = [];
  684. foreach ($data['menu'] as $t){
  685. $insert[] = [
  686. 'role_id' => $data['role_id'],
  687. 'menu_id' => $t['menu_id'],
  688. 'type' => $t['type'],
  689. 'crt_time' => time()
  690. ];
  691. if(! empty($t['button'])){
  692. foreach ($t['button'] as $b){
  693. $insert2[] = [
  694. 'role_id' => $data['role_id'],
  695. 'menu_id' => $t['menu_id'],
  696. 'button_id' => $b,
  697. 'crt_time' => time()
  698. ];
  699. }
  700. RoleMenuButton::insert($insert2);
  701. }
  702. }
  703. RoleMenu::insert($insert);
  704. DB::commit();
  705. }catch (\Throwable $exception){
  706. DB::rollBack();
  707. return [false,$exception->getMessage()];
  708. }
  709. return [true, ''];
  710. }
  711. public function roleDetail($data){
  712. if(empty($data['role_id'])) return [false,'请选择角色'];
  713. $role = Role::where('id',$data['role_id'])
  714. ->where('del_time',0)
  715. ->select('id','title')
  716. ->first();
  717. if(empty($role)) return [false,'角色不存在或已被删除'];
  718. $role = $role->toArray();
  719. $menu = RoleMenu::where('role_id',$data['role_id'])
  720. ->where('del_time',0)
  721. ->select('menu_id','type')
  722. ->get()->toArray();
  723. $button = $this->fillRoleButton([$data['role_id']]);
  724. foreach ($menu as $key => $value){
  725. $menu[$key]['button'] = $button[$value['menu_id']] ?? [];
  726. }
  727. $role['menu'] = $menu;
  728. return [true, $role];
  729. }
  730. public function departEdit($data, $user){
  731. list($status,$msg) = $this->departRule($data,$user,false);
  732. if(!$status) return [$status,$msg];
  733. $update = $msg['data'][0];
  734. $model = new Depart();
  735. $model->where('id',$data['id'])->update($update);
  736. return [true, ''];
  737. }
  738. public function departAdd($data,$user){
  739. list($status,$msg) = $this->departRule($data,$user);
  740. if(!$status) return [$status,$msg];
  741. try {
  742. DB::beginTransaction();
  743. foreach ($msg['data'] as $value){
  744. $model = new Depart();
  745. $model->parent_id = $value['parent_id'];
  746. $model->title = $value['title'];
  747. $model->code = $value['code'];
  748. $model->top_depart_id = $value['top_depart_id'];
  749. $model->save();
  750. }
  751. DB::commit();
  752. }catch (\Exception $exception){
  753. DB::rollBack();
  754. return [false,$exception->getMessage()];
  755. }
  756. return [true,''];
  757. }
  758. public function departDel($data){
  759. list($status,$msg) = $this->checkDepartDel($data);
  760. if(! $status) return [false, $msg];
  761. Depart::whereIn('id',$data['id'])->update([
  762. 'del_time'=>time()
  763. ]);
  764. return [true,''];
  765. }
  766. public function checkDepartDel($data){
  767. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  768. $bool = Depart::whereIn('parent_id',$data['id'])->where('del_time',0)->exists();
  769. if($bool) return [false,'部门下有子部门'];
  770. if($this->checkDepartHasPerson($data['id'])) return [false,'部门下有人员档案'];
  771. return [true, ''];
  772. }
  773. public function departCommon($data, $user, $field = []){
  774. if(empty($field)) $field = Depart::$field;
  775. $model = Depart::TopClear($user,$data);
  776. $model = $model->where('del_time',0)
  777. ->select($field)
  778. ->orderby('id', 'asc');
  779. if(isset($data['parent_id'])) $model->where('parent_id', $data['parent_id']);
  780. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  781. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  782. return $model;
  783. }
  784. public function departList($data, $user){
  785. $model = $this->departCommon($data, $user);
  786. $list = $model->get()->toArray();
  787. $list = $this->fillDepartList($list, $user, true);
  788. $list_tree = $list;
  789. if(! empty($list_tree)) {
  790. $minParentId = min(array_column($list_tree, 'parent_id'));
  791. $list_tree = $this->makeTree($minParentId,$list_tree);
  792. $list_tree = $this->set_sort_circle($list_tree);
  793. }
  794. return [true,['data' => $list,'tree' => $list_tree]];
  795. }
  796. public function fillDepartList($list,$user, $is_export = false){
  797. if(isset($list['data'])){
  798. $data = $list['data'];
  799. }else{
  800. $data = $list;
  801. }
  802. if($is_export){
  803. $map = Depart::where('del_time',0)
  804. ->whereIn('id', array_column($data, 'parent_id'))
  805. ->select('code','id', 'title')
  806. ->get()->toArray();
  807. $map = array_column($map,null,'id');
  808. foreach ($data as $key => $value){
  809. $tmp = $map[$value['parent_id']] ?? "";
  810. if($tmp['code'] == $user['top_depart_code']) {
  811. $code = $title = "";
  812. }else{
  813. $code = $tmp['code'];
  814. $title = $tmp['title'];
  815. }
  816. $data[$key]['parent_code'] = $code;
  817. $data[$key]['parent_title'] = $title;
  818. }
  819. }
  820. return $data;
  821. }
  822. public function departRule($data,$user, $is_check = true){
  823. if(empty($data['data'])) return [false,'数据不能为空!'];
  824. $code = array_column($data['data'],'code');
  825. $title = array_column($data['data'],'title');
  826. $code = array_map(function($val) {
  827. return $val !== null ? $val : 0;
  828. }, $code);
  829. $title = array_map(function($val) {
  830. return $val !== null ? $val : 0;
  831. }, $title);
  832. $code_count = array_count_values($code);
  833. $title_count = array_count_values($title);
  834. foreach ($code as $value){
  835. if(empty($value)) return [false,'编码不能为空!'];
  836. if($code_count[$value] > 1) return [false,'编码不能重复'];
  837. }
  838. foreach ($title as $value){
  839. if(empty($value)) return [false,'名称不能为空!'];
  840. if($title_count[$value] > 1) return [false,'名称不能重复'];
  841. }
  842. foreach ($data['data'] as $key => $value){
  843. $top_depart_id = $user['top_depart_id'];
  844. $parent_id = $value['parent_id'];
  845. if(empty($value['parent_id'])) {
  846. $parent_id = $top_depart_id;
  847. $data['data'][$key]['parent_id'] = $parent_id;
  848. }
  849. $data['data'][$key]['top_depart_id'] = $top_depart_id;
  850. $data['data'][$key]['upd_time'] = time();
  851. if($is_check){
  852. $data['data'][$key]['crt_time'] = time();
  853. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  854. ->where('top_depart_id', $top_depart_id)
  855. ->where('del_time',0)
  856. ->exists();
  857. }else{
  858. if($this->isEmpty($data,'id')) return [false,'id不能为空!'];
  859. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  860. ->where('top_depart_id', $top_depart_id)
  861. ->where('id','<>',$data['id'])
  862. ->where('del_time',0)
  863. ->exists();
  864. }
  865. if($bool) return [false,'部门编码已存在'];
  866. }
  867. return [true, $data];
  868. }
  869. public function checkDepartHasPerson($depart_id = []){
  870. if(empty($depart_id)) return false;
  871. $bool = EmployeeDepartPermission::from('employee_depart_permission as a')
  872. ->leftJoin('employee as b','b.id','a.employee_id')
  873. ->where('b.del_time',0)
  874. ->whereIn('a.depart_id',$depart_id)
  875. ->exists();
  876. return $bool;
  877. }
  878. public function fillRoleButton($role_id){
  879. $button = RoleMenuButton::whereIn('role_id',$role_id)
  880. ->where('del_time',0)
  881. ->select('menu_id','button_id')
  882. ->get()->toArray();
  883. $button_map = [];
  884. foreach ($button as $value){
  885. if(! isset($button_map[$value['menu_id']])){
  886. $button_map[$value['menu_id']][] = $value['button_id'];
  887. }else{
  888. if(! in_array($value['button_id'], $button_map[$value['menu_id']])) $button_map[$value['menu_id']][] = $value['button_id'];
  889. }
  890. }
  891. return $button_map;
  892. }
  893. public function getEmployeeMap($employee_ids){
  894. $employee_ids = array_filter((array)$employee_ids);
  895. if (empty($employee_ids)) return [];
  896. return Employee::whereIn('id', $employee_ids)
  897. ->pluck('title', 'id')
  898. ->toArray();
  899. }
  900. public static function fillMenu2($menu_id, &$user){
  901. // 直接查询匹配的菜单
  902. $menuItem = SysMenu::where('del_time',0)
  903. ->where('id', $menu_id)
  904. ->first();
  905. $func = $menuItem ? $menuItem->export_file_func : "";
  906. $funcName = $menuItem ? $menuItem->title : "";
  907. $header_default = config("excel." . $func) ?? [];
  908. // $header_f = "extra_" . $menu_id;
  909. // $service = new TableHeadService();
  910. // if(method_exists($service,$header_f)) $service->$header_f($header_default);
  911. $user['e_header_default'] = $header_default;
  912. return [$func, $funcName];
  913. }
  914. }