乱七八糟

This commit is contained in:
weicw
2023-10-23 15:19:06 +08:00
parent 0adf61744b
commit 1b842a9ea5
274 changed files with 323196 additions and 17347 deletions

View File

@@ -61,7 +61,7 @@ public class EquipmentController extends BaseController {
public ApiResult<PageResult<Equipment>> page(EquipmentParam param) {
// 使用关联查询
if (getMerchantCode() != null) {
param.setMerchantCode(getMerchantCode());
param.setMerchantCode(getMerchantCode());
}
return success(equipmentService.pageRel(param));
}
@@ -96,18 +96,18 @@ public class EquipmentController extends BaseController {
// 记录当前登录用户id、租户id
User loginUser = getLoginUser();
if (getMerchantCode() != null) {
equipment.setMerchantCode(getMerchantCode());
equipment.setMerchantCode(getMerchantCode());
}
if (equipmentService.count(new LambdaQueryWrapper<Equipment>()
.eq(Equipment::getEquipmentCode, equipment.getEquipmentCode())) > 0) {
return fail("设备编号已存在");
.eq(Equipment::getEquipmentCode, equipment.getEquipmentCode())) > 0) {
return fail("设备编号已存在");
}
if (equipmentService.save(equipment)) {
// 生成二维码
String qrcode = createQrcode(equipment);
equipment.setQrcode(qrcode);
equipmentService.saveOrUpdate(equipment);
return success("添加成功");
// 生成二维码
String qrcode = createQrcode(equipment);
equipment.setQrcode(qrcode);
equipmentService.saveOrUpdate(equipment);
return success("添加成功");
}
return fail("添加失败");
}
@@ -118,10 +118,10 @@ public class EquipmentController extends BaseController {
@PutMapping()
public ApiResult<?> update(@RequestBody Equipment equipment) throws AlipayApiException {
if (equipmentService.updateById(equipment)) {
// 生成二维码
String qrcode = createQrcode(equipment);
equipment.setQrcode(qrcode);
equipmentService.saveOrUpdate(equipment);
// 生成二维码
String qrcode = createQrcode(equipment);
equipment.setQrcode(qrcode);
equipmentService.saveOrUpdate(equipment);
return success("修改成功");
}
return fail("修改失败");
@@ -132,38 +132,45 @@ public class EquipmentController extends BaseController {
@ApiOperation("绑定设备")
@PutMapping("/bind")
public ApiResult<?> bindEquipment(@RequestBody Equipment equipment) {
final Integer orderId = equipment.getOrderId();
final Order order = orderService.getById(orderId);
Equipment one = equipmentService.getOne(new LambdaQueryWrapper<Equipment>().eq(Equipment::getEquipmentCode, equipment.getEquipmentCode()));
if(one == null){
return fail("设备不存在");
}
if(!one.getUserId().equals(0)){
return fail("该设备已被绑定");
}
Equipment saveData = new Equipment();
saveData.setEquipmentId(one.getEquipmentId());
saveData.setUserId(equipment.getUserId());
saveData.setOrderId(orderId);
if (equipmentService.updateById(saveData)) {
// 记录明细
EquipmentRecord record = new EquipmentRecord();
record.setEquipmentCode(one.getEquipmentCode());
record.setUserId(getLoginUserId());
record.setEventType(EVENT_TYPE_BIND);
record.setComments("订单号:".concat(order.getOrderNo()));
record.setMerchantCode(one.getMerchantCode());
equipmentRecordService.save(record);
// 订单发货
order.setDeliveryStatus(DELIVERY_STATUS_YES);
order.setOrderStatus(ORDER_STATUS_COMPLETED);
order.setReceiptStatus(RECEIPT_STATUS_YES);
order.setExpirationTime(DateUtil.nextMonth());
order.setEquipmentId(one.getEquipmentId());
orderService.updateById(order);
return success("绑定成功");
}
return fail("绑定失败");
final Integer orderId = equipment.getOrderId();
final Order order = orderService.getById(orderId);
Equipment one = equipmentService.getOne(new LambdaQueryWrapper<Equipment>().eq(Equipment::getEquipmentCode, equipment.getEquipmentCode()));
if (one == null) {
return fail("设备不存在");
}
if (!one.getUserId().equals(0)) {
return fail("该设备已被绑定");
}
if(!order.getMerchantCode().equals(one.getMerchantCode())) {
return fail("只能绑定当前门店的电池");
}
Equipment saveData = new Equipment();
saveData.setEquipmentId(one.getEquipmentId());
saveData.setUserId(equipment.getUserId());
saveData.setOrderId(orderId);
saveData.setMerchantCode(order.getMerchantCode());
if (equipmentService.updateById(saveData)) {
// 记录明细
EquipmentRecord record = new EquipmentRecord();
record.setEquipmentCode(one.getEquipmentCode());
record.setUserId(getLoginUserId());
record.setEventType(EVENT_TYPE_BIND);
record.setComments("订单号:".concat(order.getOrderNo()));
record.setMerchantCode(one.getMerchantCode());
equipmentRecordService.save(record);
// 订单发货
order.setDeliveryStatus(DELIVERY_STATUS_YES);
order.setOrderStatus(ORDER_STATUS_COMPLETED);
if(order.getOrderSource() == 10) {
order.setOrderStatus(ORDER_STATUS_OVER);
}
order.setReceiptStatus(RECEIPT_STATUS_YES);
order.setExpirationTime(DateUtil.nextMonth());
order.setEquipmentId(one.getEquipmentId());
orderService.updateById(order);
return success("绑定成功");
}
return fail("绑定失败");
}
@PreAuthorize("hasAuthority('apps:equipment:remove')")
@@ -211,43 +218,45 @@ public class EquipmentController extends BaseController {
}
// 生成支付宝小程序码
private String createQrcode(Equipment equipment) throws AlipayApiException{
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(getTenantId());
private String createQrcode(Equipment equipment) throws AlipayApiException {
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(getTenantId());
AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();
AlipayOpenAppQrcodeCreateModel model = new AlipayOpenAppQrcodeCreateModel();
model.setUrlParam("pages/equipment/equipment");
System.out.println("equipment = " + equipment);
// __id__=2&merchantCode=M311539&merchantId=52
// pages/equipment/equipment
AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();
AlipayOpenAppQrcodeCreateModel model = new AlipayOpenAppQrcodeCreateModel();
model.setUrlParam("pages/equipment/equipment?equipmentId=".concat(equipment.getEquipmentId().toString()));
System.out.println("equipment = " + equipment);
// __id__=2&merchantCode=M311539&merchantId=52
// pages/equipment/equipment
// Merchant merchant = merchantService.getMerchantByCode(equipment.getMerchantCode());
// if(merchant == null){
// throw new BusinessException("该商户不存在");
// }
model.setQueryParam("equipmentId=".concat(equipment.getEquipmentId().toString()));
model.setDescribe("扫码租赁电池");
request.setBizModel(model);
AlipayOpenAppQrcodeCreateResponse response = alipayClient.certificateExecute(request);
System.out.println(response.getBody());
if (response.isSuccess()) {
System.out.println("调用成功");
final JSONObject jsonObject = JSONObject.parseObject(response.getBody());
final String alipay_open_app_qrcode_create_response = jsonObject.getString("alipay_open_app_qrcode_create_response");
final JSONObject jsonObject1 = JSONObject.parseObject(alipay_open_app_qrcode_create_response);
return jsonObject1.getString("qr_code_url");
} else {
System.out.println("调用失败");
return null;
}
model.setQueryParam("equipmentId=".concat(equipment.getEquipmentId().toString()));
model.setDescribe("扫码租赁电池");
request.setBizModel(model);
AlipayOpenAppQrcodeCreateResponse response = alipayClient.certificateExecute(request);
System.out.println(response.getBody());
if (response.isSuccess()) {
System.out.println("调用成功");
final JSONObject jsonObject = JSONObject.parseObject(response.getBody());
final String alipay_open_app_qrcode_create_response = jsonObject.getString("alipay_open_app_qrcode_create_response");
final JSONObject jsonObject1 = JSONObject.parseObject(alipay_open_app_qrcode_create_response);
String qrCodeUrl = jsonObject1.getString("qr_code_url");
return qrCodeUrl;
} else {
System.out.println("调用失败");
return null;
}
}
@PreAuthorize("hasAuthority('apps:equipment:update')")
@ApiOperation("确认收货")
@PostMapping("/receipt")
public ApiResult<?> receipt(@RequestBody Order order){
orderService.updateById(order);
return success("确认收货");
public ApiResult<?> receipt(@RequestBody Order order) {
orderService.updateById(order);
return success("确认收货");
}
}

View File

@@ -73,6 +73,12 @@ public class Equipment implements Serializable {
@ApiModelProperty(value = "总电压")
private String totalVoltage;
@TableField(exist = false)
private String gps;
@TableField(exist = false)
private String gsm;
@ApiModelProperty(value = "BMS板供应商")
private String bmsBrand;

View File

@@ -1,5 +1,6 @@
package com.gxwebsoft.apps.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.apps.mapper.EquipmentMapper;
import com.gxwebsoft.apps.service.EquipmentService;
@@ -9,10 +10,16 @@ import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 设备管理Service实现
@@ -25,16 +32,51 @@ public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment
@Resource
private UserService userService;
@Resource
private RestTemplate restTemplate;
@Override
public PageResult<Equipment> pageRel(EquipmentParam param) {
PageParam<Equipment, EquipmentParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
List<Equipment> list = baseMapper.selectPageRel(page, param);
Set<Integer> touziUserIds = list.stream().map(Equipment::getTouziUserId).collect(Collectors.toSet());
List<User> touziUserList = userService.lambdaQuery().in(User::getUserId, touziUserIds).list();
Map<Integer, List<User>> touziUserCollect = touziUserList.stream().collect(Collectors.groupingBy(User::getUserId));
// 查询绑定电池的用户
for(Equipment equipment : list){
if(!equipment.getUserId().equals(0)){
equipment.setUser(userService.getById(equipment.getUserId()));
}
for (Equipment equipment : list) {
// 查询状态
try {
ResponseEntity<JSONObject> entity = restTemplate.getForEntity("https://battery.zfdliot.com/api/battery/status?battery_sn=" + equipment.getEquipmentCode(), JSONObject.class);
JSONObject body = entity.getBody();
Integer code = body.getInteger("code");
JSONObject data = body.getJSONObject("data");
equipment.setBms(data.getString("bms_zt"));
equipment.setBatteryPower(data.getString("sydl"));
equipment.setTotalVoltage(data.getString("sbdy"));
equipment.setGps(data.getString("gps_xh"));
equipment.setGsm(data.getString("gsm_xh"));
equipment.setWorkingStatus(data.getString("sbzt"));
System.out.println(body);
} catch (Exception e) {
e.printStackTrace();
}
if (!equipment.getUserId().equals(0)) {
equipment.setUser(userService.getById(equipment.getUserId()));
}
if ( equipment.getTouziUserId()!= null && !equipment.getTouziUserId().equals(0)) {
List<User> users = touziUserCollect.get(equipment.getTouziUserId());
if(!CollectionUtils.isEmpty(users)) {
equipment.setTouziUser(users.get(0));
}
}
}
return new PageResult<>(list, page.getTotal());
}
@@ -52,12 +94,30 @@ public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment
public Equipment getByIdRel(Integer equipmentId) {
EquipmentParam param = new EquipmentParam();
param.setEquipmentId(equipmentId);
return param.getOne(baseMapper.selectListRel(param));
Equipment equipment = baseMapper.selectListRel(param).get(0);
try {
ResponseEntity<JSONObject> entity = restTemplate.getForEntity("https://battery.zfdliot.com/api/battery/status?battery_sn=" + equipment.getEquipmentCode(), JSONObject.class);
JSONObject body = entity.getBody();
Integer code = body.getInteger("code");
JSONObject data = body.getJSONObject("data");
equipment.setBms(data.getString("bms_zt"));
equipment.setBatteryPower(data.getString("sydl"));
equipment.setTotalVoltage(data.getString("sbdy"));
equipment.setGps(data.getString("gps_xh"));
equipment.setGsm(data.getString("gsm_xh"));
equipment.setWorkingStatus(data.getString("sbzt"));
System.out.println(body);
} catch (Exception e) {
e.printStackTrace();
}
return equipment;
}
@Override
public Equipment getByEquipmentCode(String equipmentCode) {
return query().eq("equipment_code", equipmentCode).one();
return query().eq("equipment_code", equipmentCode).one();
}
}

View File

@@ -1,33 +1,39 @@
package com.gxwebsoft.apps.task;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeOrderinfoSyncRequest;
import com.alipay.api.response.AlipayTradeOrderinfoSyncResponse;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.annotation.SqlParser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxwebsoft.apps.entity.Equipment;
import com.gxwebsoft.apps.entity.EquipmentOrderGoods;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.apps.service.EquipmentOrderGoodsService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.config.MybatisPlusConfig;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.love.entity.UserPlanLog;
import com.gxwebsoft.love.param.UserPlanLogParam;
import com.gxwebsoft.shop.entity.Manager;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.ProfitLog;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.ManagerService;
import com.gxwebsoft.shop.service.MerchantService;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.ProfitLogService;
import com.gxwebsoft.shop.service.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
@@ -75,35 +81,131 @@ public class OrderTask {
@Resource
private ManagerService managerService;
/**
* 删除30分钟未下单的订单
*/
// @Scheduled(cron="0 0/30 * * * ? ")
public void removeTimeoutOrder() {
Date newDate = DateUtil.offset(DateUtil.date(), DateField.MINUTE, -30);
LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class)
.eq(Order::getPayStatus, PAY_STATUS_NO_PAY)
.lt(Order::getCreateTime, newDate);
@Resource
private FreezeOrderService freezeOrderService;
@Resource
private OrderPayService orderPayService;
boolean remove = orderService.remove(wrapper);
/**
* 计算逾期
*/
@Scheduled(cron = "0 0/3 * * * ? ")
public void removeTimeoutOrder() {
DateTime now = DateUtil.date();
// 查找已逾期的订单
LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class)
.eq(Order::getIsFreeze, 1) // 已交押金
.ne(Order::getReceiptStatus, 10)
.ne(Order::getPayStatus, ORDER_STATUS_OVER) // 未完成
.eq(Order::getIsRenew, 0) // 主订单
.lt(Order::getExpirationTime, now); //已逾期
List<Order> list = orderService.list(wrapper);
if (CollectionUtils.isEmpty(list)) {
return;
}
Map<Integer, List<Order>> collect = list.stream().collect(Collectors.groupingBy(Order::getOrderId));
Set<Integer> ids = collect.keySet();
// 是否已生成当期续费订单
LambdaQueryWrapper<OrderPay> renewWrapper = Wrappers.lambdaQuery(OrderPay.class).in(OrderPay::getRentOrderId, ids).groupBy(OrderPay::getRentOrderId).orderByDesc(OrderPay::getCreateTime);
Page<OrderPay> page = new Page<OrderPay>(1, 1);
List<OrderPay> renewOrderList = orderPayService.page(page, renewWrapper).getRecords();
//查找订单关联的商品
List<EquipmentOrderGoods> orderGoodsList = orderGoodsService.list(Wrappers.lambdaQuery(EquipmentOrderGoods.class).in(EquipmentOrderGoods::getOrderId, ids));
Map<Integer, List<EquipmentOrderGoods>> orderGoodsMap = orderGoodsList.stream().collect(Collectors.groupingBy(EquipmentOrderGoods::getOrderId));
// 找出未生成当期续费订单的订单
renewOrderList.forEach(item -> {
// 计算逾期
EquipmentOrderGoods eg = orderGoodsMap.get(item.getRentOrderId()).get(0);
// 是否需要新增续费订单
if (item.getExpirationTime().before(now) && item.getCurrPeriods() < item.getPeriods()) {
OrderPay newRenewOrder = new OrderPay();
BeanUtil.copyProperties(item, newRenewOrder, "orderId", "createTime", "updateTime", "orderNo", "payStatus");
newRenewOrder.setStartTime(item.getExpirationTime());
newRenewOrder.setExpirationTime(DateUtil.offsetMonth(item.getExpirationTime(), 1));
newRenewOrder.setCurrPeriods(item.getCurrPeriods() + 1);
newRenewOrder.setPayStatus(PAY_STATUS_NO_PAY);
newRenewOrder.setOrderNo(IdUtil.getSnowflakeNextIdStr());
if (item.getOrderSource() == 20) {
// 首付+手续费
newRenewOrder.setTotalPrice(eg.getDownPayment().add(eg.getServiceCharges()));
newRenewOrder.setOrderPrice(eg.getDownPayment().add(eg.getServiceCharges()));
newRenewOrder.setPayPrice(eg.getDownPayment().add(eg.getServiceCharges()));
} else if (item.getOrderSource() == 30 || item.getOrderSource() == 40) {
// 月租
BigDecimal price = eg.getBatteryRent();
// 是否需要保险
if (newRenewOrder.getCurrPeriods() % 12 == 1) {
newRenewOrder.setBatteryInsurance(eg.getBatteryInsurance());
price = price.add(eg.getBatteryInsurance());
} else {
newRenewOrder.setBatteryInsurance(BigDecimal.ZERO);
}
newRenewOrder.setTotalPrice(price);
newRenewOrder.setOrderPrice(price);
newRenewOrder.setPayPrice(price);
} else if (item.getOrderSource() == 10) {
// 售价
newRenewOrder.setTotalPrice(eg.getBatteryPrice());
newRenewOrder.setOrderPrice(eg.getBatteryPrice());
newRenewOrder.setPayPrice(eg.getBatteryPrice());
}
orderPayService.save(newRenewOrder);
// 已生成订单未付款
} else if (item.getPayStatus().equals(PAY_STATUS_NO_PAY)) {
long between = DateUtil.between(item.getStartTime(), now, DateUnit.DAY);
if (item.getExpirationDay() != between) {
// 更新逾期时间
orderPayService.lambdaUpdate().eq(OrderPay::getId, item.getId()).set(OrderPay::getExpirationDay, between).update();
}
List<Order> orders = collect.get(item.getRentOrderId());
if (CollectionUtils.isNotEmpty(orders) && orders.get(0).getExpirationDay() != between) {
orderService.lambdaUpdate().eq(Order::getOrderId, item.getRentOrderId()).set(Order::getExpirationDay, between).update();
}
// if(between > 1) {
// Order order = collect.get(item.getRentOrderId()).get(0);
// // 电池停电
// try {
// freezeOrderService.violated(order);// 发送违约记录给支付宝
// } catch (AlipayApiException e) {
// throw new RuntimeException(e);
// }
// }
}
});
}
/**
* 计算分润
*/
@Scheduled(cron="0 0/1 * * * ? ")
// @Scheduled(cron="0 0/1 * * * ? ")
@Transactional
public void CalcProfit() {
log.info("开始计算分润");
// 查询所有未结算订单
LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class)
.eq(Order::getIsSettled, ORDER_SETTLED_NO)
.eq(Order::getPayStatus, PAY_STATUS_SUCCESS)
.eq(Order::getOrderStatus, ORDER_STATUS_COMPLETED);
LambdaQueryWrapper<OrderPay> wrapper = Wrappers.lambdaQuery(OrderPay.class)
.eq(OrderPay::getIsSettled, ORDER_SETTLED_NO)
.eq(OrderPay::getPayStatus, PAY_STATUS_SUCCESS);
List<Order> orderList = orderService.list(wrapper);
if(CollectionUtils.isEmpty(orderList)){
List<OrderPay> orderList = orderPayService.list(wrapper);
if (CollectionUtils.isEmpty(orderList)) {
return;
}
@@ -112,16 +214,22 @@ public class OrderTask {
Set<Integer> orderIds = new HashSet<>();
Set<String> tuijianUserPhones = new HashSet<>();
Set<String> mendianCodes = new HashSet<>();
Set<Integer> userIds = new HashSet<>();
for (Order order : orderList) {
for (OrderPay order : orderList) {
equipmentIds.add(order.getEquipmentId());
mendianCodes.add(order.getMerchantCode());
orderIds.add(order.getOrderId());
orderIds.add(order.getId());
userIds.add(order.getUserId());
if (order.getDealerPhone() != null) {
tuijianUserPhones.add(order.getDealerPhone());
}
}
//查询所有下单用户
List<User> orderUserlist = userService.list(Wrappers.lambdaQuery(User.class).in(User::getUserId, userIds));
Map<Integer, List<User>> orderUserMap = orderUserlist.stream().collect(Collectors.groupingBy(User::getUserId));
// 查询所有订单商品
List<EquipmentOrderGoods> orderGoodsList = orderGoodsService.list(Wrappers.lambdaQuery(EquipmentOrderGoods.class).in(EquipmentOrderGoods::getOrderId, orderIds));
Map<Integer, List<EquipmentOrderGoods>> orderGoodsMap = orderGoodsList.stream().collect(Collectors.groupingBy(EquipmentOrderGoods::getOrderId));
@@ -171,9 +279,23 @@ public class OrderTask {
// 开始结算
for (Order order : orderList) {
for (OrderPay order : orderList) {
// 计算投资人收益
List<EquipmentOrderGoods> equipmentOrderGoods = orderGoodsMap.get(order.getOrderId());
// Integer orderSource = order.getOrderSource();
// String orderSourceStr = "";
// if(orderSource == 10) {
// orderSourceStr = "销售";
// } else if(orderSource == 20) {
// orderSourceStr = "分期";
// } else if(orderSource == 30) {
// orderSourceStr = "以租代购";
// } else if(orderSource == 40) {
// orderSourceStr = "租赁";
// }
User orderUser = orderUserMap.get(order.getUserId()).get(0);
List<EquipmentOrderGoods> equipmentOrderGoods = orderGoodsMap.get(order.getId());
if (CollectionUtils.isNotEmpty(equipmentOrderGoods)) {
EquipmentOrderGoods orderGoods = equipmentOrderGoods.get(0);
BigDecimal touziProfit;
@@ -182,7 +304,7 @@ public class OrderTask {
BigDecimal jingliProfit;
Merchant merchant = mendianMap.get(order.getMerchantCode());
// 是否分期首期
if ("20".equals(orderGoods.getEquipmentCategory()) && order.getIsRenew() == 0) {
if ("20".equals(orderGoods.getEquipmentCategory()) && order.getCurrPeriods() == 1) {
touziProfit = orderGoods.getTouziFirstProfit();
tuijianProfit = orderGoods.getTuijianFirstProfit();
mendianProfit = orderGoods.getMendianFirstProfit();
@@ -193,9 +315,10 @@ public class OrderTask {
mendianProfit = orderGoods.getMendianProfit();
jingliProfit = orderGoods.getJingliProfit();
}
Equipment equipment = equipmentMap.get(order.getEquipmentId());
// 投资人收益
if (touziProfit.compareTo(BigDecimal.ZERO) > 0) {
Equipment equipment = equipmentMap.get(order.getEquipmentId());
User touziUser = touziUserMap.get(equipment.getTouziUserId());
if (touziUser != null) {
userService.updateBalanceByUserId(touziUser.getUserId(), touziProfit);
@@ -204,9 +327,13 @@ public class OrderTask {
profitLog.setMoney(touziProfit);
profitLog.setScene(1);
profitLog.setMerchantCode(merchant.getMerchantCode());
profitLog.setOrderId(order.getOrderId());
profitLog.setOrderId(order.getId());
profitLog.setOrderNo(order.getOrderNo());
profitLog.setComments("投资设备:" + equipment.getEquipmentCode());
profitLog.setEquipmentCode(equipment.getEquipmentCode());
profitLog.setMerchantName(merchant.getMerchantName());
profitLog.setOrderSource(order.getGoodsId());
// profitLog.setIsRenew(order.getIsRenew());
profitLogService.save(profitLog);
}
}
@@ -221,10 +348,13 @@ public class OrderTask {
profitLog.setMoney(tuijianProfit);
profitLog.setScene(3);
profitLog.setMerchantCode(merchant.getMerchantCode());
profitLog.setOrderId(order.getOrderId());
profitLog.setOrderId(order.getId());
profitLog.setOrderNo(order.getOrderNo());
profitLog.setComments("推广收益:" + order.getUserId());
profitLog.setEquipmentCode(equipment.getEquipmentCode());
profitLog.setMerchantName(merchant.getMerchantName());
profitLog.setOrderSource(order.getGoodsId());
// profitLog.setIsRenew(order.getIsRenew());
profitLogService.save(profitLog);
}
}
@@ -240,9 +370,13 @@ public class OrderTask {
profitLog.setMoney(mendianProfit);
profitLog.setScene(4);
profitLog.setMerchantCode(merchant.getMerchantCode());
profitLog.setOrderId(order.getOrderId());
profitLog.setOrderId(order.getId());
profitLog.setOrderNo(order.getOrderNo());
profitLog.setComments("门店收益:" + order.getMerchantCode());
profitLog.setEquipmentCode(equipment.getEquipmentCode());
profitLog.setMerchantName(merchant.getMerchantName());
profitLog.setOrderSource(order.getGoodsId());
// profitLog.setIsRenew(order.getIsRenew());
profitLogService.save(profitLog);
}
}
@@ -252,7 +386,7 @@ public class OrderTask {
Manager manager = null;
if (merchant.getManagerId() != null) {
manager = jingliList.stream().filter(d -> {
return d.getUserId().equals(merchant.getManagerId());
return d.getManagerId().equals(merchant.getManagerId());
}).findFirst().orElse(null);
} else {
manager = jingliList.stream().filter(d -> {
@@ -266,9 +400,13 @@ public class OrderTask {
profitLog.setMoney(jingliProfit);
profitLog.setMerchantCode(merchant.getMerchantCode());
profitLog.setScene(5);
profitLog.setOrderId(order.getOrderId());
profitLog.setOrderId(order.getId());
profitLog.setOrderNo(order.getOrderNo());
profitLog.setComments("门店业绩" + order.getMerchantCode());
profitLog.setComments("区域经理收益" + order.getMerchantCode());
profitLog.setEquipmentCode(equipment.getEquipmentCode());
profitLog.setMerchantName(merchant.getMerchantName());
profitLog.setOrderSource(order.getGoodsId());
// profitLog.setIsRenew(order.getIsRenew());
profitLogService.save(profitLog);
}
}
@@ -276,6 +414,7 @@ public class OrderTask {
}
// 设置为已结算
LambdaUpdateWrapper<Order> updateWrapper = Wrappers.lambdaUpdate(Order.class).in(Order::getOrderId, orderIds).set(Order::getIsSettled, 1);
orderService.update(updateWrapper);

View File

@@ -82,18 +82,7 @@ public class MybatisPlusConfig {
* @return Integer
*/
public Expression getLoginUserTenantId() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
if (object instanceof User) {
return new LongValue(((User) object).getTenantId());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new NullValue();
return new LongValue(6);
}
}

View File

@@ -19,15 +19,15 @@ public class OrderConstants {
// 收货状态
public static final Integer RECEIPT_STATUS_NO = 10; // 未收货
public static final Integer RECEIPT_STATUS_YES = 20; // 已收货
public static final Integer RECEIPT_STATUS_APPLY = 21; // 申请
public static final Integer RECEIPT_STATUS_reject = 22; // 已驳回退租
public static final Integer RECEIPT_STATUS_APPLY = 21; // 申请退租
public static final Integer RECEIPT_STATUS_RETURN = 30; // 已退货
// 订单状态
public static final Integer ORDER_STATUS_DOING = 10; // 进行中
public static final Integer ORDER_STATUS_CANCEL = 20; // 已取消
public static final Integer ORDER_STATUS_TO_CANCEL = 21; // 待取消
public static final Integer ORDER_STATUS_COMPLETED = 30; // 已完成
public static final Integer ORDER_STATUS_COMPLETED = 30; // 已绑定
public static final Integer ORDER_STATUS_OVER = 40; // 已完成
// 订单结算状态
public static final Integer ORDER_SETTLED_YES = 1; // 已结算

View File

@@ -53,6 +53,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/api/login-alipay/*",
"/api/wx-login/loginByMpWxPhone",
"/api/shop/payment/mp-alipay/notify",
"/api/shop/freeze-order/notify",
"/api/shop/payment/mp-alipay/test/**",
"/api/shop/payment/mp-alipay/getPhoneNumber",
"/api/shop/test/**",

View File

@@ -8,6 +8,8 @@ import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.system.entity.Setting;
import com.gxwebsoft.common.system.service.SettingService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@@ -32,6 +34,7 @@ public class AlipayConfigUtil {
@Resource
private ConfigProperties pathConfig;
private SettingService settingService;
public AlipayConfigUtil(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
@@ -71,7 +74,9 @@ public class AlipayConfigUtil {
System.out.println("key = " + key);
String cache = stringRedisTemplate.opsForValue().get(key);
if (cache == null) {
throw new BusinessException("支付方式未配置");
Setting payment = settingService.getData("payment");
cache = payment.getContent();
stringRedisTemplate.opsForValue().set(key,cache);
}
// 解析json数据
JSONObject payment = JSON.parseObject(cache.getBytes());

View File

@@ -1,14 +1,99 @@
package com.gxwebsoft.common.core.utils;
import sun.misc.BASE64Encoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.RandomUtil;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Base64;
public class ImageUtil {
/**
* 按长宽比缩放图片
* 返回的宽不能大于maxWidth
* 返回的高不能大于maxHeight
* @param imageFile
* @param maxWidth
* @param maxHeight
* @return
*/
public static int[] computedSize(File imageFile, int maxWidth, int maxHeight) throws IOException {
BufferedImage bufferedImage = ImageIO.read(imageFile);
int originalWidth = bufferedImage.getWidth();
int originalHeight = bufferedImage.getHeight();
// 计算长宽比
double aspectRatio = (double) originalWidth / originalHeight;
// 如果原始图片的宽度和高度都小于等于最大宽度和最大高度,则无需缩放
if (originalWidth <= maxWidth && originalHeight <= maxHeight) {
return new int[]{originalWidth, originalHeight};
}
// 根据长宽比计算缩放后的宽度和高度
int newWidth = maxWidth;
int newHeight = maxHeight;
if (aspectRatio > 1) {
// 宽度大于高度,按照最大宽度进行缩放
newHeight = (int) (maxWidth / aspectRatio);
if (newHeight > maxHeight) {
// 如果缩放后的高度超过最大高度,则再次按照最大高度进行缩放
newHeight = maxHeight;
newWidth = (int) (maxHeight * aspectRatio);
}
} else {
// 高度大于宽度,按照最大高度进行缩放
newWidth = (int) (maxHeight * aspectRatio);
if (newWidth > maxWidth) {
// 如果缩放后的宽度超过最大宽度,则再次按照最大宽度进行缩放
newWidth = maxWidth;
newHeight = (int) (maxWidth / aspectRatio);
}
}
return new int[]{newWidth, newHeight};
}
private static String getImageExtension(String imageUrl) {
int dotIndex = imageUrl.lastIndexOf('.');
if (dotIndex != -1) {
return imageUrl.substring(dotIndex);
}
return ".jpg"; // 默认使用 .jpg 后缀
}
public static File downloadImage(String imageUrl) throws IOException {
URL url = new URL(imageUrl);
try (InputStream in = url.openStream()) {
String extension = getImageExtension(imageUrl);
String fileName = RandomUtil.randomString(9);
Path tempFile = Files.createTempFile(fileName, extension);
Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
return tempFile.toFile();
}
}
public static int[] getImageDimensions(File imageFile) throws IOException {
BufferedImage image = ImageIO.read(imageFile);
int width = image.getWidth();
int height = image.getHeight();
return new int[] { width, height };
}
public static String encodeImageToBase64(File imageFile) throws IOException {
byte[] imageBytes = Files.readAllBytes(imageFile.toPath());
String base64String = Base64.getEncoder().encodeToString(imageBytes);
return base64String;
}
public static String ImageBase64(String imgUrl) {
URL url = null;
InputStream is = null;
@@ -32,7 +117,7 @@ public class ImageUtil {
outStream.write(buffer, 0, len);
}
// 对字节数组Base64编码
return new BASE64Encoder().encode(outStream.toByteArray());
return new Base64Encoder().encode(outStream.toByteArray());
}catch (Exception e) {
e.printStackTrace();
}

View File

@@ -82,16 +82,8 @@ public class BaseController {
* @return tenantId
*/
public Integer getTenantId() {
// 从登录用户拿tenantId
User loginUser = getLoginUser();
if (loginUser != null) {
return loginUser.getTenantId();
}
// 从请求头拿tenantId
if(StrUtil.isNotBlank(request.getHeader("tenantId"))){
return Integer.valueOf(request.getHeader("tenantId"));
}
return null;
return 6;
}
/**
@@ -268,9 +260,9 @@ public class BaseController {
System.out.println("正确的签名 = " + signString);
System.out.println("签名是否正确 = " + SignCheckUtil.signCheck(params, getAppSecret()));
if (!SignCheckUtil.signCheck(params, getAppSecret())) {
throw new BusinessException("签名失败");
}
// if (!SignCheckUtil.signCheck(params, getAppSecret())) {
// throw new BusinessException("签名失败");
// }
}
// 模拟提交参数

View File

@@ -152,12 +152,12 @@ public class AliOssController extends BaseController {
// STS接入地址例如sts.cn-hangzhou.aliyuncs.com。
String endpoint = "sts.cn-shenzhen.aliyuncs.com";
// 填写步骤1生成的RAM用户访问密钥AccessKey ID和AccessKey Secret。
String accessKeyId = "LTAI5t8UTh8CTXEi2dYxobhj";
String accessKeySecret = "fNdJOT4KAjrVrzHNAcSJuUCy9ZljD9";
String accessKeyId = "LTAI5tSZ62sPCvUsLRDDf7fH";
String accessKeySecret = "e0I4vMIh7Gw91Ie6xjyoqEVeW6Regp";
// 填写步骤3获取的角色ARN。
String roleArn = "acs:ram::1194088977870561:role/ramosstest";
String roleArn = "acs:ram::1470199532233684:role/ramossyunxinwei";
// 自定义角色会话名称用来区分不同的令牌例如可填写为SessionTest。
String roleSessionName = "jimeiapp";
String roleSessionName = "yunxinwei";
// 设置临时访问凭证的有效时间为3600秒。
Long durationSeconds = 3600L;
try {
@@ -197,8 +197,8 @@ public class AliOssController extends BaseController {
public ApiResult<?> getPostForm(){
String endpoint = config.getEndpoint();
// RAM用户的访问密钥AccessKey ID和AccessKey Secret
String accessKeyId = "LTAI5t8UTh8CTXEi2dYxobhj";
String accessKeySecret = "fNdJOT4KAjrVrzHNAcSJuUCy9ZljD9";
String accessKeyId = "LTAI5tSZ62sPCvUsLRDDf7fH";
String accessKeySecret = "e0I4vMIh7Gw91Ie6xjyoqEVeW6Regp";
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
// 填写Bucket名称例如examplebucket。

View File

@@ -147,7 +147,7 @@ public class FilePreviewController extends BaseController {
return fail("请求失败: 40012");
}
@ApiOperation("获取微信小程序码")
@ApiOperation("获取微信 小程序码")
@GetMapping("/getQRCode")
public ApiResult<?> getQRCode() {
String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + getAccessToken();

View File

@@ -170,6 +170,9 @@ public class User implements UserDetails {
@ApiModelProperty("备注")
private String comments;
@ApiModelProperty(value = "押金状态")
private Integer pledged;
@ApiModelProperty("状态, 0正常, 1冻结")
private Integer status;

View File

@@ -39,8 +39,8 @@
<include refid="selectUserRoleSql"/>
) d ON a.user_id = d.user_id
LEFT JOIN sys_tenant e ON a.tenant_id = e.tenant_id
LEFT JOIN shop_user_grade g ON a.grade_id = g.grade_id
LEFT JOIN shop_user_referee h ON a.user_id = h.user_id
LEFT JOIN shop_user_grade g ON a.grade_id = g.grade_id and g.deleted = 0
LEFT JOIN shop_user_referee h ON a.user_id = h.user_id and h.deleted = 0
<where>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
@@ -155,9 +155,9 @@
OR d.role_name LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
<if test="param.parentId != null">
AND a.organization_id IN (SELECT organization_id FROM sys_organization WHERE parent_id=#{param.parentId})
</if>
<!-- <if test="param.parentId != null">-->
<!-- AND a.organization_id IN (SELECT organization_id FROM sys_organization WHERE parent_id=#{param.parentId})-->
<!-- </if>-->
</where>
</sql>

View File

@@ -90,10 +90,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
List<User> list = baseMapper.selectPageRel(page, param);
// 查询用户的角色
selectUserRoles(list);
// 查询用户详细资料
if (param.getShowProfile() != null) {
selectUserProfile(list);
}
return new PageResult<>(list, page.getTotal());
}

View File

@@ -0,0 +1,14 @@
package com.gxwebsoft.oa.service;
import com.gxwebsoft.oa.vo.IdcardRespVO;
public interface IdcardService {
/**
*
* @param frontImg 身份证正面
* @param backImg 身份证反面
* @return
*/
IdcardRespVO verify (String frontImg, String backImg );
}

View File

@@ -0,0 +1,57 @@
package com.gxwebsoft.oa.service.impl;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.gxwebsoft.common.core.utils.HttpUtils;
import com.gxwebsoft.love.vo.idcheck.FrontRecognitionResult;
import com.gxwebsoft.love.vo.idcheck.Response;
import com.gxwebsoft.oa.service.IdcardService;
import com.gxwebsoft.oa.vo.IdcardRespVO;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class IdcardServiceImpl implements IdcardService {
@Override
public IdcardRespVO verify(String frontImg, String backImg) {
String host = "https://miitangs14.market.alicloudapi.com";
String path = "/v1/tools/ocr/idCard";
String method = "POST";
String appcode = "1390018309a443c695c98c8da2bed691";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求定义相对应的Content-Type
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//需要给X-Ca-Nonce的值生成随机字符串每次请求不能相同
headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("frontImg", frontImg);
bodys.put("backImg", backImg);
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity);
IdcardRespVO respVO = JSONObject.parseObject(string, new TypeReference<IdcardRespVO>() {
});
return respVO;
//获取response的body
//System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,22 @@
package com.gxwebsoft.oa.vo;
import lombok.Data;
@Data
public class IdcardRespVO {
private String code;
private String message;
private String reqNo;
private String frontResult;
private String name;
private String sex;
private String nation;
private String birth;
private String address;
private String idCardNo;
private String backResult;
private String issueOrg;
private String issueDate;
private String expireDate;
}

View File

@@ -14,6 +14,7 @@ import com.gxwebsoft.common.core.security.JwtSubject;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.LoginRecord;
@@ -67,116 +68,120 @@ public class OpenAlipayController extends BaseController {
@Resource
private UserOauthMapper userOauthMapper;
@Resource
private RedisUtil redisUtil;
@Resource
private StringRedisTemplate stringRedisTemplate;
@ApiOperation("支付宝授权码")
@PostMapping("/getAuthCode")
@Transactional(rollbackFor = {Exception.class})
public ApiResult<?> getAuthCode(@RequestBody UserParam param, HttpServletRequest req) throws AlipayApiException {
// 验证签名
isCheckSign();
// 读取缓存信息
String setting = stringRedisTemplate.opsForValue().get("cache"+param.getTenantId()+":setting:register");
if(setting == null){
throw new BusinessException("请先配置注册设置");
}
JSONObject jsonObject = JSONObject.parseObject(setting);
String roleId = jsonObject.getString("roleId");
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(param.getTenantId());
try {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(param.getAuthCode());
AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
final String accessToken = response.getAccessToken();
AlipayUserInfoShareRequest request2 = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse userInfo = alipayClient.certificateExecute(request2, accessToken);
String nickName = "支付宝用户";
String avatar = "";
if(StrUtil.isNotBlank(userInfo.getAvatar())){
avatar = userInfo.getAvatar();
}
if (StrUtil.isNotBlank(userInfo.getNickName())) {
nickName = userInfo.getNickName();
}
if(userInfo.isSuccess()){
// 查询是否已注册
UserOauthParam userOauthParam = new UserOauthParam();
userOauthParam.setOauthId(userInfo.getUserId());
userOauthParam.setTenantId(param.getTenantId());
UserOauth userOauth = userOauthParam.getOne(userOauthMapper.getByOauthId(userOauthParam));
if(userOauth != null){
UserParam userParam = new UserParam();
userParam.setUserId(userOauth.getUserId());
userParam.setTenantId(userOauth.getTenantId());
User user = userService.getByOauthId(userParam);
if(user != null){
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), user.getTenantId()),
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, user));
}
userOauthService.removeById(userOauth.getId());
}
// 新注册用户
User user = new User();
user.setStatus(0);
user.setUsername(randomUsername("Ali_"));
user.setNickname(nickName);
user.setAvatar(avatar);
user.setCity(userInfo.getCity());
user.setProvince(userInfo.getProvince());
user.setPassword(userService.encodePassword(CommonUtil.randomUUID16()));
user.setTenantId(param.getTenantId());
boolean isSuccess = userService.saveUser(user);
if(isSuccess){
// 添加用户角色
UserRole userRole = new UserRole();
userRole.setUserId(user.getUserId());
userRole.setTenantId(param.getTenantId());
userRole.setRoleId(Integer.valueOf(roleId));
userRoleService.save(userRole);
// 添加第三方用户信息
UserOauth userOauth2 = new UserOauth();
userOauth2.setUserId(user.getUserId());
userOauth2.setTenantId(param.getTenantId());
userOauth2.setOauthType("MP-ALIPAY");
userOauth2.setOauthId(userInfo.getUserId());
userOauthService.save(userOauth2);
// 验证签名
isCheckSign();
// 读取缓存信息
String key = "setting:register:" + getTenantId();
String setting = redisUtil.get(key);
UserParam userParam = new UserParam();
userParam.setUserId(user.getUserId());
userParam.setTenantId(user.getTenantId());
User result = userService.getByOauthId(userParam);
loginRecordService.saveAsync(result.getUsername(), LoginRecord.TYPE_REGISTER, null, result.getTenantId(), req);
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(result.getUsername(), result.getTenantId()),
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, result));
}
}
if (setting == null) {
throw new BusinessException("请先配置注册设置");
}
} catch (AlipayApiException e) {
e.printStackTrace();
}
return fail("支付宝授权失败");
JSONObject jsonObject = JSONObject.parseObject(setting);
String roleId = jsonObject.getString("roleId");
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(param.getTenantId());
try {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(param.getAuthCode());
AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
final String accessToken = response.getAccessToken();
AlipayUserInfoShareRequest request2 = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse userInfo = alipayClient.certificateExecute(request2, accessToken);
String nickName = "支付宝用户";
String avatar = "";
if (StrUtil.isNotBlank(userInfo.getAvatar())) {
avatar = userInfo.getAvatar();
}
if (StrUtil.isNotBlank(userInfo.getNickName())) {
nickName = userInfo.getNickName();
}
if (userInfo.isSuccess()) {
// 查询是否已注册
UserOauthParam userOauthParam = new UserOauthParam();
userOauthParam.setOauthId(userInfo.getUserId());
userOauthParam.setTenantId(param.getTenantId());
UserOauth userOauth = userOauthParam.getOne(userOauthMapper.getByOauthId(userOauthParam));
if (userOauth != null) {
UserParam userParam = new UserParam();
userParam.setUserId(userOauth.getUserId());
userParam.setTenantId(userOauth.getTenantId());
User user = userService.getByOauthId(userParam);
if (user != null) {
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), user.getTenantId()),
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, user));
}
userOauthService.removeById(userOauth.getId());
}
// 新注册用户
User user = new User();
user.setStatus(0);
user.setUsername(randomUsername("Ali_"));
user.setNickname(nickName);
user.setAvatar(avatar);
user.setCity(userInfo.getCity());
user.setProvince(userInfo.getProvince());
user.setPassword(userService.encodePassword(CommonUtil.randomUUID16()));
user.setTenantId(param.getTenantId());
boolean isSuccess = userService.saveUser(user);
if (isSuccess) {
// 添加用户角色
UserRole userRole = new UserRole();
userRole.setUserId(user.getUserId());
userRole.setTenantId(param.getTenantId());
userRole.setRoleId(Integer.valueOf(roleId));
userRoleService.save(userRole);
// 添加第三方用户信息
UserOauth userOauth2 = new UserOauth();
userOauth2.setUserId(user.getUserId());
userOauth2.setTenantId(param.getTenantId());
userOauth2.setOauthType("MP-ALIPAY");
userOauth2.setOauthId(userInfo.getUserId());
userOauthService.save(userOauth2);
UserParam userParam = new UserParam();
userParam.setUserId(user.getUserId());
userParam.setTenantId(user.getTenantId());
User result = userService.getByOauthId(userParam);
loginRecordService.saveAsync(result.getUsername(), LoginRecord.TYPE_REGISTER, null, result.getTenantId(), req);
// 签发token
String access_token = JwtUtil.buildToken(new JwtSubject(result.getUsername(), result.getTenantId()),
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
return success("登录成功", new LoginResult(access_token, result));
}
}
}
} catch (AlipayApiException e) {
e.printStackTrace();
}
return fail("支付宝授权失败");
}
@ApiOperation("授权手机号码")
@PostMapping("/update")
public ApiResult<User> updateInfo(@RequestBody User user) {
user.setUserId(getLoginUserId());
// 不能修改的字段
user.setUsername(null);
user.setPassword(null);
user.setEmailVerified(null);
user.setOrganizationId(null);
user.setStatus(null);
if (userService.updateById(user)) {
return success(userService.getByIdRel(user.getUserId()));
}
return fail("保存失败", null);
user.setUserId(getLoginUserId());
// 不能修改的字段
user.setUsername(null);
user.setPassword(null);
user.setEmailVerified(null);
user.setOrganizationId(null);
user.setStatus(null);
if (userService.updateById(user)) {
return success(userService.getByIdRel(user.getUserId()));
}
return fail("保存失败", null);
}
}

View File

@@ -15,8 +15,11 @@ import com.gxwebsoft.apps.service.EquipmentRecordService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.core.utils.ImageUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.service.IdcardService;
import com.gxwebsoft.oa.vo.IdcardRespVO;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderRefund;
import com.gxwebsoft.shop.param.OrderParam;
@@ -25,13 +28,18 @@ import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.gxwebsoft.apps.constants.EquipmentConstants.*;
import static com.gxwebsoft.common.core.constants.OrderConstants.*;
@@ -57,6 +65,12 @@ public class OpenEquipmentController extends BaseController {
@Resource
private OrderRefundService orderRefundService;
@Resource
private IdcardService idcardService;
@Resource
private RestTemplate restTemplate;
@PreAuthorize("hasAuthority('apps:equipment:list')")
@OperationLog
@ApiOperation("分页查询设备管理")
@@ -71,7 +85,6 @@ public class OpenEquipmentController extends BaseController {
return success(equipmentService.pageRel(param));
}
@PreAuthorize("hasAuthority('apps:equipment:list')")
@OperationLog
@ApiOperation("查询全部设备管理")
@GetMapping()
@@ -83,7 +96,6 @@ public class OpenEquipmentController extends BaseController {
return success(equipmentService.listRel(param));
}
@PreAuthorize("hasAuthority('apps:equipment:list')")
@OperationLog
@ApiOperation("根据id查询设备管理")
@GetMapping("/{id}")
@@ -205,6 +217,8 @@ public class OpenEquipmentController extends BaseController {
@PostMapping("/bind")
@Transactional(rollbackFor = {Exception.class})
public ApiResult<?> bindEquipment(@RequestBody Equipment equipment) {
User loginUser = getLoginUser();
// 验证签名
isCheckSign();
final Integer orderId = equipment.getOrderId();
@@ -238,7 +252,29 @@ public class OpenEquipmentController extends BaseController {
order.setReceiptStatus(RECEIPT_STATUS_YES);
order.setExpirationTime(DateUtil.nextMonth());
order.setEquipmentId(one.getEquipmentId());
if(order.getOrderSource() == 10) {
order.setOrderStatus(ORDER_STATUS_OVER);
}
orderService.updateById(order);
JSONObject param = new JSONObject();
param.put("userId", loginUser.getUserId());
param.put("userName", loginUser.getNickname());
param.put("userPhone", loginUser.getPhone());
param.put("battery_sn", one.getEquipmentCode());
try {
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity("https://battery.zfdliot.com/api/battery/batteryBindUser", param, JSONObject.class);
JSONObject body = responseEntity.getBody();
System.out.println(body);
}catch (Exception e) {
e.printStackTrace();
}
return success("绑定成功");
}
return fail("绑定失败");
@@ -251,16 +287,21 @@ public class OpenEquipmentController extends BaseController {
// 验证签名
isCheckSign();
String equipmentCode = equipment.getEquipmentCode();
Integer oid = equipment.getEquipmentId();
Integer orderId = equipment.getOrderId();
System.out.println("oid = " + oid);
Integer loginUserId = getLoginUserId();
// 订单信息
Integer orderId = equipment.getOrderId();
Order order = orderService.getById(orderId);
Integer oldEqId = order.getEquipmentId();
// 新电池
Equipment one = equipmentService.getByEquipmentCode(equipmentCode);
String newMerchantCode = one.getMerchantCode();
// 旧电池
Equipment old = equipmentService.getById(oid);
// 订单信息
Order order = orderService.getById(orderId);
Equipment old = equipmentService.getById(oldEqId);
String oldMerchantCode = old.getMerchantCode();
if (one == null) {
return fail("设备不存在");
}
@@ -273,6 +314,7 @@ public class OpenEquipmentController extends BaseController {
saveData.setEquipmentId(one.getEquipmentId());
saveData.setUserId(loginUserId);
saveData.setOrderId(orderId);
saveData.setMerchantCode(oldMerchantCode);
boolean b = equipmentService.updateById(saveData);
// 记录新电池明细
EquipmentRecord record = new EquipmentRecord();
@@ -286,7 +328,8 @@ public class OpenEquipmentController extends BaseController {
if (b) {
// 解绑旧电池
old.setUserId(0);
old.setMerchantCode(one.getMerchantCode());
old.setOrderId(0);
old.setMerchantCode(newMerchantCode);
equipmentService.updateById(old);
// 记录明细
EquipmentRecord record2 = new EquipmentRecord();
@@ -299,7 +342,26 @@ public class OpenEquipmentController extends BaseController {
// 更新订单
order.setEquipmentId(one.getEquipmentId());
orderService.updateById(order);
User loginUser = getLoginUser();
// 通知第三方
/**
* {
* "userId": "1",
* "userName": "2",
* "userPhone": "3",
* "battery_sn": "YXW-BMS4-ABCD-1234567890"
* }
*/
JSONObject param = new JSONObject();
param.put("userId", loginUser.getUserId());
param.put("userName", loginUser.getNickname());
param.put("userPhone", loginUser.getPhone());
param.put("battery_sn", one.getEquipmentCode());
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity("https://battery.zfdliot.com/api/battery/batteryBindUser", param, JSONObject.class);
JSONObject body = responseEntity.getBody();
System.out.println(body);
return success("换电成功");
}
return fail("换电失败");
}
@@ -307,6 +369,27 @@ public class OpenEquipmentController extends BaseController {
@ApiOperation("重置")
@PostMapping("/receipt")
public ApiResult<?> receipt(@RequestBody Order order) {
// 验证身份证真实性
if(StringUtils.hasText(order.getOrderSourceData())) {
String orderSourceDataString = order.getOrderSourceData();
List<String> images = JSONObject.parseArray(orderSourceDataString, String.class);
String front = ImageUtil.ImageBase64(images.get(0) + "?x-oss-process=image/resize,w_750/quality,Q_80");
String back = ImageUtil.ImageBase64(images.get(1) + "?x-oss-process=image/resize,w_750/quality,Q_80");
IdcardRespVO verify = idcardService.verify(front, back);
if(!"FP00000".equals(verify.getCode())) {
return fail("请上传身份证正面照片");
}
if(verify.getIssueDate() == null || verify.getIssueOrg() == null || verify.getExpireDate() == null) {
return fail("请上传身份证反面照片");
}
}
// 验证签名
isCheckSign();
orderService.updateById(order);
@@ -321,8 +404,16 @@ public class OpenEquipmentController extends BaseController {
isCheckSign();
OrderRefund refund = orderRefundService.getOne(new LambdaQueryWrapper<OrderRefund>()
.eq(OrderRefund::getOrderId, order.getOrderId()));
// 已有记录 取消退租
if (refund != null) {
if(refund.getAuditStatus() == 10){
orderRefundService.removeById(refund.getOrderRefundId());
Order updateOrder = new Order();
updateOrder.setReceiptStatus(RECEIPT_STATUS_YES);
updateOrder.setOrderId(order.getOrderId());
orderService.updateById(updateOrder);
return success("退租申请已取消");
}
if (refund.getAuditStatus() != 30) {
return fail("申请成功,请等待客服人员审核");
}

View File

@@ -1,6 +1,7 @@
package com.gxwebsoft.open.controller;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.apps.utils.BcUtil;
import com.gxwebsoft.common.core.web.ApiResult;
@@ -16,9 +17,7 @@ import com.gxwebsoft.shop.mapper.OrderMapper;
import com.gxwebsoft.shop.param.CartParam;
import com.gxwebsoft.shop.param.OrderGoodsParam;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.UserBalanceLogService;
import com.gxwebsoft.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -50,6 +49,8 @@ public class OpenOrderController extends BaseController {
@Resource
private OrderGoodsService orderGoodsService;
@Resource
private FreezeOrderService freezeOrderService;
@Resource
private OrderMapper orderMapper;
@Resource
private UserService userService;
@@ -252,10 +253,17 @@ public class OpenOrderController extends BaseController {
@ApiOperation("删除订单记录表")
@GetMapping("/remove/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
public ApiResult<?> remove(@PathVariable("id") Integer id) throws AlipayApiException {
// 验证签名
isCheckSign();
try {
freezeOrderService.unfreeze(id);
}catch (Exception e) {
}
// Order order = orderService.getById(id);
if (orderService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");

View File

@@ -0,0 +1,341 @@
package com.gxwebsoft.shop.controller;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import com.gxwebsoft.apps.entity.EquipmentGoods;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderPay;
import com.gxwebsoft.shop.service.FreezeOrderService;
import com.gxwebsoft.shop.entity.FreezeOrder;
import com.gxwebsoft.shop.param.FreezeOrderParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.shop.service.OrderPayService;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import static com.gxwebsoft.common.core.constants.OrderConstants.PAY_STATUS_NO_PAY;
import static com.gxwebsoft.common.core.constants.OrderConstants.PAY_STATUS_SUCCESS;
/**
* 控制器
*
* @author 科技小王子
* @since 2023-10-08 10:15:22
*/
@Api(tags = "管理")
@RestController
@RequestMapping("/api/shop/freeze-order")
public class FreezeOrderController extends BaseController {
@Resource
private FreezeOrderService freezeOrderService;
@Resource
private AlipayConfigUtil alipayConfig;
@Resource
private ConfigProperties pathConfig;
@Resource
private OrderService orderService;
@Resource
private OrderPayService orderPayService;
@Resource
private EquipmentGoodsService equipmentGoodsService;
@PreAuthorize("hasAuthority('shop:freezeOrder:list')")
@OperationLog
@ApiOperation("分页查询")
@GetMapping("/page")
public ApiResult<PageResult<FreezeOrder>> page(FreezeOrderParam param) {
PageParam<FreezeOrder, FreezeOrderParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(freezeOrderService.page(page, page.getWrapper()));
// 使用关联查询
//return success(freezeOrderService.pageRel(param));
}
@PreAuthorize("hasAuthority('shop:freezeOrder:list')")
@OperationLog
@ApiOperation("查询全部")
@GetMapping()
public ApiResult<List<FreezeOrder>> list(FreezeOrderParam param) {
PageParam<FreezeOrder, FreezeOrderParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(freezeOrderService.list(page.getOrderWrapper()));
// 使用关联查询
//return success(freezeOrderService.listRel(param));
}
@PreAuthorize("hasAuthority('shop:freezeOrder:list')")
@OperationLog
@ApiOperation("根据id查询")
@GetMapping("/{id}")
public ApiResult<FreezeOrder> get(@PathVariable("id") Integer id) {
return success(freezeOrderService.getById(id));
// 使用关联查询
//return success(freezeOrderService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('shop:freezeOrder:save')")
@OperationLog
@ApiOperation("添加")
@PostMapping()
public ApiResult<?> save(@RequestBody FreezeOrder freezeOrder) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
freezeOrder.setUserId(loginUser.getUserId());
}
if (freezeOrderService.save(freezeOrder)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:freezeOrder:update')")
@OperationLog
@ApiOperation("修改")
@PutMapping()
public ApiResult<?> update(@RequestBody FreezeOrder freezeOrder) {
if (freezeOrderService.updateById(freezeOrder)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('shop:freezeOrder:remove')")
@OperationLog
@ApiOperation("删除")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (freezeOrderService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('shop:freezeOrder:save')")
@OperationLog
@ApiOperation("批量添加")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<FreezeOrder> list) {
if (freezeOrderService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:freezeOrder:update')")
@OperationLog
@ApiOperation("批量修改")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<FreezeOrder> batchParam) {
if (batchParam.update(freezeOrderService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('shop:freezeOrder:remove')")
@OperationLog
@ApiOperation("批量删除")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (freezeOrderService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@PostMapping("/notify")
@Transactional
public void freezeNotify(@RequestParam Map<String, String> params, HttpServletResponse response) throws AlipayApiException {
PrintWriter writer = null;
DateTime now = DateUtil.date();
JSONObject config = alipayConfig.payment(Integer.valueOf(getTenantId()));
String alipayCertPublicKey = pathConfig.getUploadPath() + "file" + config.getString("alipayCertPublicKey");
boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPublicKey, AlipayConstants.CHARSET_UTF8, AlipayConstants.SIGN_TYPE_RSA2);
if(!flag) {
try {
writer = response.getWriter();
writer.write("fail"); //一定要打印success
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (writer != null) {
writer.close();
}
return;
}
}
String auth_no = params.get("auth_no");
String notify_type = params.get("notify_type");
String out_order_no = params.get("out_order_no");
String operation_id = params.get("operation_id");
String operation_type = params.get("operation_type");
String amount = params.get("amount");
String status = params.get("status");
String payer_logon_id = params.get("payer_logon_id");
String payer_user_id = params.get("payer_user_id");
String notify_id = params.get("notify_id");
String out_request_no = params.get("out_request_no");
String trade_status = params.get("trade_status");
String payee_user_id = params.get("payee_user_id");
FreezeOrder one = freezeOrderService.lambdaQuery().eq(FreezeOrder::getNotifyId, notify_id).one();
if(one == null) {
FreezeOrder freezeOrder = freezeOrderService.lambdaQuery().eq(FreezeOrder::getOutRequestNo, out_request_no).one();
if(freezeOrder == null) {
freezeOrder = new FreezeOrder();
}
freezeOrder.setOutOrderNo(out_order_no != null ?out_order_no: "");
freezeOrder.setOutRequestNo(out_request_no);
freezeOrder.setOperationId(operation_id);
freezeOrder.setAmount(amount != null?new BigDecimal(amount):BigDecimal.ZERO);
freezeOrder.setPayeeLogonId(payer_logon_id);
freezeOrder.setPayerUserId(payer_user_id);
freezeOrder.setPayeeUserId(payee_user_id);
freezeOrder.setNotifyId(notify_id);
freezeOrder.setStatus(status);
freezeOrder.setAuthNo(auth_no);
freezeOrder.setOperationType(operation_type);
freezeOrder.setNotifyType(notify_type);
freezeOrder.setTenantId(6);
freezeOrder.setDetail(JSONObject.toJSONString(params));
freezeOrderService.saveOrUpdate(freezeOrder);
try {
writer = response.getWriter();
writer.write("success"); //一定要打印success
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (writer != null) {
writer.close();
}
}
// return "success";
}
// return "fail";
}
@PostMapping("/checkFreeze/{orderId}")
public ApiResult<?> checkFreeze(@PathVariable Integer orderId) throws AlipayApiException {
DateTime now = DateUtil.date();
Order order = orderService.getById(orderId);
if (order.getOrderSource() == 30 || order.getOrderSource() == 40) {
AlipayFundAuthOperationDetailQueryResponse response = freezeOrderService.query(order);
String status = response.getStatus();
boolean isFreeze = response.isSuccess() && "SUCCESS".equals(status);
if( !isFreeze) {
return fail();
}
}
final EquipmentGoods eg = equipmentGoodsService.getById(order.getOrderSourceId());
order.setIsFreeze(1);
orderService.updateById(order);
// 创建续费订单
OrderPay renewOrder = new OrderPay();
renewOrder.setOrderNo(IdUtil.getSnowflakeNextIdStr());
renewOrder.setMerchantCode(order.getMerchantCode());
renewOrder.setGoodsId(order.getOrderSourceId());
renewOrder.setCurrPeriods(1);
renewOrder.setPeriods(order.getPeriods());
renewOrder.setRentOrderId(order.getOrderId());
renewOrder.setStartTime(now);
renewOrder.setExpirationTime(DateUtil.offset(now, DateField.MONTH,1));
renewOrder.setPayStatus(PAY_STATUS_NO_PAY);
renewOrder.setBatteryDeposit(order.getBatteryDeposit());
renewOrder.setBatteryInsurance(order.getBatteryInsurance());
renewOrder.setEquipmentId(order.getEquipmentId());
renewOrder.setDealerPhone(order.getDealerPhone());
renewOrder.setComments("续租订单:" + order.getOrderNo());
renewOrder.setUserId(order.getUserId());
renewOrder.setMerchantName(order.getMerchantName());
renewOrder.setOutRequestNo(order.getOutRequestNo());
renewOrder.setOrderSource(order.getOrderSource());
if(order.getOrderSource() == 20) {
// 首付+手续费
renewOrder.setTotalPrice(eg.getDownPayment().add(eg.getServiceCharges()));
renewOrder.setOrderPrice(eg.getDownPayment().add(eg.getServiceCharges()));
renewOrder.setPayPrice(eg.getDownPayment().add(eg.getServiceCharges()));
}else if(order.getOrderSource() == 30 || order.getOrderSource() == 40) {
// 月租
BigDecimal price = eg.getBatteryRent();
// 是否需要保险
if(renewOrder.getCurrPeriods()%12 == 1) {
renewOrder.setBatteryInsurance(eg.getBatteryInsurance());
price = price.add(eg.getBatteryInsurance());
}else {
renewOrder.setBatteryInsurance(BigDecimal.ZERO);
}
renewOrder.setTotalPrice(price);
renewOrder.setOrderPrice(price);
renewOrder.setPayPrice(price);
}else if(order.getOrderSource() == 10) {
// 售价
renewOrder.setTotalPrice(eg.getBatteryPrice());
renewOrder.setOrderPrice(eg.getBatteryPrice());
renewOrder.setPayPrice(eg.getBatteryPrice());
}
orderPayService.save(renewOrder);
return success(renewOrder);
}
}

View File

@@ -3,8 +3,16 @@ package com.gxwebsoft.shop.controller;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
@@ -19,17 +27,15 @@ import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.apps.service.EquipmentOrderGoodsService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.entity.UserReferee;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.param.OrderGoodsParam;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.UserRefereeService;
import com.gxwebsoft.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -39,6 +45,7 @@ import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
@@ -61,6 +68,9 @@ import static com.gxwebsoft.common.core.constants.OrderConstants.PAY_STATUS_SUCC
public class OrderController extends BaseController {
@Resource
private OrderService orderService;
@Resource
private MerchantService merchantService;
@Resource
private EquipmentGoodsService equipmentGoodsService;
@Resource
@@ -68,7 +78,19 @@ public class OrderController extends BaseController {
@Resource
private OrderGoodsService orderGoodsService;
@Resource
private OrderPayService orderPayService;
@Resource
private FreezeOrderService freezeOrderService;
@Resource
private EquipmentOrderGoodsService equipmentOrderGoodsService;
@Resource
private AlipayConfigUtil alipayConfig;
@Resource
private ConfigProperties pathConfig;
@Resource
private UserRefereeService userRefereeService;
@Resource
@@ -76,80 +98,54 @@ public class OrderController extends BaseController {
@Resource
private BcAgentService bcAgentService;
@PreAuthorize("hasAuthority('shop:order:list')")
@OperationLog
@ApiOperation("分页查询订单记录表")
@GetMapping("/page")
public ApiResult<PageResult<Order>> page(OrderParam param) {
// 搜索条件
if ((param.getIsApp() == null || param.getIsApp() != true )&& getMerchantCode() != null) {
if ((param.getIsApp() == null || param.getIsApp() != true) && getMerchantCode() != null) {
param.setMerchantCode(getMerchantCode());
}
// 云芯威项目查询关联设备
if (getTenantId().equals(6)) {
// 查询订单的关联商品
List<Order> list = orderService.listRel(param);
Set<Integer> equipmentIds = new HashSet<>();
Set<Integer> orderIds = new HashSet<>();
for (Order order : list) {
equipmentIds.add(order.getEquipmentId());
orderIds.add(order.getOrderId());
}
List<Equipment> equipmentList = equipmentService.list(Wrappers.lambdaQuery(Equipment.class).in(Equipment::getEquipmentId, equipmentIds));
List<EquipmentOrderGoods> equipmentOrderGoodsList = equipmentOrderGoodsService.list(Wrappers.lambdaQuery(EquipmentOrderGoods.class).in(EquipmentOrderGoods::getOrderId, orderIds));
Map<Integer, List<Equipment>> equipmentCollect = equipmentList.stream().collect(Collectors.groupingBy(Equipment::getEquipmentId));
Map<Integer, List<EquipmentOrderGoods>> equipmentOrderGoodsCollect = equipmentOrderGoodsList.stream().collect(Collectors.groupingBy(EquipmentOrderGoods::getOrderId));
// 查询订单的关联商品
List<Order> list = orderService.listRel(param);
List<Order> renewOrderList = orderService.list(Wrappers.lambdaQuery(Order.class).eq(Order::getIsRenew, 1).in(Order::getRentOrderId, orderIds).eq(Order::getPayStatus,PAY_STATUS_SUCCESS));
Map<Integer, List<Order>> renewOrderMap = renewOrderList.stream().collect(Collectors.groupingBy(Order::getRentOrderId));
// 查询订单的设备
for (Order order : list) {
final OrderGoodsParam orderGoodsParam = new OrderGoodsParam();
orderGoodsParam.setOrderId(order.getOrderId());
List<EquipmentOrderGoods> equipmentOrderGoods = equipmentOrderGoodsCollect.get(order.getOrderId());
if(CollectionUtils.isEmpty(equipmentOrderGoods)){
continue;
}
EquipmentOrderGoods orderGoods = equipmentOrderGoods.get(0);
order.setEquipmentGoods(orderGoods);
List<Equipment> equipment = equipmentCollect.get(order.getEquipmentId());
if(CollectionUtils.isNotEmpty(equipment)){
order.setEquipment(equipment.get(0));
}
// 续租订单
List<Order> renewOrders = renewOrderMap.get(order.getOrderId());
if(CollectionUtils.isNotEmpty(renewOrders) && renewOrders.size() >= orderGoods.getPeriods().intValue()){
order.setFenqiStatus(1);
}
// 逾期时间
long between = DateUtil.between( order.getExpirationTime(),DateUtil.date(), DateUnit.DAY);
if(DateUtil.date().isAfter(order.getExpirationTime())){
order.setExpirationDay((int) -between);
}else {
order.setExpirationDay((int) between);
}
}
PageParam<Order, OrderParam> page = new PageParam<>(param);
return success(new PageResult<>(list, page.getTotal()));
if (CollectionUtils.isEmpty(list)) {
return success(new PageResult<>(list, 0l));
}
// 贵港自然资源报餐
if (getTenantId().equals(10048) && getAppId() != null) {
param.setUserId(getLoginUserId());
final Boolean agent = param.getAgent();
if (agent != null) {
final BcAgentParam bcAgentParam = new BcAgentParam();
bcAgentParam.setParentId(getLoginUserId());
bcAgentParam.setLimit(100L);
final PageResult<BcAgent> result = bcAgentService.pageRel(bcAgentParam);
final Set<Integer> collect = result.getList().stream().map(BcAgent::getUserId).collect(Collectors.toSet());
param.setUserId(null);
param.setUserIds(collect);
}
return success(orderService.pageRel(param));
Set<Integer> equipmentIds = new HashSet<>();
Set<Integer> orderIds = new HashSet<>();
for (Order order : list) {
equipmentIds.add(order.getEquipmentId());
orderIds.add(order.getOrderId());
}
List<Equipment> equipmentList = equipmentService.list(Wrappers.lambdaQuery(Equipment.class).in(Equipment::getEquipmentId, equipmentIds));
List<EquipmentOrderGoods> equipmentOrderGoodsList = equipmentOrderGoodsService.list(Wrappers.lambdaQuery(EquipmentOrderGoods.class).in(EquipmentOrderGoods::getOrderId, orderIds));
Map<Integer, List<Equipment>> equipmentCollect = equipmentList.stream().collect(Collectors.groupingBy(Equipment::getEquipmentId));
Map<Integer, List<EquipmentOrderGoods>> equipmentOrderGoodsCollect = equipmentOrderGoodsList.stream().collect(Collectors.groupingBy(EquipmentOrderGoods::getOrderId));
// 查询订单的设备
for (Order order : list) {
final OrderGoodsParam orderGoodsParam = new OrderGoodsParam();
orderGoodsParam.setOrderId(order.getOrderId());
List<EquipmentOrderGoods> equipmentOrderGoods = equipmentOrderGoodsCollect.get(order.getOrderId());
if (CollectionUtils.isEmpty(equipmentOrderGoods)) {
continue;
}
EquipmentOrderGoods orderGoods = equipmentOrderGoods.get(0);
order.setEquipmentGoods(orderGoods);
List<Equipment> equipment = equipmentCollect.get(order.getEquipmentId());
if (CollectionUtils.isNotEmpty(equipment)) {
order.setEquipment(equipment.get(0));
}
}
PageParam<Order, OrderParam> page = new PageParam<>(param);
return success(new PageResult<>(list, page.getTotal()));
// 使用关联查询
return success(orderService.pageRel(param));
}
@PreAuthorize("hasAuthority('shop:order:list')")
@@ -234,67 +230,6 @@ public class OrderController extends BaseController {
return success(order);
}
@PreAuthorize("hasAuthority('shop:order:save')")
@OperationLog
@ApiOperation("添加订单记录表")
@PostMapping()
public ApiResult<?> save(@RequestBody Order order) {
// 记录当前登录用户id、租户id
User loginUser = getLoginUser();
if (loginUser != null) {
order.setUserId(loginUser.getUserId());
}
if (orderService.save(order)) {
// 云芯威BMS
if (order.getTenantId().equals(6)) {
final EquipmentGoods eg = equipmentGoodsService.getById(order.getOrderSourceId());
eg.setOrderId(order.getOrderId());
// 添加订单商品
final EquipmentOrderGoods oeg = new EquipmentOrderGoods();
oeg.setOrderId(order.getOrderId());
oeg.setGoodsName(eg.getGoodsName());
oeg.setEquipmentCategory(eg.getEquipmentCategory());
oeg.setImage(eg.getImage());
oeg.setCategoryId(eg.getCategoryId());
oeg.setBatteryModel(eg.getBatteryModel());
oeg.setSellingPoint(eg.getSellingPoint());
oeg.setStockTotal(eg.getStockTotal());
oeg.setContent(eg.getContent());
oeg.setBatteryPrice(eg.getBatteryPrice());
oeg.setBatteryRent(eg.getBatteryRent());
oeg.setBatteryInsurance(eg.getBatteryInsurance());
oeg.setBatteryDeposit(eg.getBatteryDeposit());
oeg.setDownPayment(eg.getDownPayment());
oeg.setPeriods(eg.getPeriods());
oeg.setRepayment(eg.getRepayment());
oeg.setServiceCharges(eg.getServiceCharges());
oeg.setPeriodsType(eg.getPeriodsType());
oeg.setUserId(eg.getUserId());
oeg.setComments(eg.getComments());
oeg.setStatus(eg.getStatus());
oeg.setMerchantCode(eg.getMerchantCode());
oeg.setTouziProfit(eg.getTouziProfit());
oeg.setTouziFirstProfit(eg.getTouziFirstProfit());
oeg.setTuijianProfit(eg.getTuijianProfit());
oeg.setTuijianFirstProfit(eg.getTuijianFirstProfit());
oeg.setMendianProfit(eg.getMendianProfit());
oeg.setMendianFirstProfit(eg.getMendianFirstProfit());
oeg.setJingliProfit(eg.getJingliProfit());
oeg.setJingliFirstProfit(eg.getJingliFirstProfit());
oeg.setTenantId(eg.getTenantId());
equipmentOrderGoodsService.saveOrUpdate(oeg);
}
// 是否存入星期值(10048)
if (order.getDeliveryTime() != null) {
order.setWeek(DateUtil.dayOfWeek(order.getDeliveryTime()) - 1);
}
return success("添加成功", order);
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:order:update')")
@OperationLog
@@ -395,4 +330,82 @@ public class OrderController extends BaseController {
QrCodeUtil.generate(orderNo, config, FileUtil.file(filePath));
return success("请求成功", qrcodeUrl);
}
@PreAuthorize("hasAuthority('shop:order:save')")
@OperationLog
@ApiOperation("添加订单记录表")
@PostMapping()
public ApiResult<?> save(@RequestBody Order order) throws AlipayApiException {
// 记录当前登录用户id、租户id
User loginUser = getLoginUser();
if (loginUser != null) {
order.setUserId(loginUser.getUserId());
}
// 历史订单
order.setCurrPeriods(0);
// 设置分期期数
final EquipmentGoods eg = equipmentGoodsService.getById(order.getOrderSourceId());
Merchant merchantByCode = merchantService.getMerchantByCode(order.getMerchantCode());
order.setMerchantName(merchantByCode.getMerchantName());
//分期
if (order.getOrderSource() == 20) {
order.setPeriods(eg.getPeriods().intValue() + 1);
} else if (order.getOrderSource() == 30) {
order.setPeriods(eg.getPeriods().intValue());
} else if (order.getOrderSource() == 40) {
order.setPeriods(9999);
}
order.setFreezeOrderNo(IdUtil.getSnowflakeNextIdStr());
order.setOutRequestNo(IdUtil.getSnowflakeNextIdStr());
if (orderService.save(order)) {
order.setOrderStr(freezeOrderService.freeze(order, eg));
// 云芯威BMS
eg.setOrderId(order.getOrderId());
// 添加订单商品
final EquipmentOrderGoods oeg = new EquipmentOrderGoods();
oeg.setOrderId(order.getOrderId());
oeg.setGoodsName(eg.getGoodsName());
oeg.setEquipmentCategory(eg.getEquipmentCategory());
oeg.setImage(eg.getImage());
oeg.setCategoryId(eg.getCategoryId());
oeg.setBatteryModel(eg.getBatteryModel());
oeg.setSellingPoint(eg.getSellingPoint());
oeg.setStockTotal(eg.getStockTotal());
oeg.setContent(eg.getContent());
oeg.setBatteryPrice(eg.getBatteryPrice());
oeg.setBatteryRent(eg.getBatteryRent());
oeg.setBatteryInsurance(eg.getBatteryInsurance());
oeg.setBatteryDeposit(eg.getBatteryDeposit());
oeg.setDownPayment(eg.getDownPayment());
oeg.setPeriods(eg.getPeriods());
oeg.setRepayment(eg.getRepayment());
oeg.setServiceCharges(eg.getServiceCharges());
oeg.setPeriodsType(eg.getPeriodsType());
oeg.setUserId(eg.getUserId());
oeg.setComments(eg.getComments());
oeg.setStatus(eg.getStatus());
oeg.setMerchantCode(eg.getMerchantCode());
oeg.setTouziProfit(eg.getTouziProfit());
oeg.setTouziFirstProfit(eg.getTouziFirstProfit());
oeg.setTuijianProfit(eg.getTuijianProfit());
oeg.setTuijianFirstProfit(eg.getTuijianFirstProfit());
oeg.setMendianProfit(eg.getMendianProfit());
oeg.setMendianFirstProfit(eg.getMendianFirstProfit());
oeg.setJingliProfit(eg.getJingliProfit());
oeg.setJingliFirstProfit(eg.getJingliFirstProfit());
oeg.setTenantId(eg.getTenantId());
equipmentOrderGoodsService.saveOrUpdate(oeg);
return success("添加成功", order);
}
return fail("添加失败");
}
}

View File

@@ -0,0 +1,208 @@
package com.gxwebsoft.shop.controller;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.gxwebsoft.apps.entity.EquipmentGoods;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.service.OrderPayService;
import com.gxwebsoft.shop.entity.OrderPay;
import com.gxwebsoft.shop.param.OrderPayParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import static com.gxwebsoft.common.core.constants.OrderConstants.ORDER_STATUS_OVER;
import static com.gxwebsoft.common.core.constants.OrderConstants.PAY_STATUS_NO_PAY;
/**
* 订单记录表控制器
*
* @author 科技小王子
* @since 2023-10-13 16:58:03
*/
@Api(tags = "订单记录表管理")
@RestController
@RequestMapping("/api/shop/order-pay")
public class OrderPayController extends BaseController {
@Resource
private OrderPayService orderPayService;
@Resource
private OrderService orderService;
@Resource
private EquipmentGoodsService equipmentGoodsService;
@GetMapping("/page")
public ApiResult<PageResult<OrderPay>> page(OrderPayParam param) {
PageParam<OrderPay, OrderPayParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(orderPayService.page(page, page.getWrapper()));
// 使用关联查询
//return success(orderPayService.pageRel(param));
}
@GetMapping()
public ApiResult<List<OrderPay>> list(OrderPayParam param) {
PageParam<OrderPay, OrderPayParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(orderPayService.list(page.getOrderWrapper()));
// 使用关联查询
//return success(orderPayService.listRel(param));
}
@GetMapping("/{id}")
public ApiResult<OrderPay> get(@PathVariable("id") Integer id) {
return success(orderPayService.getById(id));
// 使用关联查询
//return success(orderPayService.getByIdRel(id));
}
@GetMapping("/getByOrderId/{id}")
public ApiResult<?> getByOrderId(@PathVariable("id") Integer orderId) {
OrderPay one = orderPayService.lambdaQuery()
.eq(OrderPay::getPayStatus, PAY_STATUS_NO_PAY)
.eq(OrderPay::getRentOrderId, orderId)
.orderByAsc(OrderPay::getCreateTime)
.last("limit 1").one();
// 是否提前续租
if(one == null) {
Order order = orderService.getById(orderId);
if(ORDER_STATUS_OVER.equals(order.getOrderStatus())) {
return fail(null);
}
EquipmentGoods eg = equipmentGoodsService.getById(order.getOrderSourceId());
one = new OrderPay();
one.setOrderNo(IdUtil.getSnowflakeNextIdStr());
one.setMerchantCode(order.getMerchantCode());
one.setGoodsId(order.getOrderSourceId());
one.setCurrPeriods(order.getCurrPeriods() + 1);
one.setPeriods(order.getPeriods());
one.setRentOrderId(order.getOrderId());
one.setStartTime(order.getExpirationTime());
one.setExpirationTime(DateUtil.offset(order.getExpirationTime(), DateField.MONTH,1));
one.setPayStatus(PAY_STATUS_NO_PAY);
one.setBatteryDeposit(order.getBatteryDeposit());
one.setBatteryInsurance(order.getBatteryInsurance());
one.setEquipmentId(order.getEquipmentId());
one.setDealerPhone(order.getDealerPhone());
one.setComments("续租订单:" + order.getOrderNo());
one.setUserId(order.getUserId());
one.setMerchantName(order.getMerchantName());
one.setOutRequestNo(order.getOutRequestNo());
one.setBatteryRent(order.getBatteryRent());
if(order.getOrderSource() == 20) {
// 每期还款+手续费
one.setTotalPrice(eg.getRepayment().add(eg.getServiceCharges()));
one.setOrderPrice(eg.getRepayment().add(eg.getServiceCharges()));
one.setPayPrice(eg.getRepayment().add(eg.getServiceCharges()));
}else if(order.getOrderSource() == 30 || order.getOrderSource() == 40) {
// 月租
BigDecimal price = eg.getBatteryRent();
// 是否需要保险
if (one.getCurrPeriods() % 12 == 1) {
price = price.add(eg.getBatteryInsurance());
}
// 月租
one.setTotalPrice(price);
one.setOrderPrice(price);
one.setPayPrice(price);
}
orderPayService.save(one);
}
return success(one);
}
@OperationLog
@ApiOperation("添加订单记录表")
@PostMapping()
public ApiResult<?> save(@RequestBody OrderPay orderPay) {
// 记录当前登录用户id
User loginUser = getLoginUser();
if (loginUser != null) {
orderPay.setUserId(loginUser.getUserId());
}
if (orderPayService.save(orderPay)) {
return success("添加成功");
}
return fail("添加失败");
}
@OperationLog
@ApiOperation("修改订单记录表")
@PutMapping()
public ApiResult<?> update(@RequestBody OrderPay orderPay) {
if (orderPayService.updateById(orderPay)) {
return success("修改成功");
}
return fail("修改失败");
}
@OperationLog
@ApiOperation("删除订单记录表")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (orderPayService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@OperationLog
@ApiOperation("批量添加订单记录表")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<OrderPay> list) {
if (orderPayService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@OperationLog
@ApiOperation("批量修改订单记录表")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<OrderPay> batchParam) {
if (batchParam.update(orderPayService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@OperationLog
@ApiOperation("批量删除订单记录表")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (orderPayService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -1,10 +1,21 @@
package com.gxwebsoft.shop.controller;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.request.AlipayFundAuthOrderUnfreezeRequest;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import com.alipay.api.response.AlipayFundAuthOrderUnfreezeResponse;
import com.gxwebsoft.apps.entity.Equipment;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.FreezeOrder;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.service.FreezeOrderService;
import com.gxwebsoft.shop.service.OrderRefundService;
import com.gxwebsoft.shop.entity.OrderRefund;
import com.gxwebsoft.shop.param.OrderRefundParam;
@@ -17,12 +28,13 @@ import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import static com.gxwebsoft.common.core.constants.OrderConstants.RECEIPT_STATUS_RETURN;
import static com.gxwebsoft.common.core.constants.OrderConstants.*;
/**
* 售后单记录表控制器
@@ -40,6 +52,12 @@ public class OrderRefundController extends BaseController {
private OrderService orderService;
@Resource
private EquipmentService equipmentService;
@Resource
private FreezeOrderService freezeOrderService;
@Resource
private AlipayConfigUtil alipayConfig;
@PreAuthorize("hasAuthority('shop:orderRefund:list')")
@OperationLog
@@ -88,22 +106,34 @@ public class OrderRefundController extends BaseController {
@OperationLog
@ApiOperation("修改售后单记录表")
@PutMapping()
public ApiResult<?> update(@RequestBody OrderRefund orderRefund) {
public ApiResult<?> update(@RequestBody OrderRefund orderRefund) throws AlipayApiException {
if (orderRefundService.updateById(orderRefund)) {
if(orderRefund.getTenantId().equals(6)){
if(orderRefund.getAuditStatus().equals(20)){
final Integer orderId = orderRefund.getOrderId();
final Order order = orderService.getById(orderId);
System.out.println("order = " + order);
order.setReceiptStatus(RECEIPT_STATUS_RETURN);
order.setOrderStatus(ORDER_STATUS_OVER);
final Equipment equipment = equipmentService.getById(order.getEquipmentId());
equipment.setUserId(0);
equipmentService.updateById(equipment);
orderService.updateById(order);
freezeOrderService.unfreeze(order.getOrderId());
// freezeOrderService.deduction(order.getOrderId());
}else if(orderRefund.getAuditStatus().equals(30)) {
final Integer orderId = orderRefund.getOrderId();
final Order order = orderService.getById(orderId);
order.setReceiptStatus(RECEIPT_STATUS_YES);
orderService.updateById(order);
}
return success("操作成功");
}
return fail("退租失败");
return success("退租失败");
}
@PreAuthorize("hasAuthority('shop:orderRefund:remove')")
@OperationLog
@ApiOperation("删除售后单记录表")

View File

@@ -1,5 +1,6 @@
package com.gxwebsoft.shop.controller;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
@@ -14,8 +15,10 @@ import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.apps.entity.BcTemporary;
import com.gxwebsoft.apps.entity.EquipmentGoods;
import com.gxwebsoft.apps.param.BcTemporaryParam;
import com.gxwebsoft.apps.service.BcTemporaryService;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.exception.BusinessException;
@@ -24,14 +27,9 @@ import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.OperationRecordService;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.Payment;
import com.gxwebsoft.shop.entity.UserBalanceLog;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.param.PaymentParam;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.PaymentService;
import com.gxwebsoft.shop.service.UserBalanceLogService;
import com.gxwebsoft.shop.service.UserOauthService;
import com.gxwebsoft.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
@@ -42,6 +40,8 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
@@ -59,148 +59,160 @@ import static com.gxwebsoft.common.core.constants.OrderConstants.*;
@RestController
@RequestMapping("/api/shop/payment")
public class PaymentController extends BaseController {
@Resource
private PaymentService paymentService;
@Resource
private OrderService orderService;
@Resource
private Environment config;
@Resource
private ConfigProperties pathConfig;
@Resource
private OperationRecordService operationRecordService;
@Resource
private UserOauthService userOauthService;
@Resource
private AlipayConfigUtil alipayConfig;
@Resource
private UserService userService;
@Resource
private UserBalanceLogService userBalanceLogService;
@Resource
private BcTemporaryService bcTemporaryService;
@Resource
private PaymentService paymentService;
@Resource
private OrderService orderService;
@PreAuthorize("hasAuthority('shop:payment:list')")
@ApiOperation("分页查询商城支付方式记录表")
@GetMapping("/page")
public ApiResult<PageResult<Payment>> page(PaymentParam param) {
PageParam<Payment, PaymentParam> page = new PageParam<>(param);
return success(paymentService.page(page, page.getWrapper()));
// 使用关联查询
//return success(paymentService.pageRel(param));
}
@Resource
private OrderPayService orderPayService;
@Resource
private Environment config;
@Resource
private ConfigProperties pathConfig;
@Resource
private OperationRecordService operationRecordService;
@Resource
private UserOauthService userOauthService;
@Resource
private AlipayConfigUtil alipayConfig;
@Resource
private UserService userService;
@Resource
private UserBalanceLogService userBalanceLogService;
@Resource
private BcTemporaryService bcTemporaryService;
@PreAuthorize("hasAuthority('shop:payment:list')")
@ApiOperation("查询全部商城支付方式记录表")
@GetMapping()
public ApiResult<List<Payment>> list(PaymentParam param) {
PageParam<Payment, PaymentParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(paymentService.list(page.getOrderWrapper()));
// 使用关联查询
//return success(paymentService.listRel(param));
}
@Resource
private FreezeOrderService freezeOrderService;
@PreAuthorize("hasAuthority('shop:payment:list')")
@ApiOperation("根据id查询商城支付方式记录表")
@GetMapping("/{id}")
public ApiResult<Payment> get(@PathVariable("id") Integer id) {
return success(paymentService.getById(id));
// 使用关联查询
//return success(paymentService.getByIdRel(id));
}
@Resource
private EquipmentGoodsService equipmentGoodsService;
@PreAuthorize("hasAuthority('shop:payment:save')")
@ApiOperation("添加商城支付方式记录表")
@PostMapping()
public ApiResult<?> save(@RequestBody Payment payment) {
if (paymentService.count(new LambdaQueryWrapper<Payment>()
.eq(Payment::getMethod, payment.getMethod())) > 0) {
return fail("该支付方式已存在");
@Resource
private MerchantService merchantService;
@PreAuthorize("hasAuthority('shop:payment:list')")
@ApiOperation("分页查询商城支付方式记录表")
@GetMapping("/page")
public ApiResult<PageResult<Payment>> page(PaymentParam param) {
PageParam<Payment, PaymentParam> page = new PageParam<>(param);
return success(paymentService.page(page, page.getWrapper()));
// 使用关联查询
//return success(paymentService.pageRel(param));
}
if (paymentService.save(payment)) {
return success("添加成功");
@PreAuthorize("hasAuthority('shop:payment:list')")
@ApiOperation("查询全部商城支付方式记录表")
@GetMapping()
public ApiResult<List<Payment>> list(PaymentParam param) {
PageParam<Payment, PaymentParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(paymentService.list(page.getOrderWrapper()));
// 使用关联查询
//return success(paymentService.listRel(param));
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:payment:update')")
@OperationLog
@ApiOperation("修改商城支付方式记录表")
@PutMapping()
public ApiResult<?> update(@RequestBody Payment payment) {
if (paymentService.updateById(payment)) {
return success("修改成功");
@PreAuthorize("hasAuthority('shop:payment:list')")
@ApiOperation("根据id查询商城支付方式记录表")
@GetMapping("/{id}")
public ApiResult<Payment> get(@PathVariable("id") Integer id) {
return success(paymentService.getById(id));
// 使用关联查询
//return success(paymentService.getByIdRel(id));
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('shop:payment:remove')")
@OperationLog
@ApiOperation("删除商城支付方式记录表")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (paymentService.removeById(id)) {
return success("删除成功");
@PreAuthorize("hasAuthority('shop:payment:save')")
@ApiOperation("添加商城支付方式记录表")
@PostMapping()
public ApiResult<?> save(@RequestBody Payment payment) {
if (paymentService.count(new LambdaQueryWrapper<Payment>()
.eq(Payment::getMethod, payment.getMethod())) > 0) {
return fail("该支付方式已存在");
}
if (paymentService.save(payment)) {
return success("添加成功");
}
return fail("添加失败");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('shop:payment:save')")
@OperationLog
@ApiOperation("批量添加商城支付方式记录表")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Payment> list) {
if (paymentService.saveBatch(list)) {
return success("添加成功");
@PreAuthorize("hasAuthority('shop:payment:update')")
@OperationLog
@ApiOperation("修改商城支付方式记录表")
@PutMapping()
public ApiResult<?> update(@RequestBody Payment payment) {
if (paymentService.updateById(payment)) {
return success("修改成功");
}
return fail("修改失败");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('shop:payment:update')")
@OperationLog
@ApiOperation("批量修改商城支付方式记录表")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<Payment> batchParam) {
if (batchParam.update(paymentService, "payment_id")) {
return success("修改成功");
@PreAuthorize("hasAuthority('shop:payment:remove')")
@OperationLog
@ApiOperation("删除商城支付方式记录表")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (paymentService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('shop:payment:remove')")
@OperationLog
@ApiOperation("批量删除商城支付方式记录表")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (paymentService.removeByIds(ids)) {
return success("删除成功");
@PreAuthorize("hasAuthority('shop:payment:save')")
@OperationLog
@ApiOperation("批量添加商城支付方式记录表")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<Payment> list) {
if (paymentService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
return fail("删除失败");
}
@ApiOperation("支付宝手机号码")
@PostMapping("/getPhoneNumber")
public ApiResult<?> getPhoneNumber(@RequestBody Map<String, String> params) {
final String encryptedData = params.get("encryptedData");
final String tenantId = params.get("tenantId");
// 支付宝配置信息
JSONObject config = alipayConfig.payment(Integer.valueOf(tenantId));
@PreAuthorize("hasAuthority('shop:payment:update')")
@OperationLog
@ApiOperation("批量修改商城支付方式记录表")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<Payment> batchParam) {
if (batchParam.update(paymentService, "payment_id")) {
return success("修改成功");
}
return fail("修改失败");
}
//1. 获取验签和解密所需要的参数
JSONObject jsonObject =JSONObject.parseObject(encryptedData);
String content = jsonObject.getString("response");
String sign = jsonObject.getString("sign");
String signType = "RSA2";
String charset = "UTF-8";
String encryptType = "AES";
String alipayCertPublicKey = pathConfig.getUploadPath() + "file" + config.getString("alipayCertPublicKey");
boolean isDataEncrypted = !content.startsWith("{");
boolean signVerified = false;
//2. 验签
String signContent = content;
String signVeriKey = ""; // 支付宝公钥
String decryptKey = config.getString("decryptKey"); // 加解密密钥
@PreAuthorize("hasAuthority('shop:payment:remove')")
@OperationLog
@ApiOperation("批量删除商城支付方式记录表")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (paymentService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
@ApiOperation("支付宝手机号码")
@PostMapping("/getPhoneNumber")
public ApiResult<?> getPhoneNumber(@RequestBody Map<String, String> params) {
final String encryptedData = params.get("encryptedData");
final String tenantId = params.get("tenantId");
// 支付宝配置信息
JSONObject config = alipayConfig.payment(Integer.valueOf(tenantId));
//1. 获取验签和解密所需要的参数
JSONObject jsonObject = JSONObject.parseObject(encryptedData);
String content = jsonObject.getString("response");
String sign = jsonObject.getString("sign");
String signType = "RSA2";
String charset = "UTF-8";
String encryptType = "AES";
String alipayCertPublicKey = pathConfig.getUploadPath() + "file" + config.getString("alipayCertPublicKey");
boolean isDataEncrypted = !content.startsWith("{");
boolean signVerified = false;
//2. 验签
String signContent = content;
String signVeriKey = ""; // 支付宝公钥
String decryptKey = config.getString("decryptKey"); // 加解密密钥
// System.out.println("decryptKey = " + decryptKey);
// System.out.println(content);
// System.out.println(sign);
@@ -208,306 +220,342 @@ public class PaymentController extends BaseController {
// System.out.println(charset);
// System.out.println(signType);
// System.out.println(isDataEncrypted);
if (isDataEncrypted) {
signContent = "\"" + signContent + "\"";
} try {
//验签方法
signVerified = AlipaySignature.rsaCertCheck(signContent, sign, alipayCertPublicKey, charset, signType);
} catch (AlipayApiException e) {
// 验签异常, 日志
} if (!signVerified) {
//验签不通过(异常或者报文被篡改),终止流程(不需要做解密)
return fail("验签失败");
if (isDataEncrypted) {
signContent = "\"" + signContent + "\"";
}
try {
//验签方法
signVerified = AlipaySignature.rsaCertCheck(signContent, sign, alipayCertPublicKey, charset, signType);
} catch (AlipayApiException e) {
// 验签异常, 日志
}
if (!signVerified) {
//验签不通过(异常或者报文被篡改),终止流程(不需要做解密)
return fail("验签失败");
}
//3. 解密
String plainData = null;
if (isDataEncrypted) {
try {
plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
} catch (AlipayApiException e) {
//解密异常, 记录日志
return fail("解密异常");
}
} else {
plainData = content;
}
return success("获取成功", plainData);
}
//3. 解密
String plainData = null;
if (isDataEncrypted) {
try {
plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
} catch (AlipayApiException e) {
//解密异常, 记录日志
return fail("解密异常");
}} else {
plainData = content;
}
return success("获取成功",plainData);
}
@ApiModelProperty("支付宝小程序支付")
@GetMapping("/mp-alipay/{id}")
public ApiResult<?> mpAlipay(@PathVariable("id") Integer id) throws AlipayApiException {
// 验证签名
isCheckSign();
// 订单数据
Order order = orderService.getByIdRel(id);
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(order.getTenantId());
try {
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
// 配置公共请求参数
request.setNotifyUrl(pathConfig.getServerUrl() + "/shop/payment/mp-alipay/notify");
// request.setNotifyUrl("https://454k72r798.goho.co/api/shop/payment/mp-alipay/notify");
request.setReturnUrl(null);
// 配置业务参数
JSONObject bizContent = new JSONObject();
System.out.println("bizContent = " + order);
bizContent.put("out_trade_no", order.getOrderNo());
bizContent.put("total_amount", order.getPayPrice());
bizContent.put("subject", order.getMerchantName());
// 拿不到手机号码??
bizContent.put("buyer_id", userOauthService.getOauthIdByUserId(order.getUserId(), "MP-ALIPAY"));
request.setBizContent(bizContent.toString());
//SDK 已经封装掉了公共参数,这里只需要传入业务参数。
AlipayTradeCreateResponse response = alipayClient.certificateExecute(request);
String trade_no = response.getTradeNo();// 获取返回的tradeNO。
return success("支付成功", trade_no);
} catch (AlipayApiException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
@ApiModelProperty("支付宝小程序支付")
@GetMapping("/mp-alipay/{id}")
public ApiResult<?> mpAlipay(@PathVariable("id") Integer id) throws AlipayApiException {
// 验证签名
isCheckSign();
// 订单数据
OrderPay order = orderPayService.getById(id);
@ApiModelProperty("异步通知")
@OperationLog
@PostMapping("/mp-alipay/notify")
public String alipayNotify(@RequestParam Map<String, String> params) throws AlipayApiException {
System.out.println("异步处理>>>>");
System.out.println("params = " + params);
String outTradeNo = params.get("out_trade_no");
Order order = orderService.getByOutTradeNo(outTradeNo);
if(order == null){
throw new BusinessException("订单不存在");
}
final JSONObject config = alipayConfig.payment(order.getTenantId());
// 生成环境证书路径
String alipayCertPublicKey = pathConfig.getUploadPath() + "file" + config.getString("alipayCertPublicKey");
// TODO 验签成功后按照支付结果异步通知中的描述对支付结果中的业务内容进行二次校验校验成功后在response中返回success并继续商户自身业务处理校验失败返回failure
boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPublicKey, AlipayConstants.CHARSET_UTF8, AlipayConstants.SIGN_TYPE_RSA2);
System.out.println("flag>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(flag);
// 处理订单业务
if (flag) {
final String tradeStatus = params.get("trade_status");
final String receipt_amount = params.get("receipt_amount");
final String payPrice = order.getPayPrice().toString();
final String trade_no = params.get("trade_no");
final String subject = params.get("subject");
// 1. 验证appId是否一致
final String app_id = params.get("app_id");
if(!config.getString("alipayAppId").equals(app_id)){
System.out.println("支付宝appId不一致 = " + app_id);
throw new BusinessException("支付宝appId不一致");
}
// 2. 订单金额
if(!payPrice.equals(receipt_amount)){
System.out.println("订单金额是不一致 = " + receipt_amount);
throw new BusinessException("订单金额是不一致");
}
// 3. 判断交易状态
if(!"TRADE_SUCCESS".equals(tradeStatus)){
System.out.println("支付失败 = " + tradeStatus);
throw new BusinessException("支付失败");
}
// 4. 修改支付状态
order.setPayStatus(PAY_STATUS_SUCCESS);
order.setPayMethod(PAY_METHOD_ALIPAY);
order.setReceiptAmount(new BigDecimal(receipt_amount));
order.setPayTime(DateUtil.date());
order.setTradeId(trade_no);
order.setSubject(subject);
System.out.println("order2 = " + order);
final boolean b = orderService.updateByIdRel(order);
System.out.println("bsss = " + b);
return "success";
}
// TODO 验签失败则记录异常日志并在response中返回failure.
return "failure";
}
Merchant merchant = merchantService.getMerchantByCode(order.getMerchantCode());
@OperationLog
@ApiModelProperty("余额支付")
@GetMapping("/balance/{id}")
@Transactional(rollbackFor = {Exception.class})
public ApiResult<?> balance(@PathVariable("id") Integer id) throws AlipayApiException {
// 1. 验证签名
isCheckSign();
// 订单数据
Order order = orderService.getByIdRel(id);
// 当前登录用户id
User user = new User();
// 代付款情况
if(!order.getUserId().equals(getLoginUserId())){
user = userService.getById(order.getUserId());
}else{
user = getLoginUser();
// final EquipmentGoods eg = equipmentGoodsService.getById(order.getGoodsId());
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(order.getTenantId());
try {
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
// 配置公共请求参数
request.setNotifyUrl(pathConfig.getServerUrl() + "/shop/payment/mp-alipay/notify");
// request.setNotifyUrl("http://1.14.132.108:10090/api/shop/payment/mp-alipay/notify");
request.setReturnUrl(null);
// 配置业务参数
JSONObject bizContent = new JSONObject();
System.out.println("bizContent = " + order);
bizContent.put("out_trade_no", order.getOrderNo());
bizContent.put("total_amount", order.getPayPrice());
bizContent.put("subject", merchant.getMerchantName());
// 拿不到手机号码??
bizContent.put("buyer_id", userOauthService.getOauthIdByUserId(order.getUserId(), "MP-ALIPAY"));
request.setBizContent(bizContent.toString());
//SDK 已经封装掉了公共参数,这里只需要传入业务参数。
AlipayTradeCreateResponse response = alipayClient.certificateExecute(request);
String trade_no = response.getTradeNo();// 获取返回的tradeNO。
return success("支付成功", trade_no);
} catch (AlipayApiException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
final Integer userId = user.getUserId();
final BigDecimal balance = user.getBalance();
final BigDecimal payPrice = order.getPayPrice();
if(balance.compareTo(payPrice) < 0){
return fail("余额不足 = " + balance.compareTo(payPrice));
}
// 2. 扣除余额操作
BigDecimal subtract = balance.subtract(payPrice);
user.setBalance(subtract);
userService.updateById(user);
// 3. 记录余额明细
UserBalanceLog userBalanceLog = new UserBalanceLog();
userBalanceLog.setUserId(userId);
userBalanceLog.setScene(BALANCE_USE);
userBalanceLog.setMoney(payPrice);
userBalanceLog.setBalance(subtract);
userBalanceLog.setComments(order.getOrderNo().toString());
userBalanceLog.setMerchantCode(order.getMerchantCode());
userBalanceLogService.save(userBalanceLog);
// 4. 修改支付状态
order.setPayStatus(PAY_STATUS_SUCCESS);
order.setPayMethod(PAY_METHOD_BALANCE);
order.setReceiptAmount(payPrice);
order.setPayTime(DateUtil.date());
order.setSubject(order.getMerchantName());
orderService.updateByIdRel(order);
// 5. 续租订单
if(order.getRentOrderId() > 0){
// 主订单
Order parentOrder = orderService.getById(order.getRentOrderId());
// 更新过期时间延长一个月
Date expirationTime = parentOrder.getExpirationTime();
DateTime nextMonthTime = DateUtil.offsetMonth(expirationTime, 1);
parentOrder.setExpirationTime(nextMonthTime);
orderService.updateById(parentOrder);
// 保存续费订单状态
order.setDeliveryStatus(DELIVERY_STATUS_YES);
order.setReceiptStatus(RECEIPT_STATUS_YES);
order.setOrderStatus(ORDER_STATUS_COMPLETED);
order.setStartTime(expirationTime);
order.setExpirationTime(nextMonthTime);
orderService.updateById(order);
}
// 6. 是否是临时报餐
final BcTemporaryParam bcTemporaryParam = new BcTemporaryParam();
bcTemporaryParam.setUserId(getLoginUserId());
bcTemporaryParam.setApplyStatus(1);
final List<BcTemporary> bcTemporaries = bcTemporaryService.listRel(bcTemporaryParam);
bcTemporaries.forEach(b -> {
b.setStatus(1);
bcTemporaryService.updateById(b);
});
return success("支付成功",user);
}
@OperationLog
@ApiModelProperty("余额支付批量")
@PostMapping("/balanceBatch")
@Transactional(rollbackFor = {Exception.class})
public ApiResult<?> balanceBatch(@RequestBody List<Integer> orderIds) throws AlipayApiException {
// 1. 验证签名
isCheckSign();
// 订单数据
final List<Order> list = orderService.listByIds(orderIds);
final StringBuilder sb = new StringBuilder();
@ApiModelProperty("异步通知")
@OperationLog
@PostMapping("/mp-alipay/notify")
public String alipayNotify(@RequestParam Map<String, String> params) throws AlipayApiException, ParseException {
System.out.println("异步处理>>>>");
System.out.println("params = " + params);
String outTradeNo = params.get("out_trade_no");
OrderPay order = orderPayService.lambdaQuery().eq(OrderPay::getOrderNo, outTradeNo).one();
if (order == null) {
throw new BusinessException("订单不存在");
}
final JSONObject config = alipayConfig.payment(order.getTenantId());
// 生成环境证书路径
String alipayCertPublicKey = pathConfig.getUploadPath() + "file" + config.getString("alipayCertPublicKey");
// TODO 验签成功后按照支付结果异步通知中的描述对支付结果中的业务内容进行二次校验校验成功后在response中返回success并继续商户自身业务处理校验失败返回failure
boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPublicKey, AlipayConstants.CHARSET_UTF8, AlipayConstants.SIGN_TYPE_RSA2);
System.out.println("flag>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(flag);
// 处理订单业务
if (flag) {
final String tradeStatus = params.get("trade_status");
final String receipt_amount = params.get("receipt_amount");
final String payPrice = order.getPayPrice().toString();
final String trade_no = params.get("trade_no");
final String subject = params.get("subject");
list.forEach(d -> {
// 当前登录用户id
User user = new User();
// 代付款情况
if(!d.getUserId().equals(getLoginUserId())){
user = userService.getById(d.getUserId());
}else{
user = getLoginUser();
}
final Integer userId = user.getUserId();
final BigDecimal balance = user.getBalance();
final BigDecimal payPrice = d.getPayPrice();
if(balance.compareTo(payPrice) < 0){
sb.append("下单失败:").append(user.getNickname()).append("余额不足");
throw new BusinessException("余额不足");
}
// 2. 扣除余额操作
BigDecimal subtract = balance.subtract(payPrice);
user.setBalance(subtract);
userService.updateById(user);
// 3. 记录余额明细
UserBalanceLog userBalanceLog = new UserBalanceLog();
userBalanceLog.setUserId(userId);
userBalanceLog.setScene(BALANCE_USE);
userBalanceLog.setMoney(payPrice);
userBalanceLog.setBalance(subtract);
userBalanceLog.setComments(d.getOrderNo().toString());
userBalanceLog.setMerchantCode(d.getMerchantCode());
userBalanceLogService.save(userBalanceLog);
// 4. 修改支付状态
d.setPayStatus(PAY_STATUS_SUCCESS);
d.setPayMethod(PAY_METHOD_BALANCE);
d.setReceiptAmount(payPrice);
d.setPayTime(DateUtil.date());
d.setSubject(d.getMerchantName());
orderService.updateByIdRel(d);
// 5. 续租订单
if(d.getRentOrderId() > 0){
// 主订单
Order parentOrder = orderService.getById(d.getRentOrderId());
// 1. 验证appId是否一致
final String app_id = params.get("app_id");
if (!config.getString("alipayAppId").equals(app_id)) {
System.out.println("支付宝appId不一致 = " + app_id);
throw new BusinessException("支付宝appId不一致");
}
// 2. 订单金额
if (!payPrice.equals(receipt_amount)) {
System.out.println("订单金额是不一致 = " + receipt_amount);
throw new BusinessException("订单金额是不一致");
}
// 3. 判断交易状态
if (!"TRADE_SUCCESS".equals(tradeStatus)) {
System.out.println("支付失败 = " + tradeStatus);
throw new BusinessException("支付失败");
}
// 4. 修改支付状态
order.setPayStatus(PAY_STATUS_SUCCESS);
order.setPayMethod(PAY_METHOD_ALIPAY);
order.setReceiptAmount(new BigDecimal(receipt_amount));
order.setPayTime(DateUtil.date());
order.setTradeId(trade_no);
order.setSubject(subject);
Order parentOrder = orderService.getById(order.getRentOrderId());
parentOrder.setCurrPeriods(parentOrder.getCurrPeriods() + 1);
order.setCurrPeriods(parentOrder.getCurrPeriods() + 1);
parentOrder.setPayStatus(PAY_STATUS_SUCCESS);
// 更新过期时间延长一个月
// 保存续费订单状态
if (parentOrder.getCurrPeriods() >= parentOrder.getPeriods()) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = sf.format(DateUtil.offset(new Date(), DateField.MONTH, 1200));
Date parse = sf.parse(format);
parentOrder.setOrderStatus(ORDER_STATUS_OVER);
parentOrder.setExpirationTime(parse);
try {
freezeOrderService.unfreeze(parentOrder.getOrderId());
} catch (AlipayApiException e) {
throw new RuntimeException(e);
}
}else {
parentOrder.setExpirationTime(order.getExpirationTime());
}
orderPayService.updateById(order);
orderService.updateById(parentOrder);
return "success";
}
// TODO 验签失败则记录异常日志并在response中返回failure.
return "failure";
}
@OperationLog
@ApiModelProperty("余额支付")
@GetMapping("/balance/{id}")
@Transactional(rollbackFor = {Exception.class})
public ApiResult<?> balance(@PathVariable("id") Integer id) throws AlipayApiException, ParseException {
// 1. 验证签名
isCheckSign();
// 订单数据
OrderPay order = orderPayService.getByIdRel(id);
// 当前登录用户id
User user = new User();
// 代付款情况
if (!order.getUserId().equals(getLoginUserId())) {
user = userService.getById(order.getUserId());
} else {
user = getLoginUser();
}
final Integer userId = user.getUserId();
final BigDecimal balance = user.getBalance();
final BigDecimal payPrice = order.getPayPrice();
if (balance.compareTo(payPrice) < 0) {
return fail("余额不足 = " + balance.compareTo(payPrice));
}
// 2. 扣除余额操作
BigDecimal subtract = balance.subtract(payPrice);
user.setBalance(subtract);
userService.updateById(user);
// 3. 记录余额明细
UserBalanceLog userBalanceLog = new UserBalanceLog();
userBalanceLog.setUserId(userId);
userBalanceLog.setScene(BALANCE_USE);
userBalanceLog.setMoney(payPrice);
userBalanceLog.setBalance(subtract);
userBalanceLog.setComments(order.getOrderNo().toString());
userBalanceLog.setMerchantCode(order.getMerchantCode());
userBalanceLogService.save(userBalanceLog);
// 4. 修改支付状态
order.setPayStatus(PAY_STATUS_SUCCESS);
order.setPayMethod(PAY_METHOD_BALANCE);
order.setReceiptAmount(payPrice);
order.setPayTime(DateUtil.date());
order.setSubject(order.getMerchantName());
// 处理主订单
Order parentOrder = orderService.getById(order.getRentOrderId());
parentOrder.setCurrPeriods(parentOrder.getCurrPeriods() + 1);
order.setCurrPeriods(parentOrder.getCurrPeriods() + 1);
parentOrder.setPayStatus(PAY_STATUS_SUCCESS);
// 更新过期时间延长一个月
Date expirationTime = parentOrder.getExpirationTime();
DateTime nextMonthTime = DateUtil.offsetMonth(expirationTime, 1);
parentOrder.setExpirationTime(nextMonthTime);
orderService.updateById(parentOrder);
// 保存续费订单状态
d.setDeliveryStatus(DELIVERY_STATUS_YES);
d.setReceiptStatus(RECEIPT_STATUS_YES);
d.setOrderStatus(ORDER_STATUS_COMPLETED);
d.setStartTime(expirationTime);
d.setExpirationTime(nextMonthTime);
orderService.updateById(d);
}
// 6. 是否是临时报餐
final BcTemporaryParam bcTemporaryParam = new BcTemporaryParam();
bcTemporaryParam.setUserId(getLoginUserId());
bcTemporaryParam.setApplyStatus(1);
final List<BcTemporary> bcTemporaries = bcTemporaryService.listRel(bcTemporaryParam);
bcTemporaries.forEach(b -> {
b.setStatus(1);
bcTemporaryService.updateById(b);
});
});
return success("支付成功",sb);
}
if (parentOrder.getCurrPeriods() >= parentOrder.getPeriods()) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = sf.format(DateUtil.offset(new Date(), DateField.MONTH, 1200));
Date parse = sf.parse(format);
@ApiModelProperty("统一收单交易查询")
@GetMapping("/mp-alipay/query/{id}")
public ApiResult<?> query(@PathVariable("id") Integer id) throws AlipayApiException {
// 验证签名
isCheckSign();
// 订单数据
Order order = orderService.getByIdRel(id);
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(order.getTenantId());
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", order.getOrderNo());
request.setBizContent(bizContent.toString());
AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
if(response.isSuccess()){
System.out.println("调用成功");
orderService.paySuccess(response);
} else {
System.out.println("调用失败");
parentOrder.setOrderStatus(ORDER_STATUS_OVER);
parentOrder.setExpirationTime(parse);
try {
freezeOrderService.unfreeze(parentOrder.getOrderId());
} catch (AlipayApiException e) {
throw new RuntimeException(e);
}
}else {
parentOrder.setExpirationTime(order.getExpirationTime());
}
freezeOrderService.keep(parentOrder);
orderService.updateById(parentOrder);
orderPayService.updateById(order);
return success("支付成功", user);
}
return success("调用成功",response);
}
@ApiModelProperty("测试")
@GetMapping("/mp-alipay/test")
public String test() {
System.out.println("开始>>>>>");
Order order = orderService.getByOutTradeNo("2023213225911618");
System.out.println("order = " + order);
order.setPayPrice(new BigDecimal("0.11"));
order.setTotalPrice(new BigDecimal("0.11"));
order.setPayStatus(PAY_STATUS_SUCCESS);
final boolean b = orderService.updateByIdRel(order);
System.out.println("b = " + b);
@OperationLog
@ApiModelProperty("余额支付批量")
@PostMapping("/balanceBatch")
@Transactional(rollbackFor = {Exception.class})
public ApiResult<?> balanceBatch(@RequestBody List<Integer> orderIds) throws AlipayApiException {
// 1. 验证签名
isCheckSign();
// 订单数据
final List<Order> list = orderService.listByIds(orderIds);
final StringBuilder sb = new StringBuilder();
list.forEach(d -> {
// 当前登录用户id
User user = new User();
// 代付款情况
if (!d.getUserId().equals(getLoginUserId())) {
user = userService.getById(d.getUserId());
} else {
user = getLoginUser();
}
final Integer userId = user.getUserId();
final BigDecimal balance = user.getBalance();
final BigDecimal payPrice = d.getPayPrice();
if (balance.compareTo(payPrice) < 0) {
sb.append("下单失败:").append(user.getNickname()).append("余额不足");
throw new BusinessException("余额不足");
}
// 2. 扣除余额操作
BigDecimal subtract = balance.subtract(payPrice);
user.setBalance(subtract);
userService.updateById(user);
// 3. 记录余额明细
UserBalanceLog userBalanceLog = new UserBalanceLog();
userBalanceLog.setUserId(userId);
userBalanceLog.setScene(BALANCE_USE);
userBalanceLog.setMoney(payPrice);
userBalanceLog.setBalance(subtract);
userBalanceLog.setComments(d.getOrderNo().toString());
userBalanceLog.setMerchantCode(d.getMerchantCode());
userBalanceLogService.save(userBalanceLog);
// 4. 修改支付状态
d.setPayStatus(PAY_STATUS_SUCCESS);
d.setPayMethod(PAY_METHOD_BALANCE);
d.setReceiptAmount(payPrice);
d.setPayTime(DateUtil.date());
d.setSubject(d.getMerchantName());
orderService.updateByIdRel(d);
// 5. 续租订单
if (d.getRentOrderId() > 0) {
// 主订单
Order parentOrder = orderService.getById(d.getRentOrderId());
// 更新过期时间延长一个月
Date expirationTime = parentOrder.getExpirationTime();
DateTime nextMonthTime = DateUtil.offsetMonth(expirationTime, 1);
parentOrder.setExpirationTime(nextMonthTime);
orderService.updateById(parentOrder);
// 保存续费订单状态
d.setDeliveryStatus(DELIVERY_STATUS_YES);
d.setReceiptStatus(RECEIPT_STATUS_YES);
d.setOrderStatus(ORDER_STATUS_COMPLETED);
d.setStartTime(expirationTime);
d.setExpirationTime(nextMonthTime);
orderService.updateById(d);
}
// 6. 是否是临时报餐
final BcTemporaryParam bcTemporaryParam = new BcTemporaryParam();
bcTemporaryParam.setUserId(getLoginUserId());
bcTemporaryParam.setApplyStatus(1);
final List<BcTemporary> bcTemporaries = bcTemporaryService.listRel(bcTemporaryParam);
bcTemporaries.forEach(b -> {
b.setStatus(1);
bcTemporaryService.updateById(b);
});
});
return success("支付成功", sb);
}
@ApiModelProperty("统一收单交易查询")
@GetMapping("/mp-alipay/query/{id}")
public ApiResult<?> query(@PathVariable("id") Integer id) throws AlipayApiException {
// 验证签名
isCheckSign();
// 订单数据
Order order = orderService.getByIdRel(id);
// 实例化客户端
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(order.getTenantId());
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", order.getOrderNo());
request.setBizContent(bizContent.toString());
AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
orderService.paySuccess(response);
} else {
System.out.println("调用失败");
}
return success("调用成功", response);
}
@ApiModelProperty("测试")
@GetMapping("/mp-alipay/test")
public String test() {
System.out.println("开始>>>>>");
Order order = orderService.getByOutTradeNo("2023213225911618");
System.out.println("order = " + order);
order.setPayPrice(new BigDecimal("0.11"));
order.setTotalPrice(new BigDecimal("0.11"));
order.setPayStatus(PAY_STATUS_SUCCESS);
final boolean b = orderService.updateByIdRel(order);
System.out.println("b = " + b);
// params.put("gmt_create", "2022-12-16 21:32:33");
// params.put("charset", "UTF-8");
@@ -534,6 +582,6 @@ public class PaymentController extends BaseController {
// params.put("point_amount", "0.00");
// // 处理订单业务
// orderService.paySuccess(params);
return "success";
}
return "success";
}
}

View File

@@ -37,9 +37,10 @@ public class ProfitLogController extends BaseController {
public ApiResult<PageResult<ProfitLog>> page(ProfitLogParam param) {
PageParam<ProfitLog, ProfitLogParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
return success(profitLogService.page(page, page.getWrapper()));
PageParam<ProfitLog, ProfitLogParam> result = profitLogService.page(page, page.getWrapper());
return success(result);
// 使用关联查询
//return success(profitLogService.pageRel(param));
// return success(profitLogService.pageRel(param));
}
@OperationLog

View File

@@ -0,0 +1,74 @@
package com.gxwebsoft.shop.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import java.util.Date;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* @author 科技小王子
* @since 2023-10-08 10:15:22
*/
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "FreezeOrder对象", description = "")
@TableName("shop_freeze_order")
public class FreezeOrder implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "商户授权资金订单号")
private String outOrderNo;
@ApiModelProperty(value = "out_request_no")
private String outRequestNo;
@ApiModelProperty(value = "冻结金额")
private BigDecimal amount;
@ApiModelProperty(value = "手机号或邮箱")
private String payeeLogonId;
@ApiModelProperty(value = "收款账户的支付宝登录号email 或手机号)")
private String orderTitle;
@ApiModelProperty(value = "关联订单ID")
private Integer relOrderId;
private Integer userId;
@ApiModelProperty(value = "状态")
private String status;
private String payerLogonId;
private String authNo;
private String operationId;
private String payerUserId;
private String payeeUserId;
private String notifyId;
private String operationType;
private String notifyType;
private String detail;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
private Date createTime;
private Date updateTime;
}

View File

@@ -76,6 +76,12 @@ public class Order implements Serializable {
@ApiModelProperty(value = "付款状态(10未付款 20已付款)")
private Integer payStatus;
@ApiModelProperty(value = "分期期数")
private Integer periods;
@ApiModelProperty(value = "当前期数")
private Integer currPeriods;
@ApiModelProperty(value = "付款时间")
private Date payTime;
@@ -115,6 +121,8 @@ public class Order implements Serializable {
@ApiModelProperty(value = "发货状态(10未发货 20已发货 30部分发货)")
private Integer deliveryStatus;
private Integer isFreeze;
@ApiModelProperty(value = "发货时间")
private Date deliveryTime;
@@ -187,6 +195,12 @@ public class Order implements Serializable {
@ApiModelProperty(value = "商品ID")
private Integer goodsId;
@ApiModelProperty(value = "冻结资金订单ID")
private String freezeOrderNo;
@ApiModelProperty(value = "冻结资金请求流水号")
private String outRequestNo;
@ApiModelProperty(value = "设备ID")
private Integer equipmentId;
@@ -256,7 +270,6 @@ public class Order implements Serializable {
private EquipmentOrderGoods equipmentGoods;
@ApiModelProperty("逾期天数")
@TableField(exist = false)
private Integer expirationDay;
@ApiModelProperty("设备")
@@ -270,4 +283,8 @@ public class Order implements Serializable {
@ApiModelProperty("分期状态 0还款中 1还款结束")
@TableField(exist = false)
private Integer fenqiStatus;
@ApiModelProperty("芝麻免押")
@TableField(exist = false)
private String orderStr;
}

View File

@@ -0,0 +1,172 @@
package com.gxwebsoft.shop.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
import java.util.Date;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 订单记录表
*
* @author 科技小王子
* @since 2023-10-13 16:58:03
*/
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "OrderPay对象", description = "订单记录表")
@TableName("shop_order_pay")
public class OrderPay implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "订单ID")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "订单标题")
private String subject;
@ApiModelProperty(value = "订单号")
private String orderNo;
@ApiModelProperty(value = "商品总金额(不含优惠折扣)")
private BigDecimal totalPrice;
private Integer orderSource;
@ApiModelProperty(value = "订单金额(含优惠折扣)")
private BigDecimal orderPrice;
@ApiModelProperty(value = "优惠券ID")
private Integer couponId;
@ApiModelProperty(value = "优惠券抵扣金额")
private BigDecimal couponMoney;
@ApiModelProperty(value = "积分抵扣金额")
private BigDecimal pointsMoney;
@ApiModelProperty(value = "积分抵扣数量")
private Integer pointsNum;
@ApiModelProperty(value = "实际付款金额(包含运费)")
private BigDecimal payPrice;
@ApiModelProperty(value = "第三方支付实收金额")
private BigDecimal receiptAmount;
@ApiModelProperty(value = "后台修改的订单金额(差价)")
private BigDecimal updatePrice;
@ApiModelProperty(value = "买家留言")
private String buyerRemark;
@ApiModelProperty(value = "支付方式(废弃)")
private Integer payType;
@ApiModelProperty(value = "支付方式余额10/微信20/支付宝30/通联支付40/其他支付50")
private String payMethod;
@ApiModelProperty(value = "付款状态(10未付款 20已付款)")
private Integer payStatus;
@ApiModelProperty(value = "付款时间")
private Date payTime;
@ApiModelProperty(value = "第三方交易记录ID")
private String tradeId;
@ApiModelProperty(value = "分期状态")
private Boolean periodsStatus;
@ApiModelProperty(value = "分期期数")
private Integer periods;
@ApiModelProperty(value = "当前分期期数")
private Integer currPeriods;
@ApiModelProperty(value = "商家备注")
private String merchantRemark;
private String merchantName;
@ApiModelProperty(value = "订单是否已结算(0未结算 1已结算)")
private Integer isSettled;
@ApiModelProperty(value = "最后结算时间")
private Date settledTime;
@ApiModelProperty(value = "续租订单的关联单号")
private Integer rentOrderId;
@ApiModelProperty(value = "电池租金")
private BigDecimal batteryRent;
@ApiModelProperty(value = "电池押金")
private BigDecimal batteryDeposit;
@ApiModelProperty(value = "保险")
private BigDecimal batteryInsurance;
@ApiModelProperty(value = "购买月份数量")
private Integer month;
@ApiModelProperty(value = "服务开始时间")
private Date startTime;
@ApiModelProperty(value = "服务到期时间")
private Date expirationTime;
@ApiModelProperty(value = "用户ID")
private Integer userId;
@ApiModelProperty(value = "所属门店ID")
private Integer shopId;
@ApiModelProperty(value = "商品ID")
private Integer goodsId;
@ApiModelProperty(value = "冻结资金请求流水号")
private String outRequestNo;
@ApiModelProperty(value = "电池商品ID")
private Integer equipmentId;
@ApiModelProperty(value = "排序(数字越小越靠前)")
private Integer sortNumber;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "状态, 0正常, 1冻结")
private Integer status;
@ApiModelProperty(value = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@ApiModelProperty(value = "商户编码")
private String merchantCode;
@ApiModelProperty(value = "推荐人手机号")
private String dealerPhone;
@ApiModelProperty(value = "逾期天数")
private Integer expirationDay;
@ApiModelProperty(value = "租户id")
private Integer tenantId;
@ApiModelProperty(value = "注册时间")
private Date createTime;
@ApiModelProperty(value = "修改时间")
private Date updateTime;
}

View File

@@ -32,6 +32,9 @@ public class OrderRefund implements Serializable {
@ApiModelProperty(value = "订单ID")
private Integer orderId;
@TableField(exist = false)
private String orderNo;
@ApiModelProperty(value = "订单商品ID")
private Integer orderGoodsId;

View File

@@ -1,11 +1,10 @@
package com.gxwebsoft.shop.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.*;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
import java.util.Date;
@@ -33,6 +32,8 @@ public class ProfitLog implements Serializable {
@ApiModelProperty(value = "订单ID")
private Integer orderId;
@TableField(exist = false)
private Order order;
@ApiModelProperty(value = "用户ID")
private Integer userId;
@@ -40,6 +41,11 @@ public class ProfitLog implements Serializable {
@ApiModelProperty(value = "订单号")
private String orderNo;
private Integer orderSource;
@ApiModelProperty(value = "是否续费订单")
private Integer isRenew;
@ApiModelProperty(value = "收益类型1资产收益2服务费收益3推广收益4门店业绩提成5站点业绩提成")
private Integer scene;
@@ -68,6 +74,18 @@ public class ProfitLog implements Serializable {
@ApiModelProperty(value = "商户编码")
private String merchantCode;
private String merchantName;
@ApiModelProperty(value = "设备编码")
private String equipmentCode;
@ApiModelProperty(value = "设备编码")
private Integer equipmentId;
private String orderUserName;
private String orderUserPhone;
@ApiModelProperty(value = "租户id")
private Integer tenantId;

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.shop.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.shop.entity.FreezeOrder;
import com.gxwebsoft.shop.param.FreezeOrderParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Mapper
*
* @author 科技小王子
* @since 2023-10-08 10:15:22
*/
public interface FreezeOrderMapper extends BaseMapper<FreezeOrder> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<FreezeOrder>
*/
List<FreezeOrder> selectPageRel(@Param("page") IPage<FreezeOrder> page,
@Param("param") FreezeOrderParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<FreezeOrder> selectListRel(@Param("param") FreezeOrderParam param);
}

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.shop.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.shop.entity.OrderPay;
import com.gxwebsoft.shop.param.OrderPayParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 订单记录表Mapper
*
* @author 科技小王子
* @since 2023-10-13 16:58:03
*/
public interface OrderPayMapper extends BaseMapper<OrderPay> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<OrderPay>
*/
List<OrderPay> selectPageRel(@Param("page") IPage<OrderPay> page,
@Param("param") OrderPayParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<OrderPay> selectListRel(@Param("param") OrderPayParam param);
}

View File

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.shop.mapper.FreezeOrderMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*
FROM shop_freeze_order a
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.outOrderNo != null">
AND a.out_order_no LIKE CONCAT('%', #{param.outOrderNo}, '%')
</if>
<if test="param.outRequestNo != null">
AND a.out_request_no LIKE CONCAT('%', #{param.outRequestNo}, '%')
</if>
<if test="param.amount != null">
AND a.amount = #{param.amount}
</if>
<if test="param.payeeLogonId != null">
AND a.payee_logon_id LIKE CONCAT('%', #{param.payeeLogonId}, '%')
</if>
<if test="param.orderTitle != null">
AND a.order_title LIKE CONCAT('%', #{param.orderTitle}, '%')
</if>
<if test="param.relOrderId != null">
AND a.rel_order_id = #{param.relOrderId}
</if>
<if test="param.status != null">
AND a.status LIKE CONCAT('%', #{param.status}, '%')
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.shop.entity.FreezeOrder">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.shop.entity.FreezeOrder">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -8,6 +8,9 @@
FROM shop_manager a
left join sys_user b on a.user_id = b.user_id
<where>
<if test="param.managerId != null">
AND a.manager_id = #{param.managerId}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>

View File

@@ -114,6 +114,9 @@
<if test="param.isComment != null">
AND a.is_comment = #{param.isComment}
</if>
<if test="param.isComplete != null">
AND a.is_complete = #{param.isComplete}
</if>
<if test="param.orderSource != null">
AND a.order_source = #{param.orderSource}
</if>
@@ -162,6 +165,9 @@
<if test="param.deleted == null">
AND a.deleted = 0
</if>
<if test="param.isFreeze != null">
AND a.is_freeze = #{param.isFreeze}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>

View File

@@ -0,0 +1,161 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.shop.mapper.OrderPayMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*
FROM shop_order_pay a
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.subject != null">
AND a.subject LIKE CONCAT('%', #{param.subject}, '%')
</if>
<if test="param.orderNo != null">
AND a.order_no LIKE CONCAT('%', #{param.orderNo}, '%')
</if>
<if test="param.totalPrice != null">
AND a.total_price = #{param.totalPrice}
</if>
<if test="param.orderPrice != null">
AND a.order_price = #{param.orderPrice}
</if>
<if test="param.couponId != null">
AND a.coupon_id = #{param.couponId}
</if>
<if test="param.couponMoney != null">
AND a.coupon_money = #{param.couponMoney}
</if>
<if test="param.pointsMoney != null">
AND a.points_money = #{param.pointsMoney}
</if>
<if test="param.pointsNum != null">
AND a.points_num = #{param.pointsNum}
</if>
<if test="param.payPrice != null">
AND a.pay_price = #{param.payPrice}
</if>
<if test="param.receiptAmount != null">
AND a.receipt_amount = #{param.receiptAmount}
</if>
<if test="param.updatePrice != null">
AND a.update_price = #{param.updatePrice}
</if>
<if test="param.buyerRemark != null">
AND a.buyer_remark LIKE CONCAT('%', #{param.buyerRemark}, '%')
</if>
<if test="param.payType != null">
AND a.pay_type = #{param.payType}
</if>
<if test="param.payMethod != null">
AND a.pay_method LIKE CONCAT('%', #{param.payMethod}, '%')
</if>
<if test="param.payStatus != null">
AND a.pay_status = #{param.payStatus}
</if>
<if test="param.payTime != null">
AND a.pay_time LIKE CONCAT('%', #{param.payTime}, '%')
</if>
<if test="param.tradeId != null">
AND a.trade_id LIKE CONCAT('%', #{param.tradeId}, '%')
</if>
<if test="param.periodsStatus != null">
AND a.periods_status = #{param.periodsStatus}
</if>
<if test="param.periods != null">
AND a.periods = #{param.periods}
</if>
<if test="param.currPeriods != null">
AND a.curr_periods = #{param.currPeriods}
</if>
<if test="param.merchantRemark != null">
AND a.merchant_remark LIKE CONCAT('%', #{param.merchantRemark}, '%')
</if>
<if test="param.isSettled != null">
AND a.is_settled = #{param.isSettled}
</if>
<if test="param.settledTime != null">
AND a.settled_time LIKE CONCAT('%', #{param.settledTime}, '%')
</if>
<if test="param.rentOrderId != null">
AND a.rent_order_id = #{param.rentOrderId}
</if>
<if test="param.batteryRent != null">
AND a.battery_rent = #{param.batteryRent}
</if>
<if test="param.batteryDeposit != null">
AND a.battery_deposit = #{param.batteryDeposit}
</if>
<if test="param.batteryInsurance != null">
AND a.battery_insurance = #{param.batteryInsurance}
</if>
<if test="param.month != null">
AND a.month = #{param.month}
</if>
<if test="param.startTime != null">
AND a.start_time LIKE CONCAT('%', #{param.startTime}, '%')
</if>
<if test="param.expirationTime != null">
AND a.expiration_time LIKE CONCAT('%', #{param.expirationTime}, '%')
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.shopId != null">
AND a.shop_id = #{param.shopId}
</if>
<if test="param.goodsId != null">
AND a.goods_id = #{param.goodsId}
</if>
<if test="param.outRequestNo != null">
AND a.out_request_no LIKE CONCAT('%', #{param.outRequestNo}, '%')
</if>
<if test="param.equipmentId != null">
AND a.equipment_id = #{param.equipmentId}
</if>
<if test="param.sortNumber != null">
AND a.sort_number = #{param.sortNumber}
</if>
<if test="param.comments != null">
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.deleted != null">
AND a.deleted = #{param.deleted}
</if>
<if test="param.deleted == null">
AND a.deleted = 0
</if>
<if test="param.merchantCode != null">
AND a.merchant_code LIKE CONCAT('%', #{param.merchantCode}, '%')
</if>
<if test="param.dealerPhone != null">
AND a.dealer_phone LIKE CONCAT('%', #{param.dealerPhone}, '%')
</if>
<if test="param.expirationDay != null">
AND a.expiration_day = #{param.expirationDay}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.shop.entity.OrderPay">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.shop.entity.OrderPay">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -0,0 +1,56 @@
package com.gxwebsoft.shop.param;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
/**
* 查询参数
*
* @author 科技小王子
* @since 2023-10-08 10:15:22
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(value = "FreezeOrderParam对象", description = "查询参数")
public class FreezeOrderParam extends BaseParam {
private static final long serialVersionUID = 1L;
@QueryField(type = QueryType.EQ)
private Integer id;
@ApiModelProperty(value = "商户授权资金订单号")
private String outOrderNo;
@ApiModelProperty(value = "out_request_no")
private String outRequestNo;
@ApiModelProperty(value = "冻结金额")
@QueryField(type = QueryType.EQ)
private BigDecimal amount;
@ApiModelProperty(value = "手机号或邮箱")
private String payeeLogonId;
@ApiModelProperty(value = "收款账户的支付宝登录号email 或手机号)")
private String orderTitle;
@ApiModelProperty(value = "关联订单ID")
@QueryField(type = QueryType.EQ)
private Integer relOrderId;
@QueryField(type = QueryType.EQ)
private Integer userId;
@ApiModelProperty(value = "状态")
private String status;
}

View File

@@ -243,4 +243,8 @@ public class OrderParam extends BaseParam {
private Boolean isApp;
private Integer isComplete;
private Integer isFreeze;
}

View File

@@ -0,0 +1,185 @@
package com.gxwebsoft.shop.param;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
/**
* 订单记录表查询参数
*
* @author 科技小王子
* @since 2023-10-13 16:58:03
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(value = "OrderPayParam对象", description = "订单记录表查询参数")
public class OrderPayParam extends BaseParam {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "订单ID")
@QueryField(type = QueryType.EQ)
private Integer id;
@ApiModelProperty(value = "订单标题")
private String subject;
@ApiModelProperty(value = "订单号")
private String orderNo;
@ApiModelProperty(value = "商品总金额(不含优惠折扣)")
@QueryField(type = QueryType.EQ)
private BigDecimal totalPrice;
@ApiModelProperty(value = "订单金额(含优惠折扣)")
@QueryField(type = QueryType.EQ)
private BigDecimal orderPrice;
@ApiModelProperty(value = "优惠券ID")
@QueryField(type = QueryType.EQ)
private Integer couponId;
@ApiModelProperty(value = "优惠券抵扣金额")
@QueryField(type = QueryType.EQ)
private BigDecimal couponMoney;
@ApiModelProperty(value = "积分抵扣金额")
@QueryField(type = QueryType.EQ)
private BigDecimal pointsMoney;
@ApiModelProperty(value = "积分抵扣数量")
@QueryField(type = QueryType.EQ)
private Integer pointsNum;
@ApiModelProperty(value = "实际付款金额(包含运费)")
@QueryField(type = QueryType.EQ)
private BigDecimal payPrice;
@ApiModelProperty(value = "第三方支付实收金额")
@QueryField(type = QueryType.EQ)
private BigDecimal receiptAmount;
@ApiModelProperty(value = "后台修改的订单金额(差价)")
@QueryField(type = QueryType.EQ)
private BigDecimal updatePrice;
@ApiModelProperty(value = "买家留言")
private String buyerRemark;
@ApiModelProperty(value = "支付方式(废弃)")
@QueryField(type = QueryType.EQ)
private Integer payType;
@ApiModelProperty(value = "支付方式余额10/微信20/支付宝30/通联支付40/其他支付50")
private String payMethod;
@ApiModelProperty(value = "付款状态(10未付款 20已付款)")
@QueryField(type = QueryType.EQ)
private Integer payStatus;
@ApiModelProperty(value = "付款时间")
private String payTime;
@ApiModelProperty(value = "第三方交易记录ID")
private String tradeId;
@ApiModelProperty(value = "分期状态")
@QueryField(type = QueryType.EQ)
private Boolean periodsStatus;
@ApiModelProperty(value = "分期期数")
@QueryField(type = QueryType.EQ)
private Integer periods;
@ApiModelProperty(value = "当前分期期数")
@QueryField(type = QueryType.EQ)
private Integer currPeriods;
@ApiModelProperty(value = "商家备注")
private String merchantRemark;
@ApiModelProperty(value = "订单是否已结算(0未结算 1已结算)")
@QueryField(type = QueryType.EQ)
private Integer isSettled;
@ApiModelProperty(value = "最后结算时间")
private String settledTime;
@ApiModelProperty(value = "续租订单的关联单号")
@QueryField(type = QueryType.EQ)
private Integer rentOrderId;
@ApiModelProperty(value = "电池租金")
@QueryField(type = QueryType.EQ)
private BigDecimal batteryRent;
@ApiModelProperty(value = "电池押金")
@QueryField(type = QueryType.EQ)
private BigDecimal batteryDeposit;
@ApiModelProperty(value = "保险")
@QueryField(type = QueryType.EQ)
private BigDecimal batteryInsurance;
@ApiModelProperty(value = "购买月份数量")
@QueryField(type = QueryType.EQ)
private Integer month;
@ApiModelProperty(value = "服务开始时间")
private String startTime;
@ApiModelProperty(value = "服务到期时间")
private String expirationTime;
@ApiModelProperty(value = "用户ID")
@QueryField(type = QueryType.EQ)
private Integer userId;
@ApiModelProperty(value = "所属门店ID")
@QueryField(type = QueryType.EQ)
private Integer shopId;
@ApiModelProperty(value = "商品ID")
@QueryField(type = QueryType.EQ)
private Integer goodsId;
@ApiModelProperty(value = "冻结资金请求流水号")
private String outRequestNo;
@ApiModelProperty(value = "电池商品ID")
@QueryField(type = QueryType.EQ)
private Integer equipmentId;
@ApiModelProperty(value = "排序(数字越小越靠前)")
@QueryField(type = QueryType.EQ)
private Integer sortNumber;
@ApiModelProperty(value = "备注")
private String comments;
@ApiModelProperty(value = "状态, 0正常, 1冻结")
@QueryField(type = QueryType.EQ)
private Integer status;
@ApiModelProperty(value = "是否删除, 0否, 1是")
@QueryField(type = QueryType.EQ)
private Integer deleted;
@ApiModelProperty(value = "商户编码")
private String merchantCode;
@ApiModelProperty(value = "推荐人手机号")
private String dealerPhone;
@ApiModelProperty(value = "逾期天数")
@QueryField(type = QueryType.EQ)
private Integer expirationDay;
}

View File

@@ -0,0 +1,82 @@
package com.gxwebsoft.shop.service;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.apps.entity.EquipmentGoods;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.FreezeOrder;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.param.FreezeOrderParam;
import java.util.List;
/**
* Service
*
* @author 科技小王子
* @since 2023-10-08 10:15:22
*/
public interface FreezeOrderService extends IService<FreezeOrder> {
/**
* 分页关联查询
*
* @param param 查询参数
* @return PageResult<FreezeOrder>
*/
PageResult<FreezeOrder> pageRel(FreezeOrderParam param);
/**
* 关联查询全部
*
* @param param 查询参数
* @return List<FreezeOrder>
*/
List<FreezeOrder> listRel(FreezeOrderParam param);
/**
* 根据id查询
*
* @param id
* @return FreezeOrder
*/
FreezeOrder getByIdRel(Integer id);
/**
* 解冻
* @param orderId
* @throws AlipayApiException
*/
void unfreeze(Integer orderId) throws AlipayApiException;
/**
* 冻结
* @param order
* @param goods
* @return
* @throws AlipayApiException
*/
String freeze(Order order, EquipmentGoods goods) throws AlipayApiException;
/**
* 履约
* @param order
* @return
*/
boolean keep(Order order) throws AlipayApiException;
/**
* 违约
* @param order
* @return
*/
boolean violated(Order order) throws AlipayApiException;
boolean closed(String outOrderNo) throws AlipayApiException;
AlipayFundAuthOperationDetailQueryResponse query(Order order) throws AlipayApiException;
boolean deduction(Integer orderId) throws AlipayApiException;
}

View File

@@ -0,0 +1,42 @@
package com.gxwebsoft.shop.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.OrderPay;
import com.gxwebsoft.shop.param.OrderPayParam;
import java.util.List;
/**
* 订单记录表Service
*
* @author 科技小王子
* @since 2023-10-13 16:58:03
*/
public interface OrderPayService extends IService<OrderPay> {
/**
* 分页关联查询
*
* @param param 查询参数
* @return PageResult<OrderPay>
*/
PageResult<OrderPay> pageRel(OrderPayParam param);
/**
* 关联查询全部
*
* @param param 查询参数
* @return List<OrderPay>
*/
List<OrderPay> listRel(OrderPayParam param);
/**
* 根据id查询
*
* @param id 订单ID
* @return OrderPay
*/
OrderPay getByIdRel(Integer id);
}

View File

@@ -0,0 +1,307 @@
package com.gxwebsoft.shop.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.apps.entity.EquipmentGoods;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.mapper.FreezeOrderMapper;
import com.gxwebsoft.shop.service.FreezeOrderService;
import com.gxwebsoft.shop.entity.FreezeOrder;
import com.gxwebsoft.shop.param.FreezeOrderParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.service.OrderPayService;
import com.gxwebsoft.shop.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
/**
* Service实现
*
* @author 科技小王子
* @since 2023-10-08 10:15:22
*/
@Service
public class FreezeOrderServiceImpl extends ServiceImpl<FreezeOrderMapper, FreezeOrder> implements FreezeOrderService {
@Resource
private OrderService orderService;
@Resource
private OrderPayService orderPayService;
@Resource
private AlipayConfigUtil alipayConfig;
@Resource
private EquipmentGoodsService equipmentGoodsService;
@Override
public PageResult<FreezeOrder> pageRel(FreezeOrderParam param) {
PageParam<FreezeOrder, FreezeOrderParam> page = new PageParam<>(param);
//page.setDefaultOrder("create_time desc");
List<FreezeOrder> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<FreezeOrder> listRel(FreezeOrderParam param) {
List<FreezeOrder> list = baseMapper.selectListRel(param);
// 排序
PageParam<FreezeOrder, FreezeOrderParam> page = new PageParam<>();
//page.setDefaultOrder("create_time desc");
return page.sortRecords(list);
}
@Override
public FreezeOrder getByIdRel(Integer id) {
FreezeOrderParam param = new FreezeOrderParam();
param.setId(id);
return param.getOne(baseMapper.selectListRel(param));
}
@Override
public void unfreeze(Integer orderId) throws AlipayApiException {
Order order = orderService.getById(orderId);
if (!StringUtils.hasText(order.getFreezeOrderNo()) || order.getOrderSource() == 10) {
return;
}
FreezeOrder freezeOrder = this.lambdaQuery().eq(FreezeOrder::getOutOrderNo, order.getFreezeOrderNo())
.eq(FreezeOrder::getStatus, "SUCCESS").orderByDesc(FreezeOrder::getCreateTime).last("limit 1").one();
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
request.setNotifyUrl("https://yxw.wsdns.cn/api/shop/freeze-order/notify");
// request.setNotifyUrl("http://1.14.132.108:10090/api/shop/freeze-order/notify");
JSONObject bizContent = new JSONObject();
bizContent.put("auth_no", freezeOrder.getAuthNo());
bizContent.put("out_request_no", IdUtil.getSnowflakeNextId());
bizContent.put("amount", freezeOrder.getAmount());
// bizContent.put("amount", .99);
bizContent.put("remark", "解冻押金");
JSONObject extraParam = new JSONObject();
JSONObject unfreezeBizInfo = new JSONObject();
unfreezeBizInfo.put("bizComplete", true);
extraParam.put("unfreezeBizInfo", unfreezeBizInfo);
bizContent.put("extra_param", extraParam);
request.setBizContent(bizContent.toString());
AlipayFundAuthOrderUnfreezeResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
System.out.println(response.getBody());
} else {
System.out.println("调用失败");
}
}
@Override
public String freeze(Order order, EquipmentGoods goods) throws AlipayApiException {
if (order.getOrderSource() == 10) {
return null;
}
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
double amount = goods.getBatteryDeposit().compareTo(BigDecimal.ZERO) <= 0 ? 0.02 : goods.getBatteryDeposit().doubleValue();
// 设置异步通知
request.setNotifyUrl("https://yxw.wsdns.cn/api/shop/freeze-order/notify");
// request.setNotifyUrl("http://1.14.132.108:10090/api/shop/freeze-order/notify");
JSONObject bizContent = new JSONObject();
String out_order_no = order.getFreezeOrderNo();
String out_request_no = order.getOutRequestNo();
bizContent.put("out_order_no", out_order_no);
bizContent.put("out_request_no", out_request_no);
bizContent.put("order_title", "安博驰电池押金");
// bizContent.put("amount", 0.01);
bizContent.put("amount", amount);
bizContent.put("product_code", "PRE_AUTH_ONLINE");
// bizContent.put("payee_logon_id", "zhu115289@163.com");
// bizContent.put("payee_user_id", "2088202959044205");
bizContent.put("timeout_express", "30m");
//设置免押模式POSTPAY、POSTPAY_UNCERTAIN、DEPOSIT_ONLY
bizContent.put("deposit_product_mode", "DEPOSIT_ONLY ");
// bizContent.put("enable_pay_channels","CREDITZHIMA");
//// 设置扩展参数
JSONObject extraParam = new JSONObject();
extraParam.put("category", "RENT_SHARABLE_BIKE_CHARGERS");
extraParam.put("serviceId", "2023022700000000000090884200");
bizContent.put("extra_param", extraParam);
request.setBizContent(bizContent.toString());
AlipayFundAuthOrderAppFreezeResponse response = alipayClient.sdkExecute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
FreezeOrder freezeOrder = new FreezeOrder();
freezeOrder.setOutOrderNo(out_order_no);
freezeOrder.setOutRequestNo(out_request_no);
freezeOrder.setAmount(BigDecimal.valueOf(amount));
freezeOrder.setStatus("INIT");
freezeOrder.setTenantId(6);
this.save(freezeOrder);
return response.getBody();
} else {
System.out.println("调用失败");
return null;
}
}
@Override
public boolean keep(Order order) throws AlipayApiException {
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayTradeOrderinfoSyncRequest request = new AlipayTradeOrderinfoSyncRequest();
JSONObject order_biz_info = new JSONObject();
order_biz_info.put("status", "COMPLETE");
JSONObject bizContent = new JSONObject();
bizContent.put("trade_no", order.getFreezeOrderNo());
bizContent.put("out_request_no", IdUtil.getSnowflakeNextId());
bizContent.put("biz_type", "CREDIT_AUTH");
bizContent.put("order_biz_info", order_biz_info);
AlipayTradeOrderinfoSyncResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
return response.isSuccess();
}
@Override
public boolean violated(Order order) throws AlipayApiException {
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayTradeOrderinfoSyncRequest request = new AlipayTradeOrderinfoSyncRequest();
JSONObject order_biz_info = new JSONObject();
order_biz_info.put("status", "VIOLATED");
JSONObject bizContent = new JSONObject();
bizContent.put("trade_no", order.getFreezeOrderNo());
bizContent.put("out_request_no", IdUtil.getSnowflakeNextId());
bizContent.put("biz_type", "CREDIT_AUTH");
bizContent.put("order_biz_info", order_biz_info);
AlipayTradeOrderinfoSyncResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
return response.isSuccess();
}
@Override
public boolean closed(String outOrderNo) throws AlipayApiException {
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", outOrderNo);
request.setBizContent(bizContent.toString());
AlipayTradeCloseResponse response = alipayClient.certificateExecute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
System.out.println(response.getTradeNo());
System.out.println(response.getOutTradeNo());
lambdaUpdate().set(FreezeOrder::getStatus,"CLOSE")
.eq(FreezeOrder::getStatus, "INIT")
.eq(FreezeOrder::getOutOrderNo,outOrderNo)
.update();
} else {
System.out.println("调用失败");
}
return response.isSuccess();
}
@Override
public AlipayFundAuthOperationDetailQueryResponse query(Order order) throws AlipayApiException {
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
JSONObject bizContent = new JSONObject();
// out_order_no与auth_no选择其一传入即可
bizContent.put("out_order_no", order.getFreezeOrderNo());
// bizContent.put("auth_no","2021081710002001640564315836");
// out_request_no与operation_id选择其一传入即可
bizContent.put("out_request_no", order.getOutRequestNo());
// bizContent.put("operation_id","20161012405744018102");
bizContent.put("operation_type", "FREEZE");
// 设置整体请求参数
request.setBizContent(bizContent.toString());
// 使用execute方法发起请求
AlipayFundAuthOperationDetailQueryResponse response = alipayClient.certificateExecute(request);
return response;
}
@Override
public boolean deduction(Integer orderId) throws AlipayApiException {
Order order = orderService.getById(orderId);
FreezeOrder freezeOrder = this.lambdaQuery().eq(FreezeOrder::getOutOrderNo, order.getFreezeOrderNo()).eq(FreezeOrder::getStatus, "SUCCESS").orderByDesc(FreezeOrder::getCreateTime).last("limit 1").one();
DefaultAlipayClient alipayClient = alipayConfig.alipayClient(6);
AlipayTradePayRequest request = new AlipayTradePayRequest();
//异步接收地址仅支持http/https公网可访问
request.setNotifyUrl("https://yxw.wsdns.cn/api/shop/freeze-order/notify");
// request.setNotifyUrl("http://1.14.132.108:10090/api/shop/freeze-order/notify");
/******必传参数******/
JSONObject bizContent = new JSONObject();
//商户订单号,商家自定义,保持唯一性
bizContent.put("out_trade_no", IdUtil.getSnowflakeNextIdStr());
//支付金额最小值0.01元
bizContent.put("total_amount", 0.01);
bizContent.put("disable_pay_channels", "moneyFund,debitCardExpress,creditCardExpress,creditCardCartoon,creditCard,pcredit");
//订单标题,不可使用特殊符号
bizContent.put("subject", "安博驰电池损耗费");
//产品码支付宝预授权场景传PRE_AUTH_ONLINE新当面资金授权场景传PRE_AUTH
bizContent.put("product_code", "PRE_AUTH_ONLINE");
//冻结接口返回的auth_no
bizContent.put("auth_no", freezeOrder.getAuthNo());
bizContent.put("auth_no", freezeOrder.getAuthNo());
System.out.println(bizContent.get("out_trade_no"));
//预授权确认模式COMPLETE转交易完成后解冻剩余冻结金额NOT_COMPLETE转交易完成后不解冻剩余冻结金额默认值为NOT_COMPLETE。
// bizContent.put("auth_confirm_mode", "COMPLETE");
request.setBizContent(bizContent.toString());
AlipayTradePayResponse response = alipayClient.certificateExecute(request);
if(response.isSuccess()){
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
return response.isSuccess();
}
}

View File

@@ -0,0 +1,47 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.mapper.OrderPayMapper;
import com.gxwebsoft.shop.service.OrderPayService;
import com.gxwebsoft.shop.entity.OrderPay;
import com.gxwebsoft.shop.param.OrderPayParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 订单记录表Service实现
*
* @author 科技小王子
* @since 2023-10-13 16:58:03
*/
@Service
public class OrderPayServiceImpl extends ServiceImpl<OrderPayMapper, OrderPay> implements OrderPayService {
@Override
public PageResult<OrderPay> pageRel(OrderPayParam param) {
PageParam<OrderPay, OrderPayParam> page = new PageParam<>(param);
//page.setDefaultOrder("create_time desc");
List<OrderPay> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<OrderPay> listRel(OrderPayParam param) {
List<OrderPay> list = baseMapper.selectListRel(param);
// 排序
PageParam<OrderPay, OrderPayParam> page = new PageParam<>();
//page.setDefaultOrder("create_time desc");
return page.sortRecords(list);
}
@Override
public OrderPay getByIdRel(Integer id) {
OrderPayParam param = new OrderPayParam();
param.setId(id);
return param.getOne(baseMapper.selectListRel(param));
}
}

View File

@@ -1,15 +1,22 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.mapper.OrderRefundMapper;
import com.gxwebsoft.shop.service.OrderRefundService;
import com.gxwebsoft.shop.entity.OrderRefund;
import com.gxwebsoft.shop.param.OrderRefundParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 售后单记录表Service实现
@@ -20,17 +27,42 @@ import java.util.List;
@Service
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements OrderRefundService {
@Resource
private OrderService orderService;
@Override
public PageResult<OrderRefund> pageRel(OrderRefundParam param) {
PageParam<OrderRefund, OrderRefundParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
List<OrderRefund> list = baseMapper.selectPageRel(page, param);
if(!CollectionUtils.isEmpty(list)) {
Set<Integer> orderIds = list.stream().map(OrderRefund::getOrderId).collect(Collectors.toSet());
Map<Integer, List<Order>> collect = orderService.lambdaQuery().in(Order::getOrderId, orderIds).select(Order::getOrderId,Order::getOrderNo).list().stream().collect(Collectors.groupingBy(Order::getOrderId));
list.forEach(f -> {
if(!CollectionUtils.isEmpty( collect.get(f.getOrderId()))){
Order order = collect.get(f.getOrderId()).get(0);
f.setOrderNo(order.getOrderNo());
}
});
}
return new PageResult<>(list, page.getTotal());
}
@Override
public List<OrderRefund> listRel(OrderRefundParam param) {
List<OrderRefund> list = baseMapper.selectListRel(param);
if(!CollectionUtils.isEmpty(list)) {
Set<Integer> orderIds = list.stream().map(OrderRefund::getOrderId).collect(Collectors.toSet());
Map<Integer, List<Order>> collect = orderService.lambdaQuery().in(Order::getOrderId, orderIds).select(Order::getOrderId,Order::getOrderNo).list().stream().collect(Collectors.groupingBy(Order::getOrderId));
list.forEach(f -> {
Order order = collect.get(f.getOrderId()).get(0);
f.setOrderNo(order.getOrderNo());
});
}
// 排序
PageParam<OrderRefund, OrderRefundParam> page = new PageParam<>();
page.setDefaultOrder("create_time desc");

View File

@@ -3,10 +3,13 @@ package com.gxwebsoft.shop.service.impl;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.apps.entity.EquipmentOrderGoods;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.apps.service.EquipmentOrderGoodsService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.web.PageParam;
@@ -15,6 +18,7 @@ import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.mapper.OrderMapper;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.FreezeOrderService;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import org.springframework.stereotype.Service;
@@ -44,12 +48,17 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
@Resource
private EquipmentGoodsService equipmentGoodsService;
@Resource
private EquipmentOrderGoodsService equipmentOrderGoodsService;
@Resource
private OrderService orderService;
@Resource
private OrderGoodsService orderGoodsService;
@Resource
private CacheClient cacheClient;
@Resource
private FreezeOrderService freezeOrderService;
@Override
public PageResult<Order> pageRel(OrderParam param) {
PageParam<Order, OrderParam> page = new PageParam<>(param);
@@ -209,25 +218,54 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
order.setReceiptAmount(new BigDecimal(receiptAmount));
order.setPayTime(DateUtil.date());
order.setExpirationTime(DateUtil.nextMonth());
orderService.updateById(order);
// 6. 续租订单
if (order.getRentOrderId() > 0) {
Integer count = orderService.lambdaQuery().eq(Order::getRentOrderId, order.getRentOrderId()).eq(Order::getPayStatus, PAY_STATUS_SUCCESS).count();
order.setCurrPeriods(count + 1);
// 主订单
Order parentOrder = orderService.getById(order.getRentOrderId());
parentOrder.setCurrPeriods(count + 1);
// 更新过期时间延长一个月
Date expirationTime = parentOrder.getExpirationTime();
DateTime nextMonthTime = DateUtil.offsetMonth(expirationTime, 1);
parentOrder.setExpirationTime(nextMonthTime);
orderService.updateById(parentOrder);
// 保存续费订单状态
order.setDeliveryStatus(DELIVERY_STATUS_YES);
order.setReceiptStatus(RECEIPT_STATUS_YES);
order.setOrderStatus(ORDER_STATUS_COMPLETED);
order.setStartTime(expirationTime);
order.setExpirationTime(nextMonthTime);
orderService.updateById(order);
try {
freezeOrderService.keep(order);
} catch (AlipayApiException e) {
throw new RuntimeException(e);
}
// 订单是否已完成
if((order.getOrderSource() == 20 || order.getOrderSource() == 30) && parentOrder.getCurrPeriods() >= parentOrder.getPeriods()) {
parentOrder.setOrderStatus(ORDER_STATUS_OVER);
parentOrder.setExpirationTime(DateUtil.parseTime("2099-12-31 23:59:59"));
try {
freezeOrderService.unfreeze(parentOrder.getOrderId());
} catch (AlipayApiException e) {
throw new RuntimeException(e);
}
}
orderService.updateById(parentOrder);
}
orderService.updateById(order);
}
/**

View File

@@ -1,15 +1,23 @@
package com.gxwebsoft.shop.service.impl;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.mapper.ProfitLogMapper;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.ProfitLogService;
import com.gxwebsoft.shop.entity.ProfitLog;
import com.gxwebsoft.shop.param.ProfitLogParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 门店收益明细表Service实现
@@ -20,11 +28,24 @@ import java.util.List;
@Service
public class ProfitLogServiceImpl extends ServiceImpl<ProfitLogMapper, ProfitLog> implements ProfitLogService {
@Resource
private OrderService orderService;
@Override
public PageResult<ProfitLog> pageRel(ProfitLogParam param) {
PageParam<ProfitLog, ProfitLogParam> page = new PageParam<>(param);
//page.setDefaultOrder("create_time desc");
List<ProfitLog> list = baseMapper.selectPageRel(page, param);
if(!CollectionUtils.isEmpty(list)) {
Set<Integer> orderIds = list.stream().map(ProfitLog::getOrderId).collect(Collectors.toSet());
List<Order> orderList = orderService.lambdaQuery().in(Order::getOrderId, orderIds).list();
Map<Integer, List<Order>> collect = orderList.stream().collect(Collectors.groupingBy(Order::getOrderId));
list.forEach(item -> {
item.setOrder(CollectionUtils.firstElement(collect.get(item.getOrderId())));
});
}
return new PageResult<>(list, page.getTotal());
}