ServiceWorkLogic.php 43 KB

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