1
0

ServiceWorkLogic.php 41 KB

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