ServiceWorkLogic.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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. $change_amount = MasterWorkerAccountLog::where(['work_sn'=>$result['work_sn'],'action'=>1])->value('change_amount');
  697. $result['change_amount'] = !empty($change_amount)?$change_amount:0;
  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'] == 0){
  1428. $pay_status = 0;
  1429. $order_id = $v['id'];
  1430. $sn = $v['sn'];
  1431. $work_amount = $v['order_amount'];
  1432. }
  1433. }
  1434. $result['id'] = $externalShareOrder->id;
  1435. $result['work_amount'] = $work_amount;
  1436. $result['pay_amount'] = $pay_status?$externalShareOrder->paid_amount:0;
  1437. $result['pay_status'] = $pay_status;
  1438. $result['sn'] = $sn;
  1439. $result['order_id'] = $order_id;
  1440. $result['openid'] = $externalShareOrder->openid;
  1441. if($pay_status == 0 || empty($externalShareOrder->openid)){
  1442. // 隐藏关键信息
  1443. $result['mobile'] = asteriskString($result['mobile']);
  1444. $result['real_name'] = mb_substr($result['real_name'],0,1,'UTF-8').'**';
  1445. $result['address'] = addressOmit($result['address']);
  1446. }else{
  1447. if((string)$externalShareOrder->openid !== (string)($params['openid']??'')){
  1448. return [];
  1449. }
  1450. }
  1451. // $result['tip'] = '测试提示';
  1452. return $result;
  1453. }
  1454. // 生成工单售卖 shareOrder
  1455. // 售卖工单是由客资场景下单,所以一定有尾款单
  1456. public static function shareOrderToNative($params){
  1457. // 创建分享单Id
  1458. $is_share = true;
  1459. $params['amount'] = (float)$params['amount']??0;
  1460. $shareOrder = ExternalShareOrder::where(['work_id'=>$params['id']])->findOrEmpty();
  1461. if($shareOrder->isEmpty()){
  1462. if($params['amount']){
  1463. $work = ServiceWork::where(['id'=>$params['id']])->findOrEmpty();
  1464. $work->work_status = 4;
  1465. if(empty($work->master_worker_id)) $work->master_worker_id = 2;
  1466. $work->save();
  1467. //amount user_id work_sn user_info.worker_number real_name master_worker_id
  1468. self::confirmPrice([
  1469. 'amount'=>$params['amount']??0,
  1470. 'user_id'=>$work->master_worker_id,
  1471. 'work_sn'=>$work->work_sn,
  1472. 'user_info'=>['worker_number'=>'分享报价','real_name'=>'分享报价']
  1473. ]);
  1474. $shareOrder = ExternalShareOrder::create(['order_status'=>1,'work_id'=>$params['id'],'paid_amount'=>$params['amount']??0]);
  1475. }
  1476. }else{
  1477. if($shareOrder->order_status === 1 && empty($shareOrder->openid) && $params['amount']>0){ // 可以改价
  1478. $work = ServiceWork::where(['id'=>$params['id']])->findOrEmpty();
  1479. $work->work_status = 4;
  1480. if(empty($work->master_worker_id)) $work->master_worker_id = 2;
  1481. $work->save();
  1482. //amount user_id work_sn user_info.worker_number real_name master_worker_id
  1483. self::confirmPrice([
  1484. 'amount'=>$params['amount']??0,
  1485. 'user_id'=>$work->master_worker_id,
  1486. 'work_sn'=>$work->work_sn,
  1487. 'user_info'=>['worker_number'=>'分享报价','real_name'=>'分享报价']
  1488. ]);
  1489. $shareOrder->paid_amount= $params['amount']??0;
  1490. $shareOrder->save();
  1491. }else{ // 已结束 - 不用分享二维码
  1492. if((float)$shareOrder->paid_amount>0 && empty($params['amount'])) $is_share = true;
  1493. else $is_share = false;
  1494. }
  1495. }
  1496. $share_url = $is_share?(env('project.share_quoted_host','').'?id='.$shareOrder->id):'';
  1497. return ['info'=>$shareOrder->isEmpty()?[]:$shareOrder->toArray(),'share_url'=>$shareOrder->isEmpty()?'':$share_url];
  1498. }
  1499. // 定金金额 - 即可以设置首笔金额然后让其支付
  1500. // 一定是尾款没有报价首款未支付
  1501. public static function shareFirstAmountToNative($params){
  1502. try {
  1503. if(empty($params['amount'])) throw new \Exception('需填写金额');
  1504. $rechargeOrder = RechargeOrder::where(['work_id'=>$params['id'],'payment_type'=>2])->findOrEmpty();
  1505. if(!$rechargeOrder->isEmpty() && $rechargeOrder->pay_status == 1){
  1506. throw new \Exception('尾款支付异常');
  1507. }
  1508. // 创建 $params['order_amount']
  1509. $rechargeOrder = RechargeOrder::where(['work_id'=>$params['id'],'payment_type'=>1])->findOrEmpty();
  1510. if($rechargeOrder->isEmpty()){
  1511. throw new \Exception('无需支付');
  1512. }else{
  1513. if(empty($rechargeOrder->pay_time)){
  1514. $rechargeOrder->order_total= $params['amount']??0;
  1515. $rechargeOrder->order_amount= $params['amount']??0;
  1516. $rechargeOrder->pay_status= 0;
  1517. $rechargeOrder->save();
  1518. }else{ // 已结束 - 不用分享二维码
  1519. throw new \Exception('订单已支付无需支付');
  1520. }
  1521. }
  1522. // 查询出未支付的总金额
  1523. $shareOrder = ExternalShareOrder::where(['work_id'=>$params['id']])->findOrEmpty();
  1524. if($shareOrder->isEmpty()){
  1525. $shareOrder = ExternalShareOrder::create(['order_status'=>1,'work_id'=>$params['id'],'paid_amount'=>$params['amount']??0]);
  1526. }else{
  1527. $shareOrder->openid = '';
  1528. $shareOrder->order_status = 1;
  1529. $shareOrder->paid_amount= $params['amount']??0;
  1530. $shareOrder->save();
  1531. }
  1532. return ['info'=>$shareOrder->isEmpty()?[]:$shareOrder->toArray(),'share_url'=>(env('project.share_fixed_host','').'?id='.$shareOrder->id)];
  1533. } catch (\Exception $e) {
  1534. self::setError($e->getMessage());
  1535. return false;
  1536. }
  1537. }
  1538. // 固定的尾款即同当前工单中的尾款金额
  1539. // 要付尾款则首款肯定已支付
  1540. public static function shareFixedAmountToNative($params){
  1541. try {
  1542. $rechargeOrder = RechargeOrder::where(['work_id'=>$params['id'],'pay_status'=>1,'payment_type'=>1])->findOrEmpty();
  1543. if($rechargeOrder->isEmpty()){
  1544. throw new \Exception('首款未支付');
  1545. }
  1546. // 前提是已经报价
  1547. $amount = RechargeOrder::where(['work_id'=>$params['id'],'pay_status'=>0,'payment_type'=>2])->sum('order_amount');
  1548. // 必须有未支付的尾款存在
  1549. if(empty($amount)) throw new \Exception('订单金额为0或已支付,无需支付');
  1550. // 查询出未支付的总金额
  1551. $shareOrder = ExternalShareOrder::where(['work_id'=>$params['id']])->findOrEmpty();
  1552. if($shareOrder->isEmpty()){
  1553. $shareOrder = ExternalShareOrder::create(['order_status'=>1,'work_id'=>$params['id'],'paid_amount'=>$amount??0]);
  1554. }else{
  1555. $shareOrder->openid = '';
  1556. $shareOrder->order_status = 1;
  1557. $shareOrder->paid_amount = $amount??0;
  1558. $shareOrder->save();
  1559. }
  1560. return ['info'=>$shareOrder->isEmpty()?[]:$shareOrder->toArray(),'share_url'=>(env('project.share_fixed_host','').'?id='.$shareOrder->id)];
  1561. } catch (\Exception $e) {
  1562. self::setError($e->getMessage());
  1563. return false;
  1564. }
  1565. }
  1566. }