ServiceWorkLogic.php 50 KB

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