1
0

ServiceWorkLogic.php 71 KB

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