ServiceWorkLogic.php 37 KB

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