ServiceWorkLogic.php 40 KB

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