ServiceWorkLogic.php 39 KB

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