EmployeeService.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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['is_wx_admin_title'] = Employee::IS_WX_ADMIN_TITLE_SIMPLE[$item['is_wx_admin']] ?? "";
  474. $item['state_title'] = Employee::State_Type[$item['state']] ?? "";
  475. $item['employee_type_title'] = Employee::E_State_Type[$item['employee_type']] ?? "";
  476. $item['sex_title'] = Employee::SEX_TYPE[$item['sex']] ?? "";
  477. $item['man_type_title'] = Employee::Man_Type[$item['man_type']] ?? "";
  478. $item['entrust_type_title'] = Employee::WT_Type[$item['entrust_type']] ?? "";
  479. $item['education_title'] = Employee::Education[$item['education']] ?? "";
  480. $item['crt_time'] = !empty($item['crt_time']) ? date("Y-m-d", $item['crt_time']) : "";
  481. if (isset($ergs['search_for_month_work'])) {
  482. $item['month_pw'] = []; // 默认空数组
  483. if ($status) {
  484. $item['month_pw'] = $map[$item['id']] ?? [];
  485. }
  486. }
  487. }
  488. return $data;
  489. }
  490. public function getEmployeesMonthStats($employee_ids, $month, $user)
  491. {
  492. $topDepartId = $user['top_depart_id'];
  493. // 1. 月份初始化
  494. if(is_numeric($month)){
  495. $monthStart = $month;
  496. }else{
  497. $monthStart = $this->changeDateToDate($month);
  498. $monthStr = date("Y-m", $monthStart);
  499. }
  500. $endTime = strtotime("+1 month", $monthStart) - 1;
  501. // 2. 获取当月标准工作日天数 (基数)
  502. $standardWorkDays = DB::table('calendar_details')
  503. ->where('top_depart_id', $topDepartId)
  504. ->where('del_time', 0)
  505. ->where('time', '>=', $monthStart)
  506. ->where('time', '<=', $endTime)
  507. ->where('is_work', CalendarDetails::TYPE_ONE)
  508. ->count();
  509. if ($standardWorkDays <= 0) return [false, '工作日信息未设置'];
  510. // 3. 批量获取个性化工时设置
  511. $empWorkRanges = DB::table('employee_work_range')
  512. ->whereIn('employee_id', $employee_ids)
  513. ->where('top_depart_id', $topDepartId)
  514. ->select('employee_id', DB::raw('SUM(total_work_min) as total_min'))
  515. ->groupBy('employee_id')
  516. ->pluck('total_min', 'employee_id')
  517. ->toArray();
  518. // 4. 获取公司通用工时设置
  519. $commonWorkMin = DB::table('work_range_details')
  520. ->where('top_depart_id', $topDepartId)
  521. ->where('del_time', 0)
  522. ->sum('total_work_min');
  523. if(empty($commonWorkMin)) return [false, '公司工作时段未设置'];
  524. // 5. 批量获取请假与加班汇总
  525. $actualStats = DB::table('p_leave_over_order_details as d')
  526. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  527. ->whereIn('d.employee_id', $employee_ids)
  528. ->where('m.order_time', '>=', $monthStart)
  529. ->where('m.order_time', '<=', $endTime)
  530. ->where('m.del_time', 0)
  531. ->where('d.del_time', 0)
  532. ->select(
  533. 'd.employee_id',
  534. DB::raw("SUM(CASE WHEN m.type = 1 THEN d.total_min ELSE 0 END) as leave_min"),
  535. DB::raw("SUM(CASE WHEN m.type = 2 THEN d.total_min ELSE 0 END) as overtime_min")
  536. )
  537. ->groupBy('d.employee_id')
  538. ->get()
  539. ->keyBy('employee_id');
  540. // 6. 核心逻辑汇总
  541. $result = [];
  542. foreach ($employee_ids as $empId) {
  543. // A. 确定该人员每日标准时长 (基数)
  544. $dailyStandardMin = isset($empWorkRanges[$empId]) ? (float)$empWorkRanges[$empId] : (float)$commonWorkMin;
  545. // 如果每日标准时长没设置,跳过该人防止除以0错误
  546. if ($dailyStandardMin <= 0) continue;
  547. // B. 获取加班和请假数据
  548. $empActual = $actualStats->get($empId);
  549. $leaveMin = $empActual ? (float)$empActual->leave_min : 0;
  550. $overtimeMin = $empActual ? (float)$empActual->overtime_min : 0;
  551. // 净增减工时(分)
  552. $netDiffMin = $overtimeMin - $leaveMin;
  553. // C. 计算出勤总工时 (标准总分钟 + 净增减)
  554. $standardMonthMin = $standardWorkDays * $dailyStandardMin;
  555. $finalWorkMin = $standardMonthMin + $netDiffMin;
  556. // D. 计算出勤总天数 (标准天数 + 净增减折算天数)
  557. // 计算公式:出勤天数 = (标准总分钟 + 加班分钟 - 请假分钟) / 每日标准分钟
  558. $finalAttendanceDays = round($finalWorkMin / $dailyStandardMin, 2);
  559. $result[$empId] = [
  560. // 'standard_days' => $standardWorkDays, // 标准工作天数
  561. 'attendance_days' => $finalAttendanceDays, // 出勤总天数 * (结算后)
  562. // 'standard_month_min' => $standardMonthMin, // 标准总工时 (分钟)
  563. // 'final_work_min' => $finalWorkMin, // 出勤总工时 * (结算后分钟)
  564. 'final_work_hour' => round($finalWorkMin / 60, 2), // 出勤总工时 * (结算后小时)
  565. // 'leave_min' => $leaveMin,
  566. // 'overtime_min' => $overtimeMin,
  567. // 'daily_standard_min' => $dailyStandardMin
  568. ];
  569. }
  570. return [true, $result];
  571. }
  572. public function getEmployee(array $employee_ids, $user)
  573. {
  574. if (empty($employee_ids)) return [false, []];
  575. // 1. 一次性获取所有角色
  576. $roles = DB::table('employee_role as a')
  577. ->join('role as b', 'a.role_id', '=', 'b.id')
  578. ->where('a.del_time', 0)
  579. ->where('b.del_time', 0)
  580. ->where('b.tree_type', $user['select_tree_type'])
  581. ->whereIn("a.employee_id", $employee_ids)
  582. ->select('a.employee_id', 'b.title', 'b.id')
  583. ->get();
  584. // 2. 一次性获取所有部门
  585. $departs = DB::table('employee_depart_permission as a')
  586. ->join('depart as b', 'a.depart_id', '=', 'b.id')
  587. ->whereIn("a.employee_id", $employee_ids)
  588. ->select('a.employee_id', 'b.title', 'b.id')
  589. ->orderBy('b.id')
  590. ->get();
  591. $work_range = DB::table('employee_work_range as a')
  592. ->whereIn("employee_id", $employee_ids)
  593. ->select('employee_id','start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min')
  594. ->get();
  595. // 3. 结果按员工ID分组归纳
  596. $resultMap = [];
  597. foreach ($employee_ids as $id) {
  598. $resultMap[$id] = [
  599. 'role_ids' => [],
  600. 'role_names' => [],
  601. 'depart_ids' => [],
  602. 'depart_names' => [],
  603. 'work_range' => [],
  604. ];
  605. }
  606. foreach ($roles as $r) {
  607. $resultMap[$r->employee_id]['role_ids'][] = $r->id;
  608. $resultMap[$r->employee_id]['role_names'][] = $r->title;
  609. }
  610. foreach ($departs as $d) {
  611. $resultMap[$d->employee_id]['depart_ids'][] = $d->id;
  612. $resultMap[$d->employee_id]['depart_names'][] = $d->title;
  613. }
  614. foreach ($work_range as $d) {
  615. $resultMap[$d->employee_id]['work_range'][] = $d;
  616. }
  617. return [true, $resultMap];
  618. }
  619. public function fillDataForExport($data, $column, $user, &$return)
  620. {
  621. if (empty($data)) return;
  622. $dataArray = is_array($data) ? $data : $data->toArray();
  623. $mainIds = array_column($dataArray, 'id');
  624. // 1. 获取详情映射 [员工ID => [ [部门编码, 部门名称], [部门编码, 部门名称] ]]
  625. $detailsMap = $this->getEmployeeDetailsMap($mainIds, $user);
  626. // 枚举映射
  627. $sexMap = Employee::SEX_TYPE;
  628. $eduMap = Employee::Education;
  629. $stateMap = Employee::State_Type;
  630. $eMap = Employee::E_State_Type;
  631. foreach ($dataArray as $main) {
  632. $empId = $main['id'];
  633. $details = $detailsMap[$empId] ?? [];
  634. // 2. 格式化主表信息(这些是这一人所有行共有的内容)
  635. $mainInfo = $main;
  636. $mainInfo['sex_title'] = $sexMap[$main['sex']] ?? '';
  637. $mainInfo['education_title'] = $eduMap[$main['education']] ?? '';
  638. $mainInfo['state_title'] = $stateMap[$main['state']] ?? '';
  639. $mainInfo['employee_type_title'] = $eMap[$main['employee_type']] ?? '';
  640. if (empty($details)) {
  641. // 如果没部门,保底出一行
  642. $tempRow = [];
  643. foreach ($column as $col) {
  644. $tempRow[] = $mainInfo[$col] ?? '';
  645. }
  646. $return[] = $tempRow;
  647. } else {
  648. // 3. 核心拆分点:遍历部门明细,每一个部门都产生一个新的 $tempRow
  649. foreach ($details as $sub) {
  650. // 将员工基本信息与“当前这一个”部门信息合并
  651. $fullRowData = array_merge($mainInfo, $sub);
  652. $tempRow = [];
  653. // 严格按配置顺序取值
  654. foreach ($column as $col) {
  655. $tempRow[] = $fullRowData[$col] ?? '';
  656. }
  657. // 【重点】这里是追加,不是覆盖!
  658. // 如果张三有2个部门,这里会先后 push 两次,Excel 就会多出两行
  659. $return[] = $tempRow;
  660. }
  661. }
  662. }
  663. }
  664. public function getEmployeeDetailsMap($empIds, $user)
  665. {
  666. // 关联查询权限表和部门档案
  667. $list = DB::table('employee_depart_permission as p')
  668. ->join('depart as d', 'p.depart_id', '=', 'd.id')
  669. ->whereIn('p.employee_id', $empIds)
  670. ->where('p.top_depart_id', $user['top_depart_id'])
  671. ->where('d.del_time', 0)
  672. ->select('p.employee_id', 'd.code as depart_code', 'd.title as depart_title')
  673. ->get();
  674. $res = [];
  675. foreach ($list as $item) {
  676. // 【重点】注意这里的 [],它保证了同一个 employee_id 下可以挂载多个部门数组
  677. $res[$item->employee_id][] = [
  678. 'depart_code' => $item->depart_code,
  679. 'depart_title' => $item->depart_title,
  680. ];
  681. }
  682. return $res;
  683. }
  684. public function employeeRule1(&$data, $user,$is_add = true){
  685. if(empty($data['number'])) return [false,'工号不存在'];
  686. if(empty($data['title'])) return [false,'姓名不存在'];
  687. if(! empty($data['sex']) && ! isset(Employee::SEX_TYPE[$data['sex']])) return [false, '性别不存在'];
  688. if(empty($data['mobile'])) return [false,'联系电话不能为空'];
  689. // if(! $this->isValidPhone($data['mobile'])) return [false, '手机号码格式错误'];
  690. // if(empty($data['major'])) return [false, '专业领域不能为空'];
  691. if(! empty($data['education']) && ! isset(Employee::Education[$data['education']])) return [false, '学历不存在'];
  692. if(empty($data['id_card'])) return [false, '身份证号不能为空'];
  693. if(empty($data['depart'])) return [false,'部门不能为空'];
  694. if(empty($data['state'])) return [false,'状态不能为空'];
  695. if(! isset(Employee::State_Type[$data['state']])) return [false,'状态不存在'];
  696. if(empty($data['employee_type'])) return [false,'聘用类型不能为空'];
  697. if(! isset(Employee::E_State_Type[$data['employee_type']])) return [false,'聘用类型不存在'];
  698. if(! empty($data['is_admin'])){
  699. if(! isset(Employee::IS_ADMIN_TITLE_SIMPLE[$data['is_admin']])) return [false, 'is_admin类型不存在'];
  700. if(empty($data['password'])) return [false, '密码不能为空'];
  701. if(mb_strlen($data['password']) < 6) return [false, '密码长度不得小于6位长度'];
  702. if(empty($data['role'])) return [false, '角色不能为空'];
  703. }
  704. if(! empty($data['is_wx_admin']) && ! isset(Employee::IS_WX_ADMIN_TITLE_SIMPLE[$data['is_wx_admin']])) return [false, 'is_wx_admin类型不存在'];
  705. if(empty($data['man_type'])) return [false,'是否技术人员不能为空'];
  706. if(! isset(Employee::Man_Type[$data['man_type']])) return [false,'是否技术人员不存在'];
  707. if(! isset($data['entrust_type'])) return [false,'委托方式不能为空'];
  708. if(! isset(Employee::WT_Type[$data['entrust_type']])) return [false,'委托方式不存在'];
  709. $data['top_depart_id'] = $user['top_depart_id'];
  710. if(! empty($data['work_range'])){
  711. foreach ($data['work_range'] as $key => $value){
  712. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  713. if(!$res['valid']) return [false, "开始点:" . $res['error']];
  714. if($value['start_time_hour'] > 23) return [false, false, "开始点不合法"];
  715. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  716. if(!$res['valid']) return [false, "开始分:" . $res['error']];
  717. if($value['start_time_min'] > 60) return [false, false, "开始点不合法"];
  718. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  719. if(!$res['valid']) return [false, "结束点:" . $res['error']];
  720. if($value['end_time_hour'] > 24) return [false, false, "结束点不合法"];
  721. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  722. if(!$res['valid']) return [false, "结束分:" . $res['error']];
  723. if($value['end_time_min'] > 60) return [false, false, "结束分不合法"];
  724. $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']);
  725. $data['work_range'][$key]['top_depart_id'] = $data['top_depart_id'];
  726. }
  727. }
  728. if(! $is_add){
  729. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  730. $bool = Employee::where('del_time',0)
  731. ->where('id','<>',$data['id'])
  732. ->where('top_depart_id', $data['top_depart_id'])
  733. ->where('number', $data['number'])
  734. ->exists();
  735. }else{
  736. $code = Depart::where('id', $user['top_depart_id'])->value('code');
  737. $data['account'] = $code . "_" . $data['number'];
  738. $bool = Employee::where('del_time',0)
  739. ->where('top_depart_id', $data['top_depart_id'])
  740. ->where('number', $data['number'])
  741. ->exists();
  742. }
  743. if($bool) return [false,'人员工号已存在'];
  744. return [true,''];
  745. }
  746. public function employeeRule(&$data, $user, $is_add = true){
  747. if(empty($data['number'])) return [false,'工号不存在'];
  748. if(empty($data['title'])) return [false,'姓名不存在'];
  749. if(! empty($data['sex']) && ! isset(Employee::SEX_TYPE[$data['sex']])) return [false, '性别不存在'];
  750. if(empty($data['mobile'])) return [false,'联系电话不能为空'];
  751. // if(! $this->isValidPhone($data['mobile'])) return [false, '手机号码格式错误'];
  752. // if(empty($data['major'])) return [false, '专业领域不能为空'];
  753. if(! empty($data['education']) && ! isset(Employee::Education[$data['education']])) return [false, '学历不存在'];
  754. if(empty($data['id_card'])) return [false, '身份证号不能为空'];
  755. if(empty($data['depart'])) return [false,'部门不能为空'];
  756. if(empty($data['state'])) return [false,'状态不能为空'];
  757. if(! isset(Employee::State_Type[$data['state']])) return [false,'状态不存在'];
  758. if(empty($data['employee_type'])) return [false,'聘用类型不能为空'];
  759. if(! isset(Employee::E_State_Type[$data['employee_type']])) return [false,'聘用类型不存在'];
  760. if(! empty($data['is_admin'])){
  761. if(! isset(Employee::IS_ADMIN_TITLE_SIMPLE[$data['is_admin']])) return [false, 'is_admin类型不存在'];
  762. if(empty($data['password'])) return [false, '密码不能为空'];
  763. if(mb_strlen($data['password']) < 6) return [false, '密码长度不得小于6位长度'];
  764. if(empty($data['role'])) return [false, '角色不能为空'];
  765. }
  766. if(! empty($data['is_wx_admin']) && ! isset(Employee::IS_WX_ADMIN_TITLE_SIMPLE[$data['is_wx_admin']])) return [false, 'is_wx_admin类型不存在'];
  767. if(empty($data['man_type'])) return [false,'是否技术人员不能为空'];
  768. if(! isset(Employee::Man_Type[$data['man_type']])) return [false,'是否技术人员不存在'];
  769. if(! isset($data['entrust_type'])) return [false,'委托方式不能为空'];
  770. if(! isset(Employee::WT_Type[$data['entrust_type']])) return [false,'委托方式不存在'];
  771. $data['top_depart_id'] = $user['top_depart_id'];
  772. if(! empty($data['work_range'])){
  773. foreach ($data['work_range'] as $key => $value){
  774. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  775. if(!$res['valid']) return [false, "开始点:" . $res['error']];
  776. if($value['start_time_hour'] > 23) return [false, false, "开始点不合法"];
  777. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  778. if(!$res['valid']) return [false, "开始分:" . $res['error']];
  779. if($value['start_time_min'] > 60) return [false, false, "开始点不合法"];
  780. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  781. if(!$res['valid']) return [false, "结束点:" . $res['error']];
  782. if($value['end_time_hour'] > 24) return [false, false, "结束点不合法"];
  783. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  784. if(!$res['valid']) return [false, "结束分:" . $res['error']];
  785. if($value['end_time_min'] > 60) return [false, false, "结束分不合法"];
  786. $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']);
  787. $data['work_range'][$key]['top_depart_id'] = $data['top_depart_id'];
  788. }
  789. }
  790. // 初始化查询基础条件
  791. $query = Employee::where('del_time', 0)
  792. ->where('top_depart_id', $data['top_depart_id']);
  793. if(! $is_add){
  794. if(empty($data['id'])) return [false,'ID不能为空'];
  795. // 编辑模式:排除自身 ID 记录
  796. $query->where('id', '<>', $data['id']);
  797. } else {
  798. $code = Depart::where('id', $user['top_depart_id'])->value('code');
  799. //默认账号规则
  800. $data['account'] = $code . "_" . $data['number'];
  801. }
  802. // 查出重复的人员记录信息
  803. $existUser = $query->where(function($q) use ($data) {
  804. $q->where('number', $data['number'])
  805. ->orWhere('mobile', $data['mobile']);
  806. })->first(['number', 'mobile']);
  807. if (!empty($existUser)) {
  808. if ($existUser->number == $data['number']) {
  809. return [false, '人员工号已存在'];
  810. }
  811. if ($existUser->mobile == $data['mobile']) {
  812. return [false, '手机号码已存在'];
  813. }
  814. }
  815. return [true,''];
  816. }
  817. public function roleEdit($data,$user){
  818. list($status,$msg) = $this->roleRule($data,$user, false);
  819. if(!$status) return [$status,$msg];
  820. $model = new Role();
  821. $model = $model->where('id',$data['id'])->first();
  822. $model->title = $data['title'];
  823. $model->tree_type = $user['select_tree_type'];
  824. $model->save();
  825. return [true,''];
  826. }
  827. public function roleAdd($data,$user){
  828. list($status,$msg) = $this->roleRule($data,$user);
  829. if(!$status) return [$status,$msg];
  830. $model = new Role();
  831. $model->title = $data['title'] ;
  832. $model->top_depart_id = $data['top_depart_id'];
  833. $model->tree_type = $user['select_tree_type'];
  834. $model->save();
  835. return [true,''];
  836. }
  837. public function roleDel($data){
  838. if($this->isEmpty($data,'id')) return [false,'ID必须!'];
  839. $bool = EmployeeRole::where('del_time',0)
  840. ->whereIn('role_id',$data['id'])
  841. ->exists();
  842. if($bool) return [false,'角色已绑定人员'];
  843. try {
  844. DB::beginTransaction();
  845. $time = time();
  846. Role::where('id',$data['id'])->update([
  847. 'del_time' => $time
  848. ]);
  849. RoleMenu::where('del_time',0)->where('role_id',$data['id'])->update([
  850. 'del_time' => $time
  851. ]);
  852. RoleMenuButton::where('del_time',0)->where('role_id',$data['id'])->update([
  853. 'del_time' => $time
  854. ]);
  855. DB::commit();
  856. }catch (\Exception $exception){
  857. DB::rollBack();
  858. return [false,$exception->getMessage()];
  859. }
  860. return [true, ''];
  861. }
  862. public function roleList($data,$user){
  863. $select_tree_type = $user['select_tree_type'];
  864. $model = Role::TopClear($user,$data);
  865. $model = $model->where('del_time',0)
  866. ->where('tree_type', $select_tree_type)
  867. ->select('title','crt_time','id','upd_time')
  868. ->orderBy('id','desc');
  869. if(! empty($data['title'])) $model->where('title', 'LIKE', '%' . $data['title'] . '%');
  870. $list = $this->limit($model,'',$data);
  871. return [true, $list];
  872. }
  873. public function roleRule(&$data,$user, $is_check = true){
  874. if($this->isEmpty($data,'title')) return [false,'名称不能为空'];
  875. $data['top_depart_id'] = $user['top_depart_id'];
  876. if($is_check){
  877. $bool = Role::where('title',$data['title'])
  878. ->where('top_depart_id', $data['top_depart_id'])
  879. ->where('del_time',0)
  880. ->exists();
  881. if($bool) return [false,'角色名称已存在'];
  882. }else{
  883. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  884. $top_depart_id = Role::where('id',$data['id'])->value('top_depart_id');
  885. $bool = Role::where('title',$data['title'])
  886. ->where('top_depart_id',$top_depart_id)
  887. ->where('id','<>',$data['id'])
  888. ->where('del_time',0)
  889. ->exists();
  890. if($bool) return [false,'角色名称已存在'];
  891. }
  892. return [true, ''];
  893. }
  894. public function roleMenu($data){
  895. if(empty($data['role_id'])) return [false,'角色不能为空!'];
  896. if(empty($data['menu'])) return [false,'菜单数据不能为空!'];
  897. DB::beginTransaction();
  898. try {
  899. RoleMenu::where('del_time',0)->where('role_id',$data['role_id'])->update(['del_time' => time()]);
  900. RoleMenuButton::where('del_time',0)->where('role_id',$data['role_id'])->update(['del_time' => time()]);
  901. $insert = $insert2 = [];
  902. foreach ($data['menu'] as $t){
  903. $insert[] = [
  904. 'role_id' => $data['role_id'],
  905. 'menu_id' => $t['menu_id'],
  906. 'type' => $t['type'],
  907. 'crt_time' => time()
  908. ];
  909. if(! empty($t['button'])){
  910. foreach ($t['button'] as $b){
  911. $insert2[] = [
  912. 'role_id' => $data['role_id'],
  913. 'menu_id' => $t['menu_id'],
  914. 'button_id' => $b,
  915. 'crt_time' => time()
  916. ];
  917. }
  918. RoleMenuButton::insert($insert2);
  919. }
  920. }
  921. RoleMenu::insert($insert);
  922. DB::commit();
  923. }catch (\Throwable $exception){
  924. DB::rollBack();
  925. return [false,$exception->getMessage()];
  926. }
  927. return [true, ''];
  928. }
  929. public function roleDetail($data){
  930. if(empty($data['role_id'])) return [false,'请选择角色'];
  931. $role = Role::where('id',$data['role_id'])
  932. ->where('del_time',0)
  933. ->select('id','title')
  934. ->first();
  935. if(empty($role)) return [false,'角色不存在或已被删除'];
  936. $role = $role->toArray();
  937. $menu = RoleMenu::where('role_id',$data['role_id'])
  938. ->where('del_time',0)
  939. ->select('menu_id','type')
  940. ->get()->toArray();
  941. $button = $this->fillRoleButton([$data['role_id']]);
  942. foreach ($menu as $key => $value){
  943. $menu[$key]['button'] = $button[$value['menu_id']] ?? [];
  944. }
  945. $role['menu'] = $menu;
  946. return [true, $role];
  947. }
  948. public function departEdit($data, $user){
  949. list($status,$msg) = $this->departRule($data,$user,false);
  950. if(!$status) return [$status,$msg];
  951. $update = $msg['data'][0];
  952. $model = new Depart();
  953. $model->where('id',$data['id'])->update([
  954. 'title' => $update['title'],
  955. 'code' => $update['code'],
  956. ]);
  957. return [true, ''];
  958. }
  959. public function departAdd($data,$user){
  960. list($status,$msg) = $this->departRule($data,$user);
  961. if(!$status) return [$status,$msg];
  962. try {
  963. DB::beginTransaction();
  964. foreach ($msg['data'] as $value){
  965. $model = new Depart();
  966. $model->parent_id = $value['parent_id'];
  967. $model->title = $value['title'];
  968. $model->code = $value['code'];
  969. $model->top_depart_id = $value['top_depart_id'];
  970. $model->save();
  971. }
  972. DB::commit();
  973. }catch (\Exception $exception){
  974. DB::rollBack();
  975. return [false,$exception->getMessage()];
  976. }
  977. return [true,''];
  978. }
  979. public function departDel($data){
  980. list($status,$msg) = $this->checkDepartDel($data);
  981. if(! $status) return [false, $msg];
  982. Depart::whereIn('id',$data['id'])->update([
  983. 'del_time'=>time()
  984. ]);
  985. return [true,''];
  986. }
  987. public function checkDepartDel($data){
  988. if($this->isEmpty($data,'id')) return [false,'ID不能为空'];
  989. $bool = Depart::whereIn('parent_id',$data['id'])->where('del_time',0)->exists();
  990. if($bool) return [false,'部门下有子部门'];
  991. if($this->checkDepartHasPerson($data['id'])) return [false,'部门下有人员档案'];
  992. return [true, ''];
  993. }
  994. public function departCommon($data, $user, $field = []){
  995. if(empty($field)) $field = Depart::$field;
  996. $model = Depart::TopClear($user,$data);
  997. $model = $model->where('del_time',0)
  998. ->select($field)
  999. ->orderby('id', 'asc');
  1000. if(isset($data['parent_id'])) $model->where('parent_id', $data['parent_id']);
  1001. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1002. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  1003. return $model;
  1004. }
  1005. public function departList($data, $user){
  1006. $model = $this->departCommon($data, $user);
  1007. $list = $model->get()->toArray();
  1008. $list = $this->fillDepartList($list, $user, true);
  1009. $list_tree = $list;
  1010. if(! empty($list_tree)) {
  1011. $minParentId = min(array_column($list_tree, 'parent_id'));
  1012. $list_tree = $this->makeTree($minParentId,$list_tree);
  1013. $list_tree = $this->set_sort_circle($list_tree);
  1014. }
  1015. return [true,['data' => $list,'tree' => $list_tree]];
  1016. }
  1017. public function fillDepartList($list,$user, $is_export = false){
  1018. if(isset($list['data'])){
  1019. $data = $list['data'];
  1020. }else{
  1021. $data = $list;
  1022. }
  1023. if($is_export){
  1024. $map = Depart::where('del_time',0)
  1025. ->whereIn('id', array_column($data, 'parent_id'))
  1026. ->select('code','id', 'title')
  1027. ->get()->toArray();
  1028. $map = array_column($map,null,'id');
  1029. foreach ($data as $key => $value){
  1030. $tmp = $map[$value['parent_id']] ?? "";
  1031. if($tmp['code'] == $user['top_depart_code']) {
  1032. $code = $title = "";
  1033. }else{
  1034. $code = $tmp['code'];
  1035. $title = $tmp['title'];
  1036. }
  1037. $data[$key]['parent_code'] = $code;
  1038. $data[$key]['parent_title'] = $title;
  1039. }
  1040. }
  1041. return $data;
  1042. }
  1043. public function departRule($data,$user, $is_check = true){
  1044. if(empty($data['data'])) return [false,'数据不能为空!'];
  1045. $code = array_column($data['data'],'code');
  1046. $title = array_column($data['data'],'title');
  1047. $code = array_map(function($val) {
  1048. return $val !== null ? $val : 0;
  1049. }, $code);
  1050. $title = array_map(function($val) {
  1051. return $val !== null ? $val : 0;
  1052. }, $title);
  1053. $code_count = array_count_values($code);
  1054. $title_count = array_count_values($title);
  1055. foreach ($code as $value){
  1056. if(empty($value)) return [false,'编码不能为空!'];
  1057. if($code_count[$value] > 1) return [false,'编码不能重复'];
  1058. }
  1059. foreach ($title as $value){
  1060. if(empty($value)) return [false,'名称不能为空!'];
  1061. if($title_count[$value] > 1) return [false,'名称不能重复'];
  1062. }
  1063. foreach ($data['data'] as $key => $value){
  1064. $top_depart_id = $user['top_depart_id'];
  1065. if(empty($value['parent_id'])) {
  1066. $parent_id = $top_depart_id;
  1067. $data['data'][$key]['parent_id'] = $parent_id;
  1068. }
  1069. $data['data'][$key]['top_depart_id'] = $top_depart_id;
  1070. $data['data'][$key]['upd_time'] = time();
  1071. if($is_check){
  1072. $data['data'][$key]['crt_time'] = time();
  1073. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  1074. ->where('top_depart_id', $top_depart_id)
  1075. ->where('del_time',0)
  1076. ->exists();
  1077. }else{
  1078. if($this->isEmpty($data,'id')) return [false,'id不能为空!'];
  1079. $bool = Depart::whereRaw("binary code = '{$value['code']}'")
  1080. ->where('top_depart_id', $top_depart_id)
  1081. ->where('id','<>',$data['id'])
  1082. ->where('del_time',0)
  1083. ->exists();
  1084. }
  1085. if($bool) return [false,'部门编码已存在'];
  1086. }
  1087. return [true, $data];
  1088. }
  1089. public function checkDepartHasPerson($depart_id = []){
  1090. if(empty($depart_id)) return false;
  1091. $bool = EmployeeDepartPermission::from('employee_depart_permission as a')
  1092. ->leftJoin('employee as b','b.id','a.employee_id')
  1093. ->where('b.del_time',0)
  1094. ->whereIn('a.depart_id',$depart_id)
  1095. ->exists();
  1096. return $bool;
  1097. }
  1098. public function fillRoleButton($role_id){
  1099. $button = RoleMenuButton::whereIn('role_id',$role_id)
  1100. ->where('del_time',0)
  1101. ->select('menu_id','button_id')
  1102. ->get()->toArray();
  1103. $button_map = [];
  1104. foreach ($button as $value){
  1105. if(! isset($button_map[$value['menu_id']])){
  1106. $button_map[$value['menu_id']][] = $value['button_id'];
  1107. }else{
  1108. if(! in_array($value['button_id'], $button_map[$value['menu_id']])) $button_map[$value['menu_id']][] = $value['button_id'];
  1109. }
  1110. }
  1111. return $button_map;
  1112. }
  1113. public function getEmployeeMap($employee_ids){
  1114. $employee_ids = array_filter((array)$employee_ids);
  1115. if (empty($employee_ids)) return [];
  1116. return Employee::whereIn('id', $employee_ids)
  1117. ->pluck('title', 'id')
  1118. ->toArray();
  1119. }
  1120. }