feat[文件上传和订单模块功能]:已测试通过

This commit is contained in:
2025-01-13 10:54:30 +08:00
parent 40cd308749
commit d5410d0ed6
53 changed files with 2309 additions and 131 deletions
@@ -0,0 +1,22 @@
package com.central.order;
import com.central.common.lb.annotation.EnableFeignInterceptor;
import com.central.search.annotation.EnableSearchClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author 作者 lsl E-mail: 1272745473@qq.com
*/
@EnableDiscoveryClient
@EnableSearchClient
@EnableTransactionManagement
@EnableFeignInterceptor
@SpringBootApplication
public class OrderCenterApp {
public static void main(String[] args) {
SpringApplication.run(OrderCenterApp.class, args);
}
}
@@ -0,0 +1,91 @@
package com.central.order.controller;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.LoginAppUser;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.model.Order;
import com.central.order.service.IOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* Order information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Slf4j
@RestController
@Tag(name = "Order information")
@RequiredArgsConstructor
public class OrderController {
@Autowired
private IOrderService orderService;
/**
* 列表
*/
@Operation(summary = "查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
return orderService.findList(params);
}
// 创建订单--》
// 返回前端订单信息--》
// 前端发起支付(api-order/unifiedOrder)--》
// 等待回调更新订单状态(微信支付回调接口/api-order/pay/notify)--》
// 前端支付成功后创建支付记录(/api-order/payment)
// 进入排队队列中(/api-order/queue)已支付订单列表
// 设备执行完成后更新订单状态已完成(根据设备上报状态触发或者设备直接调用接口进行更新任务状态)
@PostMapping
public Result<Order> createOrder(@RequestBody Order order) {
LoginAppUser user = LoginUserContextHolder.getUser();
order.setUserId(user.getId());
boolean result = orderService.createOrder(order);
if (result) {
return Result.succeed(order,"订单创建成功");
} else {
return Result.failed("订单创建失败");
}
}
// 支付订单
// @PutMapping("/{orderId}/pay")
// public Result<String> payOrder(@PathVariable Long orderId) {
// orderService.payOrder(orderId);
// return Result.succeed("支付订单操作已接收,正在处理");
// }
// 获取排队中的订单列表
@GetMapping("/queue")
public Result<List<Order>> getOrdersInQueue() {
List<Order> orders = orderService.getOrdersInQueue();
return Result.succeed(orders,"获取成功");
}
// 处理排队中的订单(模拟消费通知等操作)
@PutMapping("/queue/process")
public Result<String> processOrdersInQueue() {
orderService.processOrdersInQueue();
return Result.succeed("排队订单处理已启动");
}
}
@@ -0,0 +1,57 @@
package com.central.order.controller;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.service.IPaymentRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* Payment information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Slf4j
@RestController
@Tag(name = "Payment information")
@RequestMapping("/payment")
@RequiredArgsConstructor
public class PaymentRecordController {
@Autowired
private IPaymentRecordService paymentRecordService;
/**
* 列表
*/
@Operation(summary = "查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
return paymentRecordService.findList(params);
}
// 接收前端传来的订单编号和支付金额,处理订单支付
@PostMapping
public Result<String> processPayment(@RequestParam String orderNumber, @RequestParam Double paymentAmount) {
boolean result = paymentRecordService.processPayment(orderNumber, paymentAmount);
if (result) {
return Result.succeed("订单支付成功");
} else {
return Result.failed("订单支付失败");
}
}
}
@@ -0,0 +1,77 @@
package com.central.order.controller;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* pay information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Slf4j
@RestController
@Tag(name = "Pay information")
@RequiredArgsConstructor
public class WeixinPayController {
// 此处简单示例,实际可从配置中心等获取配置构建WxPayService
private static final WxPayService wxPayService = new WxPayServiceImpl();
static {
WxPayConfig payConfig = new WxPayConfig();
payConfig.setMchId("YOUR_MCH_ID");
payConfig.setMchKey("YOUR_MCH_KEY");
payConfig.setAppId("YOUR_APP_ID");
payConfig.setNotifyUrl("http://your_domain/weixin/pay/notify");
// 设置证书等其他配置信息(如果需要)
((WxPayServiceImpl) wxPayService).setConfig(payConfig);
}
// 接收前端传来的订单信息,调用微信支付统一下单接口
@PostMapping("/unifiedOrder")
public Map<String, Object> unifiedOrder(@RequestBody Map<String, Object> orderInfo) {
try {
String orderNumber = (String) orderInfo.get("orderNumber");
BigDecimal amount = new BigDecimal((String) orderInfo.get("amount"));
WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
request.setBody("商品描述"); // 可根据实际订单详情填写更准确的描述
request.setOutTradeNo(orderNumber);
request.setTotalFee(amount.multiply(new BigDecimal(100)).intValue()); // 微信支付金额单位为分
// request.setSpbillCreateDate(System.currentTimeMillis() / 1000 + "");
request.setNotifyUrl("http://your_domain/weixin/pay/notify");
request.setTradeType("JSAPI"); // 这里以公众号支付为例,根据实际情况选择支付类型,如APP支付、小程序支付等
WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(request);
if ("SUCCESS".equals(result.getReturnCode()) && "SUCCESS".equals(result.getResultCode())) {
Map<String, Object> response = new HashMap<>();
response.put("prepayId", result.getPrepayId());
// 此处还需按照微信支付要求对返回信息进行进一步处理,生成前端调起支付所需的完整参数,如签名等,此处简化示例
return response;
} else {
// 处理统一下单失败情况,返回相应错误信息给前端
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("errorMsg", "统一下单失败");
return errorResponse;
}
} catch (Exception e) {
e.printStackTrace();
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("errorMsg", "支付请求处理异常");
return errorResponse;
}
}
}
@@ -0,0 +1,66 @@
package com.central.order.controller;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* pay notify information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Slf4j
@RestController
@Tag(name = "Pay notify information")
@RequiredArgsConstructor
public class WeixinPayNotifyController {
private static final WxPayService wxPayService = new WxPayServiceImpl();
static {
WxPayConfig payConfig = new WxPayConfig();
payConfig.setMchId("YOUR_MCH_ID");
payConfig.setMchKey("YOUR_MCH_KEY");
payConfig.setAppId("YOUR_APP_ID");
payConfig.setNotifyUrl("http://your_domain/weixin/pay/notify");
// 设置证书等其他配置信息(如果需要)
((WxPayServiceImpl) wxPayService).setConfig(payConfig);
}
// 接收微信支付异步通知,验证并处理支付结果
@PostMapping("/pay/notify")
public String handleNotify(HttpServletRequest request) {
try {
// Map<String, String> notifyParams = WxPayUtil.xmlToMap(request.getInputStream());
// WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(notifyParams);
WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult("notifyParams");
if ("SUCCESS".equals(result.getResultCode())) {
// 验证通知信息的合法性,如签名等,这里微信支付工具包已做了部分验证,可根据实际情况进一步确认
String orderNumber = result.getOutTradeNo();
// 根据业务逻辑处理订单,比如更新订单状态为已支付、记录支付信息等
handleOrderAfterPayment(orderNumber);
return WxPayNotifyResponse.success("OK");
} else {
return WxPayNotifyResponse.fail("支付失败");
}
} catch (Exception e) {
e.printStackTrace();
return WxPayNotifyResponse.fail("通知处理异常");
}
}
// 处理支付完成后的订单逻辑(这里简单示例,实际需根据业务详细拓展)
private void handleOrderAfterPayment(String orderNumber) {
// 此处可调用业务逻辑层方法,比如更新订单状态、记录支付记录等操作
System.out.println("订单 " + orderNumber + " 支付成功,正在处理订单后续逻辑");
}
}
@@ -0,0 +1,50 @@
package com.central.order.controller;
import com.github.binarywang.wx.miniprogram.api.WxMaService;
import com.github.binarywang.wx.miniprogram.api.impl.WxMaServiceImpl;
import com.github.binarywang.wx.miniprogram.bean.template.WxMaSubscribeMessage;
import com.github.binarywang.wx.miniprogram.bean.template.WxMaSubscribeTemplateData;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/wx/subscribe")
public class WxSubscribeMessageController {
private final WxMaService wxMaService = new WxMaServiceImpl();
static {
wxMaService.setWxMaConfig(new WxMaInMemoryConfig());
wxMaService.getWxMaConfig().setAppId("YOUR_APPID");
wxMaService.getWxMaConfig().setAppSecret("YOUR_APPSECRET");
}
// 接收前端传来的订阅消息发送请求参数,发送订阅消息
@PostMapping("/send")
public boolean sendSubscribeMessage(@RequestBody Map<String, Object> requestData) {
try {
String openId = (String) requestData.get("openId");
String templateId = (String) requestData.get("templateId");
WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
subscribeMessage.setTemplateId(templateId);
subscribeMessage.setToUser(openId);
List<WxMaSubscribeTemplateData> data = new ArrayList<>();
// 根据订阅消息模板的关键词设置对应的数据,示例如下(假设模板有两个关键词:keyword1和keyword2)
data.add(new WxMaSubscribeTemplateData("keyword1", "具体内容1", "#FF0000"));
data.add(new WxMaSubscribeTemplateData("keyword2", "具体内容2", "#00FF00"));
subscribeMessage.setData(data);
return wxMaService.getSubscribeMsgService().sendSubscribeMsg(subscribeMessage);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
@@ -0,0 +1,48 @@
package com.central.order.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/wx/template")
public class WxTemplateMessageController {
private final WxMaS wxMaService = new WxMaServiceImpl();
static {
wxMaService.setWxMaConfig(new WxMaInMemoryConfig());
wxMaService.getWxMaConfig().setAppId("YOUR_APPID");
wxMaService.getWxMaConfig().setAppSecret("YOUR_APPSECRET");
}
// 接收前端传来的模板消息发送请求参数,发送模板消息
@PostMapping("/send")
public boolean sendTemplateMessage(@RequestBody Map<String, Object> requestData) {
try {
String formId = (String) requestData.get("formId");
String templateId = (String) requestData.get("templateId");
String openId = (String) requestData.get("openId");
WxMaTemplateMessage templateMessage = new WxMaTemplateMessage();
templateMessage.setTemplateId(templateId);
templateMessage.setToUser(openId);
templateMessage.setFormId(formId);
List<WxMaTemplateData> data = new ArrayList<>();
// 根据模板的关键词设置对应的数据,示例如下(假设模板有两个关键词:keyword1和keyword2)
data.add(new WxMaTemplateData("keyword1", "具体内容1", "#FF0000"));
data.add(new WxMaTemplateData("keyword2", "具体内容2", "#00FF00"));
templateMessage.setData(data);
return wxMaService.getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
@@ -0,0 +1,22 @@
package com.central.order.enums;
import com.central.common.enums.ZltEnum;
import lombok.Getter;
/**
* 订单状态枚举类型
*
* @author jarvis create by 2023/1/10
*/
@Getter
public enum OrderStatus implements ZltEnum {
UNPAID(0,"待支付"), PAID(1, "已支付排队中"), CANCELED(2, "已取消"),COMPLETE(3,"服务完成");
OrderStatus(Integer id, String content) {
this.id = id;
this.content = content;
}
private Integer id;
private String content;
}
@@ -0,0 +1,47 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.db.mapper.SuperMapper;
import com.central.order.model.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Order information
*
* @author lsl
* @date 2024-12-19 17:52:54
*/
@Mapper
public interface OrderMapper extends SuperMapper<Order> {
/**
* 分页查询用户列表
* @param page
* @param params
* @return
*/
List<Order> findList(Page<Order> page, @Param("p") Map<String, Object> params);
// 根据订单状态查询订单列表
List<Order> getOrdersByStatus(@Param("status") Integer status);
// 新增订单
int insertOrder(Order order);
// 根据订单编号查询订单信息
Order getOrderById(@Param("orderId") Long orderId);
// 更新订单状态
int updateOrderStatus(@Param("orderId") Long orderId, @Param("newStatus") Integer newStatus);
// 查询所有处于排队状态的订单,用于后续按顺序处理(可根据业务需求添加排序等逻辑)
List<Order> getOrdersInQueue();
// 根据店铺编号和创建时间(当天)查询订单数量
List<Order> findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual(@Param("tourismId") Long tourismId, @Param("startDate") Date startDate, @Param("endDate") Date endDate);
// 根据订单编号查询订单信息
Order getOrderByNumber(@Param("orderNumber") String orderNumber);
}
@@ -0,0 +1,33 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.db.mapper.SuperMapper;
import com.central.order.model.PaymentRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* Order information
*
* @author lsl
* @date 2024-12-19 17:52:54
*/
@Mapper
public interface PaymentRecordMapper extends SuperMapper<PaymentRecord> {
/**
* 分页查询用户列表
* @param page
* @param params
* @return
*/
List<PaymentRecord> findList(Page<PaymentRecord> page, @Param("p") Map<String, Object> params);
// 插入支付记录
int insertPaymentRecord(PaymentRecord paymentRecord);
// 根据支付流水号查询支付记录(用于幂等性判断)
PaymentRecord getPaymentRecordByNumber(@Param("paymentNumber") String paymentNumber);
}
@@ -0,0 +1,45 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* Device information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@TableName("orders")
public class Order extends SuperEntity {
private static final long serialVersionUID=1L;
private String orderNo;
private String deviceSn;
private Long userId;
private Long tourismId;
private String workspaceId;
private String orderAmount;
private Integer orderStatus;
private Date payTime;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Long createId;
private String company;
private Integer isDel;
}
@@ -0,0 +1,43 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* PaymentRecord information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@TableName("payment_records")
public class PaymentRecord {
private static final long serialVersionUID = 1L;
@TableId
private Long id;
private Long orderId;
private String orderNo;
private String paymentNumber;
private Double paymentAmount;
private Date paymentTime;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Long createId;
private String company;
private Integer isDel;
}
@@ -0,0 +1,45 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* Device information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@TableName("tourism")
public class Tourism extends SuperEntity {
private static final long serialVersionUID=1L;
private String tourismName;
private String tourismDesc;
private Integer type;
private Integer status;
private String tourismNo;
private String tourismAddress;
private String tourismPhone;
private String tourismEmail;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Long createId;
private String company;
private Integer isDel;
}
@@ -0,0 +1,29 @@
package com.central.order.scheduler;
import com.central.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Configuration
@EnableScheduling
public class OrderTimeoutScheduler {
@Autowired
private IOrderService orderService;
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
@Scheduled(fixedRate = 60 * 1000)
public void checkOrderTimeout() {
orderService.checkAndHandleOrderTimeout();
}
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
@Scheduled(fixedRate = 60 * 1000)
public void processOrdersInQueue() {
orderService.processOrdersInQueue();
}
}
@@ -0,0 +1,61 @@
package com.central.order.service;
import com.central.common.model.PageResult;
import com.central.common.service.ISuperService;
import com.central.order.model.Order;
import java.util.List;
import java.util.Map;
/**
* Firmware file information
*
* @author lsl
* @date 2024-12-19 17:52:54
*/
public interface IOrderService extends ISuperService<Order> {
/**
* 列表
* @param params
* @return
*/
PageResult<Order> findList(Map<String, Object> params);
/**
* 创建订单
*
* @param order
* @return
*/
boolean createOrder(Order order) ;
/**
* 支付
* @param orderId
*/
void payOrder(Long orderId) ;
/**
* 超时订单自动检查
*/
void checkAndHandleOrderTimeout() ;
/**
* 排队订单
* @return
*/
List<Order> getOrdersInQueue();
/**
* 排队逻辑处理
*/
void processOrdersInQueue();
/**
* 订单编号查询订单
* @param orderNumber
* @return
*/
Order getOrderByNumber(String orderNumber);
}
@@ -0,0 +1,31 @@
package com.central.order.service;
import com.central.common.model.PageResult;
import com.central.common.service.ISuperService;
import com.central.order.model.PaymentRecord;
import java.util.Map;
/**
* PaymentRecord information
*
* @author lsl
* @date 2024-12-19 17:52:54
*/
public interface IPaymentRecordService extends ISuperService<PaymentRecord> {
/**
* 列表
* @param params
* @return
*/
PageResult<PaymentRecord> findList(Map<String, Object> params);
/**
* 支付记录
* @param orderNumber
* @param paymentAmount
* @return
*/
boolean processPayment(String orderNumber, Double paymentAmount);
}
@@ -0,0 +1,180 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.enums.OrderStatus;
import com.central.order.mapper.OrderMapper;
import com.central.order.model.Order;
import com.central.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Order information
*
* @author lsl
* @date 2024-12-19 17:52:54
*/
@Slf4j
@Service
public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> implements IOrderService {
private final static String ORDER_LOCK = "order_lock_";
// 定义分布式锁的键,确保唯一性,这里以固定字符串加上当前时间戳来构造
private final static String ORDER_TIMEOUT_LOCK_ = "order_timeout_lock_" + System.currentTimeMillis();
@Autowired
private DistributedLock lock;
private final ExecutorService executorService = Executors.newFixedThreadPool(10); // 线程池,可根据实际并发量调整大小
/**
* 列表
* @param params
* @return
*/
@Override
public PageResult<Order> findList(Map<String, Object> params){
Page<Order> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List<Order> list = baseMapper.findList(page, params);
return PageResult.<Order>builder().data(list).code(0).count(page.getTotal()).build();
}
// 创建订单,初始状态为“待支付”
@Override
public boolean createOrder(Order order) {
order.setOrderStatus(OrderStatus.UNPAID.getId());
String orderNo = generateOrderNumber(2L);
order.setOrderNo(orderNo);
try {
return super.saveIdempotency(order, lock
, ORDER_LOCK+orderNo, new QueryWrapper<Order>().eq("order_no", orderNo), "订单已存在");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 支付订单,更新订单状态为“已支付(排队中)”,同时处理支付超时逻辑
@Override
public void payOrder(Long orderId) {
Order order = baseMapper.getOrderById(orderId);
if (order!= null && OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) {
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayTime(new Date());
baseMapper.updateOrderStatus(orderId, OrderStatus.PAID.getId());
// 异步启动支付超时检查任务
checkPayTimeoutAsync(orderId);
}
}
// 异步检查支付超时任务
@Async
public void checkPayTimeoutAsync(Long orderId) {
// Thread.sleep(5 * 60 * 1000); // 等待5分钟(模拟支付超时时间)
Order order = baseMapper.getOrderById(orderId);
if (order!= null && OrderStatus.PAID.getId().equals(order.getOrderStatus())) {
baseMapper.updateOrderStatus(orderId, OrderStatus.PAID.getId());
}
}
// 检查并处理订单超时逻辑,5分钟超时后自动取消
@Override
public void checkAndHandleOrderTimeout() {
List<Order> orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId());
long currentTime = new Date().getTime();
for (Order order : orders) {
long elapsedTime = currentTime - order.getCreateTime().getTime();
if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= 5) {
baseMapper.updateOrderStatus(order.getId(), OrderStatus.CANCELED.getId());
}
}
}
// 获取所有处于排队状态的订单,用于后续按顺序处理
@Override
public List<Order> getOrdersInQueue() {
return baseMapper.getOrdersInQueue();
}
// 处理排队中的订单,当排在前面的用户消费完成后通知下一位用户进行消费操作(此处简化逻辑,实际需结合业务深入实现)
@Override
public void processOrdersInQueue() {
List<Order> queueOrders = getOrdersInQueue();
for (Order order : queueOrders) {
executorService.submit(() -> {
//TODO
// 这里假设已经有逻辑判断前面的用户是否消费完成,此处简化处理
// 通知用户进行消费操作(实际可能是推送消息等方式,这里仅打印示例)
System.out.println("通知用户 " + order.getUserId() + " 进行消费操作,订单编号:" + order.getId());
// 可以在这里更新订单状态为“已消费”等后续操作,根据实际业务完善
});
}
}
@Override
public Order getOrderByNumber(String orderNumber) {
return baseMapper.getOrderByNumber(orderNumber);
}
// 生成订单编号
public String generateOrderNumber(Long tourismId) {
// 获取当前日期,格式化为 yyyyMMdd
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String currentDate = sdf.format(new Date());
// 获取当天的起始时间和结束时间,用于查询当天订单数量
Date startDate = getStartOfDay(new Date());
Date endDate = getEndOfDay(new Date());
// 查询当天已有的订单数量
List<Order> existingOrders = baseMapper.findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual(tourismId, startDate, endDate);
int orderCount = existingOrders.size();
// 生成当天订单序号,从1开始自增
int orderSequence = orderCount + 1;
// 格式化订单序号,确保序号长度固定(例如不足3位前面补0)
String formattedSequence = String.format("%03d", orderSequence);
// 拼接店铺编号、日期、订单序号形成订单编号
return tourismId + currentDate + formattedSequence;
}
// 获取当天的起始时间(0点0分0秒)
private Date getStartOfDay(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(sdf.format(date));
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
// 获取当天的结束时间(23点59分59秒)
private Date getEndOfDay(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(sdf.format(date));
date.setTime(date.getTime() + 24 * 60 * 60 * 1000 - 1);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
@@ -0,0 +1,100 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.enums.OrderStatus;
import com.central.order.mapper.PaymentRecordMapper;
import com.central.order.model.Order;
import com.central.order.model.PaymentRecord;
import com.central.order.service.IOrderService;
import com.central.order.service.IPaymentRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Order information
*
* @author lsl
* @date 2024-12-19 17:52:54
*/
@Slf4j
@Service
public class PaymentRecordServiceImpl extends SuperServiceImpl<PaymentRecordMapper, PaymentRecord> implements IPaymentRecordService {
// 定义分布式锁的键,确保唯一性,这里以固定字符串加上当前时间戳来构造
private final static String PAYMENT_RECORD_LOCK = "payment_records_lock_";
private final static String ORDER_LOCK = "order_lock_";
@Autowired
private DistributedLock lock;
private final ExecutorService executorService = Executors.newFixedThreadPool(10); // 线程池,可根据实际并发量调整大小
@Autowired
private IOrderService orderService;
/**
* 列表
*
* @param params
* @return
*/
@Override
public PageResult<PaymentRecord> findList(Map<String, Object> params) {
Page<PaymentRecord> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List<PaymentRecord> list = baseMapper.findList(page, params);
return PageResult.<PaymentRecord>builder().data(list).code(0).count(page.getTotal()).build();
}
// 处理订单支付逻辑,处理并发冲突和重复支付等问题
@Transactional
public boolean processPayment(String orderNumber, Double paymentAmount) {
// 生成唯一支付流水号,用于幂等性判断
String paymentNumber = UUID.randomUUID().toString();
// 幂等性判断,查询是否已存在相同支付流水号的支付记录
PaymentRecord existingRecord = baseMapper.getPaymentRecordByNumber(paymentNumber);
if (existingRecord != null) {
return true; // 已存在记录,说明支付已处理过,直接返回成功
}
// 根据订单编号查询订单信息
Order order = orderService.getOrderByNumber(orderNumber);
if (order == null || !OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) {
return false; // 订单不存在或状态不符合支付条件,返回失败
}
PaymentRecord paymentRecord = new PaymentRecord();
paymentRecord.setOrderNo(orderNumber);
paymentRecord.setPaymentAmount(paymentAmount);
paymentRecord.setOrderId(order.getId());
paymentRecord.setPaymentNumber(paymentNumber);
paymentRecord.setPaymentAmount(paymentAmount);
try {
order.setOrderStatus(OrderStatus.PAID.getId());
// 执行支付操作,更新订单状态为已支付,插入支付记录(在事务中保证原子性)
boolean res = orderService.saveOrUpdateIdempotency(order, lock
, ORDER_LOCK + orderNumber, new QueryWrapper<Order>().eq("order_no", orderNumber), "状态已更新");
if (res) {
return super.saveIdempotency(paymentRecord, lock
, PAYMENT_RECORD_LOCK + paymentNumber, new QueryWrapper<PaymentRecord>().eq("payment_no", paymentNumber), "订单已存在");
}
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,52 @@
package com.central.order.util;
import java.util.Map;
/**
* 获取map各类型值工具类
* @author lishilin
* @date 2020/03/12
*/
public class MapUtil {
public static String getStrValue(Map<String, Object> param, String id) {
Object val = getValue(param, id);
if (null == val) {
return null;
}
return val.toString();
}
public static Integer getIntValue(Map<String, Object> param, String id) {
Object val = getValue(param, id);
if (null == val) {
return null;
}
try {
return Integer.parseInt(param.get(id).toString());
} catch (NumberFormatException exp) {
return null;
}
}
public static Long getLongValue(Map<String, Object> param, String id) {
Object val = getValue(param, id);
if (null == val) {
return null;
}
try {
return Long.parseLong(param.get(id).toString());
} catch (NumberFormatException exp) {
return null;
}
}
public static Object getValue(Map<String, Object> param, String id) {
if (null == param && null == id) {
return null;
}
if (param.containsKey(id)) {
return param.get(id);
}
return null;
}
}
@@ -0,0 +1,119 @@
package com.central.order.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.order.util.http.HeaderUtils;
import com.central.order.util.http.HttpRequest;
import com.central.order.util.http.Response;
import com.central.order.util.http.SimpleHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* @author LSL
*/
@Slf4j
@Component
public class RequestUtils {
@Autowired
private HeaderUtils headerUtils;
/**
* 获取post请求result
* @param url 请求url
* @param jsonObject 请求参数
* @return
* @throws IOException
*/
public Map<String, String> getPostRequestResultMap(String url, JSONObject jsonObject) throws IOException {
System.out.println(url);
HttpRequest request = new SimpleHttpRequest(url);
request.headers(headerUtils.createHeadersOfJsonString(jsonObject.toJSONString()));
request.requestBody(jsonObject.toJSONString());
Response response = request.post();
Map<String, String> result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8");
return result;
}
/**
* 获取post请求result
* @param url 请求url
* @param param 请求参数
* @return
* @throws IOException
*/
public Map<String, String> getPostRequestResultMap(String url, Map param) throws IOException {
System.out.println(url);
HttpRequest request = new SimpleHttpRequest(url);
request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param)));
request.requestBody(JSON.toJSONString(param));
Response response = request.post();
Map<String, String> result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8");
return result;
}
/**
* 获取post请求result
* @param url 请求url
* @param body 请求参数
* @return
* @throws IOException
*/
public Map<String, String> getPostRequestResultMap(String url, String body) throws IOException {
System.out.println(url);
HttpRequest request = new SimpleHttpRequest(url);
request.headers(headerUtils.createHeadersOfJsonString(body));
request.requestBody(body);
Response response = request.post();
Map<String, String> result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8");
System.out.println(result);
return result;
}
/**
* @param url 请求url
* @param map 请求参数map
* @return
* @throws IOException
*/
public Map<String, String> getGetRequestResultMap(String url,Map map) throws IOException {
HttpRequest request = new SimpleHttpRequest(url);
request.headers(headerUtils.createHeadersOfParams(map));
Response response = request.get();
Map<String, String> result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8");
return result;
}
/**
* 获取post请求result
* @param url 请求url
* @param param 请求参数
* @return
* @throws IOException
*/
public Map<String, String> getThirdPartyPostRequestResultMap(String url, Map param) {
log.info("url:{} , {}",url,param);
HttpRequest request = new SimpleHttpRequest(url);
request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param)));
request.requestBody(JSON.toJSONString(param));
Response response;
Map<String, String> result = null;
try {
response = request.post();
result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8");
} catch (IOException e) {
log.info("查询异常:{}",e.getMessage());
e.printStackTrace();
}
// log.info("获取post请求result结果:{}" ,JSON.toJSONString(result));
return result;
}
}
@@ -0,0 +1,47 @@
package com.central.order.util;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
/**
* @author lishilin
* @see
* @since 2.0
*/
public class Utils {
public static Map<String,String> queryStringToMap(String queryString, String charset){
try {
Map<String,String> map = new HashMap<>();
String[] decode = URLDecoder.decode(queryString,charset).split("&");
for (String keyValue : decode) {
String[] kv = keyValue.split("[=]",2);
map.put(kv.length>1?kv[1]:"",kv[0]);
}
return map;
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
/**
* 读文件
*
* @param file 文件
* @return
* @throws IOException
* @throws IOException
*/
public static String readTxt(File file) throws IOException {
String s = "";
InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader br = new BufferedReader(in);
StringBuffer content = new StringBuffer();
while ((s = br.readLine()) != null) {
content = content.append(s);
}
return content.toString();
}
}
@@ -0,0 +1,80 @@
package com.central.order.util.http;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* @author lishilin
* @see
* @since 1.0
*/
@Component
public class HeaderUtils {
// @Value("${jetlinks.clientId}")
private String xClientId = "WFMfEGS8iHrEPRBH" ;
// @Value("${jetlinks.secureKey}")
private String secureKey = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ;
public Map<String, String> createHeadersOfParams(Map<String, Object> params) {
//时间戳
String xTimestamp = String.valueOf(System.currentTimeMillis());
//openApi客户端id
// String xClientId = "rN7cpmQb884W4hcH";
//密钥
// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi";
//将参数按ASCII排序后拼接为k1=v1&k2=v2的格式
String paramString = new TreeMap<>(params).entrySet()
.stream()
.map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue())))
.collect(Collectors.joining("&"));
System.out.println(paramString);
//param+X-Timestamp+SecureKey通过MD5加密
MessageDigest digest = DigestUtils.getMd5Digest();
System.out.println(paramString + xTimestamp + secureKey);
digest.update(paramString.getBytes());
digest.update(xTimestamp.getBytes());
digest.update(secureKey.getBytes());
Map<String, String> headers = new HashMap<>();
headers.put("X-Sign", Hex.encodeHexString(digest.digest()));
headers.put("X-Client-Id", xClientId);
headers.put("X-Timestamp", xTimestamp);
return headers;
}
public Map<String, String> createHeadersOfJsonString(String jsonString) {
//时间戳
String xTimestamp = String.valueOf(System.currentTimeMillis());
//openApi客户端id
// String xClientId = "rN7cpmQb884W4hcH";
//密钥
// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi";
//param+X-Timestamp+SecureKey通过MD5加密
MessageDigest digest = DigestUtils.getMd5Digest();
System.out.println(jsonString + xTimestamp + secureKey);
digest.update(jsonString.getBytes());
digest.update(xTimestamp.getBytes());
digest.update(secureKey.getBytes());
Map<String, String> headers = new HashMap<>(5);
headers.put("X-Sign", Hex.encodeHexString(digest.digest()));
headers.put("X-Client-Id", xClientId);
headers.put("X-Timestamp", xTimestamp);
return headers;
}
}
@@ -0,0 +1,39 @@
package com.central.order.util.http;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
/**
* @author wang
* @see
* @since 1.0
*/
public interface HttpRequest extends Closeable {
Response get() throws IOException;
Response post() throws IOException;
Response put() throws IOException;
Response delete() throws IOException;
Response patch() throws IOException;
HttpRequest encode(String encode);
HttpRequest contentType(String type);
HttpRequest param(String name, String value);
HttpRequest params(Map<String, Object> params);
HttpRequest header(String name, String value);
HttpRequest headers(Map<String, String> headers);
HttpRequest requestBody(String body);
HttpRequest resultAsJsonString();
}
@@ -0,0 +1,13 @@
package com.central.order.util.http;
import java.io.IOException;
/**
* @author wang
* @see
* @since 1.0
*/
public interface Response {
byte[] asBytes() throws IOException;
}
@@ -0,0 +1,184 @@
package com.central.order.util.http;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author wang
* @see
* @since 1.0
*/
public class SimpleHttpRequest implements HttpRequest {
private Map<String, Object> params = new LinkedHashMap<>();
private Map<String, String> headers = new LinkedHashMap<>();
private String url;
private String requestBody;
private String contentType;
private String encode = "utf-8";
protected HttpClient httpClient;
public SimpleHttpRequest(String url) {
this.url = url;
createHttpClient();
}
public SimpleHttpRequest(String url, HttpClient client) {
this.url = url;
this.httpClient = client;
}
protected void createHttpClient() {
if (httpClient == null) {
HttpClientBuilder builder = HttpClientBuilder.create();
httpClient = builder.build();
}
}
@Override
public Response get() throws IOException {
String param = EntityUtils.toString(createUrlEncodedFormEntity());
String tmpUrl = url + (url.contains("?") ? "&" : "?") + param;
HttpGet get = new HttpGet(tmpUrl);
HttpResponse response = execute(get);
return getResultValue(response);
}
@Override
public Response post() throws IOException {
HttpPost post = new HttpPost(url);
if (requestBody != null)
post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode)));
else {
post.setEntity(createUrlEncodedFormEntity());
}
HttpResponse response = execute(post);
return getResultValue(response);
}
@Override
public Response put() throws IOException {
HttpPut put = new HttpPut(url);
if (requestBody != null)
put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode)));
else {
put.setEntity(createUrlEncodedFormEntity());
}
HttpResponse response = execute(put);
return getResultValue(response);
}
protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException {
List<NameValuePair> nameValuePair = params.entrySet()
.stream().map(stringStringEntry ->
new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue())))
.collect(Collectors.toList());
return new UrlEncodedFormEntity(nameValuePair, encode);
}
@Override
public Response delete() throws IOException {
HttpDelete delete = new HttpDelete(url);
HttpResponse response = execute(delete);
return getResultValue(response);
}
@Override
public Response patch() throws IOException {
HttpPatch delete = new HttpPatch(url);
if (requestBody != null)
delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType)));
else {
delete.setEntity(createUrlEncodedFormEntity());
}
return getResultValue(execute(delete));
}
@Override
public void close() throws IOException {
if (httpClient != null && httpClient instanceof CloseableHttpClient) {
((CloseableHttpClient) httpClient).close();
}
}
@Override
public HttpRequest resultAsJsonString() {
header("Accept", "application/json");
return this;
}
@Override
public HttpRequest requestBody(String body) {
contentType("application/json");
this.requestBody = body;
return this;
}
@Override
public HttpRequest encode(String encode) {
this.encode = encode;
return this;
}
@Override
public HttpRequest contentType(String type) {
this.contentType = type;
return this;
}
@Override
public HttpRequest param(String name, String value) {
this.params.put(name, value);
return this;
}
@Override
public HttpRequest params(Map<String, Object> params) {
this.params.putAll(params);
return this;
}
@Override
public HttpRequest header(String name, String value) {
this.headers.put(name, value);
return this;
}
@Override
public HttpRequest headers(Map<String, String> header) {
this.headers.putAll(header);
return this;
}
private Response getResultValue(HttpResponse res) throws IOException {
return new SimpleResponse(res);
}
private HttpResponse execute(HttpRequestBase request) throws IOException {
putHeader(request);
return httpClient.execute(request);
}
private void putHeader(HttpUriRequest request) {
headers.forEach(request::setHeader);
}
}
@@ -0,0 +1,26 @@
package com.central.order.util.http;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* @author wang
* @see
* @since 1.0
*/
public class SimpleResponse implements Response {
HttpResponse response;
public SimpleResponse(HttpResponse response) {
this.response = response;
}
@Override
public byte[] asBytes() throws IOException {
return EntityUtils.toByteArray(response.getEntity());
}
}
@@ -0,0 +1,49 @@
spring:
datasource:
# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
url: jdbc:mysql://${zlt.datasource.ip}/order-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: ${zlt.datasource.username}
password: ${zlt.datasource.password}
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.central.device.model
global-config:
db-config:
id-type: auto
springdoc:
group-configs:
- group: 'default'
paths-to-match: '/**'
packages-to-scan: com.central.order.controller
knife4j:
enable: true
setting:
swagger-model-name: 订单中心接口文档
# 微信支付商户号
wxpay:
mchId: ${zlt.wxpay.mchId}
# 微信支付商户密钥
mchKey: ${zlt.wxpay.mchKey}
# 微信支付申请的应用ID
appId: ${zlt.wxpay.appId}
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
notifyUrl: ${zlt.wxpay.notifyUrl}
# 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径)
certPath: ${zlt.wxpay.certPath}
# 微信支付API证书密码(如果有)
certPassword: ${zlt.wxpay.certPassword}
#审计日志
# audit-log:
# enabled: true
# log-type: db
# datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
# username: ${zlt.datasource.username}
# password: ${zlt.datasource.password}
@@ -0,0 +1,11 @@
server:
port: 7002
spring:
application:
name: order-center
# cloud:
# nacos:
# discovery:
# metadata:
# version: zlt
@@ -0,0 +1,47 @@
<?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.central.order.mapper.OrderMapper">
<select id="findList" resultType="com.central.order.model.Order">
select * from orders t
</select>
<!-- 根据订单状态查询订单列表 -->
<select id="getOrdersByStatus" resultMap="OrderResultMap">
SELECT * FROM orders WHERE order_status = #{status}
</select>
<!-- 新增订单 -->
<insert id="insertOrder" keyProperty="order_id" useGeneratedKeys="true">
INSERT INTO orders (user_id, order_amount, order_status)
VALUES (#{userId}, #{orderAmount}, #{orderStatus})
</insert>
<!-- 根据订单编号查询订单信息 -->
<resultMap id="OrderResultMap" type="com.central.order.model.Order"></resultMap>
<select id="getOrderById" resultMap="OrderResultMap">
SELECT * FROM orders WHERE id = #{orderId}
</select>
<!-- 更新订单状态 -->
<update id="updateOrderStatus">
UPDATE orders
SET order_status = #{newStatus}
WHERE id = #{orderId}
</update>
<!-- 查询所有处于排队状态的订单 -->
<select id="getOrdersInQueue" resultType="com.central.order.model.Order">
SELECT * FROM orders WHERE order_status = 1
</select>
<!-- 根据店铺编号和创建时间(当天)查询订单数量 -->
<select id="findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual" resultMap="OrderResultMap">
SELECT * FROM orders
WHERE tourism_id = #{tourismId}
AND create_time >= #{startDate}
AND create_time &lt;= #{endDate}
</select>
<!-- 根据订单编号查询订单信息 -->
<select id="getOrderByNumber" resultMap="OrderResultMap">
SELECT * FROM orders WHERE order_number = #{orderNumber}
</select>
</mapper>
@@ -0,0 +1,20 @@
<?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.central.order.mapper.PaymentRecordMapper">
<select id="findList" resultType="com.central.order.model.PaymentRecord">
select * from payment_records t
</select>
<!-- 插入支付记录 -->
<insert id="insertPaymentRecord" keyProperty="paymentId" useGeneratedKeys="true">
INSERT INTO payment_records (order_id, payment_number, payment_amount, payment_time)
VALUES (#{orderId}, #{paymentNumber}, #{paymentAmount}, #{paymentTime})
</insert>
<!-- 根据支付流水号查询支付记录 -->
<resultMap id="PaymentRecordResultMap" type="com.central.order.model.PaymentRecord">
</resultMap>
<select id="getPaymentRecordByNumber" resultMap="PaymentRecordResultMap">
SELECT * FROM payment_records WHERE payment_number = #{paymentNumber}
</select>
</mapper>