1
0

ServiceWorkLogic.php 71 KB

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