ServiceWorkLogic.php 61 KB

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