ServiceWorkLogic.php 56 KB

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