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