1
0

ServiceWorkLogic.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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_operate_prohibit'] = 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. // 该工单是团队负责人在查看(不能直接判断是否为同一个团队,因为队员不能查看负责人的工单)
  386. $team_member_ids = MasterWorker::where('team_id',$params['user_info']['team_id'])->where('team_role',2)->column('id');
  387. if($lead_master_worker_id == $result['master_worker_id'] || in_array($result['master_worker_id'],$team_member_ids)){
  388. $result['is_operate_prohibit'] = 1;
  389. }else{
  390. throw new \Exception('您没有权限操作该工单');
  391. }
  392. }
  393. //工程师工单按钮状态
  394. $work_service_status = 0;
  395. $work_service_status_text = '待派单';
  396. //工单状态
  397. if($result['work_status'] == 1){
  398. $work_service_status = 1;
  399. $work_service_status_text = '待领单';
  400. }
  401. if($result['work_status'] == 2){
  402. $work_service_status = 2;
  403. $work_service_status_text = '预约上门';
  404. }
  405. if($result['work_status'] == 3){
  406. $work_service_status = 3;
  407. $work_service_status_text = '等待上门';
  408. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  409. $work_service_status = 4;
  410. $work_service_status_text = '确认上门';
  411. }
  412. }
  413. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  414. $work_service_status = 5;
  415. $work_service_status_text = '确认报价';
  416. }
  417. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  418. $work_service_status = 6;
  419. $work_service_status_text = '用户确认报价中';
  420. }
  421. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  422. $work_service_status = 7;
  423. $work_service_status_text = '完成服务';
  424. }
  425. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  426. $work_service_status = 8;
  427. $work_service_status_text = '用户确认完成服务中';
  428. }
  429. if($result['work_status'] ==6){
  430. $work_service_status = 9;
  431. $work_service_status_text = '待结算';
  432. }
  433. if($result['work_status'] ==7){
  434. $work_service_status = 10;
  435. $work_service_status_text = '已完结';
  436. }
  437. if($result['work_status'] ==8){
  438. $work_service_status = 11;
  439. $work_service_status_text = '已评价';
  440. }
  441. if($result['work_status'] ==9){
  442. $work_service_status = 12;
  443. $work_service_status_text = '已退费';
  444. }
  445. $result['work_service_status'] = $work_service_status;
  446. $result['work_service_status_text'] = $work_service_status_text;
  447. //搜索当前工单下的所有订单记录
  448. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  449. $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']);
  450. }])->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();
  451. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  452. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  453. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  454. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  455. $coupon_price = 0;
  456. foreach ($result['pay_orders'] as $k=>&$v){
  457. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  458. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  459. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  460. $v['order_type_name'] = $order_type_data[$v['order_type']];
  461. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  462. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  463. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  464. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  465. }
  466. $coupon_price += $v['coupon_price'];
  467. //服务支付类别
  468. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  469. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  470. }
  471. }
  472. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  473. //汇总优惠卷额度
  474. $result['coupon_price'] = $coupon_price;
  475. //工单总支付金额
  476. $result['worker_account'] = $result['work_amount'];
  477. // 配件信息
  478. $result['spare_parts'] = [];
  479. if($result['service_work_spare_id']){
  480. $work_spare_parts = json_decode(ServiceWorkSpare::where('id',$result['service_work_spare_id'])->value('spare_parts'),true);
  481. $spare_parts = SparePart::where('id','in',array_column($work_spare_parts,'id'))
  482. ->field(['id', 'goods_category_id', 'spare_name', 'spare_image', 'spare_number', 'spare_unit','spare_status'])
  483. ->select()
  484. ->toArray();
  485. $spare_parts = array_column($spare_parts,null,'id');
  486. foreach (array_column($work_spare_parts,null,'id') as $k=>&$v){
  487. $spare_parts[$k] = array_merge($spare_parts[$k],$v);
  488. }
  489. $result['spare_parts'] = array_values($spare_parts)??[];
  490. }
  491. // 保修卡信息
  492. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  493. $query->with(['goodsCategory'=>function ($query1) {
  494. $query1->field(['name','picture']);
  495. }]);
  496. }])->where('work_id',$result['id'])
  497. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  498. ->append(['effective_unit_text'])
  499. ->order('create_time desc')
  500. ->select()
  501. ->toArray();
  502. //查收工程师提成金额
  503. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  504. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  505. //质保金相关金额
  506. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  507. ->each(function ($item){
  508. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  509. })->toArray();
  510. //保修工单时的信息
  511. $result['effective_income_amount'] = 0;
  512. if(!empty($result['order_effective_id'])){
  513. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  514. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  515. if($serviceWork->master_worker_id != $result['master_worker_id']){
  516. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  517. }
  518. }
  519. return $result;
  520. }
  521. public static function getUserCouponDetails($params)
  522. {
  523. try{
  524. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  525. if(!$work){
  526. throw new \Exception('工单不存在');
  527. }
  528. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  529. ->where('voucher_count','>',0)
  530. ->where('voucher_status',0)
  531. ->where('expire_time','>',time())
  532. ->column('coupon_id');
  533. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  534. $data = UserCoupon::where('user_id',$work['user_id'])
  535. ->where('voucher_count','>',0)
  536. ->where('voucher_status',0)
  537. ->whereIn('coupon_id',$coupon_ids)
  538. ->append(['discount_ratio_text'])
  539. ->where('expire_time','>',time())
  540. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  541. ->select()->toArray();
  542. foreach($data as $k => $v){
  543. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  544. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  545. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  546. }
  547. return $data;
  548. } catch(\Exception $e){
  549. self::setError($e->getMessage());
  550. return false;
  551. }
  552. }
  553. public static function getDetailWorkServiceStatus($params)
  554. {
  555. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  556. //工程师工单按钮状态
  557. $work_service_status = 0;
  558. //工单状态
  559. if($result['work_status'] == 1){
  560. $work_service_status = 1;
  561. }
  562. if($result['work_status'] == 2){
  563. $work_service_status = 2;
  564. }
  565. if($result['work_status'] == 3){
  566. $work_service_status = 3;
  567. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  568. $work_service_status = 4;
  569. }
  570. }
  571. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  572. $work_service_status = 5;
  573. }
  574. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  575. $work_service_status = 6;
  576. }
  577. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  578. $work_service_status = 7;
  579. }
  580. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  581. $work_service_status = 8;
  582. }
  583. if($result['work_status'] ==6){
  584. $work_service_status = 9;
  585. }
  586. if($result['work_status'] ==7){
  587. $work_service_status = 10;
  588. }
  589. if($result['work_status'] ==8){
  590. $work_service_status = 11;
  591. }
  592. if($result['work_status'] ==9){
  593. $work_service_status = 12;
  594. }
  595. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  596. }
  597. /**
  598. * @notes 取消操作
  599. * @param array $params
  600. * @return bool
  601. * @author likeadmin
  602. * @date 2024/09/19 10:48
  603. */
  604. public static function cancel(array $params): bool
  605. {
  606. Db::startTrans();
  607. try {
  608. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  609. $serviceWorkInfo = ServiceWork::find($params['id']);
  610. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  611. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  612. }
  613. //工单如果存在费用情况,不允许取消
  614. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  615. if($paid_amount > 0){
  616. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  617. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  618. }
  619. ServiceWork::where('id', $params['id'])->update([
  620. //'work_status' => 9,
  621. 'service_status' => 4,
  622. 'remark' => $params['remark']??''
  623. ]);
  624. ServiceWorkLog::create([
  625. 'work_id' => $params['id'],
  626. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  627. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消"
  628. ]);
  629. Db::commit();
  630. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  631. return true;
  632. } catch (\Exception $e) {
  633. Db::rollback();
  634. self::setError($e->getMessage());
  635. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  636. return false;
  637. }
  638. }
  639. /**
  640. * @notes 工程师结算操作
  641. * @param array $params
  642. * @return bool
  643. * @author likeadmin
  644. * @date 2024/09/19 10:48
  645. */
  646. public static function settlement(array $params): bool
  647. {
  648. Db::startTrans();
  649. try {
  650. $serviceWorkInfo = ServiceWork::find($params['id']);
  651. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  652. throw new \Exception('该工单非待结算状态');
  653. }
  654. $ratio = 0;
  655. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  656. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  657. if($commissionConfig->isEmpty() || empty($ratio)){
  658. //获取工单对应的商品id
  659. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  660. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  661. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  662. if($rule->isEmpty()){
  663. throw new \Exception('请配置商品业绩规则');
  664. }
  665. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  666. }else{
  667. // 存在服务分类比例进行结算
  668. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  669. }
  670. Db::commit();
  671. return true;
  672. } catch (\Exception $e) {
  673. Db::rollback();
  674. self::setError($e->getMessage());
  675. return false;
  676. }
  677. }
  678. /**
  679. * 获取所有改约通知
  680. * @param $userId
  681. * @return array|false
  682. */
  683. public static function getAppointmentNotice($userId)
  684. {
  685. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  686. ->where('work_status','>',1)
  687. ->where('work_status','<',7)
  688. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  689. ->order(['appointment_time' => 'asc'])//上门时间排序
  690. ->select()->each(function (&$item){
  691. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  692. })
  693. ->toArray();
  694. }
  695. /**
  696. * @param $params
  697. * @return bool
  698. */
  699. public static function submitAppointment($params)
  700. {
  701. Db::startTrans();
  702. try {
  703. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  704. if($serviceWork->isEmpty()){
  705. throw new \Exception('工单不存在');
  706. }
  707. $serviceWork->appoint_approval = 2;
  708. $serviceWork->save();
  709. Db::commit();
  710. return true;
  711. } catch (\Exception $e) {
  712. Db::rollback();
  713. self::setError($e->getMessage());
  714. return false;
  715. }
  716. }
  717. /**
  718. * @param $params
  719. * @return bool
  720. */
  721. public static function submitChangePrice($params)
  722. {
  723. Db::startTrans();
  724. try {
  725. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  726. if($serviceWork->isEmpty()){
  727. throw new \Exception('工单不存在');
  728. }
  729. $serviceWork->work_status = 4;
  730. $serviceWork->user_confirm_status = 0;
  731. $serviceWork->price_approval = 2;
  732. $serviceWork->save();
  733. Db::commit();
  734. return true;
  735. } catch (\Exception $e) {
  736. Db::rollback();
  737. self::setError($e->getMessage());
  738. return false;
  739. }
  740. }
  741. public static function notApproved($params)
  742. {
  743. Db::startTrans();
  744. try {
  745. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  746. if($serviceWork->isEmpty()){
  747. throw new \Exception('工单不存在');
  748. }
  749. $serviceWork->refund_approval = 3;
  750. $serviceWork->save();
  751. Db::commit();
  752. return true;
  753. } catch (\Exception $e) {
  754. Db::rollback();
  755. self::setError($e->getMessage());
  756. return false;
  757. }
  758. }
  759. public static function againDoor($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. //更新预约日志
  768. //更新工单未确认上门的状态
  769. $serviceWork->work_status = 3;
  770. $serviceWork->user_confirm_status = 0;
  771. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  772. if($appoint > 2){
  773. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  774. }
  775. ServiceWorkAppointmentLog::create([
  776. 'work_id'=>$serviceWork->id,
  777. 'worker_id'=>$params['user_id'],
  778. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  779. 'this_appointment_time'=>strtotime($params['appointment_time']),
  780. ]);
  781. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  782. $serviceWork->save();
  783. Db::commit();
  784. return true;
  785. } catch (\Exception $e) {
  786. Db::rollback();
  787. self::setError($e->getMessage());
  788. return false;
  789. }
  790. }
  791. public static function cancelAllocation($params,$userInfo){
  792. Db::startTrans();
  793. try {
  794. $work = ServiceWork::findOrEmpty($params['id']);
  795. if($work->isEmpty()){
  796. throw new Exception('工单不存在');
  797. }
  798. if($work->work_status >=6 ){
  799. throw new \Exception('工单状态只能修改待结算之前的');
  800. }
  801. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  802. if($worker->isEmpty()){
  803. throw new \Exception('工程师不存在');
  804. }
  805. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  806. $work->master_worker_id = 0;
  807. $work->work_status = 0;
  808. $work->dispatch_time = 0;
  809. $work->save();
  810. $work_log = [
  811. 'work_id'=>$work->id,
  812. 'master_worker_id'=>$params['master_worker_id'],
  813. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  814. ];
  815. ServiceWorkerAllocateWorkerLogic::add($work_log);
  816. Db::commit();
  817. return true;
  818. }catch(\Exception $e){
  819. Db::rollback();
  820. dd($e->getMessage());
  821. self::setError($e->getMessage());
  822. return false;
  823. }
  824. }
  825. public static function addCustomerLog($params)
  826. {
  827. Db::startTrans();
  828. try {
  829. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  830. if($serviceWork->isEmpty()){
  831. throw new \Exception('工单不存在');
  832. }
  833. ServiceWorkCustomerLog::create([
  834. 'work_id'=>$serviceWork->id,
  835. 'content'=>$params['content']??'',
  836. 'admin_id'=>$params['admin_id']??0,
  837. 'create_time'=>time(),
  838. ]);
  839. Db::commit();
  840. return true;
  841. } catch (\Exception $e) {
  842. Db::rollback();
  843. self::setError($e->getMessage());
  844. return false;
  845. }
  846. }
  847. }