1
0

ServiceWorkLogic.php 59 KB

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