ServiceWorkLogic.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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. MasterWorker::setWorktotal('inc',$params['master_worker_id']);
  489. $work->save();
  490. $work_log = [
  491. 'work_id'=>$work->id,
  492. 'master_worker_id'=>$work->master_worker_id,
  493. 'type' => isset($params['is_grab_order'])?3:0,
  494. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  495. ];
  496. ServiceWorkerAllocateWorkerLogic::add($work_log);
  497. Db::commit();
  498. //美团的订单更新履约状态为已分配
  499. if($work->third_type == 1){
  500. ThirdOrderLogic::updateorderfulfillinfo($work,ThirdTypeEnum::MEITUAN_MEITUAN);
  501. }
  502. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  503. $workDetail = ServiceWorkLogic::detail($params);
  504. $res = event('Notice', [
  505. 'scene_id' => 113,
  506. 'params' => [
  507. 'user_id' => $params['master_worker_id'],
  508. 'order_id' => $params['id'],
  509. 'thing9' => $workDetail['title'],
  510. 'time7' => $workDetail['appointment_time'],
  511. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  512. 'phone_number6' => asteriskString($workDetail['mobile']),
  513. ]
  514. ]);
  515. return true;
  516. }catch(\Exception $e){
  517. Db::rollback();
  518. self::setError($e->getMessage());
  519. return false;
  520. }
  521. }
  522. /**
  523. * 工单详情
  524. * @param $params
  525. * @return array|false
  526. */
  527. public static function detail($params){
  528. $work_where = !empty($params['work_sn'])?['work_sn'=>$params['work_sn']]:['id'=>$params['id']];
  529. $result = ServiceWork::with([
  530. 'worker'=> function(Query $query) {
  531. $query->field('id,worker_number,real_name,mobile');
  532. },
  533. 'allocateWorkerLog' =>function(Query $query){
  534. $query->field('id,work_id,opera_log,create_time');
  535. },
  536. 'serviceWorkLog' =>function(Query $query){
  537. $query->field('id,work_id,opera_log,create_time');
  538. }
  539. ])->append(['id','work_status_text','service_status_text'])
  540. ->where($work_where)
  541. ->findOrEmpty()->toArray();
  542. $result['is_operate_prohibit'] = 0;
  543. if(isset($params['user_id']) && $result['master_worker_id'] && $params['user_id'] && ($params['user_id'] != $result['master_worker_id']) ){
  544. // 带徒师傅的工单
  545. $lead_master_worker_id = TrainingWorkerTask::where('master_worker_id',$params['user_id'])->where('training_status',2)
  546. ->where('operate_status',0)->value('lead_master_worker_id');
  547. // 团队负责人编辑 工单池(包括已派队员) 工单
  548. if($params['user_info']['team_role'] == 1 && $params['user_info']['tenant_id'] == $result['tenant_id'] ){
  549. $result['is_operate_prohibit'] = 0;
  550. }elseif(!empty($lead_master_worker_id) && !empty($result['master_worker_id']) && $lead_master_worker_id == $result['master_worker_id']){
  551. // 徒查看师父的工单 不能编辑可查看
  552. $result['is_operate_prohibit'] = 1;
  553. }else{
  554. throw new \Exception('您没有权限操作该工单');
  555. }
  556. }
  557. //工程师工单按钮状态
  558. $work_service_status = 0;
  559. $work_service_status_text = '待派单';
  560. //工单状态
  561. if($result['work_status'] == 1){
  562. $work_service_status = 1;
  563. $work_service_status_text = '待领单';
  564. }
  565. if($result['work_status'] == 2){
  566. $work_service_status = 2;
  567. $work_service_status_text = '预约上门';
  568. }
  569. if($result['work_status'] == 3){
  570. $work_service_status = 3;
  571. $work_service_status_text = '等待上门';
  572. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  573. $work_service_status = 4;
  574. $work_service_status_text = '确认上门';
  575. }
  576. }
  577. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  578. $work_service_status = 5;
  579. $work_service_status_text = '确认报价';
  580. }
  581. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  582. $work_service_status = 6;
  583. $work_service_status_text = '用户确认报价中';
  584. }
  585. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  586. $work_service_status = 7;
  587. $work_service_status_text = '完成服务';
  588. }
  589. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  590. $work_service_status = 8;
  591. $work_service_status_text = '用户确认完成服务中';
  592. }
  593. if($result['work_status'] ==6){
  594. $work_service_status = 9;
  595. $work_service_status_text = '待结算';
  596. }
  597. if($result['work_status'] ==7){
  598. $work_service_status = 10;
  599. $work_service_status_text = '已完结';
  600. }
  601. if($result['work_status'] ==8){
  602. $work_service_status = 11;
  603. $work_service_status_text = '已评价';
  604. }
  605. if($result['work_status'] ==9){
  606. $work_service_status = 12;
  607. $work_service_status_text = '已退费';
  608. }
  609. $result['work_service_status'] = $work_service_status;
  610. $result['work_service_status_text'] = $work_service_status_text;
  611. //搜索当前工单下的所有订单记录
  612. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  613. $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']);
  614. }])->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();
  615. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  616. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  617. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  618. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  619. $coupon_price = 0;
  620. foreach ($result['pay_orders'] as $k=>&$v){
  621. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  622. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  623. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  624. $v['order_type_name'] = $order_type_data[$v['order_type']];
  625. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  626. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  627. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  628. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  629. }
  630. $coupon_price += $v['coupon_price'];
  631. //服务支付类别
  632. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  633. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  634. }
  635. }
  636. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  637. //汇总优惠卷额度
  638. $result['coupon_price'] = $coupon_price;
  639. //工单总支付金额
  640. $result['worker_account'] = $result['work_amount'];
  641. // 配件信息
  642. $result['spare_parts'] = [];
  643. $result['self_spare_parts'] = [];
  644. if($result['spare_total'] > 0){
  645. $result['spare_parts'] = ServiceWorkSpare::getLists($result['id'], 1);
  646. $result['self_spare_parts'] = ServiceWorkSpare::getLists($result['id'], 2);
  647. }
  648. // 保修卡信息
  649. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  650. $query->with(['goodsCategory'=>function ($query1) {
  651. $query1->field(['name','picture']);
  652. }]);
  653. }])->where('work_id',$result['id'])
  654. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  655. ->append(['effective_unit_text'])
  656. ->order('create_time desc')
  657. ->select()
  658. ->toArray();
  659. //查收工程师提成金额
  660. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  661. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  662. //质保金相关金额
  663. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  664. ->each(function ($item){
  665. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  666. })->toArray();
  667. //保修工单时的信息
  668. $result['effective_income_amount'] = 0;
  669. if(!empty($result['order_effective_id'])){
  670. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  671. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  672. if($serviceWork->master_worker_id != $result['master_worker_id']){
  673. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  674. }
  675. }
  676. //获取美团订单信息
  677. $result['meituan_order'] = [];
  678. if($result['third_type']==1){
  679. $result['meituan_order'] = ThirdOrders::where(['work_id'=>$result['id']])->order('create_time desc')->findOrEmpty();
  680. }
  681. //工程师预约时间修改申请记录
  682. if (!empty($params['user_id'])) {
  683. $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();
  684. if ($result['appointment_log']){
  685. $result['appointment_log']['last_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['last_appointment_time']);
  686. $result['appointment_log']['this_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['this_appointment_time']);
  687. }
  688. }
  689. return $result;
  690. }
  691. public static function getUserCouponDetails($params)
  692. {
  693. try{
  694. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  695. if(!$work){
  696. throw new \Exception('工单不存在');
  697. }
  698. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  699. ->where('voucher_count','>',0)
  700. ->where('voucher_status',0)
  701. ->where('expire_time','>',time())
  702. ->column('coupon_id');
  703. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  704. $data = UserCoupon::where('user_id',$work['user_id'])
  705. ->where('voucher_count','>',0)
  706. ->where('voucher_status',0)
  707. ->whereIn('coupon_id',$coupon_ids)
  708. ->append(['discount_ratio_text'])
  709. ->where('expire_time','>',time())
  710. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  711. ->select()->toArray();
  712. foreach($data as $k => $v){
  713. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  714. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  715. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  716. }
  717. return $data;
  718. } catch(\Exception $e){
  719. self::setError($e->getMessage());
  720. return false;
  721. }
  722. }
  723. public static function getDetailWorkServiceStatus($params)
  724. {
  725. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  726. //工程师工单按钮状态
  727. $work_service_status = 0;
  728. //工单状态
  729. if($result['work_status'] == 1){
  730. $work_service_status = 1;
  731. }
  732. if($result['work_status'] == 2){
  733. $work_service_status = 2;
  734. }
  735. if($result['work_status'] == 3){
  736. $work_service_status = 3;
  737. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  738. $work_service_status = 4;
  739. }
  740. }
  741. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  742. $work_service_status = 5;
  743. }
  744. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  745. $work_service_status = 6;
  746. }
  747. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  748. $work_service_status = 7;
  749. }
  750. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  751. $work_service_status = 8;
  752. }
  753. if($result['work_status'] ==6){
  754. $work_service_status = 9;
  755. }
  756. if($result['work_status'] ==7){
  757. $work_service_status = 10;
  758. }
  759. if($result['work_status'] ==8){
  760. $work_service_status = 11;
  761. }
  762. if($result['work_status'] ==9){
  763. $work_service_status = 12;
  764. }
  765. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  766. }
  767. /**
  768. * @notes 取消操作
  769. * @param array $params
  770. * @return bool
  771. * @author likeadmin
  772. * @date 2024/09/19 10:48
  773. */
  774. public static function cancel(array $params): bool
  775. {
  776. Db::startTrans();
  777. try {
  778. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  779. $serviceWorkInfo = ServiceWork::find($params['id']);
  780. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  781. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  782. }
  783. //工单如果存在费用情况,不允许取消
  784. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  785. if($paid_amount > 0 and ($serviceWorkInfo['third_type'] == 0 && $serviceWorkInfo['external_platform_id'] == 0)){
  786. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  787. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  788. }
  789. ServiceWork::where('id', $params['id'])->update([
  790. 'work_status' => 9,
  791. 'service_status' => 4
  792. ]);
  793. ServiceWorkLog::create([
  794. 'work_id' => $params['id'],
  795. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  796. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消".($params['remark']??'')
  797. ]);
  798. Db::commit();
  799. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  800. return true;
  801. } catch (\Exception $e) {
  802. Db::rollback();
  803. self::setError($e->getMessage());
  804. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  805. return false;
  806. }
  807. }
  808. /**
  809. * @notes 工程师结算操作
  810. * @param array $params
  811. * @return bool
  812. * @author likeadmin
  813. * @date 2024/09/19 10:48
  814. */
  815. public static function settlement(array $params): bool
  816. {
  817. Db::startTrans();
  818. try {
  819. $serviceWorkInfo = ServiceWork::find($params['id']);
  820. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  821. throw new \Exception('该工单非待结算状态');
  822. }
  823. $ratio = 0;
  824. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  825. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  826. if($commissionConfig->isEmpty() || empty($ratio)){
  827. //获取工单对应的商品id
  828. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  829. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  830. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  831. if($rule->isEmpty()){
  832. throw new \Exception('请配置商品业绩规则');
  833. }
  834. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  835. }else{
  836. // 存在服务分类比例进行结算
  837. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  838. }
  839. Db::commit();
  840. return true;
  841. } catch (\Exception $e) {
  842. Db::rollback();
  843. self::setError($e->getMessage());
  844. return false;
  845. }
  846. }
  847. /**
  848. * 工程师配件审核结算操作
  849. * @param array $params
  850. * @return bool
  851. * @author liugc <466014217@qq.com>
  852. * @date 2025/5/9 9:14
  853. */
  854. public static function settlementSpare(array $params): bool
  855. {
  856. Db::startTrans();
  857. try {
  858. $spare = ServiceWorkSpare::where('id',$params['id'])->findOrEmpty();
  859. if($spare->isEmpty()){
  860. throw new \Exception('无配件审核');
  861. }else{
  862. $serviceWorkInfo = ServiceWork::find($spare->service_work_id);
  863. Log::info( '配件审核结算'.json_encode([$serviceWorkInfo['work_pay_status']]));
  864. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  865. throw new \Exception('该工单非待结算状态');
  866. }
  867. $spare->status = $params['status']??0;
  868. $spare->remark = $params['remark']??'';
  869. $spare->save();
  870. }
  871. Db::commit();
  872. // 是否所有配件审核完成
  873. SparePartLogic::isExamineOk($spare->service_work_id);
  874. return true;
  875. } catch (\Exception $e) {
  876. Db::rollback();
  877. self::setError($e->getMessage());
  878. return false;
  879. }
  880. }
  881. /**
  882. * 获取所有改约通知
  883. * @param $userId
  884. * @return array|false
  885. */
  886. public static function getAppointmentNotice($userId)
  887. {
  888. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  889. ->where('work_status','>',1)
  890. ->where('work_status','<',7)
  891. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  892. ->order(['appointment_time' => 'asc'])//上门时间排序
  893. ->select()->each(function (&$item){
  894. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  895. })
  896. ->toArray();
  897. }
  898. /**
  899. * @param $params
  900. * @return bool
  901. */
  902. public static function submitAppointment($params)
  903. {
  904. Db::startTrans();
  905. try {
  906. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  907. if($serviceWork->isEmpty()){
  908. throw new \Exception('工单不存在');
  909. }
  910. $serviceWork->appoint_approval = 2;
  911. $serviceWork->save();
  912. Db::commit();
  913. return true;
  914. } catch (\Exception $e) {
  915. Db::rollback();
  916. self::setError($e->getMessage());
  917. return false;
  918. }
  919. }
  920. /**
  921. * @param $params
  922. * @return bool
  923. */
  924. public static function submitChangePrice($params)
  925. {
  926. Db::startTrans();
  927. try {
  928. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  929. if($serviceWork->isEmpty()){
  930. throw new \Exception('工单不存在');
  931. }
  932. $serviceWork->work_status = 4;
  933. $serviceWork->user_confirm_status = 0;
  934. $serviceWork->price_approval = 2;
  935. $serviceWork->save();
  936. Db::commit();
  937. return true;
  938. } catch (\Exception $e) {
  939. Db::rollback();
  940. self::setError($e->getMessage());
  941. return false;
  942. }
  943. }
  944. public static function notApproved($params)
  945. {
  946. Db::startTrans();
  947. try {
  948. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  949. if($serviceWork->isEmpty()){
  950. throw new \Exception('工单不存在');
  951. }
  952. $serviceWork->refund_approval = 3;
  953. $serviceWork->save();
  954. Db::commit();
  955. return true;
  956. } catch (\Exception $e) {
  957. Db::rollback();
  958. self::setError($e->getMessage());
  959. return false;
  960. }
  961. }
  962. public static function againDoor($params)
  963. {
  964. Db::startTrans();
  965. try {
  966. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  967. if($serviceWork->isEmpty()){
  968. throw new \Exception('工单不存在');
  969. }
  970. //更新预约日志
  971. //更新工单未确认上门的状态
  972. $serviceWork->work_status = 3;
  973. $serviceWork->user_confirm_status = 0;
  974. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  975. if($appoint > 2){
  976. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  977. }
  978. ServiceWorkAppointmentLog::create([
  979. 'work_id'=>$serviceWork->id,
  980. 'worker_id'=>$params['user_id'],
  981. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  982. 'this_appointment_time'=>strtotime($params['appointment_time']),
  983. ]);
  984. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  985. $serviceWork->save();
  986. Db::commit();
  987. return true;
  988. } catch (\Exception $e) {
  989. Db::rollback();
  990. self::setError($e->getMessage());
  991. return false;
  992. }
  993. }
  994. public static function cancelAllocation($params,$userInfo){
  995. Db::startTrans();
  996. try {
  997. $work = ServiceWork::findOrEmpty($params['id']);
  998. if($work->isEmpty()){
  999. throw new Exception('工单不存在');
  1000. }
  1001. if($work->work_status >=6 ){
  1002. throw new \Exception('工单状态只能修改待结算之前的');
  1003. }
  1004. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  1005. if($worker->isEmpty()){
  1006. throw new \Exception('工程师不存在');
  1007. }
  1008. if ($work->tenant_id > 0) {
  1009. //团队订单取消时,派单数量减1
  1010. $updateData = date("H",strtotime($work->appointment_time)) < 12 ? ['am_order' => Db::raw('am_order - 1')] : ['pm_order' => Db::raw('pm_order - 1')];
  1011. MasterWorkerTeam::where('master_worker_id',$work->master_worker_id)->where('tenant_id',$work->tenant_id)->update($updateData);
  1012. }
  1013. $params['master_worker_id'] = (isset($params['master_worker_id']) && !empty($params['master_worker_id']))?$params['master_worker_id']:$work->master_worker_id;
  1014. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  1015. $work->master_worker_id = 0;
  1016. $work->tenant_id = 0;
  1017. $work->work_status = 0;
  1018. $work->dispatch_time = 0;
  1019. $work->first_contact_time = 0;
  1020. $work->estimated_finish_time = 0;
  1021. $work->save();
  1022. $work_log = [
  1023. 'work_id'=>$work->id,
  1024. 'master_worker_id'=>$params['master_worker_id'],
  1025. 'type' => 1,
  1026. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  1027. ];
  1028. ServiceWorkerAllocateWorkerLogic::add($work_log);
  1029. Db::commit();
  1030. return true;
  1031. }catch(\Exception $e){
  1032. Db::rollback();
  1033. self::setError($e->getMessage());
  1034. return false;
  1035. }
  1036. }
  1037. public static function addCustomerLog($params)
  1038. {
  1039. Db::startTrans();
  1040. try {
  1041. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1042. if($serviceWork->isEmpty()){
  1043. throw new \Exception('工单不存在');
  1044. }
  1045. ServiceWorkCustomerLog::create([
  1046. 'work_id'=>$serviceWork->id,
  1047. 'type'=>$params['type']??0,
  1048. 'content'=>$params['content']??'',
  1049. 'admin_id'=>$params['admin_id']??0,
  1050. 'create_time'=>time(),
  1051. ]);
  1052. Db::commit();
  1053. return true;
  1054. } catch (\Exception $e) {
  1055. Db::rollback();
  1056. self::setError($e->getMessage());
  1057. return false;
  1058. }
  1059. }
  1060. public static function distributeTenants($params,$userInfo)
  1061. {
  1062. Db::startTrans();
  1063. try {
  1064. if(empty($params['id']) || empty($params['tenant_id'])){
  1065. throw new \Exception('参数错误'.json_encode($params));
  1066. }
  1067. if (is_array($params['id'])) {
  1068. $ids = $params['id'];
  1069. } else{
  1070. $ids = [$params['id']];
  1071. }
  1072. // 取消工程师分配
  1073. foreach ($ids as $id) {
  1074. $res = self::cancelAllocation(['id'=>$id,'master_worker_id'=>''],$userInfo);
  1075. if($res === false){
  1076. Log::info('分配log'.self::getError());
  1077. }
  1078. }
  1079. ServiceWork::whereIn('id',$ids)->update(['tenant_id'=>$params['tenant_id']]);
  1080. Db::commit();
  1081. return true;
  1082. } catch (\Exception $e) {
  1083. Db::rollback();
  1084. self::setError($e->getMessage());
  1085. return false;
  1086. }
  1087. }
  1088. /**
  1089. *
  1090. * @return false|void
  1091. */
  1092. public static function contactCustomer($params)
  1093. {
  1094. try {
  1095. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1096. if($work->isEmpty()){
  1097. throw new \Exception('工单不存在');
  1098. }
  1099. if (empty($work->first_contact_time)) {
  1100. $work->first_contact_time = time();
  1101. $work->save();
  1102. }
  1103. return ['middleNumber' => $work->mobile];
  1104. if ($middleNumber = Cache::get('WORKER_MIDDLE_NUMBER_'.$work->id)) {
  1105. return ['middleNumber' => $middleNumber];
  1106. }
  1107. $worker_mobile = $params['user_info']['mobile'];
  1108. $res = VirtualCallService::auth($worker_mobile, $work->mobile, 60);
  1109. if (isset($res['result']) && $res['result'] == '000000') {
  1110. Cache::set('WORKER_MIDDLE_NUMBER_'.$work->id, $res['middleNumber'], 60); //缓存60秒
  1111. return ['middleNumber' => $res['middleNumber']];
  1112. } else {
  1113. Log::info('虚拟外呼失败:'.json_encode($res));
  1114. throw new \Exception('虚拟外呼失败');
  1115. }
  1116. return true;
  1117. }
  1118. catch (\Exception $e) {
  1119. Db::rollback();
  1120. self::setError($e->getMessage());
  1121. return false;
  1122. }
  1123. }
  1124. /**
  1125. * 添加第三方平台订单
  1126. * @return false|void
  1127. */
  1128. public static function addThirdPlatformsOrders($params)
  1129. {
  1130. try {
  1131. if($params['userAddress']){
  1132. $lon_lat = get_address_lat_lng($params['userAddress']);
  1133. $params['lon'] = $lon_lat['lon'];
  1134. $params['lat'] = $lon_lat['lat'];
  1135. }
  1136. return ThirdOrderLogic::submitOrders($params);
  1137. }catch (\Exception $e) {
  1138. self::setError($e->getMessage());
  1139. return false;
  1140. }
  1141. }
  1142. /**
  1143. * 上门码和完成码
  1144. * @param $params
  1145. * @return false|array
  1146. */
  1147. public static function confirmDoorCode($params)
  1148. {
  1149. try {
  1150. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1151. if($work->isEmpty()){
  1152. throw new Exception('工单不存在');
  1153. }
  1154. $encryptedData = encrypt($params['work_sn'], \think\facade\Config::get('project.work_sn_key'));
  1155. $user_website = \think\facade\Config::get('project.user_website');
  1156. $quoted_price = env('project.quoted_price')?:$user_website.'pages/quoted_price';
  1157. $type = $params['type']??1;
  1158. if($type == 1){
  1159. $user_website .= '?code='.$encryptedData;
  1160. }elseif($type == 2){
  1161. $user_website = $quoted_price.'?code='.$encryptedData;
  1162. }
  1163. return ['url'=>$user_website];
  1164. }catch (\Exception $e) {
  1165. self::setError($e->getMessage());
  1166. return false;
  1167. }
  1168. }
  1169. /**
  1170. * 终止结束服务操作
  1171. */
  1172. public static function terminateService($params): bool
  1173. {
  1174. Db::startTrans();
  1175. try {
  1176. $serviceWork = ServiceWork::where('work_pay_status',1)
  1177. ->where('master_worker_id','>',0)
  1178. ->whereIn('work_status',[0,1,2,3,4,5,6])
  1179. ->where('id',$params['id'])->findOrEmpty();
  1180. if($serviceWork->isEmpty()){
  1181. throw new \Exception('该工单状态不可执行结束服务');
  1182. }
  1183. if($params['isearnest'] == 1){
  1184. $serviceWork->work_status = 7;
  1185. $serviceWork->user_confirm_status = 5;
  1186. $serviceWork->service_status = 3;
  1187. $serviceWork->work_pay_status = 1;
  1188. $serviceWork->finished_time = time();
  1189. $serviceWork->remark = ($serviceWork->remark?:'')." | 终止结束服务:常规流程";
  1190. $serviceWork->save();
  1191. }else{
  1192. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('payment_type', 1)->value('paid_amount');
  1193. if($paid_amount > 0){
  1194. // 存在上门费给工程师
  1195. Log::info('终止结束服务工单'.$serviceWork->id.',上门费:'.$paid_amount);
  1196. WorkerAccountLogLogic::addAccountLog($serviceWork,$paid_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
  1197. }
  1198. ServiceWork::where('id', $params['id'])->update([
  1199. 'work_status' => 7,
  1200. 'user_confirm_status' => 5,
  1201. 'service_status' => 3,
  1202. 'finished_time' => time(),
  1203. 'work_pay_status' => 2, // 已结算则不执行 onAfterUpdate
  1204. 'settlement_amount' => $paid_amount??0,
  1205. 'worker_price' => $paid_amount??0,
  1206. 'remark' => ($serviceWork->remark?:'')." | 终止结束服务:上门费-{$paid_amount}"
  1207. ]);
  1208. }
  1209. ServiceWorkLog::create([
  1210. 'work_id' => $params['id'],
  1211. 'master_worker_id' => $serviceWork->master_worker_id,
  1212. 'opera_log' => "工单:{$serviceWork->work_sn} 终止结束服务"
  1213. ]);
  1214. Db::commit();
  1215. Log::info('终止结束服务'.json_encode([$serviceWork]));
  1216. return true;
  1217. } catch (\Exception $e) {
  1218. Db::rollback();
  1219. self::setError($e->getMessage());
  1220. Log::info('终止结束服务-Error'.json_encode([$e->getMessage()]));
  1221. return false;
  1222. }
  1223. }
  1224. /**
  1225. * 工程师抢单
  1226. */
  1227. public static function grabOrder($params): bool
  1228. {
  1229. if(!MasterWorkerLogic::isReceivingOrders($params['master_worker_id'])){
  1230. Log::info('抢单失败:工程师不能接单:'.$params['id'].'--'.$params['master_worker_id']);
  1231. self::setError('未达到接单条件');
  1232. return false;
  1233. }
  1234. $serviceWork = 0;
  1235. Db::startTrans();
  1236. try {
  1237. // 抢单
  1238. $serviceWork = ServiceWork::where(['work_pay_status'=>1,'work_status'=>0,'service_status'=>0,'master_worker_id'=>0])
  1239. ->where('id',$params['id'])->update(['master_worker_id'=>$params['master_worker_id'],'work_status'=>1]);
  1240. Db::commit();
  1241. } catch (\Exception $e) {
  1242. Db::rollback();
  1243. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id'].':'.$e->getMessage());
  1244. self::setError('抢单失败');
  1245. return false;
  1246. }
  1247. if($serviceWork == 1){
  1248. Log::info('抢单成功:'.$params['id'].'--'.$params['master_worker_id']);
  1249. $params['is_grab_order'] = 1;
  1250. self::allocateWorker($params,['admin_id'=>0,'name'=>'抢单工程师ID:'.$params['master_worker_id']]);
  1251. return true;
  1252. }else{
  1253. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id']);
  1254. self::setError('抢单失败');
  1255. return false;
  1256. }
  1257. }
  1258. /**
  1259. * 给用户发券
  1260. */
  1261. public static function userAddVoucher($params): bool
  1262. {
  1263. try {
  1264. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1265. if(!$serviceWork->isEmpty()){
  1266. $codes = [];
  1267. foreach ($params['coupon_data'] as $coupon_data) {
  1268. $coupon_data['code'] && $codes[] = $coupon_data['code'];
  1269. }
  1270. if($codes){
  1271. UserCouponLogic::grant($codes,$serviceWork->user_id,$serviceWork->id);
  1272. }
  1273. }
  1274. return true;
  1275. } catch (\Exception $e) {
  1276. self::setError($e->getMessage());
  1277. return false;
  1278. }
  1279. }
  1280. /**
  1281. * 给用户加单
  1282. */
  1283. public static function userExtendOrder($params): bool
  1284. {
  1285. try {
  1286. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1287. if(!$serviceWork->isEmpty()){
  1288. $worker_number = MasterWorker::where('id',$serviceWork->master_worker_id)->value('worker_number');
  1289. //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
  1290. $res = ServiceOrderLogic::submitOrder([
  1291. 'goods_id' => $params['goods_id'],
  1292. 'user_info' => [
  1293. 'mobile' => $serviceWork->mobile
  1294. ],
  1295. 'user_id' => $serviceWork->user_id,
  1296. 'coupon_id' => 0,
  1297. 'worker' => $worker_number,
  1298. 'terminal' => 1,
  1299. 'pay_way' => 2,
  1300. 'appointment_time' => $serviceWork->appointment_time,
  1301. 'address' => $serviceWork->address,
  1302. 'contact_people' => $serviceWork->real_name,
  1303. 'contact_number' => $serviceWork->mobile,
  1304. 'lon' => $serviceWork->lon,
  1305. 'lat' => $serviceWork->lat,
  1306. 'property_activity_id' => 0
  1307. ]);
  1308. if($res == false){
  1309. throw new \Exception(ServiceOrderLogic::getError());
  1310. }
  1311. }
  1312. return true;
  1313. } catch (\Exception $e) {
  1314. self::setError($e->getMessage());
  1315. return false;
  1316. }
  1317. }
  1318. public static function appointmentAudit($params): bool
  1319. {
  1320. Db::startTrans();
  1321. try {
  1322. $work = ServiceWork::where('id',$params['work_id'])->findOrEmpty();
  1323. if($work->isEmpty()){
  1324. throw new \Exception('工单不存在');
  1325. }
  1326. $log = ServiceWorkAppointmentLog::where('id',$params['id'])->findOrEmpty();
  1327. if($log->isEmpty()){
  1328. throw new \Exception('审核记录不存在');
  1329. }
  1330. $master = MasterWorker::where('id',$log->worker_id)->findOrEmpty();
  1331. $log->status = $params['status'];
  1332. $log->remark = $params['remark'];
  1333. $log->save();
  1334. //预约时间修改审核通过则更新工单预约时间
  1335. if ($params['status'] == 2) {
  1336. //$work->work_status = 3;//待上门
  1337. $work->appointment_time = $log->this_appointment_time;
  1338. $work->save();
  1339. //添加变更日志
  1340. $work_log = [
  1341. 'work_id'=>$work->id,
  1342. 'master_worker_id'=>$log->worker_id,
  1343. 'opera_log'=>'编号['.$master->worker_number.']'.$master->real_name.'于'.$log->create_time.'联系了客户,确认了于'.date('Y-m-d H:i:s',$log->this_appointment_time).'预约上门',
  1344. ];
  1345. ServiceWorkLogLogic::add($work_log);
  1346. }
  1347. Db::commit();
  1348. return true;
  1349. } catch (\Exception $e) {
  1350. Db::rollback();
  1351. self::setError('预约时间审核失败');
  1352. return false;
  1353. }
  1354. }
  1355. }