1
0

ServiceWorkLogic.php 43 KB

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