ServiceWorkLogic.php 68 KB

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