ServiceWorkLogic.php 63 KB

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