ServiceWorkLogic.php 61 KB

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