EmployeeService.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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([
  736. 'title' => $update['title'],
  737. 'code' => $update['code'],
  738. ]);
  739. return [true, ''];
  740. }
  741. public function departAdd($data,$user){
  742. list($status,$msg) = $this->departRule($data,$user);
  743. if(!$status) return [$status,$msg];
  744. try {
  745. DB::beginTransaction();
  746. foreach ($msg['data'] as $value){
  747. $model = new Depart();
  748. $model->parent_id = $value['parent_id'];
  749. $model->title = $value['title'];
  750. $model->code = $value['code'];
  751. $model->top_depart_id = $value['top_depart_id'];
  752. $model->save();
  753. }
  754. DB::commit();
  755. }catch (\Exception $exception){
  756. DB::rollBack();
  757. return [false,$exception->getMessage()];
  758. }
  759. return [true,''];
  760. }
  761. public function departDel($data){
  762. list($status,$msg) = $this->checkDepartDel($data);
  763. if(! $status) return [false, $msg];
  764. Depart::whereIn('id',$data['id'])->update([
  765. 'del_time'=>time()
  766. ]);
  767. return [true,''];
  768. }
  769. public function checkDepartDel($data){
  770. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  771. $bool = Depart::whereIn('parent_id',$data['id'])->where('del_time',0)->exists();
  772. if($bool) return [false,'部门下有子部门'];
  773. if($this->checkDepartHasPerson($data['id'])) return [false,'部门下有人员档案'];
  774. return [true, ''];
  775. }
  776. public function departCommon($data, $user, $field = []){
  777. if(empty($field)) $field = Depart::$field;
  778. $model = Depart::TopClear($user,$data);
  779. $model = $model->where('del_time',0)
  780. ->select($field)
  781. ->orderby('id', 'asc');
  782. if(isset($data['parent_id'])) $model->where('parent_id', $data['parent_id']);
  783. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  784. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  785. return $model;
  786. }
  787. public function departList($data, $user){
  788. $model = $this->departCommon($data, $user);
  789. $list = $model->get()->toArray();
  790. $list = $this->fillDepartList($list, $user, true);
  791. $list_tree = $list;
  792. if(! empty($list_tree)) {
  793. $minParentId = min(array_column($list_tree, 'parent_id'));
  794. $list_tree = $this->makeTree($minParentId,$list_tree);
  795. $list_tree = $this->set_sort_circle($list_tree);
  796. }
  797. return [true,['data' => $list,'tree' => $list_tree]];
  798. }
  799. public function fillDepartList($list,$user, $is_export = false){
  800. if(isset($list['data'])){
  801. $data = $list['data'];
  802. }else{
  803. $data = $list;
  804. }
  805. if($is_export){
  806. $map = Depart::where('del_time',0)
  807. ->whereIn('id', array_column($data, 'parent_id'))
  808. ->select('code','id', 'title')
  809. ->get()->toArray();
  810. $map = array_column($map,null,'id');
  811. foreach ($data as $key => $value){
  812. $tmp = $map[$value['parent_id']] ?? "";
  813. if($tmp['code'] == $user['top_depart_code']) {
  814. $code = $title = "";
  815. }else{
  816. $code = $tmp['code'];
  817. $title = $tmp['title'];
  818. }
  819. $data[$key]['parent_code'] = $code;
  820. $data[$key]['parent_title'] = $title;
  821. }
  822. }
  823. return $data;
  824. }
  825. public function departRule($data,$user, $is_check = true){
  826. if(empty($data['data'])) return [false,'数据不能为空!'];
  827. $code = array_column($data['data'],'code');
  828. $title = array_column($data['data'],'title');
  829. $code = array_map(function($val) {
  830. return $val !== null ? $val : 0;
  831. }, $code);
  832. $title = array_map(function($val) {
  833. return $val !== null ? $val : 0;
  834. }, $title);
  835. $code_count = array_count_values($code);
  836. $title_count = array_count_values($title);
  837. foreach ($code as $value){
  838. if(empty($value)) return [false,'编码不能为空!'];
  839. if($code_count[$value] > 1) return [false,'编码不能重复'];
  840. }
  841. foreach ($title as $value){
  842. if(empty($value)) return [false,'名称不能为空!'];
  843. if($title_count[$value] > 1) return [false,'名称不能重复'];
  844. }
  845. foreach ($data['data'] as $key => $value){
  846. $top_depart_id = $user['top_depart_id'];
  847. if(empty($value['parent_id'])) {
  848. $parent_id = $top_depart_id;
  849. $data['data'][$key]['parent_id'] = $parent_id;
  850. }
  851. $data['data'][$key]['top_depart_id'] = $top_depart_id;
  852. $data['data'][$key]['upd_time'] = time();
  853. if($is_check){
  854. $data['data'][$key]['crt_time'] = time();
  855. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  856. ->where('top_depart_id', $top_depart_id)
  857. ->where('del_time',0)
  858. ->exists();
  859. }else{
  860. if($this->isEmpty($data,'id')) return [false,'id不能为空!'];
  861. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  862. ->where('top_depart_id', $top_depart_id)
  863. ->where('id','<>',$data['id'])
  864. ->where('del_time',0)
  865. ->exists();
  866. }
  867. if($bool) return [false,'部门编码已存在'];
  868. }
  869. return [true, $data];
  870. }
  871. public function checkDepartHasPerson($depart_id = []){
  872. if(empty($depart_id)) return false;
  873. $bool = EmployeeDepartPermission::from('employee_depart_permission as a')
  874. ->leftJoin('employee as b','b.id','a.employee_id')
  875. ->where('b.del_time',0)
  876. ->whereIn('a.depart_id',$depart_id)
  877. ->exists();
  878. return $bool;
  879. }
  880. public function fillRoleButton($role_id){
  881. $button = RoleMenuButton::whereIn('role_id',$role_id)
  882. ->where('del_time',0)
  883. ->select('menu_id','button_id')
  884. ->get()->toArray();
  885. $button_map = [];
  886. foreach ($button as $value){
  887. if(! isset($button_map[$value['menu_id']])){
  888. $button_map[$value['menu_id']][] = $value['button_id'];
  889. }else{
  890. if(! in_array($value['button_id'], $button_map[$value['menu_id']])) $button_map[$value['menu_id']][] = $value['button_id'];
  891. }
  892. }
  893. return $button_map;
  894. }
  895. public function getEmployeeMap($employee_ids){
  896. $employee_ids = array_filter((array)$employee_ids);
  897. if (empty($employee_ids)) return [];
  898. return Employee::whereIn('id', $employee_ids)
  899. ->pluck('title', 'id')
  900. ->toArray();
  901. }
  902. public static function fillMenu2($menu_id, &$user){
  903. // 直接查询匹配的菜单
  904. $menuItem = SysMenu::where('del_time',0)
  905. ->where('id', $menu_id)
  906. ->first();
  907. $func = $menuItem ? $menuItem->export_file_func : "";
  908. $funcName = $menuItem ? $menuItem->title : "";
  909. $header_default = config("excel." . $func) ?? [];
  910. // $header_f = "extra_" . $menu_id;
  911. // $service = new TableHeadService();
  912. // if(method_exists($service,$header_f)) $service->$header_f($header_default);
  913. $user['e_header_default'] = $header_default;
  914. return [$func, $funcName];
  915. }
  916. }