ServiceWorkLogic.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. $work->price_approval = 0;
  284. $work->save();
  285. //添加变更日志
  286. $work_log = [
  287. 'work_id'=>$work->id,
  288. 'master_worker_id'=>$work->master_worker_id,
  289. '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()).'提交了报价单',
  290. ];
  291. ServiceWorkLogLogic::add($work_log);
  292. Db::commit();
  293. // 外部平台工单 - 通知外边平台
  294. if($work->external_platform_id > 0){
  295. event('ExternalPlatform', [
  296. 'scene' => 'confirm_price',
  297. 'params' => [
  298. 'work_id' => $work->id,
  299. ]
  300. ]);
  301. }
  302. }
  303. catch (\Exception $e) {
  304. Db::rollback();
  305. self::setError($e->getMessage());
  306. return false;
  307. }
  308. }
  309. /**
  310. * 工程师确认服务完成
  311. * @param $params
  312. * @return false|void
  313. */
  314. public static function confirmServiceFinish($params)
  315. {
  316. Db::startTrans();
  317. try {
  318. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  319. if($work->isEmpty()){
  320. throw new Exception('工单不存在');
  321. }
  322. if($work->user_confirm_status !=2){
  323. throw new Exception('请勿重复操作');
  324. }
  325. $work->finished_images = $params['finished_images'];
  326. $work->user_confirm_status = 3;//待确认服务完成
  327. $work->save();
  328. //添加变更日志
  329. $work_log = [
  330. 'work_id'=>$work->id,
  331. 'master_worker_id'=>$work->master_worker_id,
  332. '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()).'提交了待用户确认服务完成',
  333. ];
  334. ServiceWorkLogLogic::add($work_log);
  335. Db::commit();
  336. } catch (\Exception $e) {
  337. Db::rollback();
  338. self::setError($e->getMessage());
  339. return false;
  340. }
  341. }
  342. public static function allocateWorker($params,$userInfo){
  343. Db::startTrans();
  344. try {
  345. $work = ServiceWork::findOrEmpty($params['id']);
  346. if($work->isEmpty()){
  347. throw new Exception('工单不存在');
  348. }
  349. if($work->work_status >=6 ){
  350. throw new \Exception('工单状态只能修改待结算之前的');
  351. }
  352. if($work->master_worker_id == $params['master_worker_id']){
  353. throw new \Exception('分配的工程师相同');
  354. }
  355. $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'is_disable' =>0])->findOrEmpty();
  356. if($worker->isEmpty()){
  357. throw new \Exception('工程师不存在或被禁用');
  358. }
  359. if($worker->master_worker_id){
  360. MasterWorker::setWorktotal('dec',$worker->master_worker_id);
  361. }
  362. $work->master_worker_id = $params['master_worker_id'];
  363. $work->work_status = 1;
  364. $work->dispatch_time = time();
  365. MasterWorker::setWorktotal('inc',$params['master_worker_id']);
  366. $work->save();
  367. $work_log = [
  368. 'work_id'=>$work->id,
  369. 'master_worker_id'=>$work->master_worker_id,
  370. 'type' => 0,
  371. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  372. ];
  373. ServiceWorkerAllocateWorkerLogic::add($work_log);
  374. Db::commit();
  375. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  376. $workDetail = ServiceWorkLogic::detail($params);
  377. $res = event('Notice', [
  378. 'scene_id' => 113,
  379. 'params' => [
  380. 'user_id' => $params['master_worker_id'],
  381. 'order_id' => $params['id'],
  382. 'thing9' => $workDetail['title'],
  383. 'time7' => $workDetail['appointment_time'],
  384. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  385. 'phone_number6' => asteriskString($workDetail['mobile']),
  386. ]
  387. ]);
  388. return true;
  389. }catch(\Exception $e){
  390. Db::rollback();
  391. self::setError($e->getMessage());
  392. return false;
  393. }
  394. }
  395. /**
  396. * 工单详情
  397. * @param $params
  398. * @return array|false
  399. */
  400. public static function detail($params){
  401. $work_where = !empty($params['work_sn'])?['work_sn'=>$params['work_sn']]:['id'=>$params['id']];
  402. $result = ServiceWork::with([
  403. 'worker'=> function(Query $query) {
  404. $query->field('id,worker_number,real_name,mobile');
  405. },
  406. 'allocateWorkerLog' =>function(Query $query){
  407. $query->field('id,work_id,opera_log,create_time');
  408. },
  409. 'serviceWorkLog' =>function(Query $query){
  410. $query->field('id,work_id,opera_log,create_time');
  411. }
  412. ])->append(['id','work_status_text','service_status_text'])
  413. ->where($work_where)
  414. ->findOrEmpty()->toArray();
  415. $result['is_operate_prohibit'] = 0;
  416. if(isset($params['user_id']) && $params['user_id'] && ($params['user_id'] != $result['master_worker_id']) ){
  417. // 带徒师傅的工单
  418. $lead_master_worker_id = TrainingWorkerTask::where('master_worker_id',$params['user_id'])->where('training_status',2)
  419. ->where('operate_status',0)->value('lead_master_worker_id');
  420. // 团队负责人编辑 工单池(包括已派队员) 工单
  421. if($params['user_info']['team_role'] == 1 && $params['user_info']['tenant_id'] == $result['tenant_id'] ){
  422. $result['is_operate_prohibit'] = 0;
  423. }elseif(!empty($lead_master_worker_id) && !empty($result['master_worker_id']) && $lead_master_worker_id == $result['master_worker_id']){
  424. // 徒查看师父的工单 不能编辑可查看
  425. $result['is_operate_prohibit'] = 1;
  426. }else{
  427. throw new \Exception('您没有权限操作该工单');
  428. }
  429. }
  430. //工程师工单按钮状态
  431. $work_service_status = 0;
  432. $work_service_status_text = '待派单';
  433. //工单状态
  434. if($result['work_status'] == 1){
  435. $work_service_status = 1;
  436. $work_service_status_text = '待领单';
  437. }
  438. if($result['work_status'] == 2){
  439. $work_service_status = 2;
  440. $work_service_status_text = '预约上门';
  441. }
  442. if($result['work_status'] == 3){
  443. $work_service_status = 3;
  444. $work_service_status_text = '等待上门';
  445. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  446. $work_service_status = 4;
  447. $work_service_status_text = '确认上门';
  448. }
  449. }
  450. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  451. $work_service_status = 5;
  452. $work_service_status_text = '确认报价';
  453. }
  454. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  455. $work_service_status = 6;
  456. $work_service_status_text = '用户确认报价中';
  457. }
  458. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  459. $work_service_status = 7;
  460. $work_service_status_text = '完成服务';
  461. }
  462. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  463. $work_service_status = 8;
  464. $work_service_status_text = '用户确认完成服务中';
  465. }
  466. if($result['work_status'] ==6){
  467. $work_service_status = 9;
  468. $work_service_status_text = '待结算';
  469. }
  470. if($result['work_status'] ==7){
  471. $work_service_status = 10;
  472. $work_service_status_text = '已完结';
  473. }
  474. if($result['work_status'] ==8){
  475. $work_service_status = 11;
  476. $work_service_status_text = '已评价';
  477. }
  478. if($result['work_status'] ==9){
  479. $work_service_status = 12;
  480. $work_service_status_text = '已退费';
  481. }
  482. $result['work_service_status'] = $work_service_status;
  483. $result['work_service_status_text'] = $work_service_status_text;
  484. //搜索当前工单下的所有订单记录
  485. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  486. $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']);
  487. }])->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();
  488. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  489. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  490. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  491. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  492. $coupon_price = 0;
  493. foreach ($result['pay_orders'] as $k=>&$v){
  494. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  495. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  496. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  497. $v['order_type_name'] = $order_type_data[$v['order_type']];
  498. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  499. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  500. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  501. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  502. }
  503. $coupon_price += $v['coupon_price'];
  504. //服务支付类别
  505. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  506. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  507. }
  508. }
  509. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  510. //汇总优惠卷额度
  511. $result['coupon_price'] = $coupon_price;
  512. //工单总支付金额
  513. $result['worker_account'] = $result['work_amount'];
  514. // 配件信息
  515. $result['spare_parts'] = [];
  516. if($result['service_work_spare_id']){
  517. $work_spare_parts = json_decode(ServiceWorkSpare::where('id',$result['service_work_spare_id'])->value('spare_parts'),true);
  518. $spare_parts = SparePart::where('id','in',array_column($work_spare_parts,'id'))
  519. ->field(['id', 'goods_category_id', 'spare_name', 'spare_image', 'spare_number', 'spare_unit','spare_status'])
  520. ->select()
  521. ->toArray();
  522. $spare_parts = array_column($spare_parts,null,'id');
  523. foreach (array_column($work_spare_parts,null,'id') as $k=>&$v){
  524. $spare_parts[$k] = array_merge($spare_parts[$k],$v);
  525. }
  526. $result['spare_parts'] = array_values($spare_parts)??[];
  527. }
  528. // 保修卡信息
  529. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  530. $query->with(['goodsCategory'=>function ($query1) {
  531. $query1->field(['name','picture']);
  532. }]);
  533. }])->where('work_id',$result['id'])
  534. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  535. ->append(['effective_unit_text'])
  536. ->order('create_time desc')
  537. ->select()
  538. ->toArray();
  539. //查收工程师提成金额
  540. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  541. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  542. //质保金相关金额
  543. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  544. ->each(function ($item){
  545. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  546. })->toArray();
  547. //保修工单时的信息
  548. $result['effective_income_amount'] = 0;
  549. if(!empty($result['order_effective_id'])){
  550. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  551. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  552. if($serviceWork->master_worker_id != $result['master_worker_id']){
  553. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  554. }
  555. }
  556. //获取美团订单信息
  557. $result['meituan_order'] = [];
  558. if($result['third_type']==1){
  559. $result['meituan_order'] = ThirdOrders::where(['work_id'=>$result['id']])->order('create_time desc')->findOrEmpty();
  560. }
  561. return $result;
  562. }
  563. public static function getUserCouponDetails($params)
  564. {
  565. try{
  566. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  567. if(!$work){
  568. throw new \Exception('工单不存在');
  569. }
  570. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  571. ->where('voucher_count','>',0)
  572. ->where('voucher_status',0)
  573. ->where('expire_time','>',time())
  574. ->column('coupon_id');
  575. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  576. $data = UserCoupon::where('user_id',$work['user_id'])
  577. ->where('voucher_count','>',0)
  578. ->where('voucher_status',0)
  579. ->whereIn('coupon_id',$coupon_ids)
  580. ->append(['discount_ratio_text'])
  581. ->where('expire_time','>',time())
  582. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  583. ->select()->toArray();
  584. foreach($data as $k => $v){
  585. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  586. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  587. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  588. }
  589. return $data;
  590. } catch(\Exception $e){
  591. self::setError($e->getMessage());
  592. return false;
  593. }
  594. }
  595. public static function getDetailWorkServiceStatus($params)
  596. {
  597. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  598. //工程师工单按钮状态
  599. $work_service_status = 0;
  600. //工单状态
  601. if($result['work_status'] == 1){
  602. $work_service_status = 1;
  603. }
  604. if($result['work_status'] == 2){
  605. $work_service_status = 2;
  606. }
  607. if($result['work_status'] == 3){
  608. $work_service_status = 3;
  609. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  610. $work_service_status = 4;
  611. }
  612. }
  613. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  614. $work_service_status = 5;
  615. }
  616. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  617. $work_service_status = 6;
  618. }
  619. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  620. $work_service_status = 7;
  621. }
  622. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  623. $work_service_status = 8;
  624. }
  625. if($result['work_status'] ==6){
  626. $work_service_status = 9;
  627. }
  628. if($result['work_status'] ==7){
  629. $work_service_status = 10;
  630. }
  631. if($result['work_status'] ==8){
  632. $work_service_status = 11;
  633. }
  634. if($result['work_status'] ==9){
  635. $work_service_status = 12;
  636. }
  637. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  638. }
  639. /**
  640. * @notes 取消操作
  641. * @param array $params
  642. * @return bool
  643. * @author likeadmin
  644. * @date 2024/09/19 10:48
  645. */
  646. public static function cancel(array $params): bool
  647. {
  648. Db::startTrans();
  649. try {
  650. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  651. $serviceWorkInfo = ServiceWork::find($params['id']);
  652. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  653. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  654. }
  655. //工单如果存在费用情况,不允许取消
  656. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  657. if($paid_amount > 0 and $serviceWorkInfo['third_type'] == 0){
  658. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  659. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  660. }
  661. ServiceWork::where('id', $params['id'])->update([
  662. //'work_status' => 9,
  663. 'service_status' => 4,
  664. 'remark' => $params['remark']??''
  665. ]);
  666. ServiceWorkLog::create([
  667. 'work_id' => $params['id'],
  668. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  669. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消"
  670. ]);
  671. Db::commit();
  672. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  673. return true;
  674. } catch (\Exception $e) {
  675. Db::rollback();
  676. self::setError($e->getMessage());
  677. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  678. return false;
  679. }
  680. }
  681. /**
  682. * @notes 工程师结算操作
  683. * @param array $params
  684. * @return bool
  685. * @author likeadmin
  686. * @date 2024/09/19 10:48
  687. */
  688. public static function settlement(array $params): bool
  689. {
  690. Db::startTrans();
  691. try {
  692. $serviceWorkInfo = ServiceWork::find($params['id']);
  693. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  694. throw new \Exception('该工单非待结算状态');
  695. }
  696. $ratio = 0;
  697. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  698. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  699. if($commissionConfig->isEmpty() || empty($ratio)){
  700. //获取工单对应的商品id
  701. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  702. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  703. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  704. if($rule->isEmpty()){
  705. throw new \Exception('请配置商品业绩规则');
  706. }
  707. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  708. }else{
  709. // 存在服务分类比例进行结算
  710. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  711. }
  712. Db::commit();
  713. return true;
  714. } catch (\Exception $e) {
  715. Db::rollback();
  716. self::setError($e->getMessage());
  717. return false;
  718. }
  719. }
  720. /**
  721. * 获取所有改约通知
  722. * @param $userId
  723. * @return array|false
  724. */
  725. public static function getAppointmentNotice($userId)
  726. {
  727. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  728. ->where('work_status','>',1)
  729. ->where('work_status','<',7)
  730. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  731. ->order(['appointment_time' => 'asc'])//上门时间排序
  732. ->select()->each(function (&$item){
  733. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  734. })
  735. ->toArray();
  736. }
  737. /**
  738. * @param $params
  739. * @return bool
  740. */
  741. public static function submitAppointment($params)
  742. {
  743. Db::startTrans();
  744. try {
  745. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  746. if($serviceWork->isEmpty()){
  747. throw new \Exception('工单不存在');
  748. }
  749. $serviceWork->appoint_approval = 2;
  750. $serviceWork->save();
  751. Db::commit();
  752. return true;
  753. } catch (\Exception $e) {
  754. Db::rollback();
  755. self::setError($e->getMessage());
  756. return false;
  757. }
  758. }
  759. /**
  760. * @param $params
  761. * @return bool
  762. */
  763. public static function submitChangePrice($params)
  764. {
  765. Db::startTrans();
  766. try {
  767. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  768. if($serviceWork->isEmpty()){
  769. throw new \Exception('工单不存在');
  770. }
  771. $serviceWork->work_status = 4;
  772. $serviceWork->user_confirm_status = 0;
  773. $serviceWork->price_approval = 2;
  774. $serviceWork->save();
  775. Db::commit();
  776. return true;
  777. } catch (\Exception $e) {
  778. Db::rollback();
  779. self::setError($e->getMessage());
  780. return false;
  781. }
  782. }
  783. public static function notApproved($params)
  784. {
  785. Db::startTrans();
  786. try {
  787. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  788. if($serviceWork->isEmpty()){
  789. throw new \Exception('工单不存在');
  790. }
  791. $serviceWork->refund_approval = 3;
  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 againDoor($params)
  802. {
  803. Db::startTrans();
  804. try {
  805. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  806. if($serviceWork->isEmpty()){
  807. throw new \Exception('工单不存在');
  808. }
  809. //更新预约日志
  810. //更新工单未确认上门的状态
  811. $serviceWork->work_status = 3;
  812. $serviceWork->user_confirm_status = 0;
  813. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  814. if($appoint > 2){
  815. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  816. }
  817. ServiceWorkAppointmentLog::create([
  818. 'work_id'=>$serviceWork->id,
  819. 'worker_id'=>$params['user_id'],
  820. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  821. 'this_appointment_time'=>strtotime($params['appointment_time']),
  822. ]);
  823. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  824. $serviceWork->save();
  825. Db::commit();
  826. return true;
  827. } catch (\Exception $e) {
  828. Db::rollback();
  829. self::setError($e->getMessage());
  830. return false;
  831. }
  832. }
  833. public static function cancelAllocation($params,$userInfo){
  834. Db::startTrans();
  835. try {
  836. $work = ServiceWork::findOrEmpty($params['id']);
  837. if($work->isEmpty()){
  838. throw new Exception('工单不存在');
  839. }
  840. if($work->work_status >=6 ){
  841. throw new \Exception('工单状态只能修改待结算之前的');
  842. }
  843. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  844. if($worker->isEmpty()){
  845. throw new \Exception('工程师不存在');
  846. }
  847. if ($work->tenant_id > 0) {
  848. //团队订单取消时,派单数量减1
  849. $updateData = date("H",strtotime($work->appointment_time)) < 12 ? ['am_order' => Db::raw('am_order - 1')] : ['pm_order' => Db::raw('pm_order - 1')];
  850. MasterWorkerTeam::where('master_worker_id',$work->master_worker_id)->where('tenant_id',$work->tenant_id)->update($updateData);
  851. }
  852. $params['master_worker_id'] = (isset($params['master_worker_id']) && !empty($params['master_worker_id']))?$params['master_worker_id']:$work->master_worker_id;
  853. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  854. $work->master_worker_id = 0;
  855. $work->tenant_id = 0;
  856. $work->work_status = 0;
  857. $work->dispatch_time = 0;
  858. $work->first_contact_time = 0;
  859. $work->estimated_finish_time = 0;
  860. $work->exec_time = 0;
  861. $work->save();
  862. $work_log = [
  863. 'work_id'=>$work->id,
  864. 'master_worker_id'=>$params['master_worker_id'],
  865. 'type' => 1,
  866. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  867. ];
  868. ServiceWorkerAllocateWorkerLogic::add($work_log);
  869. Db::commit();
  870. return true;
  871. }catch(\Exception $e){
  872. Db::rollback();
  873. self::setError($e->getMessage());
  874. return false;
  875. }
  876. }
  877. public static function addCustomerLog($params)
  878. {
  879. Db::startTrans();
  880. try {
  881. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  882. if($serviceWork->isEmpty()){
  883. throw new \Exception('工单不存在');
  884. }
  885. ServiceWorkCustomerLog::create([
  886. 'work_id'=>$serviceWork->id,
  887. 'content'=>$params['content']??'',
  888. 'admin_id'=>$params['admin_id']??0,
  889. 'create_time'=>time(),
  890. ]);
  891. Db::commit();
  892. return true;
  893. } catch (\Exception $e) {
  894. Db::rollback();
  895. self::setError($e->getMessage());
  896. return false;
  897. }
  898. }
  899. public static function distributeTenants($params,$userInfo)
  900. {
  901. Db::startTrans();
  902. try {
  903. if(empty($params['id']) || empty($params['tenant_id'])){
  904. throw new \Exception('参数错误'.json_encode($params));
  905. }
  906. if (is_array($params['id'])) {
  907. $ids = $params['id'];
  908. } else{
  909. $ids = [$params['id']];
  910. }
  911. // 取消工程师分配
  912. foreach ($ids as $id) {
  913. $res = self::cancelAllocation(['id'=>$id,'master_worker_id'=>''],$userInfo);
  914. if($res === false){
  915. Log::info('分配log'.self::getError());
  916. }
  917. }
  918. ServiceWork::whereIn('id',$ids)->update(['tenant_id'=>$params['tenant_id']]);
  919. Db::commit();
  920. return true;
  921. } catch (\Exception $e) {
  922. Db::rollback();
  923. self::setError($e->getMessage());
  924. return false;
  925. }
  926. }
  927. /**
  928. *
  929. * @return false|void
  930. */
  931. public static function contactCustomer($params)
  932. {
  933. try {
  934. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  935. if($work->isEmpty()){
  936. throw new \Exception('工单不存在');
  937. }
  938. if (empty($work->first_contact_time)) {
  939. $work->first_contact_time = time();
  940. $work->save();
  941. }
  942. return true;
  943. }
  944. catch (\Exception $e) {
  945. Db::rollback();
  946. self::setError($e->getMessage());
  947. return false;
  948. }
  949. }
  950. /**
  951. * 添加第三方平台订单
  952. * @return false|void
  953. */
  954. public static function addThirdPlatformsOrders($params)
  955. {
  956. try {
  957. return ThirdOrderLogic::submitOrders($params);
  958. }catch (\Exception $e) {
  959. self::setError($e->getMessage());
  960. return false;
  961. }
  962. }
  963. /**
  964. * 上门码和完成码
  965. * @param $params
  966. * @return false|array
  967. */
  968. public static function confirmDoorCode($params)
  969. {
  970. try {
  971. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  972. if($work->isEmpty()){
  973. throw new Exception('工单不存在');
  974. }
  975. $encryptedData = encrypt($params['work_sn'], \think\facade\Config::get('project.work_sn_key'));
  976. return ['url'=>\think\facade\Config::get('project.user_website').'?code='.$encryptedData];
  977. }catch (\Exception $e) {
  978. self::setError($e->getMessage());
  979. return false;
  980. }
  981. }
  982. }