ServiceWorkLogic.php 42 KB

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