ServiceWorkLogic.php 55 KB

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