ServiceWorkLogic.php 59 KB

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