EmployeeService.php 41 KB

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