ServiceWorkLogic.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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\adminapi\logic\user\UserLogic;
  16. use app\common\enum\ThirdTypeEnum;
  17. use app\common\enum\worker\WorkerAccountLogEnum;
  18. use app\common\logic\ThirdOrderLogic;
  19. use app\common\logic\WorkerAccountLogLogic;
  20. use app\common\model\third\ThirdOrders;
  21. use app\common\model\works\ServiceWorkDeterminedPrice;
  22. use app\workerapi\logic\MasterWorkerLogic;
  23. use think\Exception;
  24. use think\db\Query;
  25. use think\facade\Db;
  26. use think\facade\Log;
  27. use app\common\logic\BaseLogic;
  28. use app\api\logic\PerformanceLogic;
  29. use app\common\model\dict\DictData;
  30. use app\common\model\coupon\UserCoupon;
  31. use app\common\model\works\ServiceWork;
  32. use app\common\model\recharge\OrderGoods;
  33. use app\common\model\spare_part\SparePart;
  34. use app\common\model\works\ServiceWorkLog;
  35. use app\common\model\coupon\CouponCategory;
  36. use app\common\model\recharge\RechargeOrder;
  37. use app\common\model\works\ServiceWorkSpare;
  38. use app\workerapi\logic\ServiceWorkLogLogic;
  39. use app\common\model\orders\OrderEffectiveLog;
  40. use app\common\model\master_worker\MasterWorker;
  41. use app\common\model\training\TrainingWorkerTask;
  42. use app\common\model\performance\PerformanceRules;
  43. use app\common\model\works\ServiceWorkCustomerLog;
  44. use app\workerapi\logic\ServiceWorkReceiveLogLogic;
  45. use app\common\model\master_worker\MasterWorkerTeam;
  46. use app\common\model\works\ServiceWorkAppointmentLog;
  47. use app\workerapi\logic\ServiceWorkerAllocateWorkerLogic;
  48. use app\common\model\master_worker\MasterWorkerAccountLog;
  49. use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
  50. use app\common\model\master_commission\MasterWorkerCommissionRatio;
  51. use app\common\model\master_commission\MasterWorkerCommissionConfig;
  52. use app\common\model\service_area\ServiceArea;
  53. use app\common\service\call\VirtualCallService;
  54. use think\facade\Cache;
  55. /**
  56. * ServiceWork逻辑
  57. * Class ServiceWorkLogic
  58. * @package app\adminapi\logic\works
  59. */
  60. class ServiceWorkLogic extends BaseLogic
  61. {
  62. /**
  63. * @notes 编辑
  64. * @param array $params
  65. * @return bool
  66. * @author likeadmin
  67. * @date 2024/07/10 18:17
  68. */
  69. public static function edit(array $params): bool
  70. {
  71. Db::startTrans();
  72. try {
  73. $userId = UserLogic::getUserIdByMobile($params['mobile']);
  74. $service_area_id = ServiceArea::serviceAreaId(['lon' => $params['lon'], 'lat' => $params['lat']]);
  75. if($params['address'] && (empty($params['lon']) || empty($params['lat']))){
  76. $lon_lat = get_address_lat_lng($params['address']);
  77. $params['lon'] = $lon_lat['lon'];
  78. $params['lat'] = $lon_lat['lat'];
  79. }
  80. ServiceWork::where('id', $params['id'])->update([
  81. 'real_name' => $params['real_name'],
  82. 'mobile' => $params['mobile'],
  83. 'user_id' => $userId,
  84. 'address' => $params['address'],
  85. 'appointment_time' => strtotime($params['appointment_time']),
  86. 'estimated_finish_time' => $params['estimated_finish_time'],
  87. 'lon' => $params['lon'],
  88. 'lat' => $params['lat'],
  89. 'service_area_id' => $service_area_id,
  90. ]);
  91. \app\common\model\orders\RechargeOrder::where('work_id',$params['id'])->update(['user_id' => $userId]);
  92. Db::commit();
  93. return true;
  94. } catch (\Exception $e) {
  95. Db::rollback();
  96. self::setError($e->getMessage());
  97. return false;
  98. }
  99. }
  100. /**
  101. *
  102. * @return false|void
  103. */
  104. public static function pickWork($params)
  105. {
  106. Db::startTrans();
  107. try {
  108. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  109. if($work->isEmpty()){
  110. throw new Exception('工单不存在');
  111. }
  112. $receive_time = time();
  113. $work->work_status = 2;//待联系
  114. $work->service_status = 1;//服务中
  115. $work->receive_time = $receive_time;
  116. $work->save();
  117. //添加变更日志
  118. $work_log = [
  119. 'work_id'=>$work->id,
  120. 'master_worker_id'=>$work->master_worker_id,
  121. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',$receive_time).'领取了工单',
  122. ];
  123. ServiceWorkLogLogic::add($work_log);
  124. //添加领单日志
  125. ServiceWorkReceiveLogLogic::add($work_log);
  126. Db::commit();
  127. // 工单状态通知外部平台 即工程师接单成功
  128. if($work->external_platform_id > 0){
  129. event('ExternalPlatform', [
  130. 'send_code' => 1001,
  131. 'params' => [
  132. 'work_id' => $work->id,
  133. ]
  134. ]);
  135. }
  136. }
  137. catch (\Exception $e) {
  138. Db::rollback();
  139. self::setError($e->getMessage());
  140. return false;
  141. }
  142. }
  143. /**
  144. * 预约成功,等待上门
  145. * @return false|void
  146. */
  147. public static function appointWork($params)
  148. {
  149. Db::startTrans();
  150. try {
  151. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  152. if($work->isEmpty()){
  153. throw new Exception('工单不存在');
  154. }
  155. if($work->work_status != 2){
  156. throw new Exception('请勿重复点击');
  157. }
  158. //判断是否有待审核的预约时间修改记录
  159. $exists = ServiceWorkAppointmentLog::where(['work_id'=>$work->id,'status'=>0])->value('id');
  160. if ($exists){
  161. throw new Exception('存在待审核的预约时间修改记录,无法修改');
  162. }
  163. //验证更改的预约时间必须是在领单时间内的半小内修改,否则不允许修改
  164. // if(strtotime($work->appointment_time) != strtotime($params['appointment_time']) && (time()-strtotime($work->receive_time))>1800){
  165. // throw new Exception('距离领单时间已超过半小时,无法修改预约时间,请联系客服');
  166. // }
  167. //添加预约时间修改待审核记录
  168. ServiceWorkAppointmentLog::create([
  169. 'status'=>0,//待审核
  170. 'work_id'=>$work->id,
  171. 'worker_id'=>$params['user_id'],
  172. 'last_appointment_time'=>strtotime($work->appointment_time),
  173. 'this_appointment_time'=>strtotime($params['appointment_time']),
  174. ]);
  175. // $work->work_status = 3;//待上门
  176. // $work->appointment_time = strtotime($params['appointment_time']);
  177. // $work->save();
  178. //添加变更日志
  179. // $work_log = [
  180. // 'work_id'=>$work->id,
  181. // 'master_worker_id'=>$work->master_worker_id,
  182. // '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'].'预约上门',
  183. // ];
  184. // ServiceWorkLogLogic::add($work_log);
  185. Db::commit();
  186. }
  187. catch (\Exception $e) {
  188. self::setError($e->getMessage());
  189. return false;
  190. }
  191. }
  192. /**
  193. * 工程师确认上门
  194. * @param $params
  195. * @return false|void
  196. */
  197. public static function confirmDoor($params)
  198. {
  199. Db::startTrans();
  200. try {
  201. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  202. if($work->isEmpty()){
  203. throw new Exception('工单不存在');
  204. }
  205. if($work->work_status != 3){
  206. throw new Exception('请勿重复点击');
  207. }
  208. $work->finally_door_time = time();//最后上门时间
  209. $work->work_status = 4;//已上门
  210. $work->save();
  211. //如果是美团订单,且上门时间小于预约时间,则修改预约时间
  212. if($work->third_type==1 and $work->finally_door_time<$work->appointment_time){
  213. $third_order = ThirdOrders::where('work_id',$work->id)->order('id desc')->findOrEmpty();
  214. if(!$third_order->isEmpty()){
  215. ThirdOrderLogic::merchantmodify([
  216. 'reserveOrderId'=>$third_order['orderId'],
  217. 'reserveUserName'=>$work['real_name'],
  218. "reservePhone"=>$work['mobile'],
  219. "reserveAddress"=>$work['address'],
  220. "bookStartTime"=>$work->finally_door_time*1000,
  221. "bookEndTime"=>($work->finally_door_time+2*3600)*1000,
  222. 'request_msg'=>$third_order['request_msg']
  223. ]);
  224. }
  225. }
  226. //添加变更日志
  227. $work_log = [
  228. 'work_id'=>$work->id,
  229. 'master_worker_id'=>$work->master_worker_id,
  230. '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()).'已上门',
  231. ];
  232. ServiceWorkLogLogic::add($work_log);
  233. Db::commit();
  234. }
  235. catch (\Exception $e) {
  236. Db::rollback();
  237. self::setError($e->getMessage());
  238. return false;
  239. }
  240. }
  241. /**
  242. * 工程师确认报价单
  243. * @param $params
  244. * @return false|void
  245. */
  246. public static function confirmPrice($params)
  247. {
  248. Db::startTrans();
  249. try {
  250. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  251. if($work->isEmpty()){
  252. throw new Exception('工单不存在');
  253. }
  254. //搜索待支付订单
  255. $paid_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>1])->findOrEmpty()->toArray();
  256. if(empty($paid_order)){
  257. throw new Exception('订单错误');
  258. }
  259. if($work->work_status != 4){
  260. throw new Exception('请勿重复操作');
  261. }
  262. // 商城配件.计算配件总价 id company_price original_price offering_price number
  263. $spare_total = 0;
  264. $work->spare_total = 0;
  265. isset($params['spare_parts']) && $params['spare_parts'] && $params['spare_parts'] = json_decode($params['spare_parts'], true);
  266. $spare_parts_ids = ServiceWorkSpare::where('service_work_id',$work['id'])->column('id');
  267. if(isset($params['spare_parts']) && $params['spare_parts']){
  268. if (count($params['spare_parts']) > 10) {
  269. throw new Exception('商城配件最多10个');
  270. }
  271. $ids = array_column($params['spare_parts'],'id');
  272. $spare_parts = SparePart::where('id','in',$ids)->column('id as spare_part_id,spare_name,spare_image,company_price,original_price,offering_price,spare_number,spare_unit,brand');
  273. $spare_parts = array_column($spare_parts,null,'spare_part_id');
  274. foreach ($params['spare_parts'] as $k => $item){
  275. if (!isset($spare_parts[$item['id']])){
  276. throw new Exception('配件信息错误');
  277. }
  278. $spare_part = $spare_parts[$item['id']];
  279. $spare_total += $spare_part['company_price']*$item['spare_number'];
  280. $data = array_merge($spare_part, ['service_work_id' => $work['id'], 'spare_number' => $item['spare_number'] * $spare_part['spare_number']]);
  281. if (current($spare_parts_ids)) {
  282. //修改
  283. ServiceWorkSpare::where("id",current($spare_parts_ids))->update($data);
  284. } else {
  285. //新增
  286. ServiceWorkSpare::create($data);
  287. }
  288. array_shift($spare_parts_ids);
  289. }
  290. $work->spare_total += $spare_total;
  291. }
  292. //自选配件
  293. isset($params['self_spare_parts']) && $params['self_spare_parts'] && $params['self_spare_parts'] = json_decode($params['self_spare_parts'], true);
  294. if(isset($params['self_spare_parts']) && $params['self_spare_parts']){
  295. if (count($params['self_spare_parts']) > 10) {
  296. throw new Exception('自选配件最多10个');
  297. }
  298. foreach ($params['self_spare_parts'] as $item){
  299. $spare_total += $item['offering_price']*$item['spare_number'];
  300. $data = [
  301. 'service_work_id'=>$work['id'],
  302. 'spare_name' => $item['spare_name'],
  303. 'spare_image' => empty($item['spare_image']) ? '' : $item['spare_image'],
  304. 'offering_price' => $item['offering_price'],
  305. 'company_price' => 0,
  306. 'original_price' => 0,
  307. 'spare_number' => $item['spare_number'],
  308. 'spare_part_id' => 0,
  309. 'brand' => $item['brand'],
  310. 'status' => 0,
  311. ];
  312. if (current($spare_parts_ids)) {
  313. //修改
  314. ServiceWorkSpare::where("id",current($spare_parts_ids))->update($data);
  315. } else {
  316. //新增
  317. ServiceWorkSpare::create($data);
  318. }
  319. array_shift($spare_parts_ids);
  320. }
  321. $work->spare_total += $spare_total;
  322. }
  323. //删除多余的配件数据
  324. if ($spare_parts_ids) {
  325. ServiceWorkSpare::where('id','in',$spare_parts_ids)->delete();
  326. }
  327. // 添加工单尾款报价记录 - 即配件费用
  328. if(isset($params['price_content'])){
  329. !is_array($params['price_content']) && $params['price_content'] = json_decode($params['price_content'], true);
  330. ServiceWorkDeterminedPrice::where('work_id',$work->id)->delete();
  331. ServiceWorkDeterminedPrice::create([
  332. 'work_id'=>$work->id,
  333. 'content'=>$params['price_content']??[],
  334. ]);
  335. $work->spare_total += array_sum('price');
  336. }
  337. // order_amount 原 = $params['amount'] 修改为 = 配件总价 + 服务尾款
  338. $order_amount = $params['amount'] + $spare_total;
  339. //定金存在尾款结算功能,全款直接提交
  340. if($paid_order['payment_type']==1){
  341. $un_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>0])->findOrEmpty();
  342. if($un_order->isEmpty()){
  343. //新增待支付尾款
  344. $order_data = [
  345. 'order_type'=>$paid_order['order_type'],
  346. 'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
  347. 'work_id'=>$paid_order['work_id'],
  348. 'user_id'=>$paid_order['user_id'],
  349. 'payment_type'=>2,
  350. 'order_total'=>$order_amount,
  351. //'order_amount'=>$params['amount'],
  352. 'order_amount'=>$order_amount,
  353. 'order_terminal'=>$paid_order['order_terminal']
  354. ];
  355. RechargeOrder::create($order_data);
  356. }else{
  357. //修改尾款信息
  358. $un_order->order_total = $order_amount;
  359. //$un_order->order_amount = $params['amount'];
  360. $un_order->order_amount = $order_amount;
  361. $un_order->save();
  362. }
  363. //更新服务费用
  364. $work->service_fee = $paid_order['paid_amount']+$params['amount'];
  365. }
  366. //总工单费用
  367. $work->work_total = $work->service_fee+$spare_total;
  368. $work->work_images = $params['work_images'];
  369. $work->explanation = $params['explanation']??'';
  370. //判断是否是第三个订单,如果是美团订单直接滤过用户确认环节
  371. if($work->third_type==1){
  372. $work->work_status = 5;
  373. $work->user_confirm_status = 2;
  374. }else{
  375. $work->user_confirm_status = 1;//待确认报价
  376. }
  377. if($work->external_platform_id > 0){
  378. $work->work_status = 5;
  379. $work->user_confirm_status = 2;
  380. }
  381. $work->price_approval = 0;
  382. $work->save();
  383. //添加变更日志
  384. $work_log = [
  385. 'work_id'=>$work->id,
  386. 'master_worker_id'=>$work->master_worker_id,
  387. '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()).'提交了报价单',
  388. ];
  389. ServiceWorkLogLogic::add($work_log);
  390. Db::commit();
  391. // 商家报价通知外部平台 即报价
  392. if($work->external_platform_id > 0){
  393. event('ExternalPlatform', [
  394. 'send_code' => 1006,
  395. 'params' => [
  396. 'work_id' => $work->id,
  397. ]
  398. ]);
  399. }
  400. }
  401. catch (\Exception $e) {
  402. Db::rollback();
  403. self::setError($e->getMessage());
  404. return false;
  405. }
  406. }
  407. /**
  408. * 工程师修改自选配件的图片
  409. * @param $params
  410. * @return false|void
  411. */
  412. public static function selfSparePart($params)
  413. {
  414. Db::startTrans();
  415. try {
  416. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  417. if($work->isEmpty()){
  418. throw new Exception('工单不存在');
  419. }
  420. $audit = ServiceWorkSpare::where(['id' => $params['id'],'service_work_id'=>$work['id']])->findOrEmpty();
  421. if(!$audit->isEmpty() && ($audit['status']!=0 && $audit['status']!=2) ){
  422. throw new Exception('当前工单配件不允许修改');
  423. }
  424. if (empty($params['spare_image'])){
  425. throw new Exception('请上传配件图片');
  426. }
  427. //修改
  428. ServiceWorkSpare::where("id",$params['id'])->where('service_work_id', $work['id'])->update(['spare_image' => $params['spare_image'], 'status' => 0]);
  429. Db::commit();
  430. return true;
  431. } catch (\Exception $e) {
  432. Db::rollback();
  433. self::setError($e->getMessage());
  434. return false;
  435. }
  436. }
  437. /**
  438. * 工程师确认服务完成
  439. * @param $params
  440. * @return false|void
  441. */
  442. public static function confirmServiceFinish($params)
  443. {
  444. Db::startTrans();
  445. try {
  446. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  447. if($work->isEmpty()){
  448. throw new Exception('工单不存在');
  449. }
  450. if($work->user_confirm_status !=2){
  451. throw new Exception('请勿重复操作');
  452. }
  453. $work->finished_images = $params['finished_images'];
  454. $work->user_confirm_status = 3;//待确认服务完成
  455. $work->save();
  456. //添加变更日志
  457. $work_log = [
  458. 'work_id'=>$work->id,
  459. 'master_worker_id'=>$work->master_worker_id,
  460. '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()).'提交了待用户确认服务完成',
  461. ];
  462. ServiceWorkLogLogic::add($work_log);
  463. Db::commit();
  464. // 外部平台工单 - 通知外边平台
  465. if($work->external_platform_id > 0){
  466. /*event('ExternalPlatform', [
  467. 'scene' => 'service_finish',
  468. 'params' => [
  469. 'work_id' => $work->id,
  470. ]
  471. ]);*/
  472. }
  473. } catch (\Exception $e) {
  474. Db::rollback();
  475. self::setError($e->getMessage());
  476. return false;
  477. }
  478. }
  479. public static function allocateWorker($params,$userInfo){
  480. Db::startTrans();
  481. try {
  482. $work = ServiceWork::findOrEmpty($params['id']);
  483. if($work->isEmpty()){
  484. throw new Exception('工单不存在');
  485. }
  486. if($work->work_status >=6 ){
  487. throw new \Exception('工单状态只能修改待结算之前的');
  488. }
  489. if($work->master_worker_id == $params['master_worker_id'] && !isset($params['is_grab_order'])){
  490. throw new \Exception('分配的工程师相同');
  491. }
  492. $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'is_disable' =>0])->findOrEmpty();
  493. if($worker->isEmpty()){
  494. throw new \Exception('工程师不存在或被禁用');
  495. }
  496. if($worker->master_worker_id && !isset($params['is_grab_order'])){
  497. MasterWorker::setWorktotal('dec',$worker->master_worker_id);
  498. }
  499. $work->master_worker_id = $params['master_worker_id'];
  500. $work->work_status = 1;
  501. $work->dispatch_time = time();
  502. MasterWorker::setWorktotal('inc',$params['master_worker_id']);
  503. $work->save();
  504. $work_log = [
  505. 'work_id'=>$work->id,
  506. 'master_worker_id'=>$work->master_worker_id,
  507. 'type' => isset($params['is_grab_order'])?3:0,
  508. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  509. ];
  510. ServiceWorkerAllocateWorkerLogic::add($work_log);
  511. Db::commit();
  512. //美团的订单更新履约状态为已分配
  513. if($work->third_type == 1){
  514. ThirdOrderLogic::updateorderfulfillinfo($work,ThirdTypeEnum::MEITUAN_MEITUAN);
  515. }
  516. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  517. $workDetail = ServiceWorkLogic::detail($params);
  518. $res = event('Notice', [
  519. 'scene_id' => 113,
  520. 'params' => [
  521. 'user_id' => $params['master_worker_id'],
  522. 'order_id' => $params['id'],
  523. 'thing9' => $workDetail['title'],
  524. 'time7' => $workDetail['appointment_time'],
  525. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  526. 'phone_number6' => asteriskString($workDetail['mobile']),
  527. ]
  528. ]);
  529. return true;
  530. }catch(\Exception $e){
  531. Db::rollback();
  532. self::setError($e->getMessage());
  533. return false;
  534. }
  535. }
  536. /**
  537. * 工单详情
  538. * @param $params
  539. * @return array|false
  540. */
  541. public static function detail($params){
  542. $work_where = !empty($params['work_sn'])?['work_sn'=>$params['work_sn']]:['id'=>$params['id']];
  543. $result = ServiceWork::with([
  544. 'worker'=> function(Query $query) {
  545. $query->field('id,worker_number,real_name,mobile');
  546. },
  547. 'allocateWorkerLog' =>function(Query $query){
  548. $query->field('id,work_id,opera_log,create_time');
  549. },
  550. 'serviceWorkLog' =>function(Query $query){
  551. $query->field('id,work_id,opera_log,create_time');
  552. }
  553. ])->append(['id','work_status_text','service_status_text'])
  554. ->where($work_where)
  555. ->findOrEmpty()->toArray();
  556. $result['is_operate_prohibit'] = 0;
  557. if(isset($params['user_id']) && $params['user_id'] && ($params['user_id'] != $result['master_worker_id']) ){
  558. // 带徒师傅的工单
  559. $lead_master_worker_id = TrainingWorkerTask::where('master_worker_id',$params['user_id'])->where('training_status',2)
  560. ->where('operate_status',0)->value('lead_master_worker_id');
  561. // 团队负责人编辑 工单池(包括已派队员) 工单
  562. if($params['user_info']['team_role'] == 1 && $params['user_info']['tenant_id'] == $result['tenant_id'] ){
  563. $result['is_operate_prohibit'] = 0;
  564. }elseif(!empty($lead_master_worker_id) && !empty($result['master_worker_id']) && $lead_master_worker_id == $result['master_worker_id']){
  565. // 徒查看师父的工单 不能编辑可查看
  566. $result['is_operate_prohibit'] = 1;
  567. }else{
  568. throw new \Exception('您没有权限操作该工单');
  569. }
  570. }
  571. //工程师工单按钮状态
  572. $work_service_status = 0;
  573. $work_service_status_text = '待派单';
  574. //工单状态
  575. if($result['work_status'] == 1){
  576. $work_service_status = 1;
  577. $work_service_status_text = '待领单';
  578. }
  579. if($result['work_status'] == 2){
  580. $work_service_status = 2;
  581. $work_service_status_text = '预约上门';
  582. }
  583. if($result['work_status'] == 3){
  584. $work_service_status = 3;
  585. $work_service_status_text = '等待上门';
  586. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  587. $work_service_status = 4;
  588. $work_service_status_text = '确认上门';
  589. }
  590. }
  591. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  592. $work_service_status = 5;
  593. $work_service_status_text = '确认报价';
  594. }
  595. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  596. $work_service_status = 6;
  597. $work_service_status_text = '用户确认报价中';
  598. }
  599. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  600. $work_service_status = 7;
  601. $work_service_status_text = '完成服务';
  602. }
  603. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  604. $work_service_status = 8;
  605. $work_service_status_text = '用户确认完成服务中';
  606. }
  607. if($result['work_status'] ==6){
  608. $work_service_status = 9;
  609. $work_service_status_text = '待结算';
  610. }
  611. if($result['work_status'] ==7){
  612. $work_service_status = 10;
  613. $work_service_status_text = '已完结';
  614. }
  615. if($result['work_status'] ==8){
  616. $work_service_status = 11;
  617. $work_service_status_text = '已评价';
  618. }
  619. if($result['work_status'] ==9){
  620. $work_service_status = 12;
  621. $work_service_status_text = '已退费';
  622. }
  623. $result['work_service_status'] = $work_service_status;
  624. $result['work_service_status_text'] = $work_service_status_text;
  625. //搜索当前工单下的所有订单记录
  626. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  627. $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']);
  628. }])->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();
  629. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  630. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  631. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  632. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  633. $coupon_price = 0;
  634. foreach ($result['pay_orders'] as $k=>&$v){
  635. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  636. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  637. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  638. $v['order_type_name'] = $order_type_data[$v['order_type']];
  639. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  640. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  641. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  642. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  643. }
  644. $coupon_price += $v['coupon_price'];
  645. //服务支付类别
  646. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  647. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  648. }
  649. }
  650. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  651. //汇总优惠卷额度
  652. $result['coupon_price'] = $coupon_price;
  653. //工单总支付金额
  654. $result['worker_account'] = $result['work_amount'];
  655. // 配件信息
  656. $result['spare_parts'] = [];
  657. $result['self_spare_parts'] = [];
  658. if($result['spare_total'] > 0){
  659. $result['spare_parts'] = ServiceWorkSpare::getLists($result['id'], 1);
  660. $result['self_spare_parts'] = ServiceWorkSpare::getLists($result['id'], 2);
  661. }
  662. // 保修卡信息
  663. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  664. $query->with(['goodsCategory'=>function ($query1) {
  665. $query1->field(['name','picture']);
  666. }]);
  667. }])->where('work_id',$result['id'])
  668. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  669. ->append(['effective_unit_text'])
  670. ->order('create_time desc')
  671. ->select()
  672. ->toArray();
  673. //查收工程师提成金额
  674. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  675. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  676. //质保金相关金额
  677. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  678. ->each(function ($item){
  679. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  680. })->toArray();
  681. //保修工单时的信息
  682. $result['effective_income_amount'] = 0;
  683. if(!empty($result['order_effective_id'])){
  684. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  685. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  686. if($serviceWork->master_worker_id != $result['master_worker_id']){
  687. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  688. }
  689. }
  690. //获取美团订单信息
  691. $result['meituan_order'] = [];
  692. if($result['third_type']==1){
  693. $result['meituan_order'] = ThirdOrders::where(['work_id'=>$result['id']])->order('create_time desc')->findOrEmpty();
  694. }
  695. //工程师预约时间修改申请记录
  696. if (!empty($params['user_id'])) {
  697. $result['appointment_log'] = ServiceWorkAppointmentLog::where('work_id',$result['id'])->where('worker_id',$params['user_id'])->where('status','<>',1)->field('id,work_id,worker_id,last_appointment_time,this_appointment_time,status,create_time')->order('id desc')->findOrEmpty();
  698. if ($result['appointment_log']){
  699. $result['appointment_log']['last_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['last_appointment_time']);
  700. $result['appointment_log']['this_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['this_appointment_time']);
  701. }
  702. }
  703. return $result;
  704. }
  705. public static function getUserCouponDetails($params)
  706. {
  707. try{
  708. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  709. if(!$work){
  710. throw new \Exception('工单不存在');
  711. }
  712. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  713. ->where('voucher_count','>',0)
  714. ->where('voucher_status',0)
  715. ->where('expire_time','>',time())
  716. ->column('coupon_id');
  717. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  718. $data = UserCoupon::where('user_id',$work['user_id'])
  719. ->where('voucher_count','>',0)
  720. ->where('voucher_status',0)
  721. ->whereIn('coupon_id',$coupon_ids)
  722. ->append(['discount_ratio_text'])
  723. ->where('expire_time','>',time())
  724. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  725. ->select()->toArray();
  726. foreach($data as $k => $v){
  727. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  728. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  729. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  730. }
  731. return $data;
  732. } catch(\Exception $e){
  733. self::setError($e->getMessage());
  734. return false;
  735. }
  736. }
  737. public static function getDetailWorkServiceStatus($params)
  738. {
  739. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  740. //工程师工单按钮状态
  741. $work_service_status = 0;
  742. //工单状态
  743. if($result['work_status'] == 1){
  744. $work_service_status = 1;
  745. }
  746. if($result['work_status'] == 2){
  747. $work_service_status = 2;
  748. }
  749. if($result['work_status'] == 3){
  750. $work_service_status = 3;
  751. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  752. $work_service_status = 4;
  753. }
  754. }
  755. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  756. $work_service_status = 5;
  757. }
  758. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  759. $work_service_status = 6;
  760. }
  761. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  762. $work_service_status = 7;
  763. }
  764. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  765. $work_service_status = 8;
  766. }
  767. if($result['work_status'] ==6){
  768. $work_service_status = 9;
  769. }
  770. if($result['work_status'] ==7){
  771. $work_service_status = 10;
  772. }
  773. if($result['work_status'] ==8){
  774. $work_service_status = 11;
  775. }
  776. if($result['work_status'] ==9){
  777. $work_service_status = 12;
  778. }
  779. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  780. }
  781. /**
  782. * @notes 取消操作
  783. * @param array $params
  784. * @return bool
  785. * @author likeadmin
  786. * @date 2024/09/19 10:48
  787. */
  788. public static function cancel(array $params): bool
  789. {
  790. Db::startTrans();
  791. try {
  792. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  793. $serviceWorkInfo = ServiceWork::find($params['id']);
  794. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  795. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  796. }
  797. //工单如果存在费用情况,不允许取消
  798. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  799. if($paid_amount > 0 and ($serviceWorkInfo['third_type'] == 0 && $serviceWorkInfo['external_platform_id'] == 0)){
  800. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  801. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  802. }
  803. ServiceWork::where('id', $params['id'])->update([
  804. 'work_status' => 9,
  805. 'service_status' => 4,
  806. 'remark' => $params['remark']??''
  807. ]);
  808. ServiceWorkLog::create([
  809. 'work_id' => $params['id'],
  810. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  811. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消"
  812. ]);
  813. Db::commit();
  814. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  815. return true;
  816. } catch (\Exception $e) {
  817. Db::rollback();
  818. self::setError($e->getMessage());
  819. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  820. return false;
  821. }
  822. }
  823. /**
  824. * @notes 工程师结算操作
  825. * @param array $params
  826. * @return bool
  827. * @author likeadmin
  828. * @date 2024/09/19 10:48
  829. */
  830. public static function settlement(array $params): bool
  831. {
  832. Db::startTrans();
  833. try {
  834. $serviceWorkInfo = ServiceWork::find($params['id']);
  835. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  836. throw new \Exception('该工单非待结算状态');
  837. }
  838. $ratio = 0;
  839. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  840. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  841. if($commissionConfig->isEmpty() || empty($ratio)){
  842. //获取工单对应的商品id
  843. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  844. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  845. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  846. if($rule->isEmpty()){
  847. throw new \Exception('请配置商品业绩规则');
  848. }
  849. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  850. }else{
  851. // 存在服务分类比例进行结算
  852. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  853. }
  854. Db::commit();
  855. return true;
  856. } catch (\Exception $e) {
  857. Db::rollback();
  858. self::setError($e->getMessage());
  859. return false;
  860. }
  861. }
  862. /**
  863. * 获取所有改约通知
  864. * @param $userId
  865. * @return array|false
  866. */
  867. public static function getAppointmentNotice($userId)
  868. {
  869. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  870. ->where('work_status','>',1)
  871. ->where('work_status','<',7)
  872. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  873. ->order(['appointment_time' => 'asc'])//上门时间排序
  874. ->select()->each(function (&$item){
  875. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  876. })
  877. ->toArray();
  878. }
  879. /**
  880. * @param $params
  881. * @return bool
  882. */
  883. public static function submitAppointment($params)
  884. {
  885. Db::startTrans();
  886. try {
  887. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  888. if($serviceWork->isEmpty()){
  889. throw new \Exception('工单不存在');
  890. }
  891. $serviceWork->appoint_approval = 2;
  892. $serviceWork->save();
  893. Db::commit();
  894. return true;
  895. } catch (\Exception $e) {
  896. Db::rollback();
  897. self::setError($e->getMessage());
  898. return false;
  899. }
  900. }
  901. /**
  902. * @param $params
  903. * @return bool
  904. */
  905. public static function submitChangePrice($params)
  906. {
  907. Db::startTrans();
  908. try {
  909. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  910. if($serviceWork->isEmpty()){
  911. throw new \Exception('工单不存在');
  912. }
  913. $serviceWork->work_status = 4;
  914. $serviceWork->user_confirm_status = 0;
  915. $serviceWork->price_approval = 2;
  916. $serviceWork->save();
  917. Db::commit();
  918. return true;
  919. } catch (\Exception $e) {
  920. Db::rollback();
  921. self::setError($e->getMessage());
  922. return false;
  923. }
  924. }
  925. public static function notApproved($params)
  926. {
  927. Db::startTrans();
  928. try {
  929. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  930. if($serviceWork->isEmpty()){
  931. throw new \Exception('工单不存在');
  932. }
  933. $serviceWork->refund_approval = 3;
  934. $serviceWork->save();
  935. Db::commit();
  936. return true;
  937. } catch (\Exception $e) {
  938. Db::rollback();
  939. self::setError($e->getMessage());
  940. return false;
  941. }
  942. }
  943. public static function againDoor($params)
  944. {
  945. Db::startTrans();
  946. try {
  947. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  948. if($serviceWork->isEmpty()){
  949. throw new \Exception('工单不存在');
  950. }
  951. //更新预约日志
  952. //更新工单未确认上门的状态
  953. $serviceWork->work_status = 3;
  954. $serviceWork->user_confirm_status = 0;
  955. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  956. if($appoint > 2){
  957. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  958. }
  959. ServiceWorkAppointmentLog::create([
  960. 'work_id'=>$serviceWork->id,
  961. 'worker_id'=>$params['user_id'],
  962. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  963. 'this_appointment_time'=>strtotime($params['appointment_time']),
  964. ]);
  965. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  966. $serviceWork->save();
  967. Db::commit();
  968. return true;
  969. } catch (\Exception $e) {
  970. Db::rollback();
  971. self::setError($e->getMessage());
  972. return false;
  973. }
  974. }
  975. public static function cancelAllocation($params,$userInfo){
  976. Db::startTrans();
  977. try {
  978. $work = ServiceWork::findOrEmpty($params['id']);
  979. if($work->isEmpty()){
  980. throw new Exception('工单不存在');
  981. }
  982. if($work->work_status >=6 ){
  983. throw new \Exception('工单状态只能修改待结算之前的');
  984. }
  985. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  986. if($worker->isEmpty()){
  987. throw new \Exception('工程师不存在');
  988. }
  989. if ($work->tenant_id > 0) {
  990. //团队订单取消时,派单数量减1
  991. $updateData = date("H",strtotime($work->appointment_time)) < 12 ? ['am_order' => Db::raw('am_order - 1')] : ['pm_order' => Db::raw('pm_order - 1')];
  992. MasterWorkerTeam::where('master_worker_id',$work->master_worker_id)->where('tenant_id',$work->tenant_id)->update($updateData);
  993. }
  994. $params['master_worker_id'] = (isset($params['master_worker_id']) && !empty($params['master_worker_id']))?$params['master_worker_id']:$work->master_worker_id;
  995. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  996. $work->master_worker_id = 0;
  997. $work->tenant_id = 0;
  998. $work->work_status = 0;
  999. $work->dispatch_time = 0;
  1000. $work->first_contact_time = 0;
  1001. $work->estimated_finish_time = 0;
  1002. $work->save();
  1003. $work_log = [
  1004. 'work_id'=>$work->id,
  1005. 'master_worker_id'=>$params['master_worker_id'],
  1006. 'type' => 1,
  1007. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  1008. ];
  1009. ServiceWorkerAllocateWorkerLogic::add($work_log);
  1010. Db::commit();
  1011. return true;
  1012. }catch(\Exception $e){
  1013. Db::rollback();
  1014. self::setError($e->getMessage());
  1015. return false;
  1016. }
  1017. }
  1018. public static function addCustomerLog($params)
  1019. {
  1020. Db::startTrans();
  1021. try {
  1022. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1023. if($serviceWork->isEmpty()){
  1024. throw new \Exception('工单不存在');
  1025. }
  1026. ServiceWorkCustomerLog::create([
  1027. 'work_id'=>$serviceWork->id,
  1028. 'content'=>$params['content']??'',
  1029. 'admin_id'=>$params['admin_id']??0,
  1030. 'create_time'=>time(),
  1031. ]);
  1032. Db::commit();
  1033. return true;
  1034. } catch (\Exception $e) {
  1035. Db::rollback();
  1036. self::setError($e->getMessage());
  1037. return false;
  1038. }
  1039. }
  1040. public static function distributeTenants($params,$userInfo)
  1041. {
  1042. Db::startTrans();
  1043. try {
  1044. if(empty($params['id']) || empty($params['tenant_id'])){
  1045. throw new \Exception('参数错误'.json_encode($params));
  1046. }
  1047. if (is_array($params['id'])) {
  1048. $ids = $params['id'];
  1049. } else{
  1050. $ids = [$params['id']];
  1051. }
  1052. // 取消工程师分配
  1053. foreach ($ids as $id) {
  1054. $res = self::cancelAllocation(['id'=>$id,'master_worker_id'=>''],$userInfo);
  1055. if($res === false){
  1056. Log::info('分配log'.self::getError());
  1057. }
  1058. }
  1059. ServiceWork::whereIn('id',$ids)->update(['tenant_id'=>$params['tenant_id']]);
  1060. Db::commit();
  1061. return true;
  1062. } catch (\Exception $e) {
  1063. Db::rollback();
  1064. self::setError($e->getMessage());
  1065. return false;
  1066. }
  1067. }
  1068. /**
  1069. *
  1070. * @return false|void
  1071. */
  1072. public static function contactCustomer($params)
  1073. {
  1074. try {
  1075. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1076. if($work->isEmpty()){
  1077. throw new \Exception('工单不存在');
  1078. }
  1079. if (empty($work->first_contact_time)) {
  1080. $work->first_contact_time = time();
  1081. $work->save();
  1082. }
  1083. if ($middleNumber = Cache::get('WORKER_MIDDLE_NUMBER_'.$work->id)) {
  1084. return ['middleNumber' => $middleNumber];
  1085. }
  1086. $worker_mobile = $params['user_info']['mobile'];
  1087. $res = VirtualCallService::auth($worker_mobile, $work->mobile, 60);
  1088. if (isset($res['result']) && $res['result'] == '000000') {
  1089. Cache::set('WORKER_MIDDLE_NUMBER_'.$work->id, $res['middleNumber'], 60); //缓存60秒
  1090. return ['middleNumber' => $res['middleNumber']];
  1091. } else {
  1092. Log::info('虚拟外呼失败:'.json_encode($res));
  1093. throw new \Exception('虚拟外呼失败');
  1094. }
  1095. return true;
  1096. }
  1097. catch (\Exception $e) {
  1098. Db::rollback();
  1099. self::setError($e->getMessage());
  1100. return false;
  1101. }
  1102. }
  1103. /**
  1104. * 添加第三方平台订单
  1105. * @return false|void
  1106. */
  1107. public static function addThirdPlatformsOrders($params)
  1108. {
  1109. try {
  1110. if($params['userAddress']){
  1111. $lon_lat = get_address_lat_lng($params['userAddress']);
  1112. $params['lon'] = $lon_lat['lon'];
  1113. $params['lat'] = $lon_lat['lat'];
  1114. }
  1115. return ThirdOrderLogic::submitOrders($params);
  1116. }catch (\Exception $e) {
  1117. self::setError($e->getMessage());
  1118. return false;
  1119. }
  1120. }
  1121. /**
  1122. * 上门码和完成码
  1123. * @param $params
  1124. * @return false|array
  1125. */
  1126. public static function confirmDoorCode($params)
  1127. {
  1128. try {
  1129. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1130. if($work->isEmpty()){
  1131. throw new Exception('工单不存在');
  1132. }
  1133. $encryptedData = encrypt($params['work_sn'], \think\facade\Config::get('project.work_sn_key'));
  1134. $user_website = \think\facade\Config::get('project.user_website');
  1135. $type = $params['type']??1;
  1136. if($type == 1){
  1137. $user_website .= '?code='.$encryptedData;
  1138. }elseif($type == 2){
  1139. $user_website .= 'pages/quoted_price?code='.$encryptedData;
  1140. }
  1141. return ['url'=>$user_website];
  1142. }catch (\Exception $e) {
  1143. self::setError($e->getMessage());
  1144. return false;
  1145. }
  1146. }
  1147. /**
  1148. * 终止结束服务操作
  1149. */
  1150. public static function terminateService($params): bool
  1151. {
  1152. Db::startTrans();
  1153. try {
  1154. $serviceWork = ServiceWork::where('work_pay_status',1)
  1155. ->where('master_worker_id','>',0)
  1156. ->whereIn('work_status',[0,1,2,3,4,5,6])
  1157. ->where('id',$params['id'])->findOrEmpty();
  1158. if($serviceWork->isEmpty()){
  1159. throw new \Exception('该工单状态不可执行结束服务');
  1160. }
  1161. if($params['isearnest'] == 1){
  1162. $serviceWork->work_status = 7;
  1163. $serviceWork->user_confirm_status = 5;
  1164. $serviceWork->service_status = 3;
  1165. $serviceWork->work_pay_status = 1;
  1166. $serviceWork->finished_time = time();
  1167. $serviceWork->remark = ($serviceWork->remark?:'')." | 终止结束服务:常规流程";
  1168. $serviceWork->save();
  1169. }else{
  1170. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('payment_type', 1)->value('paid_amount');
  1171. if($paid_amount > 0){
  1172. // 存在上门费给工程师
  1173. Log::info('终止结束服务工单'.$serviceWork->id.',上门费:'.$paid_amount);
  1174. WorkerAccountLogLogic::addAccountLog($serviceWork,$paid_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
  1175. }
  1176. ServiceWork::where('id', $params['id'])->update([
  1177. 'work_status' => 7,
  1178. 'user_confirm_status' => 5,
  1179. 'service_status' => 3,
  1180. 'finished_time' => time(),
  1181. 'work_pay_status' => 2, // 已结算则不执行 onAfterUpdate
  1182. 'settlement_amount' => $paid_amount??0,
  1183. 'worker_price' => $paid_amount??0,
  1184. 'remark' => ($serviceWork->remark?:'')." | 终止结束服务:上门费-{$paid_amount}"
  1185. ]);
  1186. }
  1187. ServiceWorkLog::create([
  1188. 'work_id' => $params['id'],
  1189. 'master_worker_id' => $serviceWork->master_worker_id,
  1190. 'opera_log' => "工单:{$serviceWork->work_sn} 终止结束服务"
  1191. ]);
  1192. Db::commit();
  1193. Log::info('终止结束服务'.json_encode([$serviceWork]));
  1194. return true;
  1195. } catch (\Exception $e) {
  1196. Db::rollback();
  1197. self::setError($e->getMessage());
  1198. Log::info('终止结束服务-Error'.json_encode([$e->getMessage()]));
  1199. return false;
  1200. }
  1201. }
  1202. /**
  1203. * 工程师抢单
  1204. */
  1205. public static function grabOrder($params): bool
  1206. {
  1207. if(MasterWorkerLogic::isReceivingOrders($params['master_worker_id'])){
  1208. Log::info('抢单失败:工程师不能接单:'.$params['id'].'--'.$params['master_worker_id']);
  1209. self::setError('未达到接单条件');
  1210. return false;
  1211. }
  1212. Db::startTrans();
  1213. try {
  1214. // 抢单
  1215. $serviceWork = ServiceWork::where(['work_pay_status'=>1,'work_status'=>0,'service_status'=>0,'master_worker_id'=>0])
  1216. ->where('id',$params['id'])->update(['master_worker_id'=>$params['master_worker_id'],'work_status'=>1]);
  1217. Db::commit();
  1218. if($serviceWork == 1){
  1219. Log::info('抢单成功:'.$params['id'].'--'.$params['master_worker_id']);
  1220. $params['is_grab_order'] = 1;
  1221. self::allocateWorker($params,['admin_id'=>0,'name'=>'抢单工程师ID:'.$params['master_worker_id']]);
  1222. return true;
  1223. }else{
  1224. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id']);
  1225. self::setError('抢单失败');
  1226. return false;
  1227. }
  1228. } catch (\Exception $e) {
  1229. Db::rollback();
  1230. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id'].':'.$e->getMessage());
  1231. self::setError('抢单失败');
  1232. return false;
  1233. }
  1234. }
  1235. public static function appointmentAudit($params): bool
  1236. {
  1237. Db::startTrans();
  1238. try {
  1239. $work = ServiceWork::where('id',$params['work_id'])->findOrEmpty();
  1240. if($work->isEmpty()){
  1241. throw new \Exception('工单不存在');
  1242. }
  1243. $log = ServiceWorkAppointmentLog::where('id',$params['id'])->findOrEmpty();
  1244. if($log->isEmpty()){
  1245. throw new \Exception('审核记录不存在');
  1246. }
  1247. $master = MasterWorker::where('id',$log->worker_id)->findOrEmpty();
  1248. $log->status = $params['status'];
  1249. $log->remark = $params['remark'];
  1250. $log->save();
  1251. //预约时间修改审核通过则更新工单预约时间
  1252. if ($params['status'] == 1) {
  1253. //$work->work_status = 3;//待上门
  1254. $work->appointment_time = $log->this_appointment_time;
  1255. $work->save();
  1256. //添加变更日志
  1257. $work_log = [
  1258. 'work_id'=>$work->id,
  1259. 'master_worker_id'=>$log->worker_id,
  1260. 'opera_log'=>'编号['.$master->worker_number.']'.$master->real_name.'于'.$log->create_time.'联系了客户,确认了于'.date('Y-m-d H:i:s',$log->this_appointment_time).'预约上门',
  1261. ];
  1262. ServiceWorkLogLogic::add($work_log);
  1263. }
  1264. Db::commit();
  1265. return true;
  1266. } catch (\Exception $e) {
  1267. Db::rollback();
  1268. self::setError('预约时间审核失败');
  1269. return false;
  1270. }
  1271. }
  1272. }