ServiceWorkLogic.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. namespace app\adminapi\logic\works;
  15. use app\common\logic\ThirdOrderLogic;
  16. use app\common\model\third\ThirdOrders;
  17. use think\Exception;
  18. use think\db\Query;
  19. use think\facade\Db;
  20. use think\facade\Log;
  21. use app\common\logic\BaseLogic;
  22. use app\api\logic\PerformanceLogic;
  23. use app\common\model\dict\DictData;
  24. use app\common\model\coupon\UserCoupon;
  25. use app\common\model\works\ServiceWork;
  26. use app\common\model\recharge\OrderGoods;
  27. use app\common\model\spare_part\SparePart;
  28. use app\common\model\works\ServiceWorkLog;
  29. use app\common\model\coupon\CouponCategory;
  30. use app\common\model\recharge\RechargeOrder;
  31. use app\common\model\works\ServiceWorkSpare;
  32. use app\workerapi\logic\ServiceWorkLogLogic;
  33. use app\common\model\orders\OrderEffectiveLog;
  34. use app\common\model\master_worker\MasterWorker;
  35. use app\common\model\training\TrainingWorkerTask;
  36. use app\common\model\performance\PerformanceRules;
  37. use app\common\model\works\ServiceWorkCustomerLog;
  38. use app\workerapi\logic\ServiceWorkReceiveLogLogic;
  39. use app\common\model\master_worker\MasterWorkerTeam;
  40. use app\common\model\works\ServiceWorkAppointmentLog;
  41. use app\workerapi\logic\ServiceWorkerAllocateWorkerLogic;
  42. use app\common\model\master_worker\MasterWorkerAccountLog;
  43. use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
  44. use app\common\model\master_commission\MasterWorkerCommissionRatio;
  45. use app\common\model\master_commission\MasterWorkerCommissionConfig;
  46. /**
  47. * ServiceWork逻辑
  48. * Class ServiceWorkLogic
  49. * @package app\adminapi\logic\works
  50. */
  51. class ServiceWorkLogic extends BaseLogic
  52. {
  53. /**
  54. * @notes 编辑
  55. * @param array $params
  56. * @return bool
  57. * @author likeadmin
  58. * @date 2024/07/10 18:17
  59. */
  60. public static function edit(array $params): bool
  61. {
  62. Db::startTrans();
  63. try {
  64. ServiceWork::where('id', $params['id'])->update([
  65. 'address' => $params['address'],
  66. 'appointment_time' => strtotime($params['appointment_time']),
  67. 'estimated_finish_time' => $params['estimated_finish_time'],
  68. 'lon' => $params['lon'],
  69. 'lat' => $params['lat'],
  70. ]);
  71. Db::commit();
  72. return true;
  73. } catch (\Exception $e) {
  74. Db::rollback();
  75. self::setError($e->getMessage());
  76. return false;
  77. }
  78. }
  79. /**
  80. *
  81. * @return false|void
  82. */
  83. public static function pickWork($params)
  84. {
  85. Db::startTrans();
  86. try {
  87. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  88. if($work->isEmpty()){
  89. throw new Exception('工单不存在');
  90. }
  91. $receive_time = time();
  92. $work->work_status = 2;//待联系
  93. $work->service_status = 1;//服务中
  94. $work->receive_time = $receive_time;
  95. $work->save();
  96. //添加变更日志
  97. $work_log = [
  98. 'work_id'=>$work->id,
  99. 'master_worker_id'=>$work->master_worker_id,
  100. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',$receive_time).'领取了工单',
  101. ];
  102. ServiceWorkLogLogic::add($work_log);
  103. //添加领单日志
  104. ServiceWorkReceiveLogLogic::add($work_log);
  105. Db::commit();
  106. }
  107. catch (\Exception $e) {
  108. Db::rollback();
  109. self::setError($e->getMessage());
  110. return false;
  111. }
  112. }
  113. /**
  114. * 预约成功,等待上门
  115. * @return false|void
  116. */
  117. public static function appointWork($params)
  118. {
  119. Db::startTrans();
  120. try {
  121. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  122. if($work->isEmpty()){
  123. throw new Exception('工单不存在');
  124. }
  125. if($work->work_status != 2){
  126. throw new Exception('请勿重复点击');
  127. }
  128. //验证更改的预约时间必须是在领单时间内的半小内修改,否则不允许修改
  129. if(strtotime($work->appointment_time) != strtotime($params['appointment_time']) && (time()-strtotime($work->receive_time))>1800){
  130. throw new Exception('距离领单时间已超过半小时,无法修改预约时间,请联系客服');
  131. }
  132. $work->work_status = 3;//待上门
  133. $work->appointment_time = strtotime($params['appointment_time']);
  134. $work->save();
  135. //添加变更日志
  136. $work_log = [
  137. 'work_id'=>$work->id,
  138. 'master_worker_id'=>$work->master_worker_id,
  139. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'联系了客户,确认了于'.$params['appointment_time'].$params['address'].'预约上门',
  140. ];
  141. ServiceWorkLogLogic::add($work_log);
  142. Db::commit();
  143. }
  144. catch (\Exception $e) {
  145. self::setError($e->getMessage());
  146. return false;
  147. }
  148. }
  149. /**
  150. * 工程师确认上门
  151. * @param $params
  152. * @return false|void
  153. */
  154. public static function confirmDoor($params)
  155. {
  156. Db::startTrans();
  157. try {
  158. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  159. if($work->isEmpty()){
  160. throw new Exception('工单不存在');
  161. }
  162. if($work->work_status != 3){
  163. throw new Exception('请勿重复点击');
  164. }
  165. $work->finally_door_time = time();//最后上门时间
  166. $work->work_status = 4;//已上门
  167. $work->save();
  168. //添加变更日志
  169. $work_log = [
  170. 'work_id'=>$work->id,
  171. 'master_worker_id'=>$work->master_worker_id,
  172. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'已上门',
  173. ];
  174. ServiceWorkLogLogic::add($work_log);
  175. Db::commit();
  176. }
  177. catch (\Exception $e) {
  178. Db::rollback();
  179. self::setError($e->getMessage());
  180. return false;
  181. }
  182. }
  183. /**
  184. * 工程师确认报价单
  185. * @param $params
  186. * @return false|void
  187. */
  188. public static function confirmPrice($params)
  189. {
  190. Db::startTrans();
  191. try {
  192. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  193. if($work->isEmpty()){
  194. throw new Exception('工单不存在');
  195. }
  196. //搜索待支付订单
  197. $paid_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>1])->findOrEmpty()->toArray();
  198. if(empty($paid_order)){
  199. throw new Exception('订单错误');
  200. }
  201. if($work->work_status != 4){
  202. throw new Exception('请勿重复操作');
  203. }
  204. // 关联配件信息.计算配件总价 id company_price original_price offering_price number
  205. $spare_total = 0;
  206. isset($params['spare_parts']) && $params['spare_parts'] && $params['spare_parts'] = json_decode($params['spare_parts'], true);
  207. if(isset($params['spare_parts']) && $params['spare_parts']){
  208. $spare_parts = $params['spare_parts'];
  209. foreach ($spare_parts as $spare){
  210. $spare_total += $spare['company_price']*$spare['number'];
  211. }
  212. $work->spare_total = $spare_total;
  213. $service_work_spare = ServiceWorkSpare::where(['service_work_id'=>$work['id']])->findOrEmpty();
  214. if($service_work_spare->isEmpty()){
  215. //新增
  216. $service_work_spare = ServiceWorkSpare::create([
  217. 'service_work_id'=>$work['id'],
  218. 'spare_parts'=>$params['spare_parts'],
  219. 'remark'=>''
  220. ]);
  221. }else{
  222. //修改
  223. $service_work_spare->spare_parts = $params['spare_parts'];
  224. $service_work_spare->save();
  225. }
  226. $work->service_work_spare_id = $service_work_spare->id;
  227. }
  228. // order_amount 原 = $params['amount'] 修改为 = 配件总价 + 服务尾款
  229. $order_amount = $params['amount'] + $spare_total;
  230. //定金存在尾款结算功能,全款直接提交
  231. if($paid_order['payment_type']==1){
  232. $un_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>0])->findOrEmpty();
  233. if($un_order->isEmpty()){
  234. //新增待支付尾款
  235. $order_data = [
  236. 'order_type'=>$paid_order['order_type'],
  237. 'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
  238. 'work_id'=>$paid_order['work_id'],
  239. 'user_id'=>$paid_order['user_id'],
  240. 'payment_type'=>2,
  241. 'order_total'=>$order_amount,
  242. //'order_amount'=>$params['amount'],
  243. 'order_amount'=>$order_amount,
  244. 'order_terminal'=>$paid_order['order_terminal']
  245. ];
  246. RechargeOrder::create($order_data);
  247. }else{
  248. //修改尾款信息
  249. $un_order->order_total = $order_amount;
  250. //$un_order->order_amount = $params['amount'];
  251. $un_order->order_amount = $order_amount;
  252. $un_order->save();
  253. }
  254. //更新服务费用
  255. $work->service_fee = $paid_order['paid_amount']+$params['amount'];
  256. }
  257. //总工单费用
  258. $work->work_total = $work->service_fee+$spare_total;
  259. $work->work_images = $params['work_images'];
  260. $work->explanation = $params['explanation']??'';
  261. //判断是否是第三个订单,如果是美团订单直接滤过用户确认环节
  262. if($work->third_type==1){
  263. $work->work_status = 5;
  264. $work->user_confirm_status = 2;
  265. }else{
  266. $work->user_confirm_status = 1;//待确认报价
  267. }
  268. $work->price_approval = 0;
  269. $work->save();
  270. //添加变更日志
  271. $work_log = [
  272. 'work_id'=>$work->id,
  273. 'master_worker_id'=>$work->master_worker_id,
  274. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'提交了报价单',
  275. ];
  276. ServiceWorkLogLogic::add($work_log);
  277. Db::commit();
  278. }
  279. catch (\Exception $e) {
  280. Db::rollback();
  281. self::setError($e->getMessage());
  282. return false;
  283. }
  284. }
  285. /**
  286. * 工程师确认服务完成
  287. * @param $params
  288. * @return false|void
  289. */
  290. public static function confirmServiceFinish($params)
  291. {
  292. Db::startTrans();
  293. try {
  294. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  295. if($work->isEmpty()){
  296. throw new Exception('工单不存在');
  297. }
  298. if($work->user_confirm_status !=2){
  299. throw new Exception('请勿重复操作');
  300. }
  301. $work->finished_images = $params['finished_images'];
  302. $work->user_confirm_status = 3;//待确认服务完成
  303. $work->save();
  304. //添加变更日志
  305. $work_log = [
  306. 'work_id'=>$work->id,
  307. 'master_worker_id'=>$work->master_worker_id,
  308. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'提交了待用户确认服务完成',
  309. ];
  310. ServiceWorkLogLogic::add($work_log);
  311. Db::commit();
  312. } catch (\Exception $e) {
  313. Db::rollback();
  314. self::setError($e->getMessage());
  315. return false;
  316. }
  317. }
  318. public static function allocateWorker($params,$userInfo){
  319. Db::startTrans();
  320. try {
  321. $work = ServiceWork::findOrEmpty($params['id']);
  322. if($work->isEmpty()){
  323. throw new Exception('工单不存在');
  324. }
  325. if($work->work_status >=6 ){
  326. throw new \Exception('工单状态只能修改待结算之前的');
  327. }
  328. if($work->master_worker_id == $params['master_worker_id']){
  329. throw new \Exception('分配的工程师相同');
  330. }
  331. $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'is_disable' =>0])->findOrEmpty();
  332. if($worker->isEmpty()){
  333. throw new \Exception('工程师不存在或被禁用');
  334. }
  335. if($worker->master_worker_id){
  336. MasterWorker::setWorktotal('dec',$worker->master_worker_id);
  337. }
  338. $work->master_worker_id = $params['master_worker_id'];
  339. $work->work_status = 1;
  340. $work->dispatch_time = time();
  341. MasterWorker::setWorktotal('inc',$params['master_worker_id']);
  342. $work->save();
  343. $work_log = [
  344. 'work_id'=>$work->id,
  345. 'master_worker_id'=>$work->master_worker_id,
  346. 'type' => 0,
  347. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  348. ];
  349. ServiceWorkerAllocateWorkerLogic::add($work_log);
  350. Db::commit();
  351. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  352. $workDetail = ServiceWorkLogic::detail($params);
  353. $res = event('Notice', [
  354. 'scene_id' => 113,
  355. 'params' => [
  356. 'user_id' => $params['master_worker_id'],
  357. 'order_id' => $params['id'],
  358. 'thing9' => $workDetail['title'],
  359. 'time7' => $workDetail['appointment_time'],
  360. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  361. 'phone_number6' => asteriskString($workDetail['mobile']),
  362. ]
  363. ]);
  364. return true;
  365. }catch(\Exception $e){
  366. Db::rollback();
  367. self::setError($e->getMessage());
  368. return false;
  369. }
  370. }
  371. /**
  372. * 工单详情
  373. * @param $params
  374. * @return array|false
  375. */
  376. public static function detail($params){
  377. $work_where = !empty($params['work_sn'])?['work_sn'=>$params['work_sn']]:['id'=>$params['id']];
  378. $result = ServiceWork::with([
  379. 'worker'=> function(Query $query) {
  380. $query->field('id,worker_number,real_name,mobile');
  381. },
  382. 'allocateWorkerLog' =>function(Query $query){
  383. $query->field('id,work_id,opera_log,create_time');
  384. },
  385. 'serviceWorkLog' =>function(Query $query){
  386. $query->field('id,work_id,opera_log,create_time');
  387. }
  388. ])->append(['id','work_status_text','service_status_text'])
  389. ->where($work_where)
  390. ->findOrEmpty()->toArray();
  391. $result['is_operate_prohibit'] = 0;
  392. if(isset($params['user_id']) && $params['user_id'] && ($params['user_id'] != $result['master_worker_id']) ){
  393. // 带徒师傅的工单
  394. $lead_master_worker_id = TrainingWorkerTask::where('master_worker_id',$params['user_id'])->where('training_status',2)
  395. ->where('operate_status',0)->value('lead_master_worker_id');
  396. // 团队负责人编辑 工单池(包括已派队员) 工单
  397. if($params['user_info']['team_role'] == 1 && $params['user_info']['tenant_id'] == $result['tenant_id'] ){
  398. $result['is_operate_prohibit'] = 0;
  399. }elseif(!empty($lead_master_worker_id) && !empty($result['master_worker_id']) && $lead_master_worker_id == $result['master_worker_id']){
  400. // 徒查看师父的工单 不能编辑可查看
  401. $result['is_operate_prohibit'] = 1;
  402. }else{
  403. throw new \Exception('您没有权限操作该工单');
  404. }
  405. }
  406. //工程师工单按钮状态
  407. $work_service_status = 0;
  408. $work_service_status_text = '待派单';
  409. //工单状态
  410. if($result['work_status'] == 1){
  411. $work_service_status = 1;
  412. $work_service_status_text = '待领单';
  413. }
  414. if($result['work_status'] == 2){
  415. $work_service_status = 2;
  416. $work_service_status_text = '预约上门';
  417. }
  418. if($result['work_status'] == 3){
  419. $work_service_status = 3;
  420. $work_service_status_text = '等待上门';
  421. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  422. $work_service_status = 4;
  423. $work_service_status_text = '确认上门';
  424. }
  425. }
  426. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  427. $work_service_status = 5;
  428. $work_service_status_text = '确认报价';
  429. }
  430. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  431. $work_service_status = 6;
  432. $work_service_status_text = '用户确认报价中';
  433. }
  434. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  435. $work_service_status = 7;
  436. $work_service_status_text = '完成服务';
  437. }
  438. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  439. $work_service_status = 8;
  440. $work_service_status_text = '用户确认完成服务中';
  441. }
  442. if($result['work_status'] ==6){
  443. $work_service_status = 9;
  444. $work_service_status_text = '待结算';
  445. }
  446. if($result['work_status'] ==7){
  447. $work_service_status = 10;
  448. $work_service_status_text = '已完结';
  449. }
  450. if($result['work_status'] ==8){
  451. $work_service_status = 11;
  452. $work_service_status_text = '已评价';
  453. }
  454. if($result['work_status'] ==9){
  455. $work_service_status = 12;
  456. $work_service_status_text = '已退费';
  457. }
  458. $result['work_service_status'] = $work_service_status;
  459. $result['work_service_status_text'] = $work_service_status_text;
  460. //搜索当前工单下的所有订单记录
  461. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  462. $query->field('id,sn,goods_id,goods_name,goods_image,goods_number,good_unit,goods_size,goods_payment_type,goods_type,goods_brand,base_service_fee,service_total,service_fee')->order(['id'=>'desc']);
  463. }])->where(['work_id'=>$result['id']])->field('id as order_id,sn,order_type,pay_status,payment_type,pay_way,pay_time,order_amount,order_total,coupon_price,create_time')->order('id asc')->select()->toArray();
  464. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  465. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  466. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  467. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  468. $coupon_price = 0;
  469. foreach ($result['pay_orders'] as $k=>&$v){
  470. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  471. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  472. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  473. $v['order_type_name'] = $order_type_data[$v['order_type']];
  474. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  475. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  476. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  477. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  478. }
  479. $coupon_price += $v['coupon_price'];
  480. //服务支付类别
  481. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  482. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  483. }
  484. }
  485. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  486. //汇总优惠卷额度
  487. $result['coupon_price'] = $coupon_price;
  488. //工单总支付金额
  489. $result['worker_account'] = $result['work_amount'];
  490. // 配件信息
  491. $result['spare_parts'] = [];
  492. if($result['service_work_spare_id']){
  493. $work_spare_parts = json_decode(ServiceWorkSpare::where('id',$result['service_work_spare_id'])->value('spare_parts'),true);
  494. $spare_parts = SparePart::where('id','in',array_column($work_spare_parts,'id'))
  495. ->field(['id', 'goods_category_id', 'spare_name', 'spare_image', 'spare_number', 'spare_unit','spare_status'])
  496. ->select()
  497. ->toArray();
  498. $spare_parts = array_column($spare_parts,null,'id');
  499. foreach (array_column($work_spare_parts,null,'id') as $k=>&$v){
  500. $spare_parts[$k] = array_merge($spare_parts[$k],$v);
  501. }
  502. $result['spare_parts'] = array_values($spare_parts)??[];
  503. }
  504. // 保修卡信息
  505. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  506. $query->with(['goodsCategory'=>function ($query1) {
  507. $query1->field(['name','picture']);
  508. }]);
  509. }])->where('work_id',$result['id'])
  510. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  511. ->append(['effective_unit_text'])
  512. ->order('create_time desc')
  513. ->select()
  514. ->toArray();
  515. //查收工程师提成金额
  516. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  517. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  518. //质保金相关金额
  519. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  520. ->each(function ($item){
  521. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  522. })->toArray();
  523. //保修工单时的信息
  524. $result['effective_income_amount'] = 0;
  525. if(!empty($result['order_effective_id'])){
  526. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  527. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  528. if($serviceWork->master_worker_id != $result['master_worker_id']){
  529. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  530. }
  531. }
  532. //获取美团订单信息
  533. $result['meituan_order'] = [];
  534. if($result['third_type']==1){
  535. $result['meituan_order'] = ThirdOrders::where(['work_id'=>$result['id']])->order('create_time desc')->findOrEmpty();
  536. }
  537. return $result;
  538. }
  539. public static function getUserCouponDetails($params)
  540. {
  541. try{
  542. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  543. if(!$work){
  544. throw new \Exception('工单不存在');
  545. }
  546. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  547. ->where('voucher_count','>',0)
  548. ->where('voucher_status',0)
  549. ->where('expire_time','>',time())
  550. ->column('coupon_id');
  551. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  552. $data = UserCoupon::where('user_id',$work['user_id'])
  553. ->where('voucher_count','>',0)
  554. ->where('voucher_status',0)
  555. ->whereIn('coupon_id',$coupon_ids)
  556. ->append(['discount_ratio_text'])
  557. ->where('expire_time','>',time())
  558. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  559. ->select()->toArray();
  560. foreach($data as $k => $v){
  561. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  562. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  563. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  564. }
  565. return $data;
  566. } catch(\Exception $e){
  567. self::setError($e->getMessage());
  568. return false;
  569. }
  570. }
  571. public static function getDetailWorkServiceStatus($params)
  572. {
  573. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  574. //工程师工单按钮状态
  575. $work_service_status = 0;
  576. //工单状态
  577. if($result['work_status'] == 1){
  578. $work_service_status = 1;
  579. }
  580. if($result['work_status'] == 2){
  581. $work_service_status = 2;
  582. }
  583. if($result['work_status'] == 3){
  584. $work_service_status = 3;
  585. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  586. $work_service_status = 4;
  587. }
  588. }
  589. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  590. $work_service_status = 5;
  591. }
  592. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  593. $work_service_status = 6;
  594. }
  595. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  596. $work_service_status = 7;
  597. }
  598. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  599. $work_service_status = 8;
  600. }
  601. if($result['work_status'] ==6){
  602. $work_service_status = 9;
  603. }
  604. if($result['work_status'] ==7){
  605. $work_service_status = 10;
  606. }
  607. if($result['work_status'] ==8){
  608. $work_service_status = 11;
  609. }
  610. if($result['work_status'] ==9){
  611. $work_service_status = 12;
  612. }
  613. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  614. }
  615. /**
  616. * @notes 取消操作
  617. * @param array $params
  618. * @return bool
  619. * @author likeadmin
  620. * @date 2024/09/19 10:48
  621. */
  622. public static function cancel(array $params): bool
  623. {
  624. Db::startTrans();
  625. try {
  626. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  627. $serviceWorkInfo = ServiceWork::find($params['id']);
  628. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  629. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  630. }
  631. //工单如果存在费用情况,不允许取消
  632. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  633. if($paid_amount > 0){
  634. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  635. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  636. }
  637. ServiceWork::where('id', $params['id'])->update([
  638. //'work_status' => 9,
  639. 'service_status' => 4,
  640. 'remark' => $params['remark']??''
  641. ]);
  642. ServiceWorkLog::create([
  643. 'work_id' => $params['id'],
  644. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  645. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消"
  646. ]);
  647. Db::commit();
  648. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  649. return true;
  650. } catch (\Exception $e) {
  651. Db::rollback();
  652. self::setError($e->getMessage());
  653. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  654. return false;
  655. }
  656. }
  657. /**
  658. * @notes 工程师结算操作
  659. * @param array $params
  660. * @return bool
  661. * @author likeadmin
  662. * @date 2024/09/19 10:48
  663. */
  664. public static function settlement(array $params): bool
  665. {
  666. Db::startTrans();
  667. try {
  668. $serviceWorkInfo = ServiceWork::find($params['id']);
  669. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  670. throw new \Exception('该工单非待结算状态');
  671. }
  672. $ratio = 0;
  673. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  674. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  675. if($commissionConfig->isEmpty() || empty($ratio)){
  676. //获取工单对应的商品id
  677. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  678. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  679. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  680. if($rule->isEmpty()){
  681. throw new \Exception('请配置商品业绩规则');
  682. }
  683. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  684. }else{
  685. // 存在服务分类比例进行结算
  686. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  687. }
  688. Db::commit();
  689. return true;
  690. } catch (\Exception $e) {
  691. Db::rollback();
  692. self::setError($e->getMessage());
  693. return false;
  694. }
  695. }
  696. /**
  697. * 获取所有改约通知
  698. * @param $userId
  699. * @return array|false
  700. */
  701. public static function getAppointmentNotice($userId)
  702. {
  703. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  704. ->where('work_status','>',1)
  705. ->where('work_status','<',7)
  706. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  707. ->order(['appointment_time' => 'asc'])//上门时间排序
  708. ->select()->each(function (&$item){
  709. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  710. })
  711. ->toArray();
  712. }
  713. /**
  714. * @param $params
  715. * @return bool
  716. */
  717. public static function submitAppointment($params)
  718. {
  719. Db::startTrans();
  720. try {
  721. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  722. if($serviceWork->isEmpty()){
  723. throw new \Exception('工单不存在');
  724. }
  725. $serviceWork->appoint_approval = 2;
  726. $serviceWork->save();
  727. Db::commit();
  728. return true;
  729. } catch (\Exception $e) {
  730. Db::rollback();
  731. self::setError($e->getMessage());
  732. return false;
  733. }
  734. }
  735. /**
  736. * @param $params
  737. * @return bool
  738. */
  739. public static function submitChangePrice($params)
  740. {
  741. Db::startTrans();
  742. try {
  743. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  744. if($serviceWork->isEmpty()){
  745. throw new \Exception('工单不存在');
  746. }
  747. $serviceWork->work_status = 4;
  748. $serviceWork->user_confirm_status = 0;
  749. $serviceWork->price_approval = 2;
  750. $serviceWork->save();
  751. Db::commit();
  752. return true;
  753. } catch (\Exception $e) {
  754. Db::rollback();
  755. self::setError($e->getMessage());
  756. return false;
  757. }
  758. }
  759. public static function notApproved($params)
  760. {
  761. Db::startTrans();
  762. try {
  763. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  764. if($serviceWork->isEmpty()){
  765. throw new \Exception('工单不存在');
  766. }
  767. $serviceWork->refund_approval = 3;
  768. $serviceWork->save();
  769. Db::commit();
  770. return true;
  771. } catch (\Exception $e) {
  772. Db::rollback();
  773. self::setError($e->getMessage());
  774. return false;
  775. }
  776. }
  777. public static function againDoor($params)
  778. {
  779. Db::startTrans();
  780. try {
  781. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  782. if($serviceWork->isEmpty()){
  783. throw new \Exception('工单不存在');
  784. }
  785. //更新预约日志
  786. //更新工单未确认上门的状态
  787. $serviceWork->work_status = 3;
  788. $serviceWork->user_confirm_status = 0;
  789. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  790. if($appoint > 2){
  791. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  792. }
  793. ServiceWorkAppointmentLog::create([
  794. 'work_id'=>$serviceWork->id,
  795. 'worker_id'=>$params['user_id'],
  796. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  797. 'this_appointment_time'=>strtotime($params['appointment_time']),
  798. ]);
  799. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  800. $serviceWork->save();
  801. Db::commit();
  802. return true;
  803. } catch (\Exception $e) {
  804. Db::rollback();
  805. self::setError($e->getMessage());
  806. return false;
  807. }
  808. }
  809. public static function cancelAllocation($params,$userInfo){
  810. Db::startTrans();
  811. try {
  812. $work = ServiceWork::findOrEmpty($params['id']);
  813. if($work->isEmpty()){
  814. throw new Exception('工单不存在');
  815. }
  816. if($work->work_status >=6 ){
  817. throw new \Exception('工单状态只能修改待结算之前的');
  818. }
  819. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  820. if($worker->isEmpty()){
  821. throw new \Exception('工程师不存在');
  822. }
  823. if ($work->tenant_id > 0) {
  824. //团队订单取消时,派单数量减1
  825. $updateData = date("H",strtotime($work->appointment_time)) < 12 ? ['am_order' => Db::raw('am_order - 1')] : ['pm_order' => Db::raw('pm_order - 1')];
  826. MasterWorkerTeam::where('master_worker_id',$work->master_worker_id)->where('tenant_id',$work->tenant_id)->update($updateData);
  827. }
  828. $params['master_worker_id'] = (isset($params['master_worker_id']) && !empty($params['master_worker_id']))?$params['master_worker_id']:$work->master_worker_id;
  829. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  830. $work->master_worker_id = 0;
  831. $work->tenant_id = 0;
  832. $work->work_status = 0;
  833. $work->dispatch_time = 0;
  834. $work->first_contact_time = 0;
  835. $work->estimated_finish_time = 0;
  836. $work->exec_time = 0;
  837. $work->save();
  838. $work_log = [
  839. 'work_id'=>$work->id,
  840. 'master_worker_id'=>$params['master_worker_id'],
  841. 'type' => 1,
  842. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  843. ];
  844. ServiceWorkerAllocateWorkerLogic::add($work_log);
  845. Db::commit();
  846. return true;
  847. }catch(\Exception $e){
  848. Db::rollback();
  849. self::setError($e->getMessage());
  850. return false;
  851. }
  852. }
  853. public static function addCustomerLog($params)
  854. {
  855. Db::startTrans();
  856. try {
  857. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  858. if($serviceWork->isEmpty()){
  859. throw new \Exception('工单不存在');
  860. }
  861. ServiceWorkCustomerLog::create([
  862. 'work_id'=>$serviceWork->id,
  863. 'content'=>$params['content']??'',
  864. 'admin_id'=>$params['admin_id']??0,
  865. 'create_time'=>time(),
  866. ]);
  867. Db::commit();
  868. return true;
  869. } catch (\Exception $e) {
  870. Db::rollback();
  871. self::setError($e->getMessage());
  872. return false;
  873. }
  874. }
  875. public static function distributeTenants($params,$userInfo)
  876. {
  877. Db::startTrans();
  878. try {
  879. if(empty($params['id']) || empty($params['tenant_id'])){
  880. throw new \Exception('参数错误'.json_encode($params));
  881. }
  882. if (is_array($params['id'])) {
  883. $ids = $params['id'];
  884. } else{
  885. $ids = [$params['id']];
  886. }
  887. // 取消工程师分配
  888. foreach ($ids as $id) {
  889. $res = self::cancelAllocation(['id'=>$id,'master_worker_id'=>''],$userInfo);
  890. if($res === false){
  891. Log::info('分配log'.self::getError());
  892. }
  893. }
  894. ServiceWork::whereIn('id',$ids)->update(['tenant_id'=>$params['tenant_id']]);
  895. Db::commit();
  896. return true;
  897. } catch (\Exception $e) {
  898. Db::rollback();
  899. self::setError($e->getMessage());
  900. return false;
  901. }
  902. }
  903. /**
  904. *
  905. * @return false|void
  906. */
  907. public static function contactCustomer($params)
  908. {
  909. try {
  910. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  911. if($work->isEmpty()){
  912. throw new \Exception('工单不存在');
  913. }
  914. if (empty($work->first_contact_time)) {
  915. $work->first_contact_time = time();
  916. $work->save();
  917. }
  918. return true;
  919. }
  920. catch (\Exception $e) {
  921. Db::rollback();
  922. self::setError($e->getMessage());
  923. return false;
  924. }
  925. }
  926. /**
  927. * 添加第三方平台订单
  928. * @return false|void
  929. */
  930. public static function addThirdPlatformsOrders($params)
  931. {
  932. try {
  933. return ThirdOrderLogic::submitOrders($params);
  934. }catch (\Exception $e) {
  935. self::setError($e->getMessage());
  936. return false;
  937. }
  938. }
  939. /**
  940. * 上门码和完成码
  941. * @param $params
  942. * @return false|array
  943. */
  944. public static function confirmDoorCode($params)
  945. {
  946. try {
  947. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  948. if($work->isEmpty()){
  949. throw new Exception('工单不存在');
  950. }
  951. $encryptedData = encrypt($params['work_sn'], \think\facade\Config::get('project.work_sn_key'));
  952. return ['url'=>\think\facade\Config::get('project.user_website').'?code='.$encryptedData];
  953. }catch (\Exception $e) {
  954. self::setError($e->getMessage());
  955. return false;
  956. }
  957. }
  958. }