ServiceWorkLogic.php 55 KB

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