ServiceWorkLogic.php 55 KB

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