ServiceWorkLogic.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  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\adminapi\logic\spare_part\SparePartLogic;
  16. use app\adminapi\logic\user\UserLogic;
  17. use app\api\logic\ServiceOrderLogic;
  18. use app\api\logic\UserCouponLogic;
  19. use app\common\enum\ThirdTypeEnum;
  20. use app\common\enum\worker\WorkerAccountLogEnum;
  21. use app\common\logic\ExternalPlatformLogic;
  22. use app\common\logic\ThirdOrderLogic;
  23. use app\common\logic\WorkerAccountLogLogic;
  24. use app\common\model\external\ExternalPlatformOrders;
  25. use app\common\model\third\ThirdOrders;
  26. use app\common\model\works\ServiceWorkDeterminedPrice;
  27. use app\workerapi\logic\MasterWorkerLogic;
  28. use think\Exception;
  29. use think\db\Query;
  30. use think\facade\Db;
  31. use think\facade\Log;
  32. use app\common\logic\BaseLogic;
  33. use app\api\logic\PerformanceLogic;
  34. use app\common\model\dict\DictData;
  35. use app\common\model\coupon\UserCoupon;
  36. use app\common\model\works\ServiceWork;
  37. use app\common\model\recharge\OrderGoods;
  38. use app\common\model\spare_part\SparePart;
  39. use app\common\model\works\ServiceWorkLog;
  40. use app\common\model\coupon\CouponCategory;
  41. use app\common\model\recharge\RechargeOrder;
  42. use app\common\model\works\ServiceWorkSpare;
  43. use app\workerapi\logic\ServiceWorkLogLogic;
  44. use app\common\model\orders\OrderEffectiveLog;
  45. use app\common\model\master_worker\MasterWorker;
  46. use app\common\model\training\TrainingWorkerTask;
  47. use app\common\model\performance\PerformanceRules;
  48. use app\common\model\works\ServiceWorkCustomerLog;
  49. use app\workerapi\logic\ServiceWorkReceiveLogLogic;
  50. use app\common\model\master_worker\MasterWorkerTeam;
  51. use app\common\model\works\ServiceWorkAppointmentLog;
  52. use app\workerapi\logic\ServiceWorkerAllocateWorkerLogic;
  53. use app\common\model\master_worker\MasterWorkerAccountLog;
  54. use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
  55. use app\common\model\master_commission\MasterWorkerCommissionRatio;
  56. use app\common\model\master_commission\MasterWorkerCommissionConfig;
  57. use app\common\model\service_area\ServiceArea;
  58. use app\common\service\call\VirtualCallService;
  59. use think\facade\Cache;
  60. /**
  61. * ServiceWork逻辑
  62. * Class ServiceWorkLogic
  63. * @package app\adminapi\logic\works
  64. */
  65. class ServiceWorkLogic extends BaseLogic
  66. {
  67. /**
  68. * @notes 编辑
  69. * @param array $params
  70. * @return bool
  71. * @author likeadmin
  72. * @date 2024/07/10 18:17
  73. */
  74. public static function edit(array $params): bool
  75. {
  76. Db::startTrans();
  77. try {
  78. $userId = UserLogic::getUserIdByMobile($params['mobile']);
  79. $service_area_id = ServiceArea::serviceAreaId(['lon' => $params['lon'], 'lat' => $params['lat']]);
  80. if($params['address'] && (empty($params['lon']) || empty($params['lat']))){
  81. $lon_lat = get_address_lat_lng($params['address']);
  82. $params['lon'] = $lon_lat['lon'];
  83. $params['lat'] = $lon_lat['lat'];
  84. }
  85. ServiceWork::where('id', $params['id'])->update([
  86. 'real_name' => $params['real_name'],
  87. 'mobile' => $params['mobile'],
  88. 'user_id' => $userId,
  89. 'address' => $params['address'],
  90. 'appointment_time' => strtotime($params['appointment_time']),
  91. 'estimated_finish_time' => $params['estimated_finish_time'],
  92. 'lon' => $params['lon'],
  93. 'lat' => $params['lat'],
  94. 'service_area_id' => $service_area_id,
  95. ]);
  96. \app\common\model\orders\RechargeOrder::where('work_id',$params['id'])->update(['user_id' => $userId]);
  97. Db::commit();
  98. return true;
  99. } catch (\Exception $e) {
  100. Db::rollback();
  101. self::setError($e->getMessage());
  102. return false;
  103. }
  104. }
  105. /**
  106. *
  107. * @return false|void
  108. */
  109. public static function pickWork($params)
  110. {
  111. Db::startTrans();
  112. try {
  113. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  114. if($work->isEmpty()){
  115. throw new Exception('工单不存在');
  116. }
  117. if ($work->work_status > 1 && $work->receive_time > 0){
  118. throw new Exception('工单已领取,请勿重复点击');
  119. }
  120. $receive_time = time();
  121. $work->work_status = 2;//待联系
  122. $work->service_status = 1;//服务中
  123. $work->receive_time = $receive_time;
  124. $work->save();
  125. //添加变更日志
  126. $work_log = [
  127. 'work_id'=>$work->id,
  128. 'master_worker_id'=>$work->master_worker_id,
  129. 'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',$receive_time).'领取了工单',
  130. ];
  131. ServiceWorkLogLogic::add($work_log);
  132. //添加领单日志
  133. ServiceWorkReceiveLogLogic::add($work_log);
  134. Db::commit();
  135. // 工单状态通知外部平台 即工程师接单成功
  136. if($work->external_platform_id > 0){
  137. event('ExternalPlatform', [
  138. 'send_code' => 1001,
  139. 'params' => [
  140. 'work_id' => $work->id,
  141. ]
  142. ]);
  143. }
  144. }
  145. catch (\Exception $e) {
  146. Db::rollback();
  147. self::setError($e->getMessage());
  148. return false;
  149. }
  150. }
  151. /**
  152. * 预约成功,等待上门
  153. * @return false|void
  154. */
  155. public static function appointWork($params)
  156. {
  157. Db::startTrans();
  158. try {
  159. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  160. if($work->isEmpty()){
  161. throw new Exception('工单不存在');
  162. }
  163. if($work->work_status != 2){
  164. throw new Exception('请勿重复点击');
  165. }
  166. //判断是否有待审核的预约时间修改记录
  167. $exists = ServiceWorkAppointmentLog::where(['work_id'=>$work->id,'status'=>0])->value('id');
  168. if ($exists){
  169. throw new Exception('存在待审核的预约时间修改记录,无法修改');
  170. }
  171. //验证更改的预约时间必须是在领单时间内的半小内修改,否则不允许修改
  172. // if(strtotime($work->appointment_time) != strtotime($params['appointment_time']) && (time()-strtotime($work->receive_time))>1800){
  173. // throw new Exception('距离领单时间已超过半小时,无法修改预约时间,请联系客服');
  174. // }
  175. //添加预约时间修改待审核记录
  176. ServiceWorkAppointmentLog::create([
  177. 'status'=>0,//待审核
  178. 'work_id'=>$work->id,
  179. 'worker_id'=>$params['user_id'],
  180. 'last_appointment_time'=>strtotime($work->appointment_time),
  181. 'this_appointment_time'=>strtotime($params['appointment_time']),
  182. ]);
  183. // $work->work_status = 3;//待上门
  184. // $work->appointment_time = strtotime($params['appointment_time']);
  185. // $work->save();
  186. //添加变更日志
  187. // $work_log = [
  188. // 'work_id'=>$work->id,
  189. // 'master_worker_id'=>$work->master_worker_id,
  190. // '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'].'预约上门',
  191. // ];
  192. // ServiceWorkLogLogic::add($work_log);
  193. Db::commit();
  194. }
  195. catch (\Exception $e) {
  196. self::setError($e->getMessage());
  197. return false;
  198. }
  199. }
  200. /**
  201. * 工程师确认上门
  202. * @param $params
  203. * @return false|void
  204. */
  205. public static function confirmDoor($params)
  206. {
  207. Db::startTrans();
  208. try {
  209. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  210. if($work->isEmpty()){
  211. throw new Exception('工单不存在');
  212. }
  213. if(!in_array($work->work_status,[2,3])){
  214. throw new Exception('禁止操作上门');
  215. }
  216. $work->finally_door_time = time();//最后上门时间
  217. $work->work_status = 4;//已上门
  218. $work->save();
  219. //添加变更日志
  220. $work_log = [
  221. 'work_id'=>$work->id,
  222. 'master_worker_id'=>$work->master_worker_id,
  223. '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()).'已上门',
  224. ];
  225. ServiceWorkLogLogic::add($work_log);
  226. Db::commit();
  227. }
  228. catch (\Exception $e) {
  229. Db::rollback();
  230. self::setError($e->getMessage());
  231. return false;
  232. }
  233. }
  234. /**
  235. * 工程师确认报价单
  236. * @param $params
  237. * @return false|void
  238. */
  239. public static function confirmPrice($params)
  240. {
  241. Db::startTrans();
  242. try {
  243. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  244. if($work->isEmpty()){
  245. throw new Exception('工单不存在');
  246. }
  247. //搜索待支付订单
  248. $paid_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>1])->findOrEmpty()->toArray();
  249. if(empty($paid_order)){
  250. throw new Exception('订单错误');
  251. }
  252. if($work->work_status != 4){
  253. throw new Exception('请勿重复操作');
  254. }
  255. // 商城配件.计算配件总价 id company_price original_price offering_price number
  256. $spare_total = 0;
  257. $work->spare_total = 0;
  258. isset($params['spare_parts']) && $params['spare_parts'] && $params['spare_parts'] = json_decode($params['spare_parts'], true);
  259. $spare_parts_ids = ServiceWorkSpare::where('service_work_id',$work['id'])->column('id');
  260. if(isset($params['spare_parts']) && $params['spare_parts']){
  261. if (count($params['spare_parts']) > 10) {
  262. throw new Exception('商城配件最多10个');
  263. }
  264. $ids = array_column($params['spare_parts'],'id');
  265. $spare_parts = SparePart::where('id','in',$ids)->column('id as spare_part_id,spare_name,spare_image,company_price,original_price,offering_price,spare_number,spare_unit,brand');
  266. $spare_parts = array_column($spare_parts,null,'spare_part_id');
  267. foreach ($params['spare_parts'] as $k => $item){
  268. if (!isset($spare_parts[$item['id']])){
  269. throw new Exception('配件信息错误');
  270. }
  271. $spare_part = $spare_parts[$item['id']];
  272. $spare_total += $spare_part['company_price']*$item['spare_number'];
  273. $data = array_merge($spare_part, ['service_work_id' => $work['id'], 'spare_number' => $item['spare_number'] * $spare_part['spare_number']]);
  274. if (current($spare_parts_ids)) {
  275. //修改
  276. ServiceWorkSpare::where("id",current($spare_parts_ids))->update($data);
  277. } else {
  278. //新增
  279. ServiceWorkSpare::create($data);
  280. }
  281. array_shift($spare_parts_ids);
  282. }
  283. $work->spare_total += $spare_total;
  284. }
  285. //自选配件
  286. isset($params['self_spare_parts']) && $params['self_spare_parts'] && $params['self_spare_parts'] = json_decode($params['self_spare_parts'], true);
  287. if(isset($params['self_spare_parts']) && $params['self_spare_parts']){
  288. if (count($params['self_spare_parts']) > 10) {
  289. throw new Exception('自选配件最多10个');
  290. }
  291. foreach ($params['self_spare_parts'] as $item){
  292. $spare_total += $item['offering_price']*$item['spare_number'];
  293. $data = [
  294. 'service_work_id'=>$work['id'],
  295. 'spare_name' => $item['spare_name'],
  296. 'spare_image' => empty($item['spare_image']) ? '' : $item['spare_image'],
  297. 'offering_price' => $item['offering_price'],
  298. 'company_price' => 0,
  299. 'original_price' => 0,
  300. 'spare_number' => $item['spare_number'],
  301. 'spare_part_id' => 0,
  302. 'brand' => $item['brand'],
  303. 'status' => 0,
  304. ];
  305. if (current($spare_parts_ids)) {
  306. //修改
  307. ServiceWorkSpare::where("id",current($spare_parts_ids))->update($data);
  308. } else {
  309. //新增
  310. ServiceWorkSpare::create($data);
  311. }
  312. array_shift($spare_parts_ids);
  313. }
  314. $work->spare_total += $spare_total;
  315. }
  316. //删除多余的配件数据
  317. if ($spare_parts_ids) {
  318. ServiceWorkSpare::where('id','in',$spare_parts_ids)->delete();
  319. }
  320. // 添加工单尾款报价记录 - 即配件费用
  321. if(isset($params['price_content'])){
  322. !is_array($params['price_content']) && $params['price_content'] = json_decode($params['price_content'], true);
  323. ServiceWorkDeterminedPrice::where('work_id',$work->id)->delete();
  324. ServiceWorkDeterminedPrice::create([
  325. 'work_id'=>$work->id,
  326. 'content'=>$params['price_content']??[],
  327. ]);
  328. $work->spare_total += array_sum('price');
  329. }
  330. // order_amount 原 = $params['amount'] 修改为 = 配件总价 + 服务尾款
  331. $order_amount = $params['amount'] + $spare_total;
  332. //定金存在尾款结算功能,全款直接提交
  333. if($paid_order['payment_type']==1){
  334. $un_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>0])->findOrEmpty();
  335. if($un_order->isEmpty()){
  336. //新增待支付尾款
  337. $order_data = [
  338. 'order_type'=>$paid_order['order_type'],
  339. 'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
  340. 'work_id'=>$paid_order['work_id'],
  341. 'user_id'=>$paid_order['user_id'],
  342. 'payment_type'=>2,
  343. 'order_total'=>$order_amount,
  344. //'order_amount'=>$params['amount'],
  345. 'order_amount'=>$order_amount,
  346. 'order_terminal'=>$paid_order['order_terminal']
  347. ];
  348. RechargeOrder::create($order_data);
  349. }else{
  350. //修改尾款信息
  351. $un_order->order_total = $order_amount;
  352. //$un_order->order_amount = $params['amount'];
  353. $un_order->order_amount = $order_amount;
  354. $un_order->save();
  355. }
  356. //更新服务费用
  357. $work->service_fee = $paid_order['paid_amount']+$params['amount'];
  358. }
  359. //总工单费用
  360. $work->work_total = $work->service_fee+$spare_total;
  361. $work->work_images = $params['work_images'];
  362. $work->explanation = $params['explanation']??'';
  363. // 是否有三方的订单来源,若存在说明三方有系统 则自动确认报价
  364. $platformOrders = ExternalPlatformOrders::where('work_id',$work->id)->findOrEmpty();
  365. if($platformOrders->isEmpty()){
  366. $work->user_confirm_status = 1;//待确认报价
  367. }else{
  368. $work->work_status = 5;
  369. $work->user_confirm_status = 2;
  370. }
  371. $work->price_approval = 0;
  372. $work->save();
  373. //添加变更日志
  374. $work_log = [
  375. 'work_id'=>$work->id,
  376. 'master_worker_id'=>$work->master_worker_id,
  377. '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()).'提交了报价单',
  378. ];
  379. ServiceWorkLogLogic::add($work_log);
  380. Db::commit();
  381. // 商家报价通知外部平台 即报价
  382. if($work->external_platform_id > 0){
  383. event('ExternalPlatform', [
  384. 'send_code' => 1006,
  385. 'params' => [
  386. 'work_id' => $work->id,
  387. ]
  388. ]);
  389. }
  390. }
  391. catch (\Exception $e) {
  392. Db::rollback();
  393. self::setError($e->getMessage());
  394. return false;
  395. }
  396. }
  397. /**
  398. * 工程师修改自选配件的图片
  399. * @param $params
  400. * @return false|void
  401. */
  402. public static function selfSparePart($params)
  403. {
  404. Db::startTrans();
  405. try {
  406. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  407. if($work->isEmpty()){
  408. throw new Exception('工单不存在');
  409. }
  410. $audit = ServiceWorkSpare::where(['id' => $params['id'],'service_work_id'=>$work['id']])->findOrEmpty();
  411. if(!$audit->isEmpty() && ($audit['status']!=0 && $audit['status']!=2) ){
  412. throw new Exception('当前工单配件不允许修改');
  413. }
  414. if (empty($params['spare_image'])){
  415. throw new Exception('请上传配件图片');
  416. }
  417. //修改
  418. ServiceWorkSpare::where("id",$params['id'])->where('service_work_id', $work['id'])->update(['spare_image' => $params['spare_image'], 'status' => 0]);
  419. Db::commit();
  420. return true;
  421. } catch (\Exception $e) {
  422. Db::rollback();
  423. self::setError($e->getMessage());
  424. return false;
  425. }
  426. }
  427. /**
  428. * 工程师确认服务完成
  429. * @param $params
  430. * @return false|void
  431. */
  432. public static function confirmServiceFinish($params)
  433. {
  434. Db::startTrans();
  435. try {
  436. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  437. if($work->isEmpty()){
  438. throw new Exception('工单不存在');
  439. }
  440. if($work->user_confirm_status !=2){
  441. throw new Exception('请勿重复操作');
  442. }
  443. $work->finished_images = $params['finished_images'];
  444. $work->user_confirm_status = 3;//待确认服务完成
  445. $work->save();
  446. //添加变更日志
  447. $work_log = [
  448. 'work_id'=>$work->id,
  449. 'master_worker_id'=>$work->master_worker_id,
  450. '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()).'提交了待用户确认服务完成',
  451. ];
  452. ServiceWorkLogLogic::add($work_log);
  453. Db::commit();
  454. // 外部平台工单 - 通知外边平台
  455. if($work->external_platform_id > 0){
  456. /*event('ExternalPlatform', [
  457. 'scene' => 'service_finish',
  458. 'params' => [
  459. 'work_id' => $work->id,
  460. ]
  461. ]);*/
  462. }
  463. } catch (\Exception $e) {
  464. Db::rollback();
  465. self::setError($e->getMessage());
  466. return false;
  467. }
  468. }
  469. public static function allocateWorker($params,$userInfo){
  470. Db::startTrans();
  471. try {
  472. $work = ServiceWork::findOrEmpty($params['id']);
  473. if($work->isEmpty()){
  474. throw new Exception('工单不存在');
  475. }
  476. if($work->work_status >=6 ){
  477. throw new \Exception('工单状态只能修改待结算之前的');
  478. }
  479. if($work->master_worker_id == $params['master_worker_id'] && !isset($params['is_grab_order'])){
  480. throw new \Exception('分配的工程师相同');
  481. }
  482. $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'is_disable' =>0])->findOrEmpty();
  483. if($worker->isEmpty()){
  484. throw new \Exception('工程师不存在或被禁用');
  485. }
  486. if($worker->master_worker_id && !isset($params['is_grab_order'])){
  487. MasterWorker::setWorktotal('dec',$worker->master_worker_id);
  488. }
  489. $work->master_worker_id = $params['master_worker_id'];
  490. $work->work_status = 1;
  491. $work->dispatch_time = time();
  492. //长期合作工程师,派单即领单
  493. if ($worker->type == 2){
  494. $work->work_status = 2;
  495. $work->receive_time = time();
  496. }
  497. MasterWorker::setWorktotal('inc',$params['master_worker_id']);
  498. $work->save();
  499. $work_log = [
  500. 'work_id'=>$work->id,
  501. 'master_worker_id'=>$work->master_worker_id,
  502. 'type' => isset($params['is_grab_order'])?3:0,
  503. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  504. ];
  505. ServiceWorkerAllocateWorkerLogic::add($work_log);
  506. Db::commit();
  507. //美团的订单更新履约状态为已分配
  508. if($work->third_type == 1){
  509. ThirdOrderLogic::updateorderfulfillinfo($work,ThirdTypeEnum::MEITUAN_MEITUAN);
  510. }
  511. // 工程师派单通知【给工程师的通知】【公众号通知,不发短信】
  512. $workDetail = ServiceWorkLogic::detail($params);
  513. $res = event('Notice', [
  514. 'scene_id' => 113,
  515. 'params' => [
  516. 'user_id' => $params['master_worker_id'],
  517. 'order_id' => $params['id'],
  518. 'thing9' => $workDetail['title'],
  519. 'time7' => $workDetail['appointment_time'],
  520. 'thing8' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  521. 'phone_number6' => asteriskString($workDetail['mobile']),
  522. ]
  523. ]);
  524. return true;
  525. }catch(\Exception $e){
  526. Db::rollback();
  527. self::setError($e->getMessage());
  528. return false;
  529. }
  530. }
  531. /**
  532. * 工单详情
  533. * @param $params
  534. * @return array|false
  535. */
  536. public static function detail($params){
  537. $work_where = !empty($params['work_sn'])?['work_sn'=>$params['work_sn']]:['id'=>$params['id']];
  538. $result = ServiceWork::with([
  539. 'worker'=> function(Query $query) {
  540. $query->field('id,worker_number,real_name,mobile,type');
  541. },
  542. 'allocateWorkerLog' =>function(Query $query){
  543. $query->field('id,work_id,opera_log,create_time');
  544. },
  545. 'serviceWorkLog' =>function(Query $query){
  546. $query->field('id,work_id,opera_log,create_time');
  547. }
  548. ])->append(['id','work_status_text','service_status_text'])
  549. ->where($work_where)
  550. ->findOrEmpty()->toArray();
  551. $result['is_operate_prohibit'] = 0;
  552. if(isset($params['user_id']) && $result['master_worker_id'] && $params['user_id'] && ($params['user_id'] != $result['master_worker_id']) ){
  553. // 带徒师傅的工单
  554. $lead_master_worker_id = TrainingWorkerTask::where('master_worker_id',$params['user_id'])->where('training_status',2)
  555. ->where('operate_status',0)->value('lead_master_worker_id');
  556. // 团队负责人编辑 工单池(包括已派队员) 工单
  557. if($params['user_info']['team_role'] == 1 && $params['user_info']['tenant_id'] == $result['tenant_id'] ){
  558. $result['is_operate_prohibit'] = 0;
  559. }elseif(!empty($lead_master_worker_id) && !empty($result['master_worker_id']) && $lead_master_worker_id == $result['master_worker_id']){
  560. // 徒查看师父的工单 不能编辑可查看
  561. $result['is_operate_prohibit'] = 1;
  562. }else{
  563. throw new \Exception('您没有权限操作该工单');
  564. }
  565. }
  566. //工程师工单按钮状态
  567. $work_service_status = 0;
  568. $work_service_status_text = '待派单';
  569. //工单状态
  570. if($result['work_status'] == 1){
  571. $work_service_status = 1;
  572. $work_service_status_text = '待领单';
  573. }
  574. if($result['work_status'] == 2){
  575. $work_service_status = 2;
  576. $work_service_status_text = '预约上门';
  577. }
  578. if($result['work_status'] == 3){
  579. $work_service_status = 3;
  580. $work_service_status_text = '等待上门';
  581. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  582. $work_service_status = 4;
  583. $work_service_status_text = '确认上门';
  584. }
  585. }
  586. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  587. $work_service_status = 5;
  588. $work_service_status_text = '确认报价';
  589. }
  590. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  591. $work_service_status = 6;
  592. $work_service_status_text = '用户确认报价中';
  593. }
  594. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  595. $work_service_status = 7;
  596. $work_service_status_text = '完成服务';
  597. }
  598. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  599. $work_service_status = 8;
  600. $work_service_status_text = '用户确认完成服务中';
  601. }
  602. if($result['work_status'] ==6){
  603. $work_service_status = 9;
  604. $work_service_status_text = '待结算';
  605. }
  606. if($result['work_status'] ==7){
  607. $work_service_status = 10;
  608. $work_service_status_text = '已完结';
  609. }
  610. if($result['work_status'] ==8){
  611. $work_service_status = 11;
  612. $work_service_status_text = '已评价';
  613. }
  614. if($result['work_status'] ==9){
  615. $work_service_status = 12;
  616. $work_service_status_text = '已退费';
  617. }
  618. $result['work_service_status'] = $work_service_status;
  619. $result['work_service_status_text'] = $work_service_status_text;
  620. //搜索当前工单下的所有订单记录
  621. $result['pay_orders'] = RechargeOrder::with(['orderGoods'=>function(Query $query){
  622. $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']);
  623. }])->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();
  624. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  625. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  626. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  627. $order_type_data = DictData::where('type_value','order_type')->column('name','value');
  628. $coupon_price = 0;
  629. foreach ($result['pay_orders'] as $k=>&$v){
  630. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  631. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  632. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  633. $v['order_type_name'] = $order_type_data[$v['order_type']];
  634. $v['pay_time'] = $v['pay_time'] && is_numeric($v['pay_time']) ? date('Y-m-d H:i:s',$v['pay_time']):'';
  635. if($v['payment_type']!=1 and !empty($result['spare_total'])){
  636. $v['order_total'] = $v['order_total'] - $result['spare_total'];
  637. $v['order_amount'] = $v['order_amount'] - $result['spare_total'];
  638. }
  639. $coupon_price += $v['coupon_price'];
  640. //服务支付类别
  641. if(!empty($v['orderGoods'][0]['goods_payment_type'])){
  642. $goods_payment_type = $v['orderGoods'][0]['goods_payment_type'];
  643. }
  644. }
  645. $result['goods_payment_type'] = !empty($goods_payment_type)?$goods_payment_type:1;
  646. //汇总优惠卷额度
  647. $result['coupon_price'] = $coupon_price;
  648. //工单总支付金额
  649. $result['worker_account'] = $result['work_amount'];
  650. // 配件信息
  651. $result['spare_parts'] = [];
  652. $result['self_spare_parts'] = [];
  653. if($result['spare_total'] > 0){
  654. $result['spare_parts'] = ServiceWorkSpare::getLists($result['id'], 1);
  655. $result['self_spare_parts'] = ServiceWorkSpare::getLists($result['id'], 2);
  656. }
  657. // 保修卡信息
  658. $result['order_effectives'] = OrderEffectiveLog::with(['goods'=>function ($query) {
  659. $query->with(['goodsCategory'=>function ($query1) {
  660. $query1->field(['name','picture']);
  661. }]);
  662. }])->where('work_id',$result['id'])
  663. ->field(['id','goods_id','sn','effective_unit','effective_num','remark','end_effective_time'])
  664. ->append(['effective_unit_text'])
  665. ->order('create_time desc')
  666. ->select()
  667. ->toArray();
  668. //查收工程师提成金额
  669. if (!empty($params['user_id']) && $result['worker']['type'] == 2) {
  670. $result['change_amount'] = "-";
  671. $result['settlement_amount'] = "-";
  672. $result['add_work_amount'] = "-";
  673. } else {
  674. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  675. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  676. }
  677. //质保金相关金额
  678. $result['retention'] = MasterWorkerRetentionMoneyLog::where('work_id',$result['id'])->visible(['action','amount'])->select()
  679. ->each(function ($item){
  680. $item['amount'] = $item['action'] == 1 ? '+'.$item['amount'] : '-'.$item['amount'];
  681. })->toArray();
  682. //保修工单时的信息
  683. $result['effective_income_amount'] = 0;
  684. if(!empty($result['order_effective_id'])){
  685. $order_effective = OrderEffectiveLog:: findOrEmpty($result['order_effective_id']);
  686. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  687. if($serviceWork->master_worker_id != $result['master_worker_id']){
  688. $result['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  689. }
  690. }
  691. //获取美团订单信息
  692. $result['meituan_order'] = [];
  693. if($result['third_type']==1){
  694. $result['meituan_order'] = ThirdOrders::where(['work_id'=>$result['id']])->order('create_time desc')->findOrEmpty();
  695. }
  696. //工程师预约时间修改申请记录
  697. if (!empty($params['user_id'])) {
  698. $result['appointment_log'] = ServiceWorkAppointmentLog::where('work_id',$result['id'])->where('worker_id',$params['user_id'])->where('status','<>',1)->field('id,work_id,worker_id,last_appointment_time,this_appointment_time,status,create_time')->order('id desc')->findOrEmpty();
  699. if ($result['appointment_log']){
  700. $result['appointment_log']['last_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['last_appointment_time']);
  701. $result['appointment_log']['this_appointment_time'] = date('Y/m/d H:i:s',$result['appointment_log']['this_appointment_time']);
  702. }
  703. }
  704. return $result;
  705. }
  706. public static function getUserCouponDetails($params)
  707. {
  708. try{
  709. $work = ServiceWork::where('id',$params['id'])->findOrEmpty();
  710. if(!$work){
  711. throw new \Exception('工单不存在');
  712. }
  713. $coupon_all_ids =UserCoupon::where('user_id',$work['user_id'])
  714. ->where('voucher_count','>',0)
  715. ->where('voucher_status',0)
  716. ->where('expire_time','>',time())
  717. ->column('coupon_id');
  718. $coupon_ids = CouponCategory::where('goods_category_id',$work['goods_category_id'])->whereIn('coupon_id',$coupon_all_ids)->column('coupon_id');
  719. $data = UserCoupon::where('user_id',$work['user_id'])
  720. ->where('voucher_count','>',0)
  721. ->where('voucher_status',0)
  722. ->whereIn('coupon_id',$coupon_ids)
  723. ->append(['discount_ratio_text'])
  724. ->where('expire_time','>',time())
  725. ->visible(['id','coupon_id','amount','amount_require','begin_use','discount_ratio','event_name','expire_time','max_deductible_price','server_category_name','mold_type'])
  726. ->select()->toArray();
  727. foreach($data as $k => $v){
  728. $data[$k]['begin_use'] = date("Y-m-d H:i:s",$v['begin_use'] );
  729. $data[$k]['expire_time'] = date("Y-m-d H:i:s",$v['expire_time'] );
  730. $data[$k]['amount_require'] = '满'.$v['amount_require'].'可用';
  731. }
  732. return $data;
  733. } catch(\Exception $e){
  734. self::setError($e->getMessage());
  735. return false;
  736. }
  737. }
  738. public static function getDetailWorkServiceStatus($params)
  739. {
  740. $result = ServiceWork::where('id',$params['id'])->field('work_status,user_confirm_status,appointment_time,price_approval,appoint_approval')->findOrEmpty()->toArray();
  741. //工程师工单按钮状态
  742. $work_service_status = 0;
  743. //工单状态
  744. if($result['work_status'] == 1){
  745. $work_service_status = 1;
  746. }
  747. if($result['work_status'] == 2){
  748. $work_service_status = 2;
  749. }
  750. if($result['work_status'] == 3){
  751. $work_service_status = 3;
  752. if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
  753. $work_service_status = 4;
  754. }
  755. }
  756. if($result['work_status'] == 4 and $result['user_confirm_status']==0){
  757. $work_service_status = 5;
  758. }
  759. if($result['work_status'] == 4 and $result['user_confirm_status']==1){
  760. $work_service_status = 6;
  761. }
  762. if($result['work_status'] == 5 and $result['user_confirm_status']==2){
  763. $work_service_status = 7;
  764. }
  765. if($result['work_status'] == 5 and $result['user_confirm_status']==3){
  766. $work_service_status = 8;
  767. }
  768. if($result['work_status'] ==6){
  769. $work_service_status = 9;
  770. }
  771. if($result['work_status'] ==7){
  772. $work_service_status = 10;
  773. }
  774. if($result['work_status'] ==8){
  775. $work_service_status = 11;
  776. }
  777. if($result['work_status'] ==9){
  778. $work_service_status = 12;
  779. }
  780. return ['work_service_status'=>$work_service_status,'price_approval'=>$result['price_approval'],'appoint_approval'=>$result['appoint_approval']];
  781. }
  782. /**
  783. * @notes 取消操作
  784. * @param array $params
  785. * @return bool
  786. * @author likeadmin
  787. * @date 2024/09/19 10:48
  788. */
  789. public static function cancel(array $params): bool
  790. {
  791. Db::startTrans();
  792. try {
  793. // 04-11-12 不做任何限制强制取消,已支付的费用给工程师余额
  794. $serviceWorkInfo = ServiceWork::find($params['id']);
  795. if((int)$serviceWorkInfo['user_confirm_status'] === 5 || (int)$serviceWorkInfo['service_status'] > 2){
  796. throw new \Exception('用户已完结该工单或已取消,已退款,不可执行取消');
  797. }
  798. //工单如果存在费用情况,不允许取消
  799. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('pay_status', 1)->value('paid_amount');
  800. if($paid_amount > 0 and ($serviceWorkInfo['third_type'] == 0 && $serviceWorkInfo['external_platform_id'] == 0)){
  801. // 4=已上门,5=服务中,6=待结算, 即工程师已上门服务过
  802. throw new Exception('工单存在费用情况,不允许取消,请走退费流程');
  803. }
  804. ServiceWork::where('id', $params['id'])->update([
  805. 'work_status' => 9,
  806. 'service_status' => 4
  807. ]);
  808. ServiceWorkLog::create([
  809. 'work_id' => $params['id'],
  810. 'master_worker_id' => $serviceWorkInfo['master_worker_id'],
  811. 'opera_log' => "工单:{$serviceWorkInfo['work_sn']}已取消".($params['remark']??'')
  812. ]);
  813. Db::commit();
  814. Log::info('取消工单'.json_encode([$serviceWorkInfo]));
  815. return true;
  816. } catch (\Exception $e) {
  817. Db::rollback();
  818. self::setError($e->getMessage());
  819. Log::info('取消工单-Error'.json_encode([$e->getMessage()]));
  820. return false;
  821. }
  822. }
  823. /**
  824. * @notes 工程师结算操作
  825. * @param array $params
  826. * @return bool
  827. * @author likeadmin
  828. * @date 2024/09/19 10:48
  829. */
  830. public static function settlement(array $params): bool
  831. {
  832. Db::startTrans();
  833. try {
  834. $serviceWorkInfo = ServiceWork::find($params['id']);
  835. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  836. throw new \Exception('该工单非待结算状态');
  837. }
  838. $ratio = 0;
  839. $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$serviceWorkInfo->master_worker_id)->where('voucher_status',2)->findOrEmpty();
  840. !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$serviceWorkInfo->goods_category_id)->value('ratio')?:0;
  841. if($commissionConfig->isEmpty() || empty($ratio)){
  842. //获取工单对应的商品id
  843. $order_sns = \app\common\model\orders\RechargeOrder::where('work_id',$serviceWorkInfo->id)->column('sn');
  844. $goods_id = OrderGoods::whereIn('sn',$order_sns)->value('goods_id');
  845. $rule = PerformanceRules::whereFindInSet('goods_id',$goods_id)->findOrEmpty();
  846. if($rule->isEmpty()){
  847. throw new \Exception('请配置商品业绩规则');
  848. }
  849. PerformanceLogic::calculatePerformance($serviceWorkInfo);
  850. }else{
  851. // 存在服务分类比例进行结算
  852. PerformanceLogic::calculatePerformanceCommission($serviceWorkInfo);
  853. }
  854. Db::commit();
  855. return true;
  856. } catch (\Exception $e) {
  857. Db::rollback();
  858. self::setError($e->getMessage());
  859. return false;
  860. }
  861. }
  862. /**
  863. * 工程师配件审核结算操作
  864. * @param array $params
  865. * @return bool
  866. * @author liugc <466014217@qq.com>
  867. * @date 2025/5/9 9:14
  868. */
  869. public static function settlementSpare(array $params): bool
  870. {
  871. Db::startTrans();
  872. try {
  873. $spare = ServiceWorkSpare::where('id',$params['id'])->findOrEmpty();
  874. if($spare->isEmpty()){
  875. throw new \Exception('无配件审核');
  876. }else{
  877. $serviceWorkInfo = ServiceWork::find($spare->service_work_id);
  878. Log::info( '配件审核结算'.json_encode([$serviceWorkInfo['work_pay_status']]));
  879. if((int)$serviceWorkInfo['work_pay_status'] !== 3){
  880. throw new \Exception('该工单非待结算状态');
  881. }
  882. $spare->status = $params['status']??0;
  883. $spare->remark = $params['remark']??'';
  884. $spare->save();
  885. }
  886. Db::commit();
  887. // 是否所有配件审核完成
  888. SparePartLogic::isExamineOk($spare->service_work_id);
  889. return true;
  890. } catch (\Exception $e) {
  891. Db::rollback();
  892. self::setError($e->getMessage());
  893. return false;
  894. }
  895. }
  896. /**
  897. * 获取所有改约通知
  898. * @param $userId
  899. * @return array|false
  900. */
  901. public static function getAppointmentNotice($userId)
  902. {
  903. return ServiceWork::where(['master_worker_id'=>$userId,'appoint_approval'=>1])
  904. ->where('work_status','>',1)
  905. ->where('work_status','<',7)
  906. ->field(['id', 'work_sn','real_name','mobile', 'address', 'title', 'appointment_time','work_status'])
  907. ->order(['appointment_time' => 'asc'])//上门时间排序
  908. ->select()->each(function (&$item){
  909. $item['last_appointment_time'] = date('Y-m-d H:i:s',ServiceWorkAppointmentLog::where('work_id',$item['id'])->order('id desc')->value('last_appointment_time'));
  910. })
  911. ->toArray();
  912. }
  913. /**
  914. * @param $params
  915. * @return bool
  916. */
  917. public static function submitAppointment($params)
  918. {
  919. Db::startTrans();
  920. try {
  921. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  922. if($serviceWork->isEmpty()){
  923. throw new \Exception('工单不存在');
  924. }
  925. $serviceWork->appoint_approval = 2;
  926. $serviceWork->save();
  927. Db::commit();
  928. return true;
  929. } catch (\Exception $e) {
  930. Db::rollback();
  931. self::setError($e->getMessage());
  932. return false;
  933. }
  934. }
  935. /**
  936. * @param $params
  937. * @return bool
  938. */
  939. public static function submitChangePrice($params)
  940. {
  941. Db::startTrans();
  942. try {
  943. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  944. if($serviceWork->isEmpty()){
  945. throw new \Exception('工单不存在');
  946. }
  947. $serviceWork->work_status = 4;
  948. $serviceWork->user_confirm_status = 0;
  949. $serviceWork->price_approval = 2;
  950. $serviceWork->save();
  951. Db::commit();
  952. return true;
  953. } catch (\Exception $e) {
  954. Db::rollback();
  955. self::setError($e->getMessage());
  956. return false;
  957. }
  958. }
  959. public static function notApproved($params)
  960. {
  961. Db::startTrans();
  962. try {
  963. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  964. if($serviceWork->isEmpty()){
  965. throw new \Exception('工单不存在');
  966. }
  967. $serviceWork->refund_approval = 3;
  968. $serviceWork->save();
  969. Db::commit();
  970. return true;
  971. } catch (\Exception $e) {
  972. Db::rollback();
  973. self::setError($e->getMessage());
  974. return false;
  975. }
  976. }
  977. public static function againDoor($params)
  978. {
  979. Db::startTrans();
  980. try {
  981. $serviceWork = ServiceWork::where('work_sn',$params['work_sn'])->findOrEmpty();
  982. if($serviceWork->isEmpty()){
  983. throw new \Exception('工单不存在');
  984. }
  985. //更新预约日志
  986. //更新工单未确认上门的状态
  987. $serviceWork->work_status = 3;
  988. $serviceWork->user_confirm_status = 0;
  989. $appoint = ServiceWorkAppointmentLog::where(['work_id'=>$serviceWork->id,'worker_id'=>$params['user_id']])->count();
  990. if($appoint > 2){
  991. throw new Exception('您的修改预约时间次数已到上限,请联系客服处理');
  992. }
  993. ServiceWorkAppointmentLog::create([
  994. 'work_id'=>$serviceWork->id,
  995. 'worker_id'=>$params['user_id'],
  996. 'last_appointment_time'=>strtotime($serviceWork->appointment_time),
  997. 'this_appointment_time'=>strtotime($params['appointment_time']),
  998. ]);
  999. $serviceWork->appointment_time = strtotime($params['appointment_time']);
  1000. $serviceWork->save();
  1001. Db::commit();
  1002. return true;
  1003. } catch (\Exception $e) {
  1004. Db::rollback();
  1005. self::setError($e->getMessage());
  1006. return false;
  1007. }
  1008. }
  1009. /**
  1010. * 取消分配
  1011. * @param $params
  1012. * @param $userInfo
  1013. * @param $type:1后台管理员取消;2工程师端取消
  1014. * @return bool
  1015. */
  1016. public static function cancelAllocation($params,$userInfo,$type = 1){
  1017. Db::startTrans();
  1018. try {
  1019. $work = ServiceWork::findOrEmpty($params['id']);
  1020. if($work->isEmpty()){
  1021. throw new Exception('工单不存在');
  1022. }
  1023. if($work->work_status >=6 ){
  1024. throw new \Exception('工单状态只能修改待结算之前的');
  1025. }
  1026. $worker = MasterWorker::where(['id'=>$work->master_worker_id])->findOrEmpty();
  1027. if($worker->isEmpty()){
  1028. throw new \Exception('工程师不存在');
  1029. }
  1030. if ($type == 2 && $worker->type == 2) {
  1031. throw new \Exception('您当前无权限取消分配');
  1032. }
  1033. if ($work->tenant_id > 0) {
  1034. //团队订单取消时,派单数量减1
  1035. $updateData = date("H",strtotime($work->appointment_time)) < 12 ? ['am_order' => Db::raw('am_order - 1')] : ['pm_order' => Db::raw('pm_order - 1')];
  1036. MasterWorkerTeam::where('master_worker_id',$work->master_worker_id)->where('tenant_id',$work->tenant_id)->update($updateData);
  1037. }
  1038. $params['master_worker_id'] = (isset($params['master_worker_id']) && !empty($params['master_worker_id']))?$params['master_worker_id']:$work->master_worker_id;
  1039. MasterWorker::setWorktotal('dec',$work->master_worker_id);
  1040. $work->master_worker_id = 0;
  1041. $work->tenant_id = 0;
  1042. $work->work_status = 0;
  1043. $work->dispatch_time = 0;
  1044. $work->first_contact_time = 0;
  1045. $work->estimated_finish_time = 0;
  1046. $work->save();
  1047. $work_log = [
  1048. 'work_id'=>$work->id,
  1049. 'master_worker_id'=>$params['master_worker_id'],
  1050. 'type' => 1,
  1051. 'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'取消了工程师'.'编号['.$worker->worker_number.']'.$worker->real_name
  1052. ];
  1053. ServiceWorkerAllocateWorkerLogic::add($work_log);
  1054. Db::commit();
  1055. return true;
  1056. }catch(\Exception $e){
  1057. Db::rollback();
  1058. self::setError($e->getMessage());
  1059. return false;
  1060. }
  1061. }
  1062. public static function addCustomerLog($params)
  1063. {
  1064. Db::startTrans();
  1065. try {
  1066. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1067. if($serviceWork->isEmpty()){
  1068. throw new \Exception('工单不存在');
  1069. }
  1070. ServiceWorkCustomerLog::create([
  1071. 'work_id'=>$serviceWork->id,
  1072. 'type'=>$params['type']??0,
  1073. 'content'=>$params['content']??'',
  1074. 'admin_id'=>$params['admin_id']??0,
  1075. 'create_time'=>time(),
  1076. ]);
  1077. Db::commit();
  1078. return true;
  1079. } catch (\Exception $e) {
  1080. Db::rollback();
  1081. self::setError($e->getMessage());
  1082. return false;
  1083. }
  1084. }
  1085. public static function distributeTenants($params,$userInfo)
  1086. {
  1087. Db::startTrans();
  1088. try {
  1089. if(empty($params['id']) || empty($params['tenant_id'])){
  1090. throw new \Exception('参数错误'.json_encode($params));
  1091. }
  1092. if (is_array($params['id'])) {
  1093. $ids = $params['id'];
  1094. } else{
  1095. $ids = [$params['id']];
  1096. }
  1097. // 取消工程师分配
  1098. foreach ($ids as $id) {
  1099. $res = self::cancelAllocation(['id'=>$id,'master_worker_id'=>''],$userInfo);
  1100. if($res === false){
  1101. Log::info('分配log'.self::getError());
  1102. }
  1103. }
  1104. ServiceWork::whereIn('id',$ids)->update(['tenant_id'=>$params['tenant_id']]);
  1105. Db::commit();
  1106. return true;
  1107. } catch (\Exception $e) {
  1108. Db::rollback();
  1109. self::setError($e->getMessage());
  1110. return false;
  1111. }
  1112. }
  1113. /**
  1114. *
  1115. * @return false|void
  1116. */
  1117. public static function contactCustomer($params)
  1118. {
  1119. try {
  1120. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1121. if($work->isEmpty()){
  1122. throw new \Exception('工单不存在');
  1123. }
  1124. if (empty($work->first_contact_time)) {
  1125. $work->first_contact_time = time();
  1126. $work->save();
  1127. }
  1128. return ['middleNumber' => $work->mobile];
  1129. if ($middleNumber = Cache::get('WORKER_MIDDLE_NUMBER_'.$work->id)) {
  1130. return ['middleNumber' => $middleNumber];
  1131. }
  1132. $worker_mobile = $params['user_info']['mobile'];
  1133. $res = VirtualCallService::auth($worker_mobile, $work->mobile, 60);
  1134. if (isset($res['result']) && $res['result'] == '000000') {
  1135. Cache::set('WORKER_MIDDLE_NUMBER_'.$work->id, $res['middleNumber'], 60); //缓存60秒
  1136. return ['middleNumber' => $res['middleNumber']];
  1137. } else {
  1138. Log::info('虚拟外呼失败:'.json_encode($res));
  1139. throw new \Exception('虚拟外呼失败');
  1140. }
  1141. return true;
  1142. }
  1143. catch (\Exception $e) {
  1144. Db::rollback();
  1145. self::setError($e->getMessage());
  1146. return false;
  1147. }
  1148. }
  1149. /**
  1150. * 添加第三方平台订单
  1151. * @return false|void
  1152. */
  1153. public static function addThirdPlatformsOrders($params)
  1154. {
  1155. try {
  1156. if($params['userAddress']){
  1157. $lon_lat = get_address_lat_lng($params['userAddress']);
  1158. $params['lon'] = $lon_lat['lon'];
  1159. $params['lat'] = $lon_lat['lat'];
  1160. }
  1161. return ThirdOrderLogic::submitOrders($params);
  1162. }catch (\Exception $e) {
  1163. self::setError($e->getMessage());
  1164. return false;
  1165. }
  1166. }
  1167. /**
  1168. * 上门码和完成码
  1169. * @param $params
  1170. * @return false|array
  1171. */
  1172. public static function confirmDoorCode($params)
  1173. {
  1174. try {
  1175. $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
  1176. if($work->isEmpty()){
  1177. throw new Exception('工单不存在');
  1178. }
  1179. $encryptedData = encrypt($params['work_sn'], \think\facade\Config::get('project.work_sn_key'));
  1180. $user_website = \think\facade\Config::get('project.user_website');
  1181. $quoted_price = env('project.quoted_price')?:$user_website.'pages/quoted_price';
  1182. $type = $params['type']??1;
  1183. if($type == 1){
  1184. $user_website .= '?code='.$encryptedData;
  1185. }elseif($type == 2){
  1186. $user_website = $quoted_price.'?code='.$encryptedData;
  1187. }
  1188. return ['url'=>$user_website];
  1189. }catch (\Exception $e) {
  1190. self::setError($e->getMessage());
  1191. return false;
  1192. }
  1193. }
  1194. /**
  1195. * 终止结束服务操作
  1196. */
  1197. public static function terminateService($params): bool
  1198. {
  1199. Db::startTrans();
  1200. try {
  1201. $serviceWork = ServiceWork::where('work_pay_status',1)
  1202. ->where('master_worker_id','>',0)
  1203. ->whereIn('work_status',[0,1,2,3,4,5,6])
  1204. ->where('id',$params['id'])->findOrEmpty();
  1205. if($serviceWork->isEmpty()){
  1206. throw new \Exception('该工单状态不可执行结束服务');
  1207. }
  1208. if($params['isearnest'] == 1){
  1209. $serviceWork->work_status = 7;
  1210. $serviceWork->user_confirm_status = 5;
  1211. $serviceWork->service_status = 3;
  1212. $serviceWork->work_pay_status = 1;
  1213. $serviceWork->finished_time = time();
  1214. $serviceWork->remark = ($serviceWork->remark?:'')." | 终止结束服务:常规流程";
  1215. $serviceWork->save();
  1216. }else{
  1217. $paid_amount = RechargeOrder::where('work_id', $params['id'])->where('payment_type', 1)->value('paid_amount');
  1218. if($paid_amount > 0){
  1219. // 存在上门费给工程师
  1220. Log::info('终止结束服务工单'.$serviceWork->id.',上门费:'.$paid_amount);
  1221. WorkerAccountLogLogic::addAccountLog($serviceWork,$paid_amount,WorkerAccountLogEnum::UM_INC_ADMIN,WorkerAccountLogEnum::INC);
  1222. }
  1223. ServiceWork::where('id', $params['id'])->update([
  1224. 'work_status' => 7,
  1225. 'user_confirm_status' => 5,
  1226. 'service_status' => 3,
  1227. 'finished_time' => time(),
  1228. 'work_pay_status' => 2, // 已结算则不执行 onAfterUpdate
  1229. 'settlement_amount' => $paid_amount??0,
  1230. 'worker_price' => $paid_amount??0,
  1231. 'remark' => ($serviceWork->remark?:'')." | 终止结束服务:上门费-{$paid_amount}"
  1232. ]);
  1233. }
  1234. ServiceWorkLog::create([
  1235. 'work_id' => $params['id'],
  1236. 'master_worker_id' => $serviceWork->master_worker_id,
  1237. 'opera_log' => "工单:{$serviceWork->work_sn} 终止结束服务"
  1238. ]);
  1239. Db::commit();
  1240. ExternalPlatformLogic::generalServiceWork('1003',['work_id' => $params['id']]);
  1241. Log::info('终止结束服务'.json_encode([$serviceWork]));
  1242. return true;
  1243. } catch (\Exception $e) {
  1244. Db::rollback();
  1245. self::setError($e->getMessage());
  1246. Log::info('终止结束服务-Error'.json_encode([$e->getMessage()]));
  1247. return false;
  1248. }
  1249. }
  1250. /**
  1251. * 工程师抢单
  1252. */
  1253. public static function grabOrder($params): bool
  1254. {
  1255. if(!MasterWorkerLogic::isReceivingOrders($params['master_worker_id'])){
  1256. Log::info('抢单失败:工程师不能接单:'.$params['id'].'--'.$params['master_worker_id']);
  1257. self::setError('未达到接单条件');
  1258. return false;
  1259. }
  1260. $serviceWork = 0;
  1261. Db::startTrans();
  1262. try {
  1263. // 抢单
  1264. $serviceWork = ServiceWork::where(['work_pay_status'=>1,'work_status'=>0,'service_status'=>0,'master_worker_id'=>0])
  1265. ->where('id',$params['id'])->update(['master_worker_id'=>$params['master_worker_id'],'work_status'=>1]);
  1266. Db::commit();
  1267. } catch (\Exception $e) {
  1268. Db::rollback();
  1269. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id'].':'.$e->getMessage());
  1270. self::setError('抢单失败');
  1271. return false;
  1272. }
  1273. if($serviceWork == 1){
  1274. Log::info('抢单成功:'.$params['id'].'--'.$params['master_worker_id']);
  1275. $params['is_grab_order'] = 1;
  1276. self::allocateWorker($params,['admin_id'=>0,'name'=>'抢单工程师ID:'.$params['master_worker_id']]);
  1277. return true;
  1278. }else{
  1279. Log::info('抢单失败:'.$params['id'].'--'.$params['master_worker_id']);
  1280. self::setError('抢单失败');
  1281. return false;
  1282. }
  1283. }
  1284. /**
  1285. * 给用户发券
  1286. */
  1287. public static function userAddVoucher($params): bool
  1288. {
  1289. try {
  1290. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1291. if(!$serviceWork->isEmpty()){
  1292. $codes = [];
  1293. foreach ($params['coupon_data'] as $coupon_data) {
  1294. $coupon_data['code'] && $codes[] = $coupon_data['code'];
  1295. }
  1296. if($codes){
  1297. UserCouponLogic::grant($codes,$serviceWork->user_id,$serviceWork->id);
  1298. }
  1299. }
  1300. return true;
  1301. } catch (\Exception $e) {
  1302. self::setError($e->getMessage());
  1303. return false;
  1304. }
  1305. }
  1306. /**
  1307. * 给用户加单
  1308. */
  1309. public static function userExtendOrder($params): bool
  1310. {
  1311. try {
  1312. $serviceWork = ServiceWork::where('id',$params['id'])->findOrEmpty();
  1313. if(!$serviceWork->isEmpty()){
  1314. $worker_number = MasterWorker::where('id',$serviceWork->master_worker_id)->value('worker_number');
  1315. //goods_id ['user_info']['mobile'] user_id coupon_id=0 worker=1 terminal=1 pay_way=2 address contact_people=real_name contact_number=mobile appointment_time lon lat property_activity_id=0
  1316. $res = ServiceOrderLogic::submitOrder([
  1317. 'goods_id' => $params['goods_id'],
  1318. 'user_info' => [
  1319. 'mobile' => $serviceWork->mobile
  1320. ],
  1321. 'user_id' => $serviceWork->user_id,
  1322. 'coupon_id' => 0,
  1323. 'worker' => $worker_number,
  1324. 'terminal' => 1,
  1325. 'pay_way' => 2,
  1326. 'appointment_time' => $serviceWork->appointment_time,
  1327. 'address' => $serviceWork->address,
  1328. 'contact_people' => $serviceWork->real_name,
  1329. 'contact_number' => $serviceWork->mobile,
  1330. 'lon' => $serviceWork->lon,
  1331. 'lat' => $serviceWork->lat,
  1332. 'property_activity_id' => 0
  1333. ]);
  1334. if($res == false){
  1335. throw new \Exception(ServiceOrderLogic::getError());
  1336. }
  1337. }
  1338. return true;
  1339. } catch (\Exception $e) {
  1340. self::setError($e->getMessage());
  1341. return false;
  1342. }
  1343. }
  1344. public static function appointmentAudit($params): bool
  1345. {
  1346. Db::startTrans();
  1347. try {
  1348. $work = ServiceWork::where('id',$params['work_id'])->findOrEmpty();
  1349. if($work->isEmpty()){
  1350. throw new \Exception('工单不存在');
  1351. }
  1352. $log = ServiceWorkAppointmentLog::where('id',$params['id'])->findOrEmpty();
  1353. if($log->isEmpty()){
  1354. throw new \Exception('审核记录不存在');
  1355. }
  1356. $master = MasterWorker::where('id',$log->worker_id)->findOrEmpty();
  1357. $log->status = $params['status'];
  1358. $log->remark = $params['remark'];
  1359. $log->save();
  1360. //预约时间修改审核通过则更新工单预约时间
  1361. if ($params['status'] == 2) {
  1362. //$work->work_status = 3;//待上门
  1363. $work->appointment_time = $log->this_appointment_time;
  1364. $work->save();
  1365. //添加变更日志
  1366. $work_log = [
  1367. 'work_id'=>$work->id,
  1368. 'master_worker_id'=>$log->worker_id,
  1369. 'opera_log'=>'编号['.$master->worker_number.']'.$master->real_name.'于'.$log->create_time.'联系了客户,确认了于'.date('Y-m-d H:i:s',$log->this_appointment_time).'预约上门',
  1370. ];
  1371. ServiceWorkLogLogic::add($work_log);
  1372. }
  1373. Db::commit();
  1374. return true;
  1375. } catch (\Exception $e) {
  1376. Db::rollback();
  1377. self::setError('预约时间审核失败');
  1378. return false;
  1379. }
  1380. }
  1381. }