EmployeeService.php 43 KB

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