ServiceWorkLogic.php 56 KB

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