ServiceWorkLogic.php 57 KB

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