EmployeeService.php 41 KB

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