ServiceWorkLogic.php 63 KB

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