EmployeeService.php 43 KB

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