ServiceWorkLogic.php 55 KB

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