ServiceWorkLogic.php 38 KB

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