ServiceWorkLogic.php 43 KB

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