ServiceWorkLogic.php 62 KB

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