ServiceWorkLogic.php 43 KB

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