ServiceWorkLogic.php 61 KB

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