1
0

ServiceWorkLogic.php 54 KB

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