EmployeeService.php 39 KB

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