ServiceWorkLogic.php 37 KB

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