ServiceWorkLogic.php 56 KB

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