1
0

ServiceWorkLogic.php 40 KB

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