1
0

ServiceWorkLogic.php 61 KB

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