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