ServiceWorkLogic.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  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->work_status = 5;
  381. $work->user_confirm_status = 2;
  382. $work->price_approval = 0;
  383. $work->save();
  384. //添加变更日志
  385. $work_log = [
  386. 'work_id'=>$work->id,
  387. 'master_worker_id'=>$work->master_worker_id,
  388. '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()).'提交了报价单',
  389. ];
  390. ServiceWorkLogLogic::add($work_log);
  391. Db::commit();
  392. // 商家报价通知外部平台 即报价
  393. if($work->external_platform_id > 0){
  394. event('ExternalPlatform', [
  395. 'send_code' => 1006,
  396. 'params' => [
  397. 'work_id' => $work->id,
  398. ]
  399. ]);
  400. }
  401. }
  402. catch (\Exception $e) {
  403. Db::rollback();
  404. self::setError($e->getMessage());
  405. return false;
  406. }
  407. }
  408. /**
  409. * 工程师修改自选配件的图片
  410. * @param $params
  411. * @return false|void
  412. */
  413. public static function selfSparePart($params)
  414. {
  415. Db::startTrans();
  416. try {
  417. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  418. if($work->isEmpty()){
  419. throw new Exception('工单不存在');
  420. }
  421. $audit = ServiceWorkSpare::where(['id' => $params['id'],'service_work_id'=>$work['id']])->findOrEmpty();
  422. if(!$audit->isEmpty() && ($audit['status']!=0 && $audit['status']!=2) ){
  423. throw new Exception('当前工单配件不允许修改');
  424. }
  425. if (empty($params['spare_image'])){
  426. throw new Exception('请上传配件图片');
  427. }
  428. //修改
  429. ServiceWorkSpare::where("id",$params['id'])->where('service_work_id', $work['id'])->update(['spare_image' => $params['spare_image'], 'status' => 0]);
  430. Db::commit();
  431. return true;
  432. } catch (\Exception $e) {
  433. Db::rollback();
  434. self::setError($e->getMessage());
  435. return false;
  436. }
  437. }
  438. /**
  439. * 工程师确认服务完成
  440. * @param $params
  441. * @return false|void
  442. */
  443. public static function confirmServiceFinish($params)
  444. {
  445. Db::startTrans();
  446. try {
  447. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  448. if($work->isEmpty()){
  449. throw new Exception('工单不存在');
  450. }
  451. if($work->user_confirm_status !=2){
  452. throw new Exception('请勿重复操作');
  453. }
  454. $work->finished_images = $params['finished_images'];
  455. $work->user_confirm_status = 3;//待确认服务完成
  456. $work->save();
  457. //添加变更日志
  458. $work_log = [
  459. 'work_id'=>$work->id,
  460. 'master_worker_id'=>$work->master_worker_id,
  461. '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()).'提交了待用户确认服务完成',
  462. ];
  463. ServiceWorkLogLogic::add($work_log);
  464. Db::commit();
  465. /*$rechargeOrder = \app\common\model\orders\RechargeOrder::where('work_id',$work->id)
  466. ->where('payment_type',0)
  467. ->where('pay_status',1)
  468. ->findOrEmpty();
  469. if(!$rechargeOrder->isEmpty()){
  470. ServiceOrderLogic::confirmServiceFinish([
  471. 'user_id'=>$work->user_id,
  472. 'sn'=>$rechargeOrder->sn,
  473. 'user_info'=>[
  474. 'real_name'=>$work->real_name,
  475. ]
  476. ]);
  477. }*/
  478. ServiceOrderLogic::confirmServiceFinish([
  479. 'user_id'=>$work->user_id,
  480. 'sn'=>$rechargeOrder->sn,
  481. 'user_info'=>[
  482. 'real_name'=>$work->real_name,
  483. ]
  484. ]);
  485. // 外部平台工单 - 通知外边平台
  486. if($work->external_platform_id > 0){
  487. ExternalPlatformLogic::generalServiceWork('1003',['work_id' => $work->id]);
  488. }
  489. } catch (\Exception $e) {
  490. Db::rollback();
  491. self::setError($e->getMessage());
  492. return false;
  493. }
  494. }
  495. public static function allocateWorker($params,$userInfo){
  496. Db::startTrans();
  497. try {
  498. $work = ServiceWork::findOrEmpty($params['id']);
  499. if($work->isEmpty()){
  500. throw new Exception('工单不存在');
  501. }
  502. if($work->work_status >=6 ){
  503. throw new \Exception('工单状态只能修改待结算之前的');
  504. }
  505. if($work->master_worker_id == $params['master_worker_id'] && !isset($params['is_grab_order'])){
  506. throw new \Exception('分配的工程师相同');
  507. }
  508. $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'is_disable' =>0])->findOrEmpty();
  509. if($worker->isEmpty()){
  510. throw new \Exception('工程师不存在或被禁用');
  511. }
  512. if($worker->master_worker_id && !isset($params['is_grab_order'])){
  513. MasterWorker::setWorktotal('dec',$worker->master_worker_id);
  514. }
  515. $work->master_worker_id = $params['master_worker_id'];
  516. $work->work_status = 1;
  517. $work->dispatch_time = time();
  518. //长期合作工程师,派单即领单
  519. if ($worker->type == 2){
  520. $work->work_status = 2;
  521. $work->receive_time = time();
  522. }
  523. MasterWorker::setWorktotal('inc',$params['master_worker_id']);
  524. $work->save();
  525. $work_log = [
  526. 'work_id'=>$work->id,
  527. 'master_worker_id'=>$work->master_worker_id,
  528. 'type' => isset($params['is_grab_order'])?3:0,
  529. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  530. ];
  531. ServiceWorkerAllocateWorkerLogic::add($work_log);
  532. Db::commit();
  533. $work->id && OnlineCustomerService::customerClsMessage('servicework',$work->id);
  534. // 外部平台工单 - 通知外边平台
  535. if($work->external_platform_id > 0){
  536. ExternalPlatformLogic::generalServiceWork('1003',['work_id' => $work->id]);
  537. }
  538. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  539. $workDetail = ServiceWorkLogic::detail($params);
  540. $res = event('Notice', [
  541. 'scene_id' => 113,
  542. 'params' => [
  543. 'user_id' => $params['master_worker_id'],
  544. 'order_id' => $params['id'],
  545. 'thing9' => $workDetail['title'],
  546. 'time7' => $workDetail['appointment_time'],
  547. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  548. 'phone_number6' => asteriskString($workDetail['mobile']),
  549. ]
  550. ]);
  551. return true;
  552. }catch(\Exception $e){
  553. Db::rollback();
  554. self::setError($e->getMessage());
  555. return false;
  556. }
  557. }
  558. /**
  559. * 工单详情
  560. * @param $params
  561. * @return array|false
  562. */
  563. public static function detail($params){
  564. $work_where = !empty($params['work_sn'])?['work_sn'=>$params['work_sn']]:['id'=>$params['id']];
  565. $result = ServiceWork::with([
  566. 'worker'=> function(Query $query) {
  567. $query->field('id,worker_number,real_name,mobile,type');
  568. },
  569. 'allocateWorkerLog' =>function(Query $query){
  570. $query->field('id,work_id,opera_log,create_time');
  571. },
  572. 'serviceWorkLog' =>function(Query $query){
  573. $query->field('id,work_id,opera_log,create_time');
  574. }
  575. ])->append(['id','work_status_text','service_status_text','external_platform_text'])
  576. ->where($work_where)
  577. ->findOrEmpty()->toArray();
  578. $result['is_operate_prohibit'] = 0;
  579. if(isset($params['user_id']) && $result['master_worker_id'] && $params['user_id'] && ($params['user_id'] != $result['master_worker_id']) ){
  580. // 带徒师傅的工单
  581. $lead_master_worker_id = TrainingWorkerTask::where('master_worker_id',$params['user_id'])->where('training_status',2)
  582. ->where('operate_status',0)->value('lead_master_worker_id');
  583. // 团队负责人编辑 工单池(包括已派队员) 工单
  584. if($params['user_info']['team_role'] == 1 && $params['user_info']['tenant_id'] == $result['tenant_id'] ){
  585. $result['is_operate_prohibit'] = 0;
  586. }elseif(!empty($lead_master_worker_id) && !empty($result['master_worker_id']) && $lead_master_worker_id == $result['master_worker_id']){
  587. // 徒查看师父的工单 不能编辑可查看
  588. $result['is_operate_prohibit'] = 1;
  589. }else{
  590. throw new \Exception('您没有权限操作该工单');
  591. }
  592. }
  593. //工程师工单按钮状态
  594. $work_service_status = 0;
  595. $work_service_status_text = '待派单';
  596. //工单状态
  597. if($result['work_status'] == 1){
  598. $work_service_status = 1;
  599. $work_service_status_text = '待领单';
  600. }
  601. if($result['work_status'] == 2){
  602. $work_service_status = 2;
  603. $work_service_status_text = '预约上门';
  604. }
  605. if($result['work_status'] == 3){
  606. $work_service_status = 3;
  607. $work_service_status_text = '等待上门';
  608. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  609. $work_service_status = 4;
  610. $work_service_status_text = '确认上门';
  611. }
  612. }
  613. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  614. $work_service_status = 5;
  615. $work_service_status_text = '确认报价';
  616. }
  617. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  618. $work_service_status = 6;
  619. $work_service_status_text = '用户确认报价中';
  620. }
  621. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  622. $work_service_status = 7;
  623. $work_service_status_text = '完成服务';
  624. }
  625. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  626. $work_service_status = 8;
  627. $work_service_status_text = '用户确认完成服务中';
  628. }
  629. if($result['work_status'] ==6){
  630. $work_service_status = 9;
  631. $work_service_status_text = '待结算';
  632. }
  633. if($result['work_status'] ==7){
  634. $work_service_status = 10;
  635. $work_service_status_text = '已完结';
  636. }
  637. if($result['work_status'] ==8){
  638. $work_service_status = 11;
  639. $work_service_status_text = '已评价';
  640. }
  641. if($result['work_status'] ==9){
  642. $work_service_status = 12;
  643. $work_service_status_text = '已退费';
  644. }
  645. $result['work_service_status'] = $work_service_status;
  646. $result['work_service_status_text'] = $work_service_status_text;
  647. //搜索当前工单下的所有订单记录
  648. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  649. $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']);
  650. }])->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();
  651. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  652. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  653. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  654. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  655. $coupon_price = 0;
  656. foreach ($result['pay_orders'] as $k=>&$v){
  657. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  658. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  659. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  660. $v['order_type_name'] = $order_type_data[$v['order_type']];
  661. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  662. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  663. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  664. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  665. }
  666. $coupon_price += $v['coupon_price'];
  667. //服务支付类别
  668. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  669. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  670. }
  671. }
  672. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  673. //汇总优惠卷额度
  674. $result['coupon_price'] = $coupon_price;
  675. //工单总支付金额
  676. $result['worker_account'] = $result['work_amount'];
  677. // 配件信息
  678. $result['spare_parts'] = [];
  679. $result['self_spare_parts'] = [];
  680. if($result['spare_total'] > 0){
  681. $result['spare_parts'] = ServiceWorkSpare::getLists($result['id'], 1);
  682. $result['self_spare_parts'] = ServiceWorkSpare::getLists($result['id'], 2);
  683. }
  684. // 保修卡信息
  685. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  686. $query->with(['goodsCategory'=>function ($query1) {
  687. $query1->field(['name','picture']);
  688. }]);
  689. }])->where('work_id',$result['id'])
  690. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  691. ->append(['effective_unit_text'])
  692. ->order('create_time desc')
  693. ->select()
  694. ->toArray();
  695. //查收工程师提成金额
  696. if (!empty($params['user_id']) && $result['worker']['type'] == 2) {
  697. $result['change_amount'] = "-";
  698. $result['settlement_amount'] = "-";
  699. $result['add_work_amount'] = "-";
  700. } else {
  701. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  702. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  703. }
  704. //质保金相关金额
  705. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  706. ->each(function ($item){
  707. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  708. })->toArray();
  709. //保修工单时的信息
  710. $result['effective_income_amount'] = 0;
  711. if(!empty($result['order_effective_id'])){
  712. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  713. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  714. if($serviceWork->master_worker_id != $result['master_worker_id']){
  715. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  716. }
  717. }
  718. //获取美团订单信息
  719. $result['meituan_order'] = [];
  720. if($result['third_type']==1){
  721. $result['meituan_order'] = ThirdOrders::where(['work_id'=>$result['id']])->order('create_time desc')->findOrEmpty();
  722. }
  723. //工程师预约时间修改申请记录
  724. if (!empty($params['user_id'])) {
  725. $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();
  726. if ($result['appointment_log']){
  727. $result['appointment_log']['last_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['last_appointment_time']);
  728. $result['appointment_log']['this_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['this_appointment_time']);
  729. }
  730. }
  731. return $result;
  732. }
  733. public static function getUserCouponDetails($params)
  734. {
  735. try{
  736. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  737. if(!$work){
  738. throw new \Exception('工单不存在');
  739. }
  740. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  741. ->where('voucher_count','>',0)
  742. ->where('voucher_status',0)
  743. ->where('expire_time','>',time())
  744. ->column('coupon_id');
  745. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  746. $data = UserCoupon::where('user_id',$work['user_id'])
  747. ->where('voucher_count','>',0)
  748. ->where('voucher_status',0)
  749. ->whereIn('coupon_id',$coupon_ids)
  750. ->append(['discount_ratio_text'])
  751. ->where('expire_time','>',time())
  752. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  753. ->select()->toArray();
  754. foreach($data as $k => $v){
  755. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  756. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  757. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  758. }
  759. return $data;
  760. } catch(\Exception $e){
  761. self::setError($e->getMessage());
  762. return false;
  763. }
  764. }
  765. public static function getDetailWorkServiceStatus($params)
  766. {
  767. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  768. //工程师工单按钮状态
  769. $work_service_status = 0;
  770. //工单状态
  771. if($result['work_status'] == 1){
  772. $work_service_status = 1;
  773. }
  774. if($result['work_status'] == 2){
  775. $work_service_status = 2;
  776. }
  777. if($result['work_status'] == 3){
  778. $work_service_status = 3;
  779. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  780. $work_service_status = 4;
  781. }
  782. }
  783. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  784. $work_service_status = 5;
  785. }
  786. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  787. $work_service_status = 6;
  788. }
  789. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  790. $work_service_status = 7;
  791. }
  792. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  793. $work_service_status = 8;
  794. }
  795. if($result['work_status'] ==6){
  796. $work_service_status = 9;
  797. }
  798. if($result['work_status'] ==7){
  799. $work_service_status = 10;
  800. }
  801. if($result['work_status'] ==8){
  802. $work_service_status = 11;
  803. }
  804. if($result['work_status'] ==9){
  805. $work_service_status = 12;
  806. }
  807. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  808. }
  809. /**
  810. * @notes 取消操作
  811. * @param array $params
  812. * @return bool
  813. * @author likeadmin
  814. * @date 2024/09/19 10:48
  815. */
  816. public static function cancel(array $params): bool
  817. {
  818. Db::startTrans();
  819. try {
  820. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  821. $serviceWorkInfo = ServiceWork::find($params['id']);
  822. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  823. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  824. }
  825. //工单如果存在费用情况,不允许取消
  826. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  827. if($paid_amount > 0 and ($serviceWorkInfo['third_type'] == 0 && $serviceWorkInfo['external_platform_id'] == 0)){
  828. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  829. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  830. }
  831. ServiceWork::where('id', $params['id'])->update([
  832. 'work_status' => 9,
  833. 'service_status' => 4
  834. ]);
  835. ServiceWorkLog::create([
  836. 'work_id' => $params['id'],
  837. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  838. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消".($params['remark']??'')
  839. ]);
  840. Db::commit();
  841. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  842. return true;
  843. } catch (\Exception $e) {
  844. Db::rollback();
  845. self::setError($e->getMessage());
  846. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  847. return false;
  848. }
  849. }
  850. /**
  851. * @notes 工程师结算操作
  852. * @param array $params
  853. * @return bool
  854. * @author likeadmin
  855. * @date 2024/09/19 10:48
  856. */
  857. public static function settlement(array $params): bool
  858. {
  859. Db::startTrans();
  860. try {
  861. $serviceWorkInfo = ServiceWork::find($params['id']);
  862. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  863. throw new \Exception('该工单非待结算状态');
  864. }
  865. $ratio = 0;
  866. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  867. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  868. if($commissionConfig->isEmpty() || empty($ratio)){
  869. //获取工单对应的商品id
  870. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  871. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  872. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  873. if($rule->isEmpty()){
  874. throw new \Exception('请配置商品业绩规则');
  875. }
  876. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  877. }else{
  878. // 存在服务分类比例进行结算
  879. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  880. }
  881. Db::commit();
  882. return true;
  883. } catch (\Exception $e) {
  884. Db::rollback();
  885. self::setError($e->getMessage());
  886. return false;
  887. }
  888. }
  889. /**
  890. * 工程师配件审核结算操作
  891. * @param array $params
  892. * @return bool
  893. * @author liugc <466014217@qq.com>
  894. * @date 2025/5/9 9:14
  895. */
  896. public static function settlementSpare(array $params): bool
  897. {
  898. Db::startTrans();
  899. try {
  900. $spare = ServiceWorkSpare::where('id',$params['id'])->findOrEmpty();
  901. if($spare->isEmpty()){
  902. throw new \Exception('无配件审核');
  903. }else{
  904. $serviceWorkInfo = ServiceWork::find($spare->service_work_id);
  905. Log::info( '配件审核结算'.json_encode([$serviceWorkInfo['work_pay_status']]));
  906. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  907. throw new \Exception('该工单非待结算状态');
  908. }
  909. $spare->status = $params['status']??0;
  910. $spare->remark = $params['remark']??'';
  911. $spare->save();
  912. }
  913. Db::commit();
  914. // 是否所有配件审核完成
  915. SparePartLogic::isExamineOk($spare->service_work_id);
  916. return true;
  917. } catch (\Exception $e) {
  918. Db::rollback();
  919. self::setError($e->getMessage());
  920. return false;
  921. }
  922. }
  923. /**
  924. * 获取所有改约通知
  925. * @param $userId
  926. * @return array|false
  927. */
  928. public static function getAppointmentNotice($userId)
  929. {
  930. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  931. ->where('work_status','>',1)
  932. ->where('work_status','<',7)
  933. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  934. ->order(['appointment_time' => 'asc'])//上门时间排序
  935. ->select()->each(function (&$item){
  936. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  937. })
  938. ->toArray();
  939. }
  940. /**
  941. * @param $params
  942. * @return bool
  943. */
  944. public static function submitAppointment($params)
  945. {
  946. Db::startTrans();
  947. try {
  948. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  949. if($serviceWork->isEmpty()){
  950. throw new \Exception('工单不存在');
  951. }
  952. $serviceWork->appoint_approval = 2;
  953. $serviceWork->save();
  954. Db::commit();
  955. return true;
  956. } catch (\Exception $e) {
  957. Db::rollback();
  958. self::setError($e->getMessage());
  959. return false;
  960. }
  961. }
  962. /**
  963. * @param $params
  964. * @return bool
  965. */
  966. public static function submitChangePrice($params)
  967. {
  968. Db::startTrans();
  969. try {
  970. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  971. if($serviceWork->isEmpty()){
  972. throw new \Exception('工单不存在');
  973. }
  974. $serviceWork->work_status = 4;
  975. $serviceWork->user_confirm_status = 0;
  976. $serviceWork->price_approval = 2;
  977. $serviceWork->save();
  978. Db::commit();
  979. return true;
  980. } catch (\Exception $e) {
  981. Db::rollback();
  982. self::setError($e->getMessage());
  983. return false;
  984. }
  985. }
  986. public static function notApproved($params)
  987. {
  988. Db::startTrans();
  989. try {
  990. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  991. if($serviceWork->isEmpty()){
  992. throw new \Exception('工单不存在');
  993. }
  994. $serviceWork->refund_approval = 3;
  995. $serviceWork->save();
  996. Db::commit();
  997. return true;
  998. } catch (\Exception $e) {
  999. Db::rollback();
  1000. self::setError($e->getMessage());
  1001. return false;
  1002. }
  1003. }
  1004. public static function againDoor($params)
  1005. {
  1006. Db::startTrans();
  1007. try {
  1008. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  1009. if($serviceWork->isEmpty()){
  1010. throw new \Exception('工单不存在');
  1011. }
  1012. //更新预约日志
  1013. //更新工单未确认上门的状态
  1014. $serviceWork->work_status = 3;
  1015. $serviceWork->user_confirm_status = 0;
  1016. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  1017. if($appoint > 2){
  1018. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  1019. }
  1020. ServiceWorkAppointmentLog::create([
  1021. 'work_id'=>$serviceWork->id,
  1022. 'worker_id'=>$params['user_id'],
  1023. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  1024. 'this_appointment_time'=>strtotime($params['appointment_time']),
  1025. ]);
  1026. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  1027. $serviceWork->save();
  1028. Db::commit();
  1029. return true;
  1030. } catch (\Exception $e) {
  1031. Db::rollback();
  1032. self::setError($e->getMessage());
  1033. return false;
  1034. }
  1035. }
  1036. /**
  1037. * 取消分配
  1038. * @param $params
  1039. * @param $userInfo
  1040. * @param $type:1后台管理员取消;2工程师端取消
  1041. * @return bool
  1042. */
  1043. public static function cancelAllocation($params,$userInfo,$type = 1){
  1044. Db::startTrans();
  1045. try {
  1046. $work = ServiceWork::findOrEmpty($params['id']);
  1047. if($work->isEmpty()){
  1048. throw new Exception('工单不存在');
  1049. }
  1050. if($work->work_status >=6 ){
  1051. throw new \Exception('工单状态只能修改待结算之前的');
  1052. }
  1053. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  1054. if($worker->isEmpty()){
  1055. throw new \Exception('工程师不存在');
  1056. }
  1057. if ($type == 2 && $worker->type == 2) {
  1058. throw new \Exception('您当前无权限取消分配');
  1059. }
  1060. if ($work->tenant_id > 0) {
  1061. //团队订单取消时,派单数量减1
  1062. $updateData = date("H",strtotime($work->appointment_time)) < 12 ? ['am_order' => Db::raw('am_order - 1')] : ['pm_order' => Db::raw('pm_order - 1')];
  1063. MasterWorkerTeam::where('master_worker_id',$work->master_worker_id)->where('tenant_id',$work->tenant_id)->update($updateData);
  1064. }
  1065. $params['master_worker_id'] = (isset($params['master_worker_id']) && !empty($params['master_worker_id']))?$params['master_worker_id']:$work->master_worker_id;
  1066. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  1067. $work->master_worker_id = 0;
  1068. $work->tenant_id = 0;
  1069. $work->work_status = 0;
  1070. $work->dispatch_time = 0;
  1071. $work->first_contact_time = 0;
  1072. $work->estimated_finish_time = 0;
  1073. $work->save();
  1074. $work_log = [
  1075. 'work_id'=>$work->id,
  1076. 'master_worker_id'=>$params['master_worker_id'],
  1077. 'type' => 1,
  1078. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  1079. ];
  1080. ServiceWorkerAllocateWorkerLogic::add($work_log);
  1081. Db::commit();
  1082. // TODO tmp - 订单通知
  1083. $servicework_notific_arr = Cache::store('common_redis')->get('servicework_notific');
  1084. if(empty($servicework_notific_arr)) $servicework_notific_arr = [];
  1085. $servicework_notific_arr[$work->id] = 1;
  1086. Cache::store('common_redis')->set('servicework_notific',$servicework_notific_arr);
  1087. return true;
  1088. }catch(\Exception $e){
  1089. Db::rollback();
  1090. self::setError($e->getMessage());
  1091. return false;
  1092. }
  1093. }
  1094. public static function addCustomerLog($params)
  1095. {
  1096. Db::startTrans();
  1097. try {
  1098. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1099. if($serviceWork->isEmpty()){
  1100. throw new \Exception('工单不存在');
  1101. }
  1102. $res = ServiceWorkCustomerLog::create([
  1103. 'work_id'=>$serviceWork->id,
  1104. 'type'=>$params['type']??0,
  1105. 'content'=>$params['content']??'',
  1106. 'admin_id'=>$params['admin_id']??0,
  1107. 'create_time'=>time(),
  1108. ]);
  1109. Db::commit();
  1110. $res && OnlineCustomerService::customerClsMessage('servicework',$serviceWork->id);
  1111. return true;
  1112. } catch (\Exception $e) {
  1113. Db::rollback();
  1114. self::setError($e->getMessage());
  1115. return false;
  1116. }
  1117. }
  1118. public static function distributeTenants($params,$userInfo)
  1119. {
  1120. Db::startTrans();
  1121. try {
  1122. if(empty($params['id']) || empty($params['tenant_id'])){
  1123. throw new \Exception('参数错误'.json_encode($params));
  1124. }
  1125. if (is_array($params['id'])) {
  1126. $ids = $params['id'];
  1127. } else{
  1128. $ids = [$params['id']];
  1129. }
  1130. // 取消工程师分配
  1131. foreach ($ids as $id) {
  1132. $res = self::cancelAllocation(['id'=>$id,'master_worker_id'=>''],$userInfo);
  1133. if($res === false){
  1134. Log::info('分配log'.self::getError());
  1135. }
  1136. }
  1137. ServiceWork::whereIn('id',$ids)->update(['tenant_id'=>$params['tenant_id']]);
  1138. Db::commit();
  1139. return true;
  1140. } catch (\Exception $e) {
  1141. Db::rollback();
  1142. self::setError($e->getMessage());
  1143. return false;
  1144. }
  1145. }
  1146. /**
  1147. *
  1148. * @return false|void
  1149. */
  1150. public static function contactCustomer($params)
  1151. {
  1152. try {
  1153. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1154. if($work->isEmpty()){
  1155. throw new \Exception('工单不存在');
  1156. }
  1157. if (empty($work->first_contact_time)) {
  1158. $work->first_contact_time = time();
  1159. $work->save();
  1160. }
  1161. return ['middleNumber' => $work->mobile];
  1162. if ($middleNumber = Cache::get('WORKER_MIDDLE_NUMBER_'.$work->id)) {
  1163. return ['middleNumber' => $middleNumber];
  1164. }
  1165. $worker_mobile = $params['user_info']['mobile'];
  1166. $res = VirtualCallService::auth($worker_mobile, $work->mobile, 60);
  1167. if (isset($res['result']) && $res['result'] == '000000') {
  1168. Cache::set('WORKER_MIDDLE_NUMBER_'.$work->id, $res['middleNumber'], 60); //缓存60秒
  1169. return ['middleNumber' => $res['middleNumber']];
  1170. } else {
  1171. Log::info('虚拟外呼失败:'.json_encode($res));
  1172. throw new \Exception('虚拟外呼失败');
  1173. }
  1174. return true;
  1175. }
  1176. catch (\Exception $e) {
  1177. Db::rollback();
  1178. self::setError($e->getMessage());
  1179. return false;
  1180. }
  1181. }
  1182. /**
  1183. * 添加第三方平台订单
  1184. * @return false|void
  1185. */
  1186. public static function addThirdPlatformsOrders($params)
  1187. {
  1188. try {
  1189. if($params['userAddress']){
  1190. $lon_lat = get_address_lat_lng($params['userAddress']);
  1191. $params['lon'] = $lon_lat['lon'];
  1192. $params['lat'] = $lon_lat['lat'];
  1193. }
  1194. return ThirdOrderLogic::submitOrders($params);
  1195. }catch (\Exception $e) {
  1196. self::setError($e->getMessage());
  1197. return false;
  1198. }
  1199. }
  1200. /**
  1201. * 上门码和完成码
  1202. * @param $params
  1203. * @return false|array
  1204. */
  1205. public static function confirmDoorCode($params)
  1206. {
  1207. try {
  1208. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1209. if($work->isEmpty()){
  1210. throw new Exception('工单不存在');
  1211. }
  1212. $encryptedData = encrypt($params['work_sn'], \think\facade\Config::get('project.work_sn_key'));
  1213. $user_website = \think\facade\Config::get('project.user_website');
  1214. $quoted_price = env('project.quoted_price')?:$user_website.'pages/quoted_price';
  1215. $type = $params['type']??1;
  1216. if($type == 1){
  1217. $user_website .= '?code='.$encryptedData;
  1218. }elseif($type == 2){
  1219. $user_website = $quoted_price.'?code='.$encryptedData;
  1220. }
  1221. return ['url'=>$user_website];
  1222. }catch (\Exception $e) {
  1223. self::setError($e->getMessage());
  1224. return false;
  1225. }
  1226. }
  1227. /**
  1228. * 终止结束服务操作
  1229. */
  1230. public static function terminateService($params): bool
  1231. {
  1232. Db::startTrans();
  1233. try {
  1234. $serviceWork = ServiceWork::where('work_pay_status',1)
  1235. ->where('master_worker_id','>',0)
  1236. ->whereIn('work_status',[0,1,2,3,4,5,6])
  1237. ->where('id',$params['id'])->findOrEmpty();
  1238. if($serviceWork->isEmpty()){
  1239. throw new \Exception('该工单状态不可执行结束服务');
  1240. }
  1241. if($params['isearnest'] == 1){
  1242. $serviceWork->work_status = 7;
  1243. $serviceWork->user_confirm_status = 5;
  1244. $serviceWork->service_status = 3;
  1245. $serviceWork->work_pay_status = 1;
  1246. $serviceWork->finished_time = time();
  1247. $serviceWork->remark = ($serviceWork->remark?:'')." | 终止结束服务:常规流程";
  1248. $serviceWork->save();
  1249. }else{
  1250. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('payment_type', 1)->value('paid_amount');
  1251. if($paid_amount > 0){
  1252. // 存在上门费给工程师
  1253. Log::info('终止结束服务工单'.$serviceWork->id.',上门费:'.$paid_amount);
  1254. WorkerAccountLogLogic::addAccountLog($serviceWork,$paid_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
  1255. }
  1256. ServiceWork::where('id', $params['id'])->update([
  1257. 'work_status' => 7,
  1258. 'user_confirm_status' => 5,
  1259. 'service_status' => 3,
  1260. 'finished_time' => time(),
  1261. 'work_pay_status' => 2, // 已结算则不执行 onAfterUpdate
  1262. 'settlement_amount' => $paid_amount??0,
  1263. 'worker_price' => $paid_amount??0,
  1264. 'remark' => ($serviceWork->remark?:'')." | 终止结束服务:上门费-{$paid_amount}"
  1265. ]);
  1266. }
  1267. ServiceWorkLog::create([
  1268. 'work_id' => $params['id'],
  1269. 'master_worker_id' => $serviceWork->master_worker_id,
  1270. 'opera_log' => "工单:{$serviceWork->work_sn} 终止结束服务"
  1271. ]);
  1272. Db::commit();
  1273. // 外部平台工单 - 通知外边平台
  1274. if($serviceWork->external_platform_id > 0){
  1275. ExternalPlatformLogic::generalServiceWork('1003',['work_id' => $serviceWork->id]);
  1276. }
  1277. Log::info('终止结束服务'.json_encode([$serviceWork]));
  1278. return true;
  1279. } catch (\Exception $e) {
  1280. Db::rollback();
  1281. self::setError($e->getMessage());
  1282. Log::info('终止结束服务-Error'.json_encode([$e->getMessage()]));
  1283. return false;
  1284. }
  1285. }
  1286. /**
  1287. * 工程师抢单
  1288. */
  1289. public static function grabOrder($params): bool
  1290. {
  1291. if(!MasterWorkerLogic::isReceivingOrders($params['master_worker_id'])){
  1292. Log::info('抢单失败:工程师不能接单:'.$params['id'].'--'.$params['master_worker_id']);
  1293. self::setError('未达到接单条件');
  1294. return false;
  1295. }
  1296. $serviceWork = 0;
  1297. Db::startTrans();
  1298. try {
  1299. // 抢单
  1300. $serviceWork = ServiceWork::where(['work_pay_status'=>1,'work_status'=>0,'service_status'=>0,'master_worker_id'=>0])
  1301. ->where('id',$params['id'])->update(['master_worker_id'=>$params['master_worker_id'],'work_status'=>1]);
  1302. Db::commit();
  1303. } catch (\Exception $e) {
  1304. Db::rollback();
  1305. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id'].':'.$e->getMessage());
  1306. self::setError('抢单失败');
  1307. return false;
  1308. }
  1309. if($serviceWork == 1){
  1310. Log::info('抢单成功:'.$params['id'].'--'.$params['master_worker_id']);
  1311. $params['is_grab_order'] = 1;
  1312. self::allocateWorker($params,['admin_id'=>0,'name'=>'抢单工程师ID:'.$params['master_worker_id']]);
  1313. return true;
  1314. }else{
  1315. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id']);
  1316. self::setError('抢单失败');
  1317. return false;
  1318. }
  1319. }
  1320. /**
  1321. * 给用户发券
  1322. */
  1323. public static function userAddVoucher($params): bool
  1324. {
  1325. try {
  1326. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1327. if(!$serviceWork->isEmpty()){
  1328. $codes = [];
  1329. foreach ($params['coupon_data'] as $coupon_data) {
  1330. $coupon_data['code'] && $codes[] = $coupon_data['code'];
  1331. }
  1332. if($codes){
  1333. UserCouponLogic::grant($codes,$serviceWork->user_id,$serviceWork->id);
  1334. }
  1335. }
  1336. return true;
  1337. } catch (\Exception $e) {
  1338. self::setError($e->getMessage());
  1339. return false;
  1340. }
  1341. }
  1342. /**
  1343. * 给用户加单
  1344. */
  1345. public static function userExtendOrder($params): bool
  1346. {
  1347. try {
  1348. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1349. if(!$serviceWork->isEmpty()){
  1350. $worker_number = MasterWorker::where('id',$serviceWork->master_worker_id)->value('worker_number');
  1351. //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
  1352. $res = ServiceOrderLogic::submitOrder([
  1353. 'goods_id' => $params['goods_id'],
  1354. 'user_info' => [
  1355. 'mobile' => $serviceWork->mobile
  1356. ],
  1357. 'user_id' => $serviceWork->user_id,
  1358. 'coupon_id' => 0,
  1359. 'worker' => $worker_number,
  1360. 'terminal' => 1,
  1361. 'pay_way' => 2,
  1362. 'appointment_time' => $serviceWork->appointment_time,
  1363. 'address' => $serviceWork->address,
  1364. 'contact_people' => $serviceWork->real_name,
  1365. 'contact_number' => $serviceWork->mobile,
  1366. 'lon' => $serviceWork->lon,
  1367. 'lat' => $serviceWork->lat,
  1368. 'property_activity_id' => 0
  1369. ]);
  1370. if($res == false){
  1371. throw new \Exception(ServiceOrderLogic::getError());
  1372. }
  1373. }
  1374. return true;
  1375. } catch (\Exception $e) {
  1376. self::setError($e->getMessage());
  1377. return false;
  1378. }
  1379. }
  1380. public static function appointmentAudit($params): bool
  1381. {
  1382. Db::startTrans();
  1383. try {
  1384. $work = ServiceWork::where('id',$params['work_id'])->findOrEmpty();
  1385. if($work->isEmpty()){
  1386. throw new \Exception('工单不存在');
  1387. }
  1388. $log = ServiceWorkAppointmentLog::where('id',$params['id'])->findOrEmpty();
  1389. if($log->isEmpty()){
  1390. throw new \Exception('审核记录不存在');
  1391. }
  1392. $master = MasterWorker::where('id',$log->worker_id)->findOrEmpty();
  1393. $log->status = $params['status'];
  1394. $log->remark = $params['remark'];
  1395. $log->save();
  1396. //预约时间修改审核通过则更新工单预约时间
  1397. if ($params['status'] == 2) {
  1398. //$work->work_status = 3;//待上门
  1399. $work->appointment_time = $log->this_appointment_time;
  1400. $work->save();
  1401. //添加变更日志
  1402. $work_log = [
  1403. 'work_id'=>$work->id,
  1404. 'master_worker_id'=>$log->worker_id,
  1405. 'opera_log'=>'编号['.$master->worker_number.']'.$master->real_name.'于'.$log->create_time.'联系了客户,确认了于'.date('Y-m-d H:i:s',$log->this_appointment_time).'预约上门',
  1406. ];
  1407. ServiceWorkLogLogic::add($work_log);
  1408. }
  1409. Db::commit();
  1410. return true;
  1411. } catch (\Exception $e) {
  1412. Db::rollback();
  1413. self::setError('预约时间审核失败');
  1414. return false;
  1415. }
  1416. }
  1417. }