ServiceOrderLogic.php 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. <?php
  2. namespace app\api\logic;
  3. use app\adminapi\logic\master_worker\MasterWorkerLogic;
  4. use app\adminapi\service\DistributeLeafletsService;
  5. use app\common\enum\GoodsEnum;
  6. use app\common\enum\PayEnum;
  7. use app\common\enum\RefundEnum;
  8. use app\common\enum\WorkEnum;
  9. use app\common\enum\YesNoEnum;
  10. use app\common\logic\BaseLogic;
  11. use app\common\logic\PaymentLogic;
  12. use app\common\logic\PayNotifyLogic;
  13. use app\common\logic\RefundLogic;
  14. use app\common\model\coupon\CouponCategory;
  15. use app\common\model\coupon\UserCoupon;
  16. use app\common\model\dict\DictData;
  17. use app\common\model\equity\UserEquity;
  18. use app\common\model\external\ExternalPlatform;
  19. use app\common\model\goods\Goods;
  20. use app\common\model\master_commission\MasterWorkerCommissionConfig;
  21. use app\common\model\master_commission\MasterWorkerCommissionNotice;
  22. use app\common\model\master_worker\MasterWorker;
  23. use app\common\model\master_worker\MasterWorkerRule;
  24. use app\common\model\orders\OrderEffectiveLog;
  25. use app\common\model\orders\RechargeOrder;
  26. use app\common\model\property\PropertyActivity;
  27. use app\common\model\recharge\OrderGoods;
  28. use app\common\model\refund\RefundRecord;
  29. use app\common\model\service_area\ServiceArea;
  30. use app\common\model\spare_part\SparePart;
  31. use app\common\model\works\ServiceWork;
  32. use app\common\model\works\ServiceWorkAppointmentLog;
  33. use app\common\model\works\ServiceWorkDeterminedPrice;
  34. use app\common\model\works\ServiceWorkSpare;
  35. use app\workerapi\logic\ServiceWorkLogLogic;
  36. use think\Exception;
  37. use think\facade\Db;
  38. use think\facade\Log;
  39. /**
  40. * 订单逻辑层
  41. * Class ServiceOrderLogic
  42. * @package app\api\logic
  43. */
  44. class ServiceOrderLogic extends BaseLogic
  45. {
  46. /**
  47. * 判断是否在某服务区 返回服务区城市信息
  48. * @param $params
  49. * @return bool
  50. */
  51. public static function isService($params):array
  52. {
  53. // 查询服务区所有的地点
  54. $rules = ServiceArea::field(['id', 'province', 'city','county', 'area_name', 'electronic_fence'])->select()->toArray();
  55. $point=['lng'=> $params['lon'],'lat'=> $params['lat']];
  56. foreach ($rules as $value){
  57. foreach ($value['electronic_fence'] as $polygon) {
  58. if (isPointInPolygon($point, $polygon)) {
  59. return [
  60. 'id'=>$value['id'],
  61. 'city'=>$value['city'],
  62. 'county'=>$value['county'],
  63. 'area_name'=>$value['area_name']
  64. ];
  65. }
  66. }
  67. }
  68. throw new Exception('已超出服务区域!-1001');
  69. }
  70. /**
  71. * 提交订单
  72. * @param array $params
  73. * @return array|false
  74. */
  75. public static function submitOrder($params)
  76. {
  77. Db::startTrans();
  78. try {
  79. // 订单位置是否在服务区内
  80. $areas = self::isService($params);
  81. $goods = Goods::findOrEmpty($params['goods_id']);
  82. if($goods->isEmpty()){
  83. throw new Exception('产品不存在!');
  84. }
  85. if(empty($params['user_info']['mobile'])){
  86. throw new Exception('请先补充您的联系方式后在提交订单');
  87. }
  88. // TODO tmp防抖1m
  89. $isExist = ServiceWork::where(['user_id'=>$params['user_id'],'goods_category_id'=>$goods['goods_category_id']])->where('create_time','>',(time() - 60))->findOrEmpty();
  90. if(!$isExist->isEmpty()){
  91. throw new Exception('请勿重复下单!');
  92. }
  93. //根据服务工单计算当前订单应支付金额
  94. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE){
  95. //一口价订单
  96. $order_total = $goods['service_fee'];
  97. $order_amount = $goods['service_fee'];
  98. }else if ($goods['goods_payment_type'] == GoodsEnum::DEP_GOODS_PAYMENT_TYPE){
  99. $order_total = $goods['service_fee'];
  100. $order_amount = $goods['service_fee'];
  101. }
  102. else{
  103. $order_total = $goods['base_service_fee'];
  104. $order_amount = $goods['service_fee'];
  105. }
  106. //优惠券验证
  107. if(!empty($params['coupon_id'])){
  108. $user_coupon = UserCoupon::where(['id'=>$params['coupon_id'],'user_id'=>$params['user_id'],'voucher_status'=>0])
  109. ->where('voucher_count','>',0)
  110. ->where('expire_time','>=',time())
  111. ->where('begin_use','<',time())
  112. ->findOrEmpty();
  113. if($user_coupon->isEmpty()){
  114. throw new Exception('该优惠券无法使用');
  115. }
  116. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE and $order_amount<$user_coupon['amount_require']){
  117. throw new Exception('该优惠劵不满足满减使用条件');
  118. }
  119. if($goods['goods_payment_type'] != GoodsEnum::ISGOODS_PAYMENT_TYPE){
  120. throw new Exception('请在支付尾款的时候使用该优惠券');
  121. }
  122. //优惠券折扣
  123. if($user_coupon['mold_type'] == 1){
  124. //按比例折扣
  125. if($user_coupon['discount_ratio']>=1){
  126. throw new Exception('优惠券有误,请联系客服');
  127. }
  128. $order_coupon_amount = $order_amount*(1-$user_coupon['discount_ratio']);
  129. }else{
  130. $order_coupon_amount = $user_coupon['amount'];
  131. }
  132. if(!empty($user_coupon['max_deductible_price'])){
  133. $order_amount = ($order_coupon_amount>$user_coupon['max_deductible_price'])?($order_amount-$user_coupon['max_deductible_price']):($order_amount-$order_coupon_amount);
  134. }else{
  135. $order_amount = $order_amount-$order_coupon_amount;
  136. }
  137. $user_coupon->voucher_status = 1;
  138. $user_coupon->voucher_count = $user_coupon->voucher_count-1;
  139. $user_coupon->save();
  140. }
  141. // TODO tmp外部平台
  142. // 外部平台appid
  143. $external_platform_id = ExternalPlatform::where('appid',$params['platform_appid']??0)->value('id')?:0;
  144. // 若为详情页加单
  145. if(isset($params['service_work_id']) && !empty($params['service_work_id'])){
  146. $external_platform_id = ServiceWork::where('id',$params['service_work_id'])->value('external_platform_id')??0;
  147. }
  148. //生成服务工单
  149. $work_data = [
  150. 'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
  151. 'real_name' => $params['contact_people'],
  152. 'mobile' => $params['contact_number'],
  153. 'address' => $params['address'],
  154. 'province' => $areas['province']??0,
  155. 'city' => $areas['city']??0,
  156. 'area_name' => $areas['area_name']??'',
  157. 'service_area_id' => $areas['id']??0,
  158. 'title' => $goods->goods_name,
  159. 'category_type' => $goods['category_type'],
  160. 'goods_category_ids' => $goods['goods_category_ids'],
  161. 'goods_category_id' => $goods['goods_category_id'],
  162. 'base_service_fee' => $goods['base_service_fee'],
  163. 'service_fee' => $goods['service_fee'],
  164. 'work_pay_status'=>WorkEnum::UN_PAY_STATUS,
  165. 'appointment_time' => strtotime($params['appointment_time']),
  166. 'user_id'=>$params['user_id'],
  167. 'lon'=>!empty($params['lon'])?$params['lon']:0,
  168. 'lat'=>!empty($params['lat'])?$params['lat']:0,
  169. 'property_activity_id'=>!empty($params['property_activity_id'])?$params['property_activity_id']:0,
  170. 'user_equity_id'=>$params['user_equity_id']??0,
  171. 'external_platform_id'=>$external_platform_id??0,
  172. ];
  173. //判断是否是加单
  174. if(!empty($params['worker']) || (isset($params['service_work_id']) && !empty($params['service_work_id']))){
  175. isset($params['service_work_id']) && $params['service_work_id'] && $worker_id = ServiceWork::where('id',$params['service_work_id'])->value('master_worker_id');
  176. $params['worker'] && $worker_id = MasterWorker::where('worker_number',$params['worker'])->value('id');
  177. $work_data['master_worker_id'] = $worker_id;
  178. $work_data['work_status'] = 4;
  179. $work_data['dispatch_time'] = time();
  180. $work_data['work_type'] = 2;
  181. $work_data['data_type'] = 1;
  182. }
  183. //判断是否是复购单
  184. $is_work = ServiceWork::where(['user_id'=>$params['user_id'],'service_status'=>3])->findOrEmpty();
  185. if(!$is_work->isEmpty()){
  186. $work_data['data_type'] = 1;
  187. }
  188. $service_work = ServiceWork::create($work_data);
  189. //使用权益卡时订单应支付金额=0
  190. if(isset($params['user_equity_id']) && $params['user_equity_id']){
  191. $userEquity = UserEquity::with(['equityConfig'])->where(['user_id'=>$params['user_id'],'id'=>$params['user_equity_id']])->findOrEmpty();
  192. if($userEquity->isEmpty() || (int)$userEquity['equityConfig']['status'] === 2){
  193. throw new Exception('您的权益卡已关闭,请重新选择权益卡!');
  194. }
  195. if(!isset($params['equity_external_source']) && (int)$userEquity['equityConfig']['is_oneself_operate'] === 2){
  196. throw new Exception('该权益卡无需自行下单!');
  197. }
  198. $order_total = 0;
  199. $order_amount = 0;
  200. }
  201. //生成服务订单
  202. $data = [
  203. 'work_id'=> $service_work['id'],
  204. 'sn' => generate_sn(RechargeOrder::class, 'sn'),
  205. 'order_type'=>0,//服务订单
  206. 'order_terminal' => $params['terminal'],
  207. 'payment_type'=>$goods['goods_payment_type']==GoodsEnum::ISGOODS_PAYMENT_TYPE?0:1,
  208. 'user_id' => $params['user_id'],
  209. 'pay_status' => PayEnum::UNPAID,
  210. 'coupon_id'=>!empty($params['coupon_id'])?$params['coupon_id']:0,
  211. 'coupon_price'=>!empty($order_coupon_amount)?$order_coupon_amount:0,
  212. 'pay_way' => $params['pay_way'],
  213. 'order_total' => $order_total,
  214. 'order_amount' => $order_amount,
  215. ];
  216. $order = RechargeOrder::create($data);
  217. //生成订单服务详情
  218. OrderGoods::create([
  219. 'sn' => $order['sn'],
  220. 'goods_id' => $params['goods_id'],
  221. 'category_type' => $goods['category_type'],
  222. 'goods_category_ids' => $goods['goods_category_ids'],
  223. 'goods_category_id' => $goods['goods_category_id'],
  224. 'goods_name' => $goods['goods_name'],
  225. 'goods_image' => $goods['goods_image'],
  226. 'goods_video' => $goods['goods_video'],
  227. 'goods_number' => $goods['goods_number'],
  228. 'good_unit' => $goods['good_unit'],
  229. 'goods_size' => $goods['goods_size'],
  230. 'goods_type' => $goods['goods_type'],
  231. 'goods_brand' => $goods['goods_brand'],
  232. 'install_guide' => $goods['install_guide'],
  233. 'goods_payment_type'=>$goods['goods_payment_type'],
  234. 'base_service_fee' => $goods['base_service_fee'],
  235. 'service_total' => $goods['service_total'],
  236. 'service_fee' => $goods['service_fee'],
  237. 'service_image' => $goods['service_image'],
  238. 'warranty_period'=>$goods['warranty_period'],
  239. 'fee_schedule' => $goods['fee_schedule'],
  240. 'goods_status' => $goods['goods_status'],
  241. ]);
  242. Db::commit();
  243. } catch (\Exception $e) {
  244. Db::rollback();
  245. self::setError($e->getMessage());
  246. return false;
  247. }
  248. return [
  249. 'order_id' => (int)$order['id'],
  250. 'work_id' => (int)$order['work_id'],
  251. ];
  252. }
  253. /**
  254. * 提交尾款订单
  255. * @param array $params
  256. * @return array|false
  257. */
  258. public static function submitFinalOrder($params)
  259. {
  260. Db::startTrans();
  261. try {
  262. $order = \app\common\model\recharge\RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  263. if ($order->isEmpty()) {
  264. throw new Exception('订单不存在');
  265. }
  266. //判断订单类型.服务订单尾款处理
  267. if($order['order_type'] == 0 and $order['pay_status'] == PayEnum::ISPAID)//服务工单
  268. {
  269. $order = RechargeOrder::where(['work_id'=>$order['work_id'],'pay_status'=>0])->findOrEmpty();
  270. if($order->isEmpty()){
  271. throw new Exception('订单已支付');
  272. }
  273. }
  274. if ($order['pay_status'] == PayEnum::ISPAID) {
  275. throw new Exception('订单已支付');
  276. }
  277. $order_goods = OrderGoods::where('sn',$params['sn'])->findOrEmpty();
  278. $goods = Goods::findOrEmpty($order_goods['goods_id']);
  279. //判断是否存在优惠券
  280. if(!empty($params['coupon_id']) && empty($order['coupon_id'])){
  281. $user_coupon = UserCoupon::where(['id'=>$params['coupon_id'],'user_id'=>$params['user_id'],'voucher_status'=>0])
  282. ->where('voucher_count','>',0)
  283. ->where('expire_time','>=',time())
  284. ->where('begin_use','<',time())
  285. ->findOrEmpty();
  286. if($user_coupon->isEmpty()){
  287. throw new Exception('该优惠券不满足使用条件');
  288. }
  289. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE and $order['order_amount']<$user_coupon['amount_require']){
  290. throw new Exception('该优惠劵不满足满减使用条件');
  291. }
  292. //优惠券折扣
  293. if($user_coupon['mold_type'] == 1){
  294. //按比例折扣
  295. if($user_coupon['discount_ratio']>=1){
  296. throw new Exception('优惠券有误,请联系客服');
  297. }
  298. $order_coupon_amount = $order['order_amount']*(1-$user_coupon['discount_ratio']);
  299. }else{
  300. $order_coupon_amount = $user_coupon['amount'];
  301. }
  302. if(!empty($user_coupon['max_deductible_price'])){
  303. $order_amount = ($order_coupon_amount>$user_coupon['max_deductible_price'])?($order['order_amount']-$user_coupon['max_deductible_price']):($order['order_amount']-$order_coupon_amount);
  304. }else{
  305. $order_amount = $order['order_amount']-$order_coupon_amount;
  306. }
  307. $user_coupon->voucher_status = 1;
  308. $user_coupon->voucher_count = $user_coupon->voucher_count-1;
  309. $user_coupon->save();
  310. $order->coupon_id = !empty($params['coupon_id'])?$params['coupon_id']:0;
  311. $order->coupon_price = !empty($order_coupon_amount)?$order_coupon_amount:0;
  312. $order->order_amount = !empty($order_amount)?$order_amount:$order->order_amount;
  313. $order->save();
  314. }
  315. Db::commit();
  316. } catch (\Exception $e) {
  317. Db::rollback();
  318. self::setError($e->getMessage());
  319. return false;
  320. }
  321. return [
  322. 'order_id' => (int)$order['id'],
  323. 'work_id' => (int)$order['work_id'],
  324. ];
  325. }
  326. /**
  327. * 重置订单优惠券
  328. * * @param $params
  329. * * * @return array|false
  330. */
  331. public static function cancelOrderCoupon($params)
  332. {
  333. Db::startTrans();
  334. try {
  335. $order = \app\common\model\recharge\RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  336. if ($order->isEmpty()) {
  337. throw new Exception('订单不存在');
  338. }
  339. //判断订单类型.服务订单尾款处理
  340. if($order['order_type'] == 0 and $order['pay_status'] == PayEnum::ISPAID)//服务工单
  341. {
  342. $order = RechargeOrder::where(['work_id'=>$order['work_id'],'pay_status'=>0])->findOrEmpty();
  343. if($order->isEmpty()){
  344. throw new Exception('订单已支付');
  345. }
  346. }
  347. if ($order['pay_status'] == PayEnum::ISPAID) {
  348. throw new Exception('订单已支付');
  349. }
  350. if(!empty($order['coupon_id'])){
  351. $user_coupon_ed = UserCoupon::findOrEmpty($order['coupon_id']);
  352. if(!$user_coupon_ed->isEmpty()){
  353. $user_coupon_ed->voucher_count = $user_coupon_ed->voucher_count+1;
  354. $user_coupon_ed->voucher_status = 0;
  355. $user_coupon_ed->save();
  356. $order->order_amount = $order->order_amount+$order->coupon_price;
  357. $order->coupon_id = 0;
  358. $order->coupon_price = 0;
  359. $order->save();
  360. }
  361. }
  362. Db::commit();
  363. } catch (\Exception $e) {
  364. Db::rollback();
  365. self::setError($e->getMessage());
  366. return false;
  367. }
  368. }
  369. /**
  370. * 获取订单工程师信息
  371. * * @param $params
  372. * * @return array|false
  373. */
  374. public static function getMasterWorker($params)
  375. {
  376. try {
  377. $order_info = \app\common\model\recharge\RechargeOrder::with(['order_goods'=>function ($query) {
  378. $query->visible(['goods_name','goods_image','goods_number','good_unit']);
  379. },'service_work'=>function ($query) {
  380. $query->visible(['real_name','mobile','address','service_status','appointment_time','master_worker_id','work_images','finished_images','finished_time'])->append(['service_status_text','user_service_status','user_service_status_text']);
  381. }])
  382. ->visible(['id','sn','payment_type','order_total','order_amount','pay_status','create_time','title','work_id'])
  383. ->where([
  384. 'order_type' => 0,
  385. 'user_id' => $params['user_id'],
  386. 'sn'=>$params['sn']
  387. ])->findOrEmpty()->toArray();
  388. $data = [];
  389. //获取工程师参数
  390. if(!empty($order_info['service_work']['master_worker_id'])){
  391. $worker = MasterWorker::find($order_info['service_work']['master_worker_id']);
  392. $data['avatar'] = $worker['avatar'];
  393. $data['real_name'] = $worker['real_name'];
  394. $data['worker_number'] = $worker['worker_number'];
  395. $data['mobile'] = $worker['mobile'];
  396. $maintain_exp_type = !empty($worker->worker_register->maintain_exp_type)?$worker->worker_register->maintain_exp_type:'';
  397. $data['worker_exp'] = DictData::where(['type_value'=>'worker_exp_type','value'=>$maintain_exp_type])->value('name');
  398. $data['appointment_time'] = $order_info['service_work']['appointment_time'];
  399. }
  400. return $data;
  401. }
  402. catch (\Exception $e) {
  403. self::setError($e->getMessage());
  404. return false;
  405. }
  406. }
  407. /**
  408. * 获取订单详情
  409. * @param $params
  410. * @return array|false
  411. */
  412. public static function detail($params)
  413. {
  414. try {
  415. $order_info = \app\common\model\recharge\RechargeOrder::with(['order_goods'=>function ($query) {
  416. $query->visible(['goods_id','goods_name','goods_image','goods_number','good_unit']);
  417. },'service_work'=>function ($query) {
  418. $query->visible(['id','work_sn','real_name','mobile','address','service_status','appointment_time','master_worker_id','work_images','explanation','finished_images','finished_time','spare_total','refund_approval','property_activity_id','order_effective_id','external_platform_id'])->append(['service_status_text','user_service_status','user_service_status_text','external_platform_text']);
  419. }])
  420. ->visible(['id','sn','payment_type','order_total','order_amount','paid_amount','pay_status','create_time','title','work_id'])
  421. ->where([
  422. 'order_type' => 0,
  423. 'user_id' => $params['user_id'],
  424. 'sn'=>$params['sn']
  425. ])->findOrEmpty()->toArray();
  426. if(empty($order_info)){
  427. throw new Exception('订单不存在');
  428. }
  429. $order_info['master_worker'] = [
  430. 'avatar' => '',
  431. 'real_name'=>'',
  432. 'worker_number'=>'',
  433. 'mobile'=>'',
  434. 'worker_exp'=>''
  435. ];
  436. //查询总价
  437. $order_info['order_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('order_amount');
  438. $order_info['paid_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('paid_amount');
  439. //退款金额
  440. $order_refund_amount = 0;
  441. //获取工程师参数
  442. if(!empty($order_info['service_work']['master_worker_id'])){
  443. $worker = MasterWorker::find($order_info['service_work']['master_worker_id']);
  444. $order_info['master_worker']['avatar'] = !empty($worker)?$worker['avatar']:'';
  445. $order_info['master_worker']['real_name'] = !empty($worker)?$worker['real_name']:'';
  446. $order_info['master_worker']['worker_number'] = !empty($worker)?$worker['worker_number']:'';
  447. $order_info['master_worker']['mobile'] = !empty($worker)?$worker['mobile']:'';
  448. $maintain_exp_type = !empty($worker->worker_register->maintain_exp_type)?$worker->worker_register->maintain_exp_type:'';
  449. $order_info['master_worker']['worker_exp'] = DictData::where(['type_value'=>'worker_exp_type','value'=>$maintain_exp_type])->value('name');
  450. }
  451. //搜索当前工单下的所有订单记录
  452. $order_info['pay_orders'] = \app\common\model\recharge\RechargeOrder::where(['work_id'=>$order_info['work_id']])->field('id as order_id, pay_status ,refund_status,payment_type,pay_way,pay_time,order_total,order_amount,coupon_price')->order('id asc')->select()->toArray();
  453. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  454. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  455. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  456. $coupon_price = 0;
  457. foreach ($order_info['pay_orders'] as $k=>&$v){
  458. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  459. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  460. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  461. if($v['refund_status']==1){
  462. $order_refund_amount += $v['order_amount'];
  463. $refund_status = RefundRecord::where('order_id',$v['order_id'])->value('refund_status');
  464. }
  465. if($v['payment_type']!=1 and !empty($order_info['service_work']['spare_total'])){
  466. $v['order_amount_total'] = $v['order_amount'];
  467. $v['order_amount'] = $v['order_amount'] - $order_info['service_work']['spare_total'];
  468. }
  469. $coupon_price += $v['coupon_price'];
  470. }
  471. //汇总优惠卷额度
  472. $order_info['coupon_price'] = $coupon_price;
  473. //退款汇总
  474. $order_info['refund_amount'] = $order_refund_amount;
  475. if(isset($refund_status)){
  476. switch ($refund_status){
  477. case 0:
  478. $order_info['refund_status'] = '退款中';
  479. break;
  480. case 1:
  481. $order_info['refund_status'] = '退款成功';
  482. break;
  483. case 2:
  484. $order_info['refund_status'] = '退款失败';
  485. break;
  486. }
  487. }else{
  488. $order_info['refund_status'] = '未退款';
  489. }
  490. // 所有配件
  491. $order_info['spare_total'] = $order_info['service_work']['spare_total']??0;
  492. $order_info['spare_parts'] = [];
  493. $order_info['self_spare_parts'] = [];
  494. if($order_info['service_work']['spare_total']){
  495. $order_info['spare_parts'] = ServiceWorkSpare::getLists($order_info['work_id'], 1);
  496. $order_info['self_spare_parts'] = ServiceWorkSpare::getLists($order_info['work_id'], 2);
  497. }
  498. //获取所有的改约记录
  499. $order_info['appoint_list'] = [];
  500. $appoint_log = ServiceWorkAppointmentLog::where('work_id',$order_info['work_id'])->order('id desc')->select()->toArray();
  501. if(!empty($appoint_log)){
  502. $order_info['appoint_list'][0]['appointment_time'] = date('Y-m-d H:i:s',$appoint_log[0]['this_appointment_time']);
  503. foreach ($appoint_log as $k1=>$v1){
  504. $order_info['appoint_list'][$k1+1]['appointment_time'] = date('Y-m-d H:i:s',$v1['last_appointment_time']);
  505. }
  506. }
  507. //获取是否是活动工单
  508. if(!empty($order_info['service_work']['property_activity_id'])){
  509. $propertyActivity = PropertyActivity::findOrEmpty($order_info['service_work']['property_activity_id']);
  510. $order_info['service_work']['url_page'] = rawurlencode($params['domain'].'/static/wxapp/H5/'.$propertyActivity['url_page'].'/index.html?property_activity_id='.$propertyActivity['id'].'&token='.$params['user_info']['token']);
  511. }
  512. //保修工单时的信息
  513. $order_info['effective_income_amount'] = 0;
  514. if(!empty($order_info['service_work']['order_effective_id'])){
  515. $order_effective = OrderEffectiveLog:: findOrEmpty($order_info['service_work']['order_effective_id']);
  516. $serviceWork = ServiceWork::findOrEmpty($order_effective->work_id);
  517. if($serviceWork->master_worker_id != $order_info['service_work']['master_worker_id']){
  518. $order_info['effective_income_amount'] = \app\adminapi\logic\effective\OrderEffectiveLogLogic::commissionAndAssuranceDeposit($serviceWork);
  519. }
  520. }
  521. // 尾款报价信息
  522. if($order_info['service_work']['id']){
  523. $determinedPrice = ServiceWorkDeterminedPrice::where('work_id',$order_info['service_work']['id'])->findOrEmpty();
  524. if(!$determinedPrice->isEmpty()){
  525. $order_info['price_content'] = $determinedPrice->toArray()['content'];
  526. }
  527. }
  528. return $order_info;
  529. }
  530. catch (\Exception $e) {
  531. self::setError($e->getMessage());
  532. return false;
  533. }
  534. }
  535. public static function getDetailStatus($params)
  536. {
  537. try {
  538. $order_info = \app\common\model\recharge\RechargeOrder::with(['service_work'=>function ($query) {
  539. $query->visible(['work_sn'])->append(['service_status_text','user_service_status','user_service_status_text']);
  540. }])
  541. ->visible(['id','sn'])
  542. ->where([
  543. 'order_type' => 0,
  544. 'user_id' => $params['user_id'],
  545. 'sn'=>$params['sn']
  546. ])->findOrEmpty()->toArray();
  547. if(empty($order_info)){
  548. throw new Exception('订单不存在');
  549. }
  550. return $order_info;
  551. }
  552. catch (\Exception $e) {
  553. self::setError($e->getMessage());
  554. return false;
  555. }
  556. }
  557. /**
  558. * 获取订单支付详情--这个用于尾款支付的时候,自动使用了优惠券,不要随便调用
  559. * @param $params
  560. * @return array|false
  561. */
  562. public static function orderPayInfo($params)
  563. {
  564. Db::startTrans();
  565. try {
  566. $order_info = \app\common\model\recharge\RechargeOrder::with(['order_goods'=>function ($query) {
  567. $query->visible(['goods_id','goods_payment_type','goods_category_id']);
  568. },'service_work'=>function ($query) {
  569. $query->visible(['service_fee','spare_total','goods_category_id']);
  570. }])
  571. ->visible(['id','pay_status','sn','work_id','coupon_id','coupon_price'])
  572. ->where([
  573. 'order_type' => 0,
  574. 'user_id' => $params['user_id'],
  575. 'sn'=>$params['sn']
  576. ])->findOrEmpty()->toArray();
  577. if(empty($order_info)){
  578. throw new Exception('订单不存在');
  579. }
  580. //查询总价
  581. $order_info['order_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('order_amount');
  582. $order_info['paid_amount'] = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id']])->sum('paid_amount');
  583. //搜索当前工单下的所有订单记录
  584. $order_info['pay_orders'] = \app\common\model\recharge\RechargeOrder::where(['work_id'=>$order_info['work_id']])->field('id as order_id, pay_status,refund_status,payment_type,pay_way,pay_time,order_total,order_amount,coupon_id,coupon_price')->order('id asc')->select()->toArray();
  585. $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
  586. $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
  587. $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
  588. $coupon_price = 0;
  589. //退款金额
  590. $order_refund_amount = 0;
  591. $payment_type = 0;
  592. foreach ($order_info['pay_orders'] as $k=>&$v){
  593. $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
  594. $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
  595. $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
  596. if($v['refund_status']==1){
  597. $order_refund_amount += $v['order_amount'];
  598. $refund_status = RefundRecord::where('order_id',$v['order_id'])->value('refund_status');
  599. }
  600. if($v['payment_type']!=1 and !empty($order_info['service_work']['spare_total'])){
  601. $v['order_total'] = $v['order_total'] - $order_info['service_work']['spare_total'];
  602. $v['order_amount'] = $v['order_amount'] - $order_info['service_work']['spare_total'] + $v['coupon_price'];
  603. }
  604. if($v['pay_status']!=0){
  605. $coupon_price += $v['coupon_price'];
  606. }
  607. if($v['pay_status'] == 0){
  608. $order_info['coupon_id'] = $v['coupon_id'];
  609. $order_info['coupon_price'] = $v['coupon_price'];
  610. }
  611. $payment_type = $v['payment_type'];
  612. }
  613. $order_info['payment_type'] = $payment_type;
  614. //汇总优惠卷额度
  615. $order_info['coupon_price'] = $coupon_price;
  616. //退款汇总
  617. $order_info['refund_amount'] = $order_refund_amount;
  618. if(isset($refund_status)){
  619. switch ($refund_status){
  620. case 0:
  621. $order_info['refund_status'] = '退款中';
  622. break;
  623. case 1:
  624. $order_info['refund_status'] = '退款成功';
  625. break;
  626. case 2:
  627. $order_info['refund_status'] = '退款失败';
  628. break;
  629. }
  630. }else{
  631. $order_info['refund_status'] = '未退款';
  632. }
  633. // 所有配件
  634. $order_info['spare_total'] = $order_info['service_work']['spare_total']??0;
  635. $order_info['spare_parts'] = [];
  636. $order_info['self_spare_parts'] = [];
  637. if($order_info['service_work']['spare_total'] > 0){
  638. $order_info['spare_parts'] = ServiceWorkSpare::getLists($order_info['work_id'], 1);
  639. $order_info['self_spare_parts'] = ServiceWorkSpare::getLists($order_info['work_id'], 2);
  640. }
  641. //获取是否存在可使用优惠券
  642. if(!empty($order_info['coupon_id'])){
  643. $order_info['order_amount'] = $order_info['order_amount'] + $order_info['coupon_price'];
  644. $order_info['coupon'] = UserCoupon::where('id',$order_info['coupon_id'])->findOrEmpty()->toArray();
  645. $usable_coupon = true;
  646. }else{
  647. if(!empty($order_info['order_goods'][0])){
  648. $usable_coupon = UserCouponLogic::categoryWithAmountLists(['user_id'=>$params['user_id'],'amount'=>$order_info['order_amount'],'goods_category_id'=>$order_info['order_goods'][0]['goods_category_id'],'goods_id'=>$order_info['order_goods'][0]['goods_id']]);
  649. if(!empty($usable_coupon[0]['id'])){
  650. //绑定最新可使用优惠券
  651. $final_order = \app\common\model\recharge\RechargeOrder::where(['order_type'=>0,'user_id'=>$params['user_id'],'work_id'=>$order_info['work_id'],'pay_status'=>0])->findOrEmpty();
  652. if(!empty($final_order)){
  653. $user_coupon = UserCoupon::where('id',$usable_coupon[0]['id'])->findOrEmpty();
  654. $user_coupon->voucher_status = 1;
  655. $user_coupon->voucher_count = $user_coupon->voucher_count-1;
  656. $user_coupon->save();
  657. $final_order->coupon_id = $usable_coupon[0]['id'];
  658. $final_order->coupon_price = $usable_coupon[0]['amount'];
  659. $final_order->order_amount = $final_order->order_amount - $usable_coupon[0]['amount'];
  660. $final_order->save();
  661. $order_info['coupon'] = $usable_coupon[0];
  662. }
  663. }
  664. }
  665. }
  666. $order_info['usable_coupon'] = !empty($usable_coupon)?true:false;
  667. Db::commit();
  668. return $order_info;
  669. } catch (\Exception $e) {
  670. Db::rollback();
  671. self::setError($e->getMessage());
  672. return false;
  673. }
  674. }
  675. /**
  676. * 取消订单
  677. * @param $params
  678. * @return false|void
  679. */
  680. public static function cancelOrder($params)
  681. {
  682. Db::startTrans();
  683. try {
  684. $work_id = \app\common\model\recharge\RechargeOrder::where([
  685. 'order_type' => 0,
  686. 'user_id' => $params['user_id'],
  687. 'sn'=>$params['sn']
  688. ])->value('work_id');
  689. if(empty($work_id)){
  690. throw new Exception('订单不存在');
  691. }
  692. $payed_order = \app\common\model\recharge\RechargeOrder::where(['user_id'=>$params['user_id'],'work_id'=>$work_id,'pay_status'=>1])->findOrEmpty();
  693. if(!$payed_order->isEmpty()){
  694. throw new Exception('存在已支付订单,不允许取消订单,请联系客服');
  695. }
  696. //软删除订单
  697. $cancel_order = \app\common\model\recharge\RechargeOrder::where(['user_id'=>$params['user_id'],'work_id'=>$work_id])->findOrEmpty();
  698. $cancel_order->pay_status = 2;
  699. $cancel_order->save();
  700. //更新工单状态为已取消
  701. $service_work = ServiceWork::find($work_id);
  702. $service_work->service_status = 4;
  703. $service_work->save();
  704. //判断如果存在优惠券,返还优惠券
  705. if(!empty($payed_order->coupon_id)){
  706. $user_coupon = UserCoupon::where(['user_id'=>$payed_order->user_id,'id'=>$payed_order->coupon_id])->findOrEmpty();
  707. $user_coupon->voucher_status = 0;
  708. $user_coupon->voucher_count = $user_coupon->voucher_count+1;
  709. $user_coupon->save();
  710. }
  711. Db::commit();
  712. if($cancel_order->pay_time){
  713. // 订单取消通知【给用户】
  714. event('Notice', [
  715. 'scene_id' => 122,
  716. 'params' => [
  717. 'user_id' => $params['user_id']
  718. ]
  719. ]);
  720. }
  721. }
  722. catch (\Exception $e) {
  723. Db::rollback();
  724. self::setError($e->getMessage());
  725. return false;
  726. }
  727. }
  728. /**
  729. * 用户确认尾款报价单
  730. * @param $params
  731. * @return false|void
  732. */
  733. public static function confirmOrder($params)
  734. {
  735. Db::startTrans();
  736. try {
  737. $work_id = \app\common\model\recharge\RechargeOrder::where([
  738. 'order_type' => 0,
  739. 'user_id' => $params['user_id'],
  740. 'sn'=>$params['sn']
  741. ])->value('work_id');
  742. if(empty($work_id)){
  743. throw new Exception('订单不存在');
  744. }
  745. //更新工单状态为已取消
  746. $service_work = ServiceWork::find($work_id);
  747. if($service_work->user_confirm_status==2){
  748. throw new Exception('请勿重复操作');
  749. }
  750. $service_work->work_status = 5;
  751. $service_work->user_confirm_status = 2;
  752. $service_work->save();
  753. $work_log = [
  754. 'work_id'=>$work_id,
  755. 'master_worker_id'=>$service_work->master_worker_id,
  756. 'opera_log'=>'用户'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'确认了报价单',
  757. ];
  758. ServiceWorkLogLogic::add($work_log);
  759. Db::commit();
  760. }
  761. catch (\Exception $e) {
  762. Db::rollback();
  763. self::setError($e->getMessage());
  764. return false;
  765. }
  766. }
  767. /**
  768. * 用户确认服务完成
  769. * @param $params
  770. * @return false|void
  771. */
  772. public static function confirmServiceFinish($params)
  773. {
  774. Db::startTrans();
  775. try {
  776. $work_id = \app\common\model\recharge\RechargeOrder::where([
  777. 'order_type' => 0,
  778. 'user_id' => $params['user_id'],
  779. 'sn'=>$params['sn']
  780. ])->value('work_id');
  781. if(empty($work_id)){
  782. throw new Exception('订单不存在');
  783. }
  784. $service_work = ServiceWork::find($work_id);
  785. $orders = RechargeOrder::where(['work_id'=>$work_id,'user_id'=>$params['user_id']])->select()->toArray();
  786. //确认所有订单总金额和结算金额
  787. //若订单是全款已支付订单
  788. if(count($orders)==1 and $orders[0]['payment_type']==0 and $orders[0]['pay_status']==1){
  789. $service_work->work_status = 7;
  790. $service_work->user_confirm_status = 5;
  791. $service_work->service_status = 3;
  792. $service_work->work_pay_status = 1;
  793. }else{
  794. $service_work->work_status = 6;
  795. $service_work->user_confirm_status = 4;
  796. }
  797. $service_work->finished_time = time();
  798. $service_work->save();
  799. //保修工单时,且尾款=0,直接支付无需用户操作支付
  800. if($service_work->order_effective_id >0){
  801. $paid_amount = 0;
  802. $order_id = 0;
  803. foreach ($orders as $order) {
  804. if($order['payment_type'] == 2) $order_id = $order['id'];
  805. $paid_amount += $order['order_amount'];
  806. }
  807. if($paid_amount == 0){
  808. // 直接支付
  809. $order = PaymentLogic::getPayOrderInfo(['order_id'=>$order_id]);
  810. if ($order) {
  811. //支付流程
  812. $result = PaymentLogic::workerPay(1, 'goods', $order, ['terminal'=>0], '');
  813. /*if ($result && ($result['need_pay'] == 0)) {
  814. $service_work->work_status = 7;
  815. $service_work->user_confirm_status = 5;
  816. $service_work->service_status = 3;
  817. $service_work->work_pay_status = 1;
  818. }*/
  819. }
  820. }
  821. }
  822. //更新工程师的进行工单数量
  823. $service_work->master_worker_id && MasterWorker::setWorktotal('dec',$service_work->master_worker_id);
  824. $work_log = [
  825. 'work_id'=>$work_id,
  826. 'master_worker_id'=>$service_work->master_worker_id,
  827. 'opera_log'=>'用户'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'确认服务完成',
  828. ];
  829. ServiceWorkLogLogic::add($work_log);
  830. Db::commit();
  831. }
  832. catch (\Exception $e) {
  833. Db::rollback();
  834. self::setError($e->getMessage());
  835. return false;
  836. }
  837. }
  838. public static function approvalChangePrice($params)
  839. {
  840. Db::startTrans();
  841. try {
  842. $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  843. if($order->isEmpty()){
  844. throw new Exception('订单不存在');
  845. }
  846. $work = ServiceWork::findOrEmpty($order->work_id);
  847. if($work->isEmpty()){
  848. throw new Exception('工单不存在');
  849. }
  850. $work->work_status = 4;
  851. $work->user_confirm_status = 0;
  852. $work->price_approval = 1;
  853. $work->save();
  854. Db::commit();
  855. }
  856. catch (\Exception $e) {
  857. Db::rollback();
  858. self::setError($e->getMessage());
  859. return false;
  860. }
  861. }
  862. public static function approvalChangeAppointment($params)
  863. {
  864. Db::startTrans();
  865. try {
  866. $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  867. if($order->isEmpty()){
  868. throw new Exception('订单不存在');
  869. }
  870. $work = ServiceWork::findOrEmpty($order->work_id);
  871. if($work->isEmpty()){
  872. throw new Exception('工单不存在');
  873. }
  874. if($work->master_worker_id!=0){
  875. //更新工单未确认上门的状态
  876. $work->work_status = 3;
  877. $work->user_confirm_status = 0;
  878. $work->appoint_approval = 1;
  879. }
  880. ServiceWorkAppointmentLog::create([
  881. 'work_id'=>$work->id,
  882. 'last_appointment_time'=>strtotime($work->appointment_time),
  883. 'this_appointment_time'=>strtotime($params['appointment_time']),
  884. ]);
  885. //修改预计完成时间
  886. if ($work->estimated_finish_time) {
  887. $work->estimated_finish_time = strtotime($params['appointment_time']) + (strtotime($work->estimated_finish_time) - strtotime($work->appointment_time));
  888. }
  889. $work->appointment_time = strtotime($params['appointment_time']);
  890. $work->save();
  891. Db::commit();
  892. if($work->master_worker_id!=0){
  893. $workDetail = ServiceWorkAppointmentLog::where(['work_id'=>$work->id])->order('id desc')->findOrEmpty();
  894. $masterDetail = MasterWorkerLogic::detail(['id'=>$work->master_worker_id]);
  895. // 修改预约时间通知【给用户的通知】
  896. event('Notice', [
  897. 'scene_id' => 117,
  898. 'params' => [
  899. 'user_id' => $work->user_id,
  900. 'date' => $params['appointment_time'],
  901. 'tel' => asteriskString($masterDetail['mobile']),
  902. ]
  903. ]);
  904. // 修改预约时间通知【给工程师的通知,仅限公众号】
  905. event('Notice', [
  906. 'scene_id' => 118,
  907. 'params' => [
  908. 'user_id' => $work->master_worker_id,
  909. 'order_id' => $work->id,
  910. 'thing4' => $work->title,
  911. 'time5' => date('Y-m-d H:i:s',$workDetail['last_appointment_time']),
  912. 'time6' => date('Y-m-d H:i:s',$workDetail['this_appointment_time']),
  913. 'thing11' => addressOmit($work->address),
  914. 'phone_number8' => asteriskString($work->mobile),
  915. ]
  916. ]);
  917. }
  918. }
  919. catch (\Exception $e) {
  920. Db::rollback();
  921. self::setError($e->getMessage());
  922. return false;
  923. }
  924. return $work;
  925. }
  926. public static function approvalRefund($params)
  927. {
  928. Db::startTrans();
  929. try {
  930. $order = RechargeOrder::where('sn',$params['sn'])->findOrEmpty();
  931. if($order->isEmpty()){
  932. throw new Exception('订单不存在');
  933. }
  934. $work = ServiceWork::findOrEmpty($order->work_id);
  935. if($work->isEmpty()){
  936. throw new Exception('工单不存在');
  937. }
  938. $work->refund_approval = 1;
  939. $work->save();
  940. //判断是否已下单时间过了两小时,并且师傅暂未上门,距离预约时间两小时以上
  941. if(($order['pay_time']+7200)>time() and $work['work_status']<4 and (strtotime($work['appointment_time'])-7200)>time()){
  942. //生成退款订单
  943. \app\common\model\recharge\RechargeOrder::update([
  944. 'id' => $order['id'],
  945. 'refund_status' => YesNoEnum::YES,
  946. ]);
  947. // 生成退款记录
  948. $recordSn = generate_sn(RefundRecord::class, 'sn');
  949. $record = RefundRecord::create([
  950. 'sn' => $recordSn,
  951. 'user_id' => $order['user_id'],
  952. 'order_id' => $order['id'],
  953. 'order_sn' => $order['sn'],
  954. 'order_type' => RefundEnum::ORDER_TYPE_ORDER,
  955. 'order_amount' => $order['order_amount'],
  956. 'refund_amount' => $order['order_amount'],
  957. 'refund_type' => RefundEnum::TYPE_ADMIN,
  958. 'transaction_id' => $order['transaction_id'] ?? '',
  959. 'refund_way' => RefundEnum::getRefundWayByPayWay($order['pay_way']),
  960. ]);
  961. //更新工单状态
  962. ServiceWork::update([
  963. 'id'=>$order['work_id'],
  964. 'service_status'=>5
  965. ]);
  966. // 退款
  967. RefundLogic::refund($order, $record['id'], $order['order_amount'], 1);
  968. }
  969. Db::commit();
  970. }
  971. catch (\Exception $e) {
  972. Db::rollback();
  973. self::setError($e->getMessage());
  974. return false;
  975. }
  976. }
  977. /**
  978. * 订单完成通知【给用户】 - 全款 -通知
  979. * @param $params
  980. * @return bool
  981. */
  982. public static function serviceFinishNotice($params)
  983. {
  984. try {
  985. $order = RechargeOrder::where('sn', $params['sn'])
  986. ->where('payment_type','=',0)
  987. ->where('pay_status','=',1)
  988. ->findOrEmpty();
  989. if(!$order->isEmpty()){
  990. event('Notice', [
  991. 'scene_id' => 120,
  992. 'params' => [
  993. 'user_id' => $order['user_id']
  994. ]
  995. ]);
  996. }
  997. return true;
  998. }catch (\Exception $e) {
  999. return false;
  1000. }
  1001. }
  1002. /**
  1003. * 工程师完单的时候设置单量规则 - 通知
  1004. * @param $params
  1005. * @return bool
  1006. */
  1007. public static function orderQuantityRule($params)
  1008. {
  1009. try {
  1010. $work_id = \app\common\model\recharge\RechargeOrder::where([
  1011. 'order_type' => 0,
  1012. 'user_id' => $params['user_id'],
  1013. 'sn'=>$params['sn']
  1014. ])->value('work_id');
  1015. if(empty($work_id)){
  1016. throw new Exception('订单不存在');
  1017. }
  1018. $service_work = ServiceWork::find($work_id);
  1019. $commission_config_id = MasterWorkerCommissionConfig::where('voucher_status','=',2)
  1020. ->where('master_worker_id', $service_work['master_worker_id'])
  1021. ->value('id');
  1022. if($commission_config_id){
  1023. // 工程师完单的时候设置该规则关闭,以及短信通知工程师
  1024. $noticeRule = Db::name('master_worker_commission_notice')->alias('n')
  1025. ->leftJoin('service_work sw', 'n.master_worker_id = sw.master_worker_id AND sw.create_time >= n.signing_date AND sw.create_time <= n.signing_date_end')
  1026. ->field([
  1027. 'n.id', 'n.commission_config_id', 'n.master_worker_id', 'n.day_num', 'n.order_num', 'n.signing_date', 'n.signing_date_end','n.is_notice',
  1028. Db::raw("COUNT(sw.id) AS order_count")
  1029. ])
  1030. ->where('n.commission_config_id', $commission_config_id)
  1031. ->group('n.master_worker_id, n.id')
  1032. ->select()->toArray();
  1033. $is_off = true;
  1034. foreach ($noticeRule as $item) {
  1035. if($item['order_num'] <= $item['order_count'] && empty($item['is_notice'])){
  1036. Log::info('orderQuantityRule:'.json_encode($item));
  1037. MasterWorkerCommissionNotice::where('id',$item['id'])->update([
  1038. 'is_notice'=>1
  1039. ]);
  1040. event('Notice', [
  1041. 'scene_id' => 128,
  1042. 'params' => [
  1043. 'user_id' => $service_work['master_worker_id'],
  1044. 'number1' => $item['day_num'],
  1045. 'number' => $item['order_num']
  1046. ]
  1047. ]);
  1048. }
  1049. if($item['order_num'] > $item['order_count']){
  1050. $is_off = false;
  1051. }
  1052. }
  1053. if($is_off){
  1054. MasterWorkerCommissionConfig::where('id',$commission_config_id)->update([
  1055. 'voucher_status'=>1
  1056. ]);
  1057. }
  1058. }
  1059. return true;
  1060. }catch (\Exception $e) {
  1061. Log::info('orderQuantityRule:'.$e->getMessage());
  1062. return false;
  1063. }
  1064. }
  1065. /**
  1066. * 提交订单
  1067. * @param array $params
  1068. * @return array|false
  1069. */
  1070. public static function firmSubmitOrder($params)
  1071. {
  1072. Db::startTrans();
  1073. try {
  1074. // 订单位置是否在服务区内
  1075. $areas = self::isService($params);
  1076. $goods = Goods::findOrEmpty($params['goods_id']);
  1077. if($goods->isEmpty()){
  1078. throw new Exception('产品不存在!');
  1079. }
  1080. if(empty($params['user_info']['mobile'])){
  1081. throw new Exception('请先补充您的联系方式后在提交订单');
  1082. }
  1083. //根据服务工单计算当前订单应支付金额
  1084. if($goods['goods_payment_type'] == GoodsEnum::ISGOODS_PAYMENT_TYPE){
  1085. //一口价订单
  1086. $order_total = $goods['service_fee'];
  1087. $order_amount = $goods['service_fee'];
  1088. }else if ($goods['goods_payment_type'] == GoodsEnum::DEP_GOODS_PAYMENT_TYPE){
  1089. $order_total = $goods['service_fee'];
  1090. $order_amount = $goods['service_fee'];
  1091. }
  1092. else{
  1093. $order_total = $goods['base_service_fee'];
  1094. $order_amount = $goods['service_fee'];
  1095. }
  1096. //生成服务工单
  1097. $work_data = [
  1098. 'work_sn' => generate_sn(ServiceWork::class, 'work_sn'),
  1099. 'real_name' => $params['contact_people'],
  1100. 'mobile' => $params['contact_number'],
  1101. 'address' => $params['address'],
  1102. 'title' => $goods->goods_name . '*' . $goods->goods_number.$goods->good_unit,
  1103. 'category_type' => $goods['category_type'],
  1104. 'goods_category_ids' => $goods['goods_category_ids'],
  1105. 'goods_category_id' => $goods['goods_category_id'],
  1106. 'base_service_fee' => $goods['base_service_fee'],
  1107. 'service_fee' => $goods['service_fee'],
  1108. 'work_pay_status'=>WorkEnum::UN_PAY_STATUS,
  1109. 'work_type'=> 1,
  1110. 'appointment_time' => strtotime($params['appointment_time']),
  1111. 'user_id'=>$params['user_id'],
  1112. 'lon'=>!empty($params['lon'])?$params['lon']:0,
  1113. 'lat'=>!empty($params['lat'])?$params['lat']:0,
  1114. 'province' => $areas['province']??0,
  1115. 'city' => $areas['city']??0,
  1116. 'area_name' => $areas['area_name']??'',
  1117. 'service_area_id' => $areas['id']??0,
  1118. ];
  1119. $service_work = ServiceWork::create($work_data);
  1120. //生成服务订单
  1121. $data = [
  1122. 'work_id'=> $service_work['id'],
  1123. 'sn' => generate_sn(RechargeOrder::class, 'sn'),
  1124. 'order_type'=>0,//服务订单
  1125. 'order_terminal' => $params['terminal'],
  1126. 'payment_type'=>$goods['goods_payment_type']==GoodsEnum::ISGOODS_PAYMENT_TYPE?0:1,
  1127. 'user_id' => $params['user_id'],
  1128. 'pay_status' => PayEnum::UNPAID,
  1129. 'coupon_id'=>!empty($params['coupon_id'])?$params['coupon_id']:0,
  1130. 'coupon_price'=>!empty($order_coupon_amount)?$order_coupon_amount:0,
  1131. 'pay_way' => $params['pay_way'],
  1132. 'order_total' => $order_total,
  1133. 'order_amount' => $order_amount,
  1134. ];
  1135. $order = RechargeOrder::create($data);
  1136. //生成订单服务详情
  1137. OrderGoods::create([
  1138. 'sn' => $order['sn'],
  1139. 'goods_id' => $params['goods_id'],
  1140. 'category_type' => $goods['category_type'],
  1141. 'goods_category_ids' => $goods['goods_category_ids'],
  1142. 'goods_category_id' => $goods['goods_category_id'],
  1143. 'goods_name' => $goods['goods_name'],
  1144. 'goods_image' => $goods['goods_image'],
  1145. 'goods_video' => $goods['goods_video'],
  1146. 'goods_number' => $goods['goods_number'],
  1147. 'good_unit' => $goods['good_unit'],
  1148. 'goods_size' => $goods['goods_size'],
  1149. 'goods_type' => $goods['goods_type'],
  1150. 'goods_brand' => $goods['goods_brand'],
  1151. 'install_guide' => $goods['install_guide'],
  1152. 'goods_payment_type'=>$goods['goods_payment_type'],
  1153. 'base_service_fee' => $goods['base_service_fee'],
  1154. 'service_total' => $goods['service_total'],
  1155. 'service_fee' => $goods['service_fee'],
  1156. 'service_image' => $goods['service_image'],
  1157. 'warranty_period'=>$goods['warranty_period'],
  1158. 'fee_schedule' => $goods['fee_schedule'],
  1159. 'goods_status' => $goods['goods_status'],
  1160. ]);
  1161. Db::commit();
  1162. } catch (\Exception $e) {
  1163. Db::rollback();
  1164. self::setError($e->getMessage());
  1165. return false;
  1166. }
  1167. return [
  1168. 'order_id' => (int)$order['id'],
  1169. 'work_id' => (int)$order['work_id'],
  1170. ];
  1171. }
  1172. /**
  1173. * 绑定工程师-设置为加单
  1174. * * @param array $params
  1175. * * @return array|false
  1176. */
  1177. public static function bindWorkerAndWork(array $params)
  1178. {
  1179. Db::startTrans();
  1180. try {
  1181. $order = RechargeOrder::where(['sn'=>$params['sn'],'user_id'=>$params['user_id']])->findOrEmpty();
  1182. if($order->isEmpty()){
  1183. throw new Exception('订单不存在');
  1184. }
  1185. $work = ServiceWork::where(['id'=>$order['work_id']])->findOrEmpty();
  1186. if($work->isEmpty()){
  1187. throw new Exception('工单不存在');
  1188. }
  1189. /*if($work['work_status']!=WorkEnum::WORK_STATUS_WAIT_SERVICE){
  1190. throw new Exception('工单状态不正确,无法绑定');
  1191. }*/
  1192. // 20250310 未上门状态强转新工程师
  1193. if((int)$work['work_status'] > 3){
  1194. throw new Exception('工单状态不正确,无法绑定');
  1195. }
  1196. $worker = MasterWorker::where('id',$params['worker_id'])->findOrEmpty();
  1197. if($worker->isEmpty()){
  1198. throw new Exception('工程师不存在');
  1199. }
  1200. $work->master_worker_id = $params['worker_id'];
  1201. $work->work_status = WorkEnum::WORK_STATUS_WORKER;
  1202. $work->receive_time = time();
  1203. $work->work_type = 2;//加单状态
  1204. $work->save();
  1205. Db::commit();
  1206. } catch (\Exception $e) {
  1207. Db::rollback();
  1208. self::setError($e->getMessage());
  1209. return false;
  1210. }
  1211. }
  1212. /**
  1213. * 0元支付直接完成支付
  1214. * @param array $params attach out_trade_no
  1215. * @return bool|void
  1216. */
  1217. public static function zeroDirectlyPayment(array $params, $extra = [])
  1218. {
  1219. try {
  1220. $message['out_trade_no'] = mb_substr($params['out_trade_no'], 0, 18);
  1221. $order = RechargeOrder::where(['sn' => $params['out_trade_no']])->findOrEmpty();
  1222. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  1223. return true;
  1224. }
  1225. switch ($params['attach']) {
  1226. case 'recharge':
  1227. PayNotifyLogic::handle('recharge', $params['out_trade_no'], $extra);
  1228. break;
  1229. case 'goods':
  1230. $res = PayNotifyLogic::handle('goods', $params['out_trade_no'], $extra);
  1231. if($res === true){
  1232. // 用户下单后,给订单运营专员(配置固定ID)发送公众号提醒(订单信息)
  1233. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  1234. ->where('payment_type','IN',[0,1])
  1235. ->where('pay_status','=',1)
  1236. ->findOrEmpty();
  1237. if(!$order->isEmpty()){
  1238. $workDetail = ServiceWork::findOrEmpty($order->work_id);
  1239. if(!$workDetail->isEmpty()){
  1240. event('Notice', [
  1241. 'scene_id' => 100,
  1242. 'params' => [
  1243. 'user_id' => 0,
  1244. 'order_id' => $workDetail['id'],
  1245. 'thing3' => $workDetail['title'],
  1246. 'time6' => $workDetail['appointment_time'],
  1247. 'phone_number8' => asteriskString($workDetail['mobile']),
  1248. 'thing5' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  1249. ]
  1250. ]);
  1251. }
  1252. }
  1253. // 订单完成通知【给用户】 - 尾款 -通知
  1254. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  1255. ->where('payment_type','=',2)
  1256. ->where('pay_status','=',1)
  1257. ->findOrEmpty();
  1258. if(!$order->isEmpty()){
  1259. event('Notice', [
  1260. 'scene_id' => 120,
  1261. 'params' => [
  1262. 'user_id' => $order['user_id']
  1263. ]
  1264. ]);
  1265. }
  1266. }
  1267. break;
  1268. }
  1269. return true;
  1270. } catch (\Exception $e) {
  1271. self::setError($e->getMessage());
  1272. return false;
  1273. }
  1274. }
  1275. }