EmployeeService.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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($is_export){
  740. $map = Depart::where('del_time',0)
  741. ->whereIn('id', array_column($list['data'], 'parent_id'))
  742. ->select('code','id', 'title')
  743. ->get()->toArray();
  744. $map = array_column($map,null,'id');
  745. foreach ($list['data'] as $key => $value){
  746. $tmp = $map[$value['parent_id']] ?? "";
  747. if($tmp['code'] == $user['top_depart_code']) {
  748. $code = $title = "";
  749. }else{
  750. $code = $tmp['code'];
  751. $title = $tmp['title'];
  752. }
  753. $list['data'][$key]['parent_code'] = $code;
  754. $list['data'][$key]['parent_title'] = $title;
  755. }
  756. }
  757. return $list;
  758. }
  759. public function departRule($data,$user, $is_check = true){
  760. if(empty($data['data'])) return [false,'数据不能为空!'];
  761. $code = array_column($data['data'],'code');
  762. $title = array_column($data['data'],'title');
  763. $code = array_map(function($val) {
  764. return $val !== null ? $val : 0;
  765. }, $code);
  766. $title = array_map(function($val) {
  767. return $val !== null ? $val : 0;
  768. }, $title);
  769. $code_count = array_count_values($code);
  770. $title_count = array_count_values($title);
  771. foreach ($code as $value){
  772. if(empty($value)) return [false,'编码不能为空!'];
  773. if($code_count[$value] > 1) return [false,'编码不能重复'];
  774. }
  775. foreach ($title as $value){
  776. if(empty($value)) return [false,'名称不能为空!'];
  777. if($title_count[$value] > 1) return [false,'名称不能重复'];
  778. }
  779. foreach ($data['data'] as $key => $value){
  780. $top_depart_id = $user['top_depart_id'];
  781. $parent_id = $value['parent_id'];
  782. if(empty($value['parent_id'])) {
  783. $parent_id = $top_depart_id;
  784. $data['data'][$key]['parent_id'] = $parent_id;
  785. }
  786. $data['data'][$key]['top_depart_id'] = $top_depart_id;
  787. $data['data'][$key]['upd_time'] = time();
  788. if($is_check){
  789. $data['data'][$key]['crt_time'] = time();
  790. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  791. ->where('top_depart_id', $top_depart_id)
  792. ->where('del_time',0)
  793. ->exists();
  794. }else{
  795. if($this->isEmpty($data,'id')) return [false,'id不能为空!'];
  796. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  797. ->where('top_depart_id', $top_depart_id)
  798. ->where('id','<>',$data['id'])
  799. ->where('del_time',0)
  800. ->exists();
  801. }
  802. if($bool) return [false,'部门编码已存在'];
  803. }
  804. return [true, $data];
  805. }
  806. public function checkDepartHasPerson($depart_id = []){
  807. if(empty($depart_id)) return false;
  808. $bool = EmployeeDepartPermission::from('employee_depart_permission as a')
  809. ->leftJoin('employee as b','b.id','a.employee_id')
  810. ->where('b.del_time',0)
  811. ->whereIn('a.depart_id',$depart_id)
  812. ->exists();
  813. return $bool;
  814. }
  815. public function fillRoleButton($role_id){
  816. $button = RoleMenuButton::whereIn('role_id',$role_id)
  817. ->where('del_time',0)
  818. ->select('menu_id','button_id')
  819. ->get()->toArray();
  820. $button_map = [];
  821. foreach ($button as $value){
  822. if(! isset($button_map[$value['menu_id']])){
  823. $button_map[$value['menu_id']][] = $value['button_id'];
  824. }else{
  825. if(! in_array($value['button_id'], $button_map[$value['menu_id']])) $button_map[$value['menu_id']][] = $value['button_id'];
  826. }
  827. }
  828. return $button_map;
  829. }
  830. public function getEmployeeMap($employee_ids){
  831. $employee_ids = array_filter((array)$employee_ids);
  832. if (empty($employee_ids)) return [];
  833. return Employee::whereIn('id', $employee_ids)
  834. ->pluck('title', 'id')
  835. ->toArray();
  836. }
  837. public static function fillMenu2($menu_id, &$user){
  838. // 直接查询匹配的菜单
  839. $menuItem = SysMenu::where('del_time',0)
  840. ->where('id', $menu_id)
  841. ->first();
  842. $func = $menuItem ? $menuItem->export_file_func : "";
  843. $funcName = $menuItem ? $menuItem->title : "";
  844. $header_default = config("excel." . $func) ?? [];
  845. // $header_f = "extra_" . $menu_id;
  846. // $service = new TableHeadService();
  847. // if(method_exists($service,$header_f)) $service->$header_f($header_default);
  848. $user['e_header_default'] = $header_default;
  849. return [$func, $funcName];
  850. }
  851. }