ServiceWorkLogic.php 37 KB

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