ServiceWorkLogic.php 51 KB

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