ServiceWorkLogic.php 54 KB

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