EmployeeService.php 41 KB

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