EmployeeService.php 53 KB

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