EmployeeService.php 41 KB

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