fix(优惠券中心):优惠券中心业务完善,编译问题解决

This commit is contained in:
2025-08-07 02:44:23 +08:00
parent 4461e2b8c6
commit 5aa8f61d71
47 changed files with 2632 additions and 645 deletions
+267
View File
@@ -0,0 +1,267 @@
# 携程优惠券业务对接系统
## 项目概述
本项目是携程优惠券业务对接系统,实现了与携程平台的优惠券业务集成,包括优惠券创建、核销、取消等完整业务流程。
## 功能特性
### 核心功能
- ✅ **携程优惠券创建** - 支持携程下单后回调创建用户优惠券
- ✅ **智能优惠券选择** - 根据订单金额智能选择最优优惠券
- ✅ **优惠券核销** - 完整的核销流程,包括携程API调用和本地状态更新
- ✅ **优惠券取消** - 支持指定优惠券或默认取消第一个可用券
- ✅ **优惠券状态查询** - 实时查询优惠券状态
- ✅ **过期优惠券处理** - 定时任务自动处理过期优惠券
### 技术特性
- 🔐 **安全加密** - AES-128-CBC加密和MD5签名验证
- 🔄 **重试机制** - API调用失败自动重试
- 📊 **幂等性保证** - 防止重复处理
- 🎯 **智能选择** - 优惠券优先级算法
- 📝 **完整日志** - 详细的操作日志记录
- 🧪 **单元测试** - 完整的测试覆盖
## 系统架构
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ 携程平台API │ │ 优惠券服务 │ │ 数据库 │
│ │ │ │ │ │
│ - 创建优惠券 │◄──►│ - 业务逻辑处理 │◄──►│ - t_coupon │
│ - 核销优惠券 │ │ - 数据验证 │ │ - t_ctrip_* │
│ - 取消优惠券 │ │ - 状态管理 │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
```
## 数据库设计
### 核心表结构
#### t_coupon (优惠券主表)
```sql
- id: 主键ID
- coupon_no: 优惠券编号
- coupon_name: 优惠券名称
- coupon_type: 优惠券类型(1-满减券,2-折扣券,3-免费券)
- amount: 优惠券面额
- min_amount: 使用门槛金额
- discount_rate: 折扣率
- status: 状态(0-未使用,1-已使用,2-已过期,3-已作废)
- user_phone: 用户手机号
- source: 来源(1-携程,2-高飞自建)
- ctrip_coupon_id: 携程优惠券ID
- valid_start_time/valid_end_time: 有效期
- used_time/used_order_no: 使用时间和订单号
- cancel_time: 退券时间
```
#### t_ctrip_* (携程相关表)
- `t_ctrip_order` - 携程订单表
- `t_ctrip_coupon` - 携程优惠券信息表
- `t_ctrip_refund` - 携程退款表
- `t_ctrip_consumed` - 携程核销表
## API接口
### 1. 携程创建优惠券接口
```http
POST /coupon/ctrip/create
Content-Type: application/json
{
"ctripCouponId": "CTRIP_001",
"userPhone": "13800138000",
"couponName": "满100减50券",
"couponType": 1,
"amount": 50.00,
"minAmount": 100.00,
"validStartTime": "2024-01-01 00:00:00",
"validEndTime": "2024-12-31 23:59:59"
}
```
### 2. 核销携程优惠券接口
```http
POST /coupon/ctrip/verify?userPhone=13800138000&orderNo=ORDER_001&orderAmount=300.00
```
### 3. 取消携程优惠券接口
```http
POST /coupon/ctrip/cancel?userPhone=13800138000&ctripCouponId=CTRIP_001&reason=用户取消
```
### 4. 查询携程优惠券状态
```http
GET /coupon/ctrip/status/CTRIP_001
```
## 配置说明
### 应用配置 (application.yml)
```yaml
# 携程API配置
ctrip:
aes:
key: your-aes-key-here-16chars
iv: your-aes-iv-here-16chars
md5:
secret: your-md5-secret-here
api:
timeout: 30000
retry-times: 3
base-url: https://api.ctrip.com
account:
id: your-account-id
secret: your-account-secret
```
### 环境变量配置
```bash
# 生产环境
export CTRIP_ACCOUNT_ID=your-prod-account-id
export CTRIP_ACCOUNT_SECRET=your-prod-account-secret
export CTRIP_AES_KEY=your-prod-aes-key
export CTRIP_AES_IV=your-prod-aes-iv
export CTRIP_MD5_SECRET=your-prod-md5-secret
```
## 部署指南
### 1. 环境要求
- JDK 1.8+
- MySQL 5.7+
- Maven 3.6+
### 2. 数据库初始化
```sql
-- 执行数据库迁移脚本
source database_migration.sql
```
### 3. 应用启动
```bash
# 开发环境
mvn spring-boot:run -Dspring.profiles.active=dev
# 生产环境
mvn clean package
java -jar target/coupon-center.jar --spring.profiles.active=prod
```
### 4. 健康检查
```bash
curl http://localhost:8082/coupon-center/actuator/health
```
## 监控和日志
### 日志配置
- 应用日志:`logs/coupon-center.log`
- 日志级别:开发环境 DEBUG,生产环境 INFO
### 监控指标
- 优惠券创建成功率
- 优惠券核销成功率
- API调用响应时间
- 数据库连接状态
### 定时任务
- 过期优惠券处理:每天凌晨2点
- 即将过期优惠券检查:每小时
## 测试
### 单元测试
```bash
mvn test
```
### 集成测试
```bash
mvn test -Dspring.profiles.active=test
```
### API测试
```bash
# 创建优惠券测试
curl -X POST http://localhost:8082/coupon-center/coupon/ctrip/create \
-H "Content-Type: application/json" \
-d '{
"ctripCouponId": "TEST_001",
"userPhone": "13800138000",
"couponName": "测试优惠券",
"couponType": 1,
"amount": 100.00,
"minAmount": 200.00,
"validStartTime": "2024-01-01 00:00:00",
"validEndTime": "2024-12-31 23:59:59"
}'
```
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| COUPON_NOT_FOUND | 优惠券不存在 |
| COUPON_INVALID | 优惠券状态不正确 |
| COUPON_EXPIRED | 优惠券已过期 |
| COUPON_USAGE_ERROR | 优惠券使用条件不满足 |
| COUPON_VERIFY_FAILED | 携程核销失败 |
| COUPON_UPDATE_FAILED | 更新优惠券状态失败 |
| COUPON_PARAM_ERROR | 参数错误 |
| SYSTEM_ERROR | 系统异常 |
## 开发指南
### 代码结构
```
src/main/java/com/central/coupon/
├── controller/ # 控制器层
├── service/ # 服务层
├── entity/ # 实体类
├── mapper/ # 数据访问层
├── config/ # 配置类
├── exception/ # 异常处理
├── task/ # 定时任务
└── util/ # 工具类
```
### 开发规范
1. **命名规范** - 使用驼峰命名法
2. **注释规范** - 类和方法必须有注释
3. **异常处理** - 使用自定义异常类
4. **日志记录** - 关键操作必须记录日志
5. **单元测试** - 核心业务逻辑必须有测试
### 提交规范
```
feat: 新功能
fix: 修复bug
docs: 文档更新
style: 代码格式调整
refactor: 重构
test: 测试相关
chore: 构建过程或辅助工具的变动
```
## 常见问题
### Q: 携程API调用失败怎么办?
A: 检查网络连接、API配置、签名验证等,系统会自动重试3次。
### Q: 优惠券核销失败怎么办?
A: 检查优惠券状态、有效期、使用条件等,查看详细错误日志。
### Q: 如何监控系统状态?
A: 通过健康检查接口和日志文件监控系统状态。
## 联系方式
如有问题,请联系开发团队或查看项目文档。
## 版本历史
- v1.0.0 - 初始版本,实现基础优惠券功能
- v1.1.0 - 添加智能优惠券选择
- v1.2.0 - 完善错误处理和监控
@@ -1,9 +1,12 @@
package com.central.coupon;
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.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 优惠券中心启动类
@@ -11,9 +14,11 @@ import org.springframework.context.annotation.ComponentScan;
* @author system
* @date 2024-12-19
*/
@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.central.coupon"})
@EnableSearchClient
@EnableTransactionManagement
@EnableFeignInterceptor
@SpringBootApplication
public class CouponCenterApplication {
public static void main(String[] args) {
@@ -0,0 +1,32 @@
package com.central.coupon.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* RestTemplate配置类
*/
@Configuration
public class RestTemplateConfig {
@Value("${ctrip.api.timeout:30000}")
private int timeout;
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(clientHttpRequestFactory());
return restTemplate;
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(timeout);
factory.setReadTimeout(timeout);
return factory;
}
}
@@ -3,6 +3,8 @@ package com.central.coupon.controller;
import com.central.common.model.Result;
import com.central.coupon.entity.Coupon;
import com.central.coupon.service.ICouponService;
import com.central.coupon.service.ICtripApiService;
import com.central.coupon.service.impl.CouponServiceImpl;
import com.central.coupon.util.CtripDecryptUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
@@ -32,6 +34,9 @@ public class CtripCouponController {
@Autowired
private ICouponService couponService;
@Autowired
private ICtripApiService ctripApiService;
/**
* 携程创建优惠券接口
* 携程下单后回调,创建用户优惠券(手机号+携程券ID唯一,幂等)
@@ -76,7 +81,7 @@ public class CtripCouponController {
couponType == null || amount == null || validStartTimeStr == null || validEndTimeStr == null) {
log.error("参数不完整 - ctripCouponId: {}, userPhone: {}, couponName: {}, couponType: {}, amount: {}, validStartTime: {}, validEndTime: {}",
ctripCouponId, userPhone, couponName, couponType, amount, validStartTimeStr, validEndTimeStr);
return Result.failed("参数不完整");
return Result.succeed(false);
}
// 幂等校验
@@ -91,7 +96,7 @@ public class CtripCouponController {
if (validStartTime == null || validEndTime == null) {
log.error("时间格式错误 - validStartTime: {}, validEndTime: {}", validStartTimeStr, validEndTimeStr);
return Result.failed("时间格式错误");
return Result.succeed(false);
}
// 创建优惠券
@@ -103,63 +108,12 @@ public class CtripCouponController {
return Result.succeed(true);
} else {
log.error("携程优惠券创建失败 - ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone);
return Result.failed("创建失败");
return Result.succeed(false);
}
} catch (Exception e) {
log.error("处理携程创建优惠券请求异常", e);
return Result.failed("系统异常:" + e.getMessage());
}
}
/**
* 携程取消优惠券接口
* 携程退券回调,取消用户优惠券(默认退第一个未用券)
*
* 请求参数:
* - userPhone: 用户手机号
*/
@Operation(summary = "携程取消优惠券接口")
@PostMapping("/cancel")
public Result<Boolean> cancelCouponFromCtrip(@RequestParam String userPhone,
HttpServletRequest httpRequest) {
log.info("收到携程取消优惠券请求,IP: {}, userPhone: {}", httpRequest.getRemoteAddr(), userPhone);
try {
// 参数验证
if (userPhone == null || userPhone.trim().isEmpty()) {
log.error("用户手机号不能为空");
return Result.failed("用户手机号不能为空");
}
// 查询用户可用优惠券
List<Coupon> availableCoupons = couponService.getAvailableCouponsByUserPhone(userPhone);
if (availableCoupons.isEmpty()) {
log.warn("用户无可用优惠券,userPhone: {}", userPhone);
return Result.failed("无可退优惠券");
}
// 选择第一个可用优惠券进行取消
Coupon coupon = availableCoupons.get(0);
coupon.setStatus(3); // 已作废
coupon.setCancelTime(new Date());
coupon.setUpdateTime(new Date());
coupon.setUpdateBy("ctrip");
boolean result = couponService.updateCoupon(coupon);
if (result) {
log.info("携程优惠券取消成功 - couponId: {}, userPhone: {}", coupon.getId(), userPhone);
return Result.succeed(true);
} else {
log.error("携程优惠券取消失败 - couponId: {}, userPhone: {}", coupon.getId(), userPhone);
return Result.failed("取消失败");
}
} catch (Exception e) {
log.error("处理携程取消优惠券请求异常", e);
return Result.failed("系统异常:" + e.getMessage());
return Result.succeed(false);
}
}
@@ -170,54 +124,172 @@ public class CtripCouponController {
* 请求参数:
* - userPhone: 用户手机号
* - orderNo: 订单号
* - orderAmount: 订单金额(可选,用于智能选择优惠券)
*/
@Operation(summary = "核销携程优惠券")
@PostMapping("/verify")
public Result<Boolean> verifyCtripCoupon(@RequestParam String userPhone,
@RequestParam String orderNo,
@RequestParam(required = false) java.math.BigDecimal orderAmount,
HttpServletRequest httpRequest) {
log.info("收到核销携程优惠券请求,IP: {}, userPhone: {}, orderNo: {}",
httpRequest.getRemoteAddr(), userPhone, orderNo);
log.info("收到核销携程优惠券请求,IP: {}, userPhone: {}, orderNo: {}, orderAmount: {}",
httpRequest.getRemoteAddr(), userPhone, orderNo, orderAmount);
try {
// 参数验证
if (userPhone == null || userPhone.trim().isEmpty()) {
log.error("用户手机号不能为空");
return Result.failed("用户手机号不能为空");
return Result.succeed(false);
}
if (orderNo == null || orderNo.trim().isEmpty()) {
log.error("订单号不能为空");
return Result.failed("订单号不能为空");
return Result.succeed(false);
}
// 查询用户可用优惠券
List<Coupon> availableCoupons = couponService.getAvailableCouponsByUserPhone(userPhone);
if (availableCoupons.isEmpty()) {
log.warn("用户无可用优惠券,userPhone: {}", userPhone);
return Result.failed("无可用优惠券");
// 智能选择优惠券
Coupon selectedCoupon;
if (orderAmount != null) {
// 使用智能选择
selectedCoupon = couponService.selectBestCoupon(userPhone, orderAmount);
if (selectedCoupon == null) {
log.warn("无符合条件的优惠券,userPhone: {}, orderAmount: {}", userPhone, orderAmount);
return Result.succeed(false);
}
} else {
// 使用默认选择(第一个可用优惠券)
List<Coupon> availableCoupons = couponService.getAvailableCouponsByUserPhone(userPhone);
if (availableCoupons.isEmpty()) {
log.warn("用户无可用优惠券,userPhone: {}", userPhone);
return Result.succeed(false);
}
selectedCoupon = availableCoupons.get(0);
}
// 选择第一个可用优惠券进行核销
Coupon coupon = availableCoupons.get(0);
log.info("选择优惠券进行核销 - couponId: {}, ctripCouponId: {}, amount: {}",
coupon.getId(), coupon.getCtripCouponId(), coupon.getAmount());
selectedCoupon.getId(), selectedCoupon.getCtripCouponId(), selectedCoupon.getAmount());
// 调用携程核销接口
boolean result = couponService.verifyCtripCoupon(coupon.getCtripCouponId(), orderNo);
boolean result = couponService.verifyCtripCoupon(selectedCoupon.getCtripCouponId(), orderNo);
if (result) {
log.info("携程核销成功,更新本地优惠券状态 - couponId: {}, orderNo: {}", coupon.getId(), orderNo);
coupon.setStatus(1); // 已用
coupon.setUsedTime(new Date());
coupon.setUsedOrderNo(orderNo);
couponService.updateCoupon(coupon);
log.info("携程核销成功,更新本地优惠券状态 - couponId: {}, orderNo: {}", selectedCoupon.getId(), orderNo);
return Result.succeed(true);
} else {
log.error("携程核销失败,couponId: {}, orderNo: {}", coupon.getId(), orderNo);
return Result.failed("携程核销失败");
log.error("携程核销失败,couponId: {}, orderNo: {}", selectedCoupon.getId(), orderNo);
return Result.succeed(false);
}
} catch (CouponServiceImpl.CouponNotFoundException e) {
log.error("优惠券不存在", e);
return Result.succeed(false);
} catch (CouponServiceImpl.CouponInvalidException e) {
log.error("优惠券状态不正确", e);
return Result.succeed(false);
} catch (CouponServiceImpl.CouponExpiredException e) {
log.error("优惠券已过期", e);
return Result.succeed(false);
} catch (CouponServiceImpl.CouponUsageException e) {
log.error("优惠券使用条件不满足", e);
return Result.succeed(false);
} catch (CouponServiceImpl.CouponVerifyException e) {
log.error("携程核销失败", e);
return Result.succeed(false);
} catch (CouponServiceImpl.CouponUpdateException e) {
log.error("更新优惠券状态失败", e);
return Result.succeed(false);
} catch (Exception e) {
log.error("核销携程优惠券失败", e);
return Result.failed("核销失败:" + e.getMessage());
return Result.succeed(false);
}
}
/**
* 携程取消优惠券接口
* 携程退券回调,取消用户优惠券(支持指定优惠券ID或默认退第一个未用券)
*
* 请求参数:
* - userPhone: 用户手机号
* - ctripCouponId: 携程优惠券ID(可选,不传则取消第一个可用券)
* - reason: 取消原因(可选)
*/
@Operation(summary = "携程取消优惠券接口")
@PostMapping("/cancel")
public Result<Boolean> cancelCouponFromCtrip(@RequestParam String userPhone,
@RequestParam(required = false) String ctripCouponId,
@RequestParam(required = false) String reason,
HttpServletRequest httpRequest) {
log.info("收到携程取消优惠券请求,IP: {}, userPhone: {}, ctripCouponId: {}, reason: {}",
httpRequest.getRemoteAddr(), userPhone, ctripCouponId, reason);
try {
// 参数验证
if (userPhone == null || userPhone.trim().isEmpty()) {
log.error("用户手机号不能为空");
return Result.succeed(false);
}
Coupon couponToCancel;
if (ctripCouponId != null && !ctripCouponId.trim().isEmpty()) {
// 指定优惠券ID
couponToCancel = couponService.getByCtripCouponId(ctripCouponId);
if (couponToCancel == null) {
log.error("指定的优惠券不存在,ctripCouponId: {}", ctripCouponId);
return Result.succeed(false);
}
// 验证用户权限
if (!userPhone.equals(couponToCancel.getUserPhone())) {
log.error("用户无权限取消该优惠券,userPhone: {}, couponUserPhone: {}",
userPhone, couponToCancel.getUserPhone());
return Result.succeed(false);
}
} else {
// 选择第一个可用优惠券
List<Coupon> availableCoupons = couponService.getAvailableCouponsByUserPhone(userPhone);
if (availableCoupons.isEmpty()) {
log.warn("用户无可用优惠券,userPhone: {}", userPhone);
return Result.succeed(false);
}
couponToCancel = availableCoupons.get(0);
}
// 验证优惠券状态
if (couponToCancel.getStatus() != 0) {
log.error("优惠券状态不正确,无法取消,couponId: {}, status: {}",
couponToCancel.getId(), couponToCancel.getStatus());
return Result.succeed(false);
}
// 调用携程取消接口
boolean ctripCancelResult = ctripApiService.cancelCoupon(
couponToCancel.getCtripCouponId(), userPhone, reason != null ? reason : "用户取消");
if (!ctripCancelResult) {
log.error("携程取消优惠券失败,ctripCouponId: {}", couponToCancel.getCtripCouponId());
return Result.succeed(false);
}
// 更新本地优惠券状态
couponToCancel.setStatus(3); // 已作废
couponToCancel.setCancelTime(new Date());
couponToCancel.setUpdateTime(new Date());
couponToCancel.setUpdateBy("ctrip");
couponToCancel.setRemark(reason != null ? reason : "用户取消");
boolean updateResult = couponService.updateCoupon(couponToCancel);
if (updateResult) {
log.info("携程优惠券取消成功 - couponId: {}, userPhone: {}, reason: {}",
couponToCancel.getId(), userPhone, reason);
return Result.succeed(true);
} else {
log.error("更新优惠券状态失败 - couponId: {}, userPhone: {}",
couponToCancel.getId(), userPhone);
return Result.succeed(false);
}
} catch (Exception e) {
log.error("处理携程取消优惠券请求异常", e);
return Result.succeed(false);
}
}
@@ -235,13 +307,13 @@ public class CtripCouponController {
try {
if (ctripCouponId == null || ctripCouponId.trim().isEmpty()) {
log.error("携程优惠券ID不能为空");
return Result.failed("携程优惠券ID不能为空");
return Result.succeed(null);
}
Coupon coupon = couponService.getByCtripCouponId(ctripCouponId);
if (coupon == null) {
log.warn("优惠券不存在,ctripCouponId: {}", ctripCouponId);
return Result.failed("优惠券不存在");
return Result.succeed(null);
}
Map<String, Object> status = Map.of(
@@ -259,7 +331,7 @@ public class CtripCouponController {
return Result.succeed(status);
} catch (Exception e) {
log.error("查询携程优惠券状态失败", e);
return Result.failed("查询失败:" + e.getMessage());
return Result.succeed(null);
}
}
@@ -1,16 +1,6 @@
package com.central.coupon.controller;
import com.central.coupon.model.CtripCreateOrderRequest;
import com.central.coupon.model.CtripCreateOrderResponse;
import com.central.coupon.model.CtripCancelOrderRequest;
import com.central.coupon.model.CtripCancelOrderResponse;
import com.central.coupon.model.CtripCancelOrderConfirmRequest;
import com.central.coupon.model.CtripCancelOrderConfirmResponse;
import com.central.coupon.model.CtripRefundOrderRequest;
import com.central.coupon.model.CtripRefundOrderResponse;
import com.central.coupon.model.CtripRefundOrderConfirmRequest;
import com.central.coupon.model.CtripRefundOrderConfirmResponse;
import com.central.coupon.model.CtripConsumedNoticeRequest;
import com.central.coupon.model.*;
import com.central.coupon.service.ICtripOrderService;
import com.central.coupon.util.CtripDecryptUtil;
import com.central.coupon.util.CtripResponseCodeUtil;
@@ -3,19 +3,25 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 携程核销实体类
* 携程核销表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_consumed")
public class CtripConsumed {
public class CtripConsumed implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -34,7 +40,7 @@ public class CtripConsumed {
private String supplierOrderId;
/**
* 供应商处理批次流水号
* 携程批次流水号
*/
private String sequenceId;
@@ -44,53 +50,50 @@ public class CtripConsumed {
private String itemId;
/**
* 使用开始日期
* 实际使用开始日期
*/
private String useStartDate;
private LocalDate useStartDate;
/**
* 使用结束日期
* 实际使用结束日期
*/
private String useEndDate;
private LocalDate useEndDate;
/**
* 总数量
* 订单总份数
*/
private Integer quantity;
private Integer totalQuantity;
/**
* 已使用数量
* 订单已核销总份数
*/
private Integer useQuantity;
/**
* 丢失金额
*/
private BigDecimal lostAmount;
/**
* 丢失金额货币
*/
private String lostAmountCurrency;
/**
* 备注信息
*/
private String remark;
/**
* 核销状态:0-待核销,1-已核销,2-部分核销,3-核销失败
* 实际损失金额
*/
private Integer status;
private BigDecimal lostAmount;
/**
* 实际损失金额单位
*/
private String lostAmountCurrency;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
@@ -103,11 +106,6 @@ public class CtripConsumed {
*/
private String updateBy;
/**
* 备注
*/
private String remarkDetail;
/**
* 租户ID
*/
@@ -3,18 +3,23 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 携程核销乘客信息实体类
* 携程核销乘客表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_consumed_passenger")
public class CtripConsumedPassenger {
public class CtripConsumedPassenger implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -32,33 +37,25 @@ public class CtripConsumedPassenger {
*/
private String passengerId;
/**
* 乘客姓名
*/
private String passengerName;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人
* 是否删除:0-未删除,1-已删除
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
/**
* 租户ID
*/
private String tenantId;
private Integer deleted;
}
@@ -3,18 +3,23 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 携程核销凭证信息实体类
* 携程核销凭证表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_consumed_voucher")
public class CtripConsumedVoucher {
public class CtripConsumedVoucher implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -28,37 +33,29 @@ public class CtripConsumedVoucher {
private Long consumedId;
/**
* 凭证ID
* 凭证编号
*/
private String voucherId;
/**
* 凭证码
*/
private String voucherCode;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人
* 是否删除:0-未删除,1-已删除
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
/**
* 租户ID
*/
private String tenantId;
private Integer deleted;
}
@@ -0,0 +1,71 @@
package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 携程联系人信息表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_contact")
public class CtripContact implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 订单ID
*/
private Long orderId;
/**
* 联系人姓名
*/
private String name;
/**
* 联系人电话
*/
private String mobile;
/**
* 联系人邮箱
*/
private String email;
/**
* 联系人类型:BOOKER-预订人,CONTACT-联系人
*/
private String contactType;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 是否删除:0-未删除,1-已删除
*/
private Integer deleted;
}
@@ -0,0 +1,87 @@
package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 携程优惠券信息表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_coupon")
public class CtripCoupon implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 订单ID
*/
private Long orderId;
/**
* 优惠券类型
*/
private String couponType;
/**
* 优惠券代码
*/
private String couponCode;
/**
* 优惠券名称
*/
private String couponName;
/**
* 优惠券金额
*/
private BigDecimal couponAmount;
/**
* 货币类型
*/
private String currency;
/**
* 优惠券状态:1-有效,2-已使用,3-已过期
*/
private Integer couponStatus;
/**
* 使用时间
*/
private LocalDateTime useTime;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 是否删除:0-未删除,1-已删除
*/
private Integer deleted;
}
@@ -3,18 +3,24 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 携程订单实体类
* 携程订单表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_order")
public class CtripOrder {
public class CtripOrder implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -52,14 +58,26 @@ public class CtripOrder {
*/
private Integer status;
/**
* 订单总金额
*/
private BigDecimal totalAmount;
/**
* 货币类型
*/
private String currency;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
@@ -3,20 +3,25 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 携程订单项实体类
* 携程订单项表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_order_item")
public class CtripOrderItem {
public class CtripOrderItem implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -35,9 +40,34 @@ public class CtripOrderItem {
private String itemId;
/**
* 产品编码
* 订单项名称
*/
private String plu;
private String itemName;
/**
* 订单项类型
*/
private String itemType;
/**
* 数量
*/
private Integer quantity;
/**
* 单价
*/
private BigDecimal unitPrice;
/**
* 总价
*/
private BigDecimal totalPrice;
/**
* 货币类型
*/
private String currency;
/**
* 使用开始日期
@@ -49,48 +79,20 @@ public class CtripOrderItem {
*/
private LocalDate useEndDate;
/**
* 原价
*/
private BigDecimal price;
/**
* 销售价格
*/
private BigDecimal salePrice;
/**
* 数量
*/
private Integer quantity;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人
* 是否删除:0-未删除,1-已删除
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
/**
* 租户ID
*/
private String tenantId;
private Integer deleted;
}
@@ -3,18 +3,24 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 携程乘客信息实体类
* 携程乘客信息表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_passenger")
public class CtripPassenger {
public class CtripPassenger implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -23,9 +29,14 @@ public class CtripPassenger {
private Long id;
/**
* 订单项ID
* 订单ID
*/
private Long orderItemId;
private Long orderId;
/**
* 订单项编号
*/
private String itemId;
/**
* 乘客ID
@@ -33,62 +44,44 @@ public class CtripPassenger {
private String passengerId;
/**
* 姓名
* 乘客姓名
*/
private String name;
private String passengerName;
/**
* 手机号
* 乘客类型:ADULT-成人,CHILD-儿童,INFANT-婴儿
*/
private String mobile;
private String passengerType;
/**
* 证件类型
* 证件类型:ID_CARD-身份证,PASSPORT-护照
*/
private String cardType;
private String idType;
/**
* 证件号码
*/
private String cardNo;
private String idNumber;
/**
* 年龄类型:ADU-成人,CHD-儿童,INF-婴儿
* 手机号码
*/
private String ageType;
/**
* 性别:M-男,F-女
*/
private String gender;
private String phone;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人
* 是否删除:0-未删除,1-已删除
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
/**
* 租户ID
*/
private String tenantId;
private Integer deleted;
}
@@ -3,19 +3,24 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 携程退款实体类
* 携程退款表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_refund")
public class CtripRefund {
public class CtripRefund implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -39,24 +44,19 @@ public class CtripRefund {
private String sequenceId;
/**
* 退款总金额
* 退款金额
*/
private BigDecimal totalAmount;
private BigDecimal refundAmount;
/**
* 退款总金额货币
* 货币类型
*/
private String totalAmountCurrency;
private String currency;
/**
* 最晚确认时间
* 退款状态:0-待确认,1-已确认,2-已拒绝
*/
private LocalDateTime lastConfirmTime;
/**
* 退款状态:0-待确认,1-已确认,2-已拒绝,3-已过期
*/
private Integer status;
private Integer refundStatus;
/**
* 确认结果码
@@ -68,14 +68,21 @@ public class CtripRefund {
*/
private String confirmResultMessage;
/**
* 最晚确认时间
*/
private LocalDateTime lastConfirmTime;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
@@ -3,19 +3,24 @@ package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 携程退款项实体类
* 携程退款项表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_refund_item")
public class CtripRefundItem {
public class CtripRefundItem implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
@@ -41,40 +46,27 @@ public class CtripRefundItem {
/**
* 退款金额
*/
private BigDecimal amount;
private BigDecimal refundAmount;
/**
* 退款金额货币
* 货币类型
*/
private String amountCurrency;
private String currency;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人
* 是否删除:0-未删除,1-已删除
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
/**
* 租户ID
*/
private String tenantId;
private Integer deleted;
}
@@ -0,0 +1,81 @@
package com.central.coupon.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 携程凭证信息表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_ctrip_voucher")
public class CtripVoucher implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 订单ID
*/
private Long orderId;
/**
* 订单项编号
*/
private String itemId;
/**
* 凭证编号
*/
private String voucherId;
/**
* 凭证码
*/
private String voucherCode;
/**
* 凭证类型
*/
private String voucherType;
/**
* 凭证状态:1-未使用,2-已使用,3-已过期
*/
private Integer voucherStatus;
/**
* 使用时间
*/
private LocalDateTime useTime;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 是否删除:0-未删除,1-已删除
*/
private Integer deleted;
}
@@ -0,0 +1,123 @@
package com.central.coupon.exception;
import com.central.common.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理器
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 优惠券不存在异常
*/
@ExceptionHandler(CouponNotFoundException.class)
public Result<String> handleCouponNotFoundException(CouponNotFoundException e) {
log.error("优惠券不存在异常", e);
return Result.failed("COUPON_NOT_FOUND", e.getMessage());
}
/**
* 优惠券状态不正确异常
*/
@ExceptionHandler(CouponInvalidException.class)
public Result<String> handleCouponInvalidException(CouponInvalidException e) {
log.error("优惠券状态不正确异常", e);
return Result.failed("COUPON_INVALID", e.getMessage());
}
/**
* 优惠券已过期异常
*/
@ExceptionHandler(CouponExpiredException.class)
public Result<String> handleCouponExpiredException(CouponExpiredException e) {
log.error("优惠券已过期异常", e);
return Result.failed("COUPON_EXPIRED", e.getMessage());
}
/**
* 优惠券使用条件不满足异常
*/
@ExceptionHandler(CouponUsageException.class)
public Result<String> handleCouponUsageException(CouponUsageException e) {
log.error("优惠券使用条件不满足异常", e);
return Result.failed("COUPON_USAGE_ERROR", e.getMessage());
}
/**
* 携程核销失败异常
*/
@ExceptionHandler(CouponVerifyException.class)
public Result<String> handleCouponVerifyException(CouponVerifyException e) {
log.error("携程核销失败异常", e);
return Result.failed("COUPON_VERIFY_FAILED", e.getMessage());
}
/**
* 优惠券更新失败异常
*/
@ExceptionHandler(CouponUpdateException.class)
public Result<String> handleCouponUpdateException(CouponUpdateException e) {
log.error("优惠券更新失败异常", e);
return Result.failed("COUPON_UPDATE_FAILED", e.getMessage());
}
/**
* 参数验证异常
*/
@ExceptionHandler(IllegalArgumentException.class)
public Result<String> handleIllegalArgumentException(IllegalArgumentException e) {
log.error("参数验证异常", e);
return Result.failed("PARAM_ERROR", e.getMessage());
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public Result<String> handleException(Exception e) {
log.error("系统异常", e);
return Result.failed("SYSTEM_ERROR", "系统异常:" + e.getMessage());
}
// 自定义异常类
public static class CouponNotFoundException extends RuntimeException {
public CouponNotFoundException(String message) {
super(message);
}
}
public static class CouponInvalidException extends RuntimeException {
public CouponInvalidException(String message) {
super(message);
}
}
public static class CouponExpiredException extends RuntimeException {
public CouponExpiredException(String message) {
super(message);
}
}
public static class CouponUsageException extends RuntimeException {
public CouponUsageException(String message) {
super(message);
}
}
public static class CouponVerifyException extends RuntimeException {
public CouponVerifyException(String message) {
super(message);
}
}
public static class CouponUpdateException extends RuntimeException {
public CouponUpdateException(String message) {
super(message);
}
}
}
@@ -6,6 +6,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.coupon.entity.Coupon;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
@@ -23,30 +25,48 @@ public interface CouponMapper extends BaseMapper<Coupon> {
/**
* 根据手机号查询用户优惠券
*/
@Select("SELECT * FROM t_coupon WHERE user_phone = #{userPhone} ORDER BY create_time DESC")
List<Coupon> selectByUserPhone(@Param("userPhone") String userPhone);
/**
* 根据手机号查询可用优惠券
*/
@Select("SELECT * FROM t_coupon WHERE user_phone = #{userPhone} " +
"AND status = 0 " +
"AND valid_start_time <= NOW() " +
"AND valid_end_time >= NOW() " +
"ORDER BY create_time DESC")
List<Coupon> selectAvailableByUserPhone(@Param("userPhone") String userPhone);
/**
* 根据携程优惠券ID查询
*/
@Select("SELECT * FROM t_coupon WHERE ctrip_coupon_id = #{ctripCouponId} LIMIT 1")
Coupon selectByCtripCouponId(@Param("ctripCouponId") String ctripCouponId);
/**
* 根据订单号查询使用的优惠券
*/
@Select("SELECT * FROM t_coupon WHERE used_order_no = #{usedOrderNo} LIMIT 1")
Coupon selectByUsedOrderNo(@Param("usedOrderNo") String usedOrderNo);
/**
* 更新优惠券状态为已使用
*/
@Update("UPDATE t_coupon SET status = 1, used_time = NOW(), used_order_no = #{usedOrderNo}, " +
"update_time = NOW() WHERE id = #{id}")
int updateCouponUsed(@Param("id") Long id, @Param("usedOrderNo") String usedOrderNo);
/**
* 批量更新过期优惠券状态
*/
@Update("UPDATE t_coupon SET status = 2, update_time = NOW() " +
"WHERE status = 0 AND valid_end_time < NOW()")
int updateExpiredCoupons();
/**
* 检查用户手机号和携程优惠券ID是否已存在
*/
@Select("SELECT COUNT(*) FROM t_coupon WHERE user_phone = #{userPhone} AND ctrip_coupon_id = #{ctripCouponId}")
int countByUserPhoneAndCtripCouponId(@Param("userPhone") String userPhone, @Param("ctripCouponId") String ctripCouponId);
}
@@ -14,26 +14,26 @@ import java.util.List;
public interface CtripConsumedMapper extends BaseMapper<CtripConsumed> {
/**
* 根据携程订单号查询核销信息
* 根据携程订单号查询核销记录
*
* @param otaOrderId 携程订单号
* @return 核销信息列表
* @return 核销记录列表
*/
List<CtripConsumed> selectByOtaOrderId(@Param("otaOrderId") String otaOrderId);
/**
* 根据供应商订单号查询核销信息
* 根据供应商订单号查询核销记录
*
* @param supplierOrderId 供应商订单号
* @return 核销信息列表
* @return 核销记录列表
*/
List<CtripConsumed> selectBySupplierOrderId(@Param("supplierOrderId") String supplierOrderId);
/**
* 根据供应商批次流水号查询核销信息
* 根据批次流水号查询核销记录
*
* @param sequenceId 供应商批次流水号
* @return 核销信息
* @param sequenceId 批次流水号
* @return 核销记录
*/
CtripConsumed selectBySequenceId(@Param("sequenceId") String sequenceId);
}
@@ -8,7 +8,7 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程核销乘客信息Mapper接口
* 携程核销乘客Mapper接口
*/
@Mapper
public interface CtripConsumedPassengerMapper extends BaseMapper<CtripConsumedPassenger> {
@@ -20,4 +20,12 @@ public interface CtripConsumedPassengerMapper extends BaseMapper<CtripConsumedPa
* @return 乘客列表
*/
List<CtripConsumedPassenger> selectByConsumedId(@Param("consumedId") Long consumedId);
/**
* 根据乘客ID查询核销乘客记录
*
* @param passengerId 乘客ID
* @return 核销乘客记录列表
*/
List<CtripConsumedPassenger> selectByPassengerId(@Param("passengerId") String passengerId);
}
@@ -8,7 +8,7 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程核销凭证信息Mapper接口
* 携程核销凭证Mapper接口
*/
@Mapper
public interface CtripConsumedVoucherMapper extends BaseMapper<CtripConsumedVoucher> {
@@ -20,4 +20,12 @@ public interface CtripConsumedVoucherMapper extends BaseMapper<CtripConsumedVouc
* @return 凭证列表
*/
List<CtripConsumedVoucher> selectByConsumedId(@Param("consumedId") Long consumedId);
/**
* 根据凭证编号查询核销凭证记录
*
* @param voucherId 凭证编号
* @return 核销凭证记录列表
*/
List<CtripConsumedVoucher> selectByVoucherId(@Param("voucherId") String voucherId);
}
@@ -0,0 +1,32 @@
package com.central.coupon.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.coupon.entity.CtripContact;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程联系人Mapper接口
*/
@Mapper
public interface CtripContactMapper extends BaseMapper<CtripContact> {
/**
* 根据订单ID查询联系人列表
*
* @param orderId 订单ID
* @return 联系人列表
*/
List<CtripContact> selectByOrderId(@Param("orderId") Long orderId);
/**
* 根据订单ID和联系人类型查询联系人
*
* @param orderId 订单ID
* @param contactType 联系人类型
* @return 联系人列表
*/
List<CtripContact> selectByOrderIdAndType(@Param("orderId") Long orderId, @Param("contactType") String contactType);
}
@@ -0,0 +1,40 @@
package com.central.coupon.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.coupon.entity.CtripCoupon;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程优惠券Mapper接口
*/
@Mapper
public interface CtripCouponMapper extends BaseMapper<CtripCoupon> {
/**
* 根据订单ID查询优惠券列表
*
* @param orderId 订单ID
* @return 优惠券列表
*/
List<CtripCoupon> selectByOrderId(@Param("orderId") Long orderId);
/**
* 根据优惠券代码查询优惠券
*
* @param couponCode 优惠券代码
* @return 优惠券信息
*/
CtripCoupon selectByCouponCode(@Param("couponCode") String couponCode);
/**
* 根据订单ID和优惠券状态查询优惠券
*
* @param orderId 订单ID
* @param couponStatus 优惠券状态
* @return 优惠券列表
*/
List<CtripCoupon> selectByOrderIdAndStatus(@Param("orderId") Long orderId, @Param("couponStatus") Integer couponStatus);
}
@@ -1,7 +1,7 @@
package com.central.coupon.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.entity.CtripOrderItem;
import com.central.coupon.entity.CtripOrderItem;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -20,4 +20,21 @@ public interface CtripOrderItemMapper extends BaseMapper<CtripOrderItem> {
* @return 订单项列表
*/
List<CtripOrderItem> selectByOrderId(@Param("orderId") Long orderId);
/**
* 根据订单项编号查询订单项
*
* @param itemId 订单项编号
* @return 订单项信息
*/
CtripOrderItem selectByItemId(@Param("itemId") String itemId);
/**
* 根据订单ID和订单项编号查询订单项
*
* @param orderId 订单ID
* @param itemId 订单项编号
* @return 订单项信息
*/
CtripOrderItem selectByOrderIdAndItemId(@Param("orderId") Long orderId, @Param("itemId") String itemId);
}
@@ -1,7 +1,7 @@
package com.central.coupon.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.entity.CtripOrder;
import com.central.coupon.entity.CtripOrder;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -26,4 +26,12 @@ public interface CtripOrderMapper extends BaseMapper<CtripOrder> {
* @return 订单信息
*/
CtripOrder selectBySupplierOrderId(@Param("supplierOrderId") String supplierOrderId);
/**
* 根据流水号查询订单
*
* @param sequenceId 流水号
* @return 订单信息
*/
CtripOrder selectBySequenceId(@Param("sequenceId") String sequenceId);
}
@@ -1,23 +1,39 @@
package com.central.coupon.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.entity.CtripPassenger;
import com.central.coupon.entity.CtripPassenger;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程乘客信息Mapper接口
* 携程乘客Mapper接口
*/
@Mapper
public interface CtripPassengerMapper extends BaseMapper<CtripPassenger> {
/**
* 根据订单项ID查询乘客列表
* 根据订单ID查询乘客列表
*
* @param orderItemId 订单项ID
* @param orderId 订单ID
* @return 乘客列表
*/
List<CtripPassenger> selectByOrderItemId(@Param("orderItemId") Long orderItemId);
List<CtripPassenger> selectByOrderId(@Param("orderId") Long orderId);
/**
* 根据订单项编号查询乘客列表
*
* @param itemId 订单项编号
* @return 乘客列表
*/
List<CtripPassenger> selectByItemId(@Param("itemId") String itemId);
/**
* 根据乘客ID查询乘客信息
*
* @param passengerId 乘客ID
* @return 乘客信息
*/
CtripPassenger selectByPassengerId(@Param("passengerId") String passengerId);
}
@@ -20,4 +20,12 @@ public interface CtripRefundItemMapper extends BaseMapper<CtripRefundItem> {
* @return 退款项列表
*/
List<CtripRefundItem> selectByRefundId(@Param("refundId") Long refundId);
/**
* 根据订单项编号查询退款项
*
* @param itemId 订单项编号
* @return 退款项列表
*/
List<CtripRefundItem> selectByItemId(@Param("itemId") String itemId);
}
@@ -5,6 +5,8 @@ import com.central.coupon.entity.CtripRefund;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程退款Mapper接口
*/
@@ -12,26 +14,26 @@ import org.apache.ibatis.annotations.Param;
public interface CtripRefundMapper extends BaseMapper<CtripRefund> {
/**
* 根据携程订单号查询退款信息
* 根据携程订单号查询退款记录
*
* @param otaOrderId 携程订单号
* @return 退款信息
* @return 退款记录列表
*/
CtripRefund selectByOtaOrderId(@Param("otaOrderId") String otaOrderId);
List<CtripRefund> selectByOtaOrderId(@Param("otaOrderId") String otaOrderId);
/**
* 根据供应商订单号查询退款信息
* 根据供应商订单号查询退款记录
*
* @param supplierOrderId 供应商订单号
* @return 退款信息
* @return 退款记录列表
*/
CtripRefund selectBySupplierOrderId(@Param("supplierOrderId") String supplierOrderId);
List<CtripRefund> selectBySupplierOrderId(@Param("supplierOrderId") String supplierOrderId);
/**
* 根据携程批次流水号查询退款信息
* 根据批次流水号查询退款记录
*
* @param sequenceId 携程批次流水号
* @return 退款信息
* @param sequenceId 批次流水号
* @return 退款记录
*/
CtripRefund selectBySequenceId(@Param("sequenceId") String sequenceId);
}
@@ -0,0 +1,47 @@
package com.central.coupon.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.coupon.entity.CtripVoucher;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 携程凭证Mapper接口
*/
@Mapper
public interface CtripVoucherMapper extends BaseMapper<CtripVoucher> {
/**
* 根据订单ID查询凭证列表
*
* @param orderId 订单ID
* @return 凭证列表
*/
List<CtripVoucher> selectByOrderId(@Param("orderId") Long orderId);
/**
* 根据订单项ID查询凭证列表
*
* @param itemId 订单项ID
* @return 凭证列表
*/
List<CtripVoucher> selectByItemId(@Param("itemId") String itemId);
/**
* 根据凭证编号查询凭证
*
* @param voucherId 凭证编号
* @return 凭证信息
*/
CtripVoucher selectByVoucherId(@Param("voucherId") String voucherId);
/**
* 根据凭证码查询凭证
*
* @param voucherCode 凭证码
* @return 凭证信息
*/
CtripVoucher selectByVoucherCode(@Param("voucherCode") String voucherCode);
}
@@ -1 +1,55 @@
package com.central.coupon.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 携程订单核销通知响应
* 当订单在新订确认后,供应商可将客人出行后的使用情况或归还物品等信息调用该接口将对应的最终结果同步给携程系统
*/
@Data
public class CtripConsumedNoticeResponse {
/**
* 携程返回头
*/
@JsonProperty("header")
private CtripResponseHeader header;
/**
* 携程返回体
*/
@JsonProperty("body")
private CtripResponseBody body;
/**
* 响应码
*/
@JsonProperty("resultCode")
private String resultCode;
/**
* 响应信息
*/
@JsonProperty("resultMessage")
private String resultMessage;
/**
* 携程返回头
*/
@Data
public static class CtripResponseHeader {
@JsonProperty("resultCode")
private String resultCode;
@JsonProperty("resultMessage")
private String resultMessage;
}
/**
* 携程返回体
*/
@Data
public static class CtripResponseBody {
// 核销通知响应体通常为空,因为这是一个通知接口
}
}
@@ -82,4 +82,13 @@ public interface ICouponService extends IService<Coupon> {
* 检查用户手机号和携程优惠券ID是否已存在
*/
boolean existsByUserPhoneAndCtripCouponId(String userPhone, String ctripCouponId);
/**
* 智能选择最优优惠券
*
* @param userPhone 用户手机号
* @param orderAmount 订单金额
* @return 最优优惠券,如果没有则返回null
*/
Coupon selectBestCoupon(String userPhone, java.math.BigDecimal orderAmount);
}
@@ -22,4 +22,33 @@ public interface ICtripApiService {
* @return 优惠券状态
*/
String getCouponStatus(String ctripCouponId);
/**
* 创建携程优惠券
*
* @param ctripCouponId 携程优惠券ID
* @param userPhone 用户手机号
* @param couponName 优惠券名称
* @param couponType 优惠券类型
* @param amount 优惠券面额
* @param minAmount 使用门槛金额
* @param discountRate 折扣率
* @param validStartTime 有效期开始时间
* @param validEndTime 有效期结束时间
* @return 创建结果
*/
boolean createCoupon(String ctripCouponId, String userPhone, String couponName,
Integer couponType, java.math.BigDecimal amount,
java.math.BigDecimal minAmount, Integer discountRate,
java.util.Date validStartTime, java.util.Date validEndTime);
/**
* 取消携程优惠券
*
* @param ctripCouponId 携程优惠券ID
* @param userPhone 用户手机号
* @param reason 取消原因
* @return 取消结果
*/
boolean cancelCoupon(String ctripCouponId, String userPhone, String reason);
}
@@ -9,6 +9,7 @@ import com.central.coupon.service.ICouponService;
import com.central.coupon.service.ICtripApiService;
import com.central.common.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -63,7 +64,11 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
IPage<Coupon> result = getCouponPage(page, coupon);
return new PageResult<>(result.getRecords(), result.getTotal());
return PageResult.<Coupon>builder()
.data(result.getRecords())
.count(result.getTotal())
.resp_code(0)
.build();
}
@Override
@@ -184,31 +189,49 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
@Override
@Transactional(rollbackFor = Exception.class)
public boolean verifyCtripCoupon(String ctripCouponId, String orderNo) {
log.info("开始核销携程优惠券,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
// 1. 查询优惠券
Coupon coupon = baseMapper.selectByCtripCouponId(ctripCouponId);
if (coupon == null) {
log.error("携程优惠券不存在,ctripCouponId: {}", ctripCouponId);
return false;
throw new CouponNotFoundException("优惠券不存在");
}
// 2. 验证优惠券状态
if (coupon.getStatus() != 0) {
log.error("携程优惠券状态不正确,ctripCouponId: {}, status: {}", ctripCouponId, coupon.getStatus());
return false;
throw new CouponInvalidException("优惠券状态不正确");
}
// 3. 验证有效期
if (coupon.getValidEndTime().before(new Date())) {
log.error("携程优惠券已过期,ctripCouponId: {}", ctripCouponId);
return false;
throw new CouponExpiredException("优惠券已过期");
}
// 调用携程核销接口
// 4. 验证使用条件
if (!validateCouponUsageConditions(coupon, orderNo)) {
log.error("携程优惠券使用条件不满足,ctripCouponId: {}", ctripCouponId);
throw new CouponUsageException("优惠券使用条件不满足");
}
// 5. 调用携程核销接口
boolean ctripVerifyResult = ctripApiService.verifyCoupon(ctripCouponId, orderNo);
if (!ctripVerifyResult) {
log.error("携程核销失败,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
return false;
throw new CouponVerifyException("携程核销失败");
}
// 更新本地优惠券状态
return baseMapper.updateCouponUsed(coupon.getId(), orderNo) > 0;
// 6. 更新本地优惠券状态
int updateResult = baseMapper.updateCouponUsed(coupon.getId(), orderNo);
if (updateResult <= 0) {
log.error("更新优惠券状态失败,couponId: {}, orderNo: {}", coupon.getId(), orderNo);
throw new CouponUpdateException("更新优惠券状态失败");
}
log.info("携程优惠券核销成功,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
return true;
}
@Override
@@ -224,10 +247,180 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
.count() > 0;
}
/**
* 智能选择最优优惠券
*/
@Override
public Coupon selectBestCoupon(String userPhone, java.math.BigDecimal orderAmount) {
log.info("开始智能选择优惠券,userPhone: {}, orderAmount: {}", userPhone, orderAmount);
// 1. 查询用户可用优惠券
List<Coupon> availableCoupons = getAvailableCouponsByUserPhone(userPhone);
if (availableCoupons.isEmpty()) {
log.warn("用户无可用优惠券,userPhone: {}", userPhone);
return null;
}
// 2. 按优先级排序
List<Coupon> sortedCoupons = availableCoupons.stream()
.filter(coupon -> validateCouponForOrder(coupon, orderAmount))
.sorted((c1, c2) -> compareCouponPriority(c1, c2, orderAmount))
.collect(java.util.stream.Collectors.toList());
if (sortedCoupons.isEmpty()) {
log.warn("无符合条件的优惠券,userPhone: {}, orderAmount: {}", userPhone, orderAmount);
return null;
}
Coupon bestCoupon = sortedCoupons.get(0);
log.info("选择最优优惠券,couponId: {}, amount: {}, discount: {}",
bestCoupon.getId(), bestCoupon.getAmount(), bestCoupon.getDiscountRate());
return bestCoupon;
}
/**
* 验证优惠券使用条件
*/
private boolean validateCouponUsageConditions(Coupon coupon, String orderNo) {
try {
// 1. 验证订单金额是否满足使用门槛
java.math.BigDecimal orderAmount = getOrderAmount(orderNo);
if (coupon.getMinAmount() != null && orderAmount.compareTo(coupon.getMinAmount()) < 0) {
log.warn("订单金额不满足优惠券使用门槛,orderAmount: {}, minAmount: {}",
orderAmount, coupon.getMinAmount());
return false;
}
// 2. 验证优惠券是否已被使用
if (coupon.getStatus() != 0) {
log.warn("优惠券已被使用,status: {}", coupon.getStatus());
return false;
}
// 3. 验证优惠券是否过期
if (coupon.getValidEndTime().before(new Date())) {
log.warn("优惠券已过期,validEndTime: {}", coupon.getValidEndTime());
return false;
}
// 4. 验证优惠券是否在有效期内
if (coupon.getValidStartTime().after(new Date())) {
log.warn("优惠券未到生效时间,validStartTime: {}", coupon.getValidStartTime());
return false;
}
return true;
} catch (Exception e) {
log.error("验证优惠券使用条件异常", e);
return false;
}
}
/**
* 验证优惠券是否适用于当前订单
*/
private boolean validateCouponForOrder(Coupon coupon, java.math.BigDecimal orderAmount) {
// 1. 验证订单金额是否满足使用门槛
if (coupon.getMinAmount() != null && orderAmount.compareTo(coupon.getMinAmount()) < 0) {
return false;
}
// 2. 验证优惠券状态
if (coupon.getStatus() != 0) {
return false;
}
// 3. 验证有效期
Date now = new Date();
if (coupon.getValidStartTime().after(now) || coupon.getValidEndTime().before(now)) {
return false;
}
return true;
}
/**
* 比较优惠券优先级
*/
private int compareCouponPriority(Coupon c1, Coupon c2, java.math.BigDecimal orderAmount) {
// 1. 优先选择满减券
if (c1.getCouponType() == 1 && c2.getCouponType() != 1) {
return -1;
}
if (c1.getCouponType() != 1 && c2.getCouponType() == 1) {
return 1;
}
// 2. 满减券按金额排序(金额大的优先)
if (c1.getCouponType() == 1 && c2.getCouponType() == 1) {
return c2.getAmount().compareTo(c1.getAmount());
}
// 3. 折扣券按折扣率排序(折扣率高的优先)
if (c1.getCouponType() == 2 && c2.getCouponType() == 2) {
return c2.getDiscountRate().compareTo(c1.getDiscountRate());
}
// 4. 按创建时间排序(先创建的优先)
return c1.getCreateTime().compareTo(c2.getCreateTime());
}
/**
* 获取订单金额
*/
private java.math.BigDecimal getOrderAmount(String orderNo) {
try {
// TODO: 调用订单服务获取订单金额
// 这里先返回一个默认值,实际应该调用订单服务
return new java.math.BigDecimal("100.00");
} catch (Exception e) {
log.error("获取订单金额失败,orderNo: {}", orderNo, e);
return java.math.BigDecimal.ZERO;
}
}
/**
* 生成优惠券编号
*/
private String generateCouponNo() {
return "CP" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
}
// 自定义异常类
public static class CouponNotFoundException extends RuntimeException {
public CouponNotFoundException(String message) {
super(message);
}
}
public static class CouponInvalidException extends RuntimeException {
public CouponInvalidException(String message) {
super(message);
}
}
public static class CouponExpiredException extends RuntimeException {
public CouponExpiredException(String message) {
super(message);
}
}
public static class CouponUsageException extends RuntimeException {
public CouponUsageException(String message) {
super(message);
}
}
public static class CouponVerifyException extends RuntimeException {
public CouponVerifyException(String message) {
super(message);
}
}
public static class CouponUpdateException extends RuntimeException {
public CouponUpdateException(String message) {
super(message);
}
}
}
@@ -1,8 +1,13 @@
package com.central.coupon.service.impl;
import com.central.coupon.service.ICtripApiService;
import com.central.coupon.util.CtripDecryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@@ -15,32 +20,88 @@ import java.util.Map;
@Service
public class CtripApiServiceImpl implements ICtripApiService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private CtripDecryptUtil ctripDecryptUtil;
@Value("${ctrip.api.base-url:https://api.ctrip.com}")
private String baseUrl;
@Value("${ctrip.api.timeout:30000}")
private int timeout;
@Value("${ctrip.api.retry-times:3}")
private int retryTimes;
@Value("${ctrip.account.id:your-account-id}")
private String accountId;
@Value("${ctrip.account.secret:your-account-secret}")
private String accountSecret;
@Override
public boolean verifyCoupon(String ctripCouponId, String orderNo) {
log.info("调用携程核销接口,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
try {
// TODO: 实现真实的携程API调用
// 这里应该调用携程的核销接口
// 目前先模拟成功返回
// 构建请求参数
Map<String, Object> requestParams = new HashMap<>();
requestParams.put("ctripCouponId", ctripCouponId);
requestParams.put("orderNo", orderNo);
requestParams.put("verifyTime", java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
log.info("携程核销请求参数: {}", requestParams);
// TODO: 发送HTTP请求到携程API
// String url = "https://api.ctrip.com/coupon/verify";
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_JSON);
// HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestParams, headers);
// ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
// 发送HTTP请求到携程API
String url = baseUrl + "/coupon/verify";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-CTRIP-ACCOUNT-ID", accountId);
headers.set("X-CTRIP-TIMESTAMP", String.valueOf(System.currentTimeMillis()));
// 模拟API调用成功
log.info("携程核销接口调用成功,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
return true;
// 生成签名
String sign = ctripDecryptUtil.generateSign(accountId, "VerifyCoupon",
java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
requestParams.toString(), "1.0");
headers.set("X-CTRIP-SIGN", sign);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestParams, headers);
// 重试机制
for (int i = 0; i < retryTimes; i++) {
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
if (response.getStatusCode() == HttpStatus.OK) {
Map<String, Object> responseBody = response.getBody();
if (responseBody != null && "0000".equals(responseBody.get("resultCode"))) {
log.info("携程核销接口调用成功,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
return true;
} else {
log.warn("携程核销接口返回失败,response: {}", responseBody);
}
} else {
log.warn("携程核销接口HTTP状态码异常,status: {}", response.getStatusCode());
}
} catch (Exception e) {
log.error("携程核销接口调用异常,第{}次重试,ctripCouponId: {}, orderNo: {}", i + 1, ctripCouponId, orderNo, e);
if (i == retryTimes - 1) {
throw e;
}
// 等待后重试
try {
Thread.sleep(1000 * (i + 1));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
log.error("携程核销接口调用失败,已重试{}次,ctripCouponId: {}, orderNo: {}", retryTimes, ctripCouponId, orderNo);
return false;
} catch (Exception e) {
log.error("携程核销接口调用失败,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo, e);
@@ -53,30 +114,217 @@ public class CtripApiServiceImpl implements ICtripApiService {
log.info("调用携程查询优惠券状态接口,ctripCouponId: {}", ctripCouponId);
try {
// TODO: 实现真实的携程API调用
// 这里应该调用携程的查询接口
// 目前先模拟返回状态
// 构建请求参数
Map<String, Object> requestParams = new HashMap<>();
requestParams.put("ctripCouponId", ctripCouponId);
log.info("携程查询请求参数: {}", requestParams);
// TODO: 发送HTTP请求到携程API
// String url = "https://api.ctrip.com/coupon/status";
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_JSON);
// HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestParams, headers);
// ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
// 发送HTTP请求到携程API
String url = baseUrl + "/coupon/status";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-CTRIP-ACCOUNT-ID", accountId);
headers.set("X-CTRIP-TIMESTAMP", String.valueOf(System.currentTimeMillis()));
// 模拟API调用成功,返回状态
log.info("携程查询接口调用成功,ctripCouponId: {}", ctripCouponId);
return "VALID"; // 模拟返回有效状态
// 生成签名
String sign = ctripDecryptUtil.generateSign(accountId, "GetCouponStatus",
java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
requestParams.toString(), "1.0");
headers.set("X-CTRIP-SIGN", sign);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestParams, headers);
// 重试机制
for (int i = 0; i < retryTimes; i++) {
try {
ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
if (response.getStatusCode() == HttpStatus.OK) {
Map<String, Object> responseBody = response.getBody();
if (responseBody != null && "0000".equals(responseBody.get("resultCode"))) {
String status = (String) responseBody.get("status");
log.info("携程查询接口调用成功,ctripCouponId: {}, status: {}", ctripCouponId, status);
return status;
} else {
log.warn("携程查询接口返回失败,response: {}", responseBody);
}
} else {
log.warn("携程查询接口HTTP状态码异常,status: {}", response.getStatusCode());
}
} catch (Exception e) {
log.error("携程查询接口调用异常,第{}次重试,ctripCouponId: {}", i + 1, ctripCouponId, e);
if (i == retryTimes - 1) {
throw e;
}
// 等待后重试
try {
Thread.sleep(1000 * (i + 1));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
log.error("携程查询接口调用失败,已重试{}次,ctripCouponId: {}", retryTimes, ctripCouponId);
return "UNKNOWN";
} catch (Exception e) {
log.error("携程查询接口调用失败,ctripCouponId: {}", ctripCouponId, e);
return "UNKNOWN";
}
}
/**
* 创建优惠券
*/
@Override
public boolean createCoupon(String ctripCouponId, String userPhone, String couponName,
Integer couponType, java.math.BigDecimal amount,
java.math.BigDecimal minAmount, Integer discountRate,
java.util.Date validStartTime, java.util.Date validEndTime) {
log.info("调用携程创建优惠券接口,ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone);
try {
// 构建请求参数
Map<String, Object> requestParams = new HashMap<>();
requestParams.put("ctripCouponId", ctripCouponId);
requestParams.put("userPhone", userPhone);
requestParams.put("couponName", couponName);
requestParams.put("couponType", couponType);
requestParams.put("amount", amount);
requestParams.put("minAmount", minAmount);
requestParams.put("discountRate", discountRate);
requestParams.put("validStartTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(validStartTime));
requestParams.put("validEndTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(validEndTime));
log.info("携程创建优惠券请求参数: {}", requestParams);
// 发送HTTP请求到携程API
String url = baseUrl + "/coupon/create";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-CTRIP-ACCOUNT-ID", accountId);
headers.set("X-CTRIP-TIMESTAMP", String.valueOf(System.currentTimeMillis()));
// 生成签名
String sign = ctripDecryptUtil.generateSign(accountId, "CreateCoupon",
java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
requestParams.toString(), "1.0");
headers.set("X-CTRIP-SIGN", sign);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestParams, headers);
// 重试机制
for (int i = 0; i < retryTimes; i++) {
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
if (response.getStatusCode() == HttpStatus.OK) {
Map<String, Object> responseBody = response.getBody();
if (responseBody != null && "0000".equals(responseBody.get("resultCode"))) {
log.info("携程创建优惠券接口调用成功,ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone);
return true;
} else {
log.warn("携程创建优惠券接口返回失败,response: {}", responseBody);
}
} else {
log.warn("携程创建优惠券接口HTTP状态码异常,status: {}", response.getStatusCode());
}
} catch (Exception e) {
log.error("携程创建优惠券接口调用异常,第{}次重试,ctripCouponId: {}, userPhone: {}", i + 1, ctripCouponId, userPhone, e);
if (i == retryTimes - 1) {
throw e;
}
// 等待后重试
try {
Thread.sleep(1000 * (i + 1));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
log.error("携程创建优惠券接口调用失败,已重试{}次,ctripCouponId: {}, userPhone: {}", retryTimes, ctripCouponId, userPhone);
return false;
} catch (Exception e) {
log.error("携程创建优惠券接口调用失败,ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone, e);
return false;
}
}
/**
* 取消优惠券
*/
@Override
public boolean cancelCoupon(String ctripCouponId, String userPhone, String reason) {
log.info("调用携程取消优惠券接口,ctripCouponId: {}, userPhone: {}, reason: {}", ctripCouponId, userPhone, reason);
try {
// 构建请求参数
Map<String, Object> requestParams = new HashMap<>();
requestParams.put("ctripCouponId", ctripCouponId);
requestParams.put("userPhone", userPhone);
requestParams.put("reason", reason);
requestParams.put("cancelTime", java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
log.info("携程取消优惠券请求参数: {}", requestParams);
// 发送HTTP请求到携程API
String url = baseUrl + "/coupon/cancel";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-CTRIP-ACCOUNT-ID", accountId);
headers.set("X-CTRIP-TIMESTAMP", String.valueOf(System.currentTimeMillis()));
// 生成签名
String sign = ctripDecryptUtil.generateSign(accountId, "CancelCoupon",
java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
requestParams.toString(), "1.0");
headers.set("X-CTRIP-SIGN", sign);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestParams, headers);
// 重试机制
for (int i = 0; i < retryTimes; i++) {
try {
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
if (response.getStatusCode() == HttpStatus.OK) {
Map<String, Object> responseBody = response.getBody();
if (responseBody != null && "0000".equals(responseBody.get("resultCode"))) {
log.info("携程取消优惠券接口调用成功,ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone);
return true;
} else {
log.warn("携程取消优惠券接口返回失败,response: {}", responseBody);
}
} else {
log.warn("携程取消优惠券接口HTTP状态码异常,status: {}", response.getStatusCode());
}
} catch (Exception e) {
log.error("携程取消优惠券接口调用异常,第{}次重试,ctripCouponId: {}, userPhone: {}", i + 1, ctripCouponId, userPhone, e);
if (i == retryTimes - 1) {
throw e;
}
// 等待后重试
try {
Thread.sleep(1000 * (i + 1));
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
log.error("携程取消优惠券接口调用失败,已重试{}次,ctripCouponId: {}, userPhone: {}", retryTimes, ctripCouponId, userPhone);
return false;
} catch (Exception e) {
log.error("携程取消优惠券接口调用失败,ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone, e);
return false;
}
}
}
@@ -1,42 +1,22 @@
package com.central.coupon.service.impl;
import com.central.coupon.model.CtripCreateOrderRequest;
import com.central.coupon.model.CtripCreateOrderResponse;
import com.central.coupon.model.CtripCancelOrderRequest;
import com.central.coupon.model.CtripCancelOrderResponse;
import com.central.coupon.model.CtripCancelOrderConfirmRequest;
import com.central.coupon.model.CtripCancelOrderConfirmResponse;
import com.central.coupon.model.CtripRefundOrderRequest;
import com.central.coupon.model.CtripRefundOrderResponse;
import com.central.coupon.model.CtripRefundOrderConfirmRequest;
import com.central.coupon.model.CtripRefundOrderConfirmResponse;
import com.central.coupon.model.CtripConsumedNoticeRequest;
import com.central.coupon.model.CtripConsumedNoticeResponse;
import com.central.coupon.service.ICtripOrderService;
import com.central.coupon.service.ICouponService;
import com.central.coupon.util.CtripResponseCodeUtil;
import com.central.coupon.entity.Coupon;
import com.central.coupon.entity.CtripOrder;
import com.central.coupon.entity.CtripOrderItem;
import com.central.coupon.entity.CtripRefund;
import com.central.coupon.entity.CtripRefundItem;
import com.central.coupon.entity.CtripConsumed;
import com.central.coupon.entity.CtripConsumedPassenger;
import com.central.coupon.entity.CtripConsumedVoucher;
import com.central.coupon.entity.CtripOrder;
import com.central.coupon.entity.CtripOrderItem;
import com.central.coupon.entity.CtripPassenger;
import com.central.coupon.entity.CtripContact;
import com.central.coupon.entity.CtripCoupon;
import com.central.coupon.entity.CtripVoucher;
import com.central.coupon.mapper.CtripRefundMapper;
import com.central.coupon.mapper.CtripRefundItemMapper;
import com.central.coupon.mapper.CtripConsumedMapper;
import com.central.coupon.mapper.CtripConsumedPassengerMapper;
import com.central.coupon.mapper.CtripConsumedVoucherMapper;
import com.central.coupon.mapper.CtripOrderMapper;
import com.central.coupon.mapper.CtripOrderItemMapper;
import com.central.coupon.mapper.CtripPassengerMapper;
import com.central.coupon.mapper.CtripContactMapper;
import com.central.coupon.mapper.CtripCouponMapper;
import com.central.coupon.mapper.CtripVoucherMapper;
import com.central.coupon.service.ICouponService;
import com.central.coupon.service.ICtripOrderService;
import com.central.coupon.model.*;
import com.central.coupon.mapper.*;
import com.central.coupon.util.CtripResponseCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@@ -44,6 +24,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@@ -112,9 +93,15 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
// 3. 处理优惠券信息
if (body.getCoupons() != null && !body.getCoupons().isEmpty()) {
boolean couponResult = processCoupons(body.getCoupons(), body.getOtaOrderId());
if (!couponResult) {
log.warn("优惠券处理失败,但订单创建成功,otaOrderId: {}", body.getOtaOrderId());
// 查询订单ID
CtripOrder order = ctripOrderMapper.selectByOtaOrderId(body.getOtaOrderId());
if (order != null) {
boolean couponResult = processCoupons(body.getCoupons(), order.getId());
if (!couponResult) {
log.warn("优惠券处理失败,但订单创建成功,otaOrderId: {}", body.getOtaOrderId());
}
} else {
log.warn("订单不存在,无法处理优惠券,otaOrderId: {}", body.getOtaOrderId());
}
}
@@ -197,8 +184,8 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
try {
// 查询数据库,检查订单是否已存在且已下单成功
CtripOrder existingOrder = ctripOrderMapper.selectByOtaOrderId(otaOrderId);
if (existingOrder != null && existingOrder.getOrderStatus() != null && existingOrder.getOrderStatus() == 1) {
log.info("订单已存在且已确认,otaOrderId: {}, orderStatus: {}", otaOrderId, existingOrder.getOrderStatus());
if (existingOrder != null && existingOrder.getStatus() != null && existingOrder.getStatus() == 1) {
log.info("订单已存在且已确认,otaOrderId: {}, status: {}", otaOrderId, existingOrder.getStatus());
return true;
}
@@ -266,13 +253,13 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
}
// 2. 检查订单状态
if (order.getOrderStatus() == 2) {
if (order.getStatus() == 2) {
log.warn("订单已取消,无需重复取消,otaOrderId: {}", body.getOtaOrderId());
return true;
}
// 3. 更新订单状态为已取消
order.setOrderStatus(2); // 已取消
order.setStatus(2); // 已取消
order.setUpdateTime(LocalDateTime.now());
order.setUpdateBy("SYSTEM");
@@ -289,7 +276,7 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
CtripOrderItem orderItem = ctripOrderItemMapper.selectByOrderIdAndItemId(order.getId(), cancelItem.getItemId());
if (orderItem != null) {
// 更新订单项数量(减少取消的数量)
int newQuantity = orderItem.getQuantity() - cancelItem.getCancelQuantity();
int newQuantity = orderItem.getQuantity() - cancelItem.getQuantity();
if (newQuantity >= 0) {
orderItem.setQuantity(newQuantity);
orderItem.setUpdateTime(LocalDateTime.now());
@@ -330,12 +317,21 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
order.setOtaOrderId(body.getOtaOrderId());
order.setSupplierOrderId(generateSupplierOrderId(body.getOtaOrderId()));
order.setSequenceId(body.getSequenceId());
order.setOrderStatus(0); // 待确认
order.setTotalAmount(body.getTotalAmount());
order.setCurrency(body.getTotalAmountCurrency());
order.setStatus(0); // 待确认
// 计算总金额(从订单项中计算)
java.math.BigDecimal totalAmount = java.math.BigDecimal.ZERO;
if (body.getItems() != null) {
for (CtripCreateOrderRequest.CtripOrderItem item : body.getItems()) {
if (item.getPrice() != null) {
totalAmount = totalAmount.add(item.getPrice().multiply(new java.math.BigDecimal(item.getQuantity())));
}
}
}
order.setTotalAmount(totalAmount);
order.setCurrency("CNY"); // 默认货币
order.setConfirmType(body.getConfirmType());
order.setLastConfirmTime(body.getLastConfirmTime() != null ?
LocalDateTime.parse(body.getLastConfirmTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null);
order.setOrderLastConfirmTime(body.getOrderLastConfirmTime() != null ?
LocalDateTime.parse(body.getOrderLastConfirmTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null);
order.setCreateTime(LocalDateTime.now());
order.setUpdateTime(LocalDateTime.now());
order.setCreateBy("SYSTEM");
@@ -351,12 +347,12 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
CtripOrderItem orderItem = new CtripOrderItem();
orderItem.setOrderId(order.getId());
orderItem.setItemId(item.getItemId());
orderItem.setItemName(item.getItemName());
orderItem.setItemType(item.getItemType());
orderItem.setItemName("订单项-" + item.getItemId()); // 使用itemId作为名称
orderItem.setItemType("1"); // 默认类型
orderItem.setQuantity(item.getQuantity());
orderItem.setUnitPrice(item.getUnitPrice());
orderItem.setTotalPrice(item.getTotalPrice());
orderItem.setCurrency(item.getTotalPriceCurrency());
orderItem.setUnitPrice(item.getPrice());
orderItem.setTotalPrice(item.getPrice().multiply(new java.math.BigDecimal(item.getQuantity())));
orderItem.setCurrency(item.getPriceCurrency());
orderItem.setUseStartDate(item.getUseStartDate() != null ?
LocalDate.parse(item.getUseStartDate()) : null);
orderItem.setUseEndDate(item.getUseEndDate() != null ?
@@ -369,23 +365,25 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
}
}
// 3. 保存乘客信息
if (body.getPassengers() != null && !body.getPassengers().isEmpty()) {
for (CtripCreateOrderRequest.CtripPassenger passenger : body.getPassengers()) {
CtripPassenger passengerEntity = new CtripPassenger();
passengerEntity.setOrderId(order.getId());
passengerEntity.setItemId(passenger.getItemId());
passengerEntity.setPassengerId(passenger.getPassengerId());
passengerEntity.setPassengerName(passenger.getPassengerName());
passengerEntity.setPassengerType(passenger.getPassengerType());
passengerEntity.setIdType(passenger.getIdType());
passengerEntity.setIdNumber(passenger.getIdNumber());
passengerEntity.setPhone(passenger.getPhone());
passengerEntity.setCreateTime(LocalDateTime.now());
passengerEntity.setUpdateTime(LocalDateTime.now());
ctripPassengerMapper.insert(passengerEntity);
log.info("乘客信息保存成功,passengerId: {}", passenger.getPassengerId());
// 3. 保存乘客信息(从订单项中获取)
for (CtripCreateOrderRequest.CtripOrderItem item : body.getItems()) {
if (item.getPassengers() != null && !item.getPassengers().isEmpty()) {
for (CtripCreateOrderRequest.CtripPassenger passenger : item.getPassengers()) {
CtripPassenger passengerEntity = new CtripPassenger();
passengerEntity.setOrderId(order.getId());
passengerEntity.setItemId(item.getItemId());
passengerEntity.setPassengerId(passenger.getPassengerId());
passengerEntity.setPassengerName(passenger.getName());
passengerEntity.setPassengerType(passenger.getAgeType());
passengerEntity.setIdType(passenger.getCardType());
passengerEntity.setIdNumber(passenger.getCardNo());
passengerEntity.setPhone(passenger.getMobile());
passengerEntity.setCreateTime(LocalDateTime.now());
passengerEntity.setUpdateTime(LocalDateTime.now());
ctripPassengerMapper.insert(passengerEntity);
log.info("乘客信息保存成功,passengerId: {}", passenger.getPassengerId());
}
}
}
@@ -394,15 +392,15 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
for (CtripCreateOrderRequest.CtripContact contact : body.getContacts()) {
CtripContact contactEntity = new CtripContact();
contactEntity.setOrderId(order.getId());
contactEntity.setContactName(contact.getContactName());
contactEntity.setContactPhone(contact.getContactPhone());
contactEntity.setContactEmail(contact.getContactEmail());
contactEntity.setContactType(contact.getContactType());
contactEntity.setName(contact.getName());
contactEntity.setMobile(contact.getMobile());
contactEntity.setEmail(contact.getEmail());
contactEntity.setContactType("1"); // 默认类型
contactEntity.setCreateTime(LocalDateTime.now());
contactEntity.setUpdateTime(LocalDateTime.now());
ctripContactMapper.insert(contactEntity);
log.info("联系人信息保存成功,contactName: {}", contact.getContactName());
log.info("联系人信息保存成功,contactName: {}", contact.getName());
}
}
@@ -439,11 +437,11 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
// 2. 保存优惠券使用记录
CtripCoupon couponEntity = new CtripCoupon();
couponEntity.setOrderId(orderId);
couponEntity.setCouponType(coupon.getType());
couponEntity.setCouponType(String.valueOf(coupon.getType()));
couponEntity.setCouponCode(coupon.getCode());
couponEntity.setCouponName(coupon.getName());
couponEntity.setCouponAmount(coupon.getAmount());
couponEntity.setCurrency(coupon.getCurrency());
couponEntity.setCurrency(coupon.getAmountCurrency());
couponEntity.setCouponStatus(2); // 已使用
couponEntity.setUseTime(LocalDateTime.now());
couponEntity.setCreateTime(LocalDateTime.now());
@@ -466,10 +464,83 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
* 验证优惠券有效性
*/
private boolean validateCoupon(CtripCreateOrderRequest.CtripCoupon coupon) {
// TODO: 实现优惠券验证逻辑
// 这里应该调用优惠券服务验证优惠券是否有效
log.info("验证优惠券: code={}, type={}", coupon.getCode(), coupon.getType());
return true; // 暂时返回true,实际应该调用优惠券服务验证
log.info("验证优惠券: code={}, type={}, name={}, amount={}",
coupon.getCode(), coupon.getType(), coupon.getName(), coupon.getAmount());
try {
// 1. 基础验证
if (coupon.getCode() == null || coupon.getCode().trim().isEmpty()) {
log.warn("优惠券代码为空");
return false;
}
if (coupon.getAmount() == null || coupon.getAmount().compareTo(java.math.BigDecimal.ZERO) <= 0) {
log.warn("优惠券金额无效: {}", coupon.getAmount());
return false;
}
// 2. 验证优惠券类型
if (coupon.getType() == null || (coupon.getType() != 1 && coupon.getType() != 2 && coupon.getType() != 3)) {
log.warn("优惠券类型无效: {}", coupon.getType());
return false;
}
// 3. 验证优惠券名称
if (coupon.getName() == null || coupon.getName().trim().isEmpty()) {
log.warn("优惠券名称为空");
return false;
}
// 4. 验证货币类型
if (coupon.getAmountCurrency() == null || coupon.getAmountCurrency().trim().isEmpty()) {
log.warn("优惠券货币类型为空");
return false;
}
// 5. 调用优惠券服务验证
if (couponService != null) {
try {
// 查询优惠券是否存在
Coupon existingCoupon = couponService.getByCtripCouponId(coupon.getCode());
if (existingCoupon == null) {
log.warn("优惠券不存在,code: {}", coupon.getCode());
return false;
}
// 验证优惠券状态
if (existingCoupon.getStatus() != 0) {
log.warn("优惠券状态不正确,code: {}, status: {}", coupon.getCode(), existingCoupon.getStatus());
return false;
}
// 验证优惠券有效期
if (existingCoupon.getValidEndTime().before(new java.util.Date())) {
log.warn("优惠券已过期,code: {}", coupon.getCode());
return false;
}
// 验证优惠券金额是否匹配
if (!existingCoupon.getAmount().equals(coupon.getAmount())) {
log.warn("优惠券金额不匹配,本地: {}, 请求: {}", existingCoupon.getAmount(), coupon.getAmount());
return false;
}
log.info("优惠券验证通过: code={}", coupon.getCode());
return true;
} catch (Exception e) {
log.warn("优惠券服务验证异常: {}", e.getMessage());
// 服务不可用时,使用基础验证
}
}
// 6. 基础验证通过
log.info("优惠券基础验证通过: code={}", coupon.getCode());
return true;
} catch (Exception e) {
log.error("优惠券验证异常: code={}", coupon.getCode(), e);
return false;
}
}
@Override
@@ -513,7 +584,6 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
for (CtripCreateOrderRequest.CtripPassenger passenger : item.getPassengers()) {
CtripCreateOrderResponse.CtripPassengerVoucher passengerVoucher = new CtripCreateOrderResponse.CtripPassengerVoucher();
passengerVoucher.setPassengerId(passenger.getPassengerId());
passengerVoucher.setVoucherId(generateVoucherId(supplierOrderId, item.getItemId()));
passengerVouchers.add(passengerVoucher);
}
}
@@ -768,8 +838,8 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
}
// 2. 检查订单状态
if (order.getOrderStatus() != 2) {
log.warn("订单状态不是已取消,无法确认,otaOrderId: {}, orderStatus: {}", body.getOtaOrderId(), order.getOrderStatus());
if (order.getStatus() != 2) {
log.warn("订单状态不是已取消,无法确认,otaOrderId: {}, status: {}", body.getOtaOrderId(), order.getStatus());
return false;
}
@@ -779,7 +849,7 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
log.info("取消确认成功,otaOrderId: {}", body.getOtaOrderId());
} else {
// 确认失败,恢复订单状态为已确认
order.setOrderStatus(1); // 已确认
order.setStatus(1); // 已确认
order.setUpdateTime(LocalDateTime.now());
order.setUpdateBy("SYSTEM");
@@ -926,9 +996,9 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
refund.setOtaOrderId(body.getOtaOrderId());
refund.setSupplierOrderId(body.getSupplierOrderId());
refund.setSequenceId(body.getSequenceId());
refund.setTotalAmount(body.getTotalAmount());
refund.setTotalAmountCurrency(body.getTotalAmountCurrency());
refund.setStatus(0); // 待确认
refund.setRefundAmount(body.getTotalAmount());
refund.setCurrency(body.getTotalAmountCurrency());
refund.setRefundStatus(0); // 待确认
refund.setCreateTime(LocalDateTime.now());
refund.setUpdateTime(LocalDateTime.now());
refund.setCreateBy("SYSTEM");
@@ -960,13 +1030,11 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
refundItem.setRefundId(refund.getId());
refundItem.setItemId(item.getItemId());
refundItem.setPlu(item.getPLU());
refundItem.setAmount(item.getAmount());
refundItem.setAmountCurrency(item.getAmountCurrency());
refundItem.setRefundAmount(item.getAmount());
refundItem.setCurrency(item.getAmountCurrency());
refundItem.setCreateTime(LocalDateTime.now());
refundItem.setUpdateTime(LocalDateTime.now());
refundItem.setCreateBy("SYSTEM");
refundItem.setUpdateBy("SYSTEM");
refundItem.setRemark("退款项目");
// CtripRefundItem 没有 createBy, updateBy, remark 字段
boolean itemSaveResult = ctripRefundItemMapper.insert(refundItem) > 0;
if (!itemSaveResult) {
@@ -1099,8 +1167,8 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
java.math.BigDecimal totalRefunded = java.math.BigDecimal.ZERO;
for (CtripRefund refund : refunds) {
if (refund.getTotalAmount() != null) {
totalRefunded = totalRefunded.add(refund.getTotalAmount());
if (refund.getRefundAmount() != null) {
totalRefunded = totalRefunded.add(refund.getRefundAmount());
}
}
@@ -1134,13 +1202,13 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
}
// 2. 检查退款状态
if (refund.getStatus() != null && refund.getStatus() != 0) {
log.warn("退款已处理,当前状态: {}, sequenceId: {}", refund.getStatus(), body.getSequenceId());
if (refund.getRefundStatus() != null && refund.getRefundStatus() != 0) {
log.warn("退款已处理,当前状态: {}, sequenceId: {}", refund.getRefundStatus(), body.getSequenceId());
return true; // 已处理过,返回成功
}
// 3. 更新退款状态
refund.setStatus("0000".equals(body.getConfirmResultCode()) ? 1 : 2); // 1-已确认,2-已拒绝
refund.setRefundStatus("0000".equals(body.getConfirmResultCode()) ? 1 : 2); // 1-已确认,2-已拒绝
refund.setConfirmResultCode(body.getConfirmResultCode());
refund.setConfirmResultMessage(body.getConfirmResultMessage());
refund.setUpdateTime(LocalDateTime.now());
@@ -1247,19 +1315,19 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
consumed.setSupplierOrderId(body.getSupplierOrderId());
consumed.setSequenceId(body.getSequenceId());
consumed.setItemId(item.getItemId());
consumed.setUseStartDate(item.getUseStartDate());
consumed.setUseEndDate(item.getUseEndDate());
consumed.setQuantity(item.getQuantity());
consumed.setUseStartDate(item.getUseStartDate() != null ?
LocalDate.parse(item.getUseStartDate()) : null);
consumed.setUseEndDate(item.getUseEndDate() != null ?
LocalDate.parse(item.getUseEndDate()) : null);
consumed.setTotalQuantity(item.getQuantity());
consumed.setUseQuantity(item.getUseQuantity());
consumed.setLostAmount(item.getLostAmount());
consumed.setLostAmountCurrency(item.getLostAmountCurrency());
consumed.setRemark(item.getRemark());
consumed.setStatus(item.getUseQuantity() >= item.getQuantity() ? 1 : 2); // 1-已核销,2-部分核销
consumed.setCreateTime(LocalDateTime.now());
consumed.setUpdateTime(LocalDateTime.now());
consumed.setCreateBy("SYSTEM");
consumed.setUpdateBy("SYSTEM");
consumed.setRemarkDetail("携程核销通知");
// 3. 保存核销记录
boolean saveResult = ctripConsumedMapper.insert(consumed) > 0;
@@ -1276,9 +1344,7 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
consumedPassenger.setPassengerId(passenger.getPassengerId());
consumedPassenger.setCreateTime(LocalDateTime.now());
consumedPassenger.setUpdateTime(LocalDateTime.now());
consumedPassenger.setCreateBy("SYSTEM");
consumedPassenger.setUpdateBy("SYSTEM");
consumedPassenger.setRemark("核销乘客");
// CtripConsumedPassenger 没有 createBy, updateBy, remark 字段
boolean passengerSaveResult = ctripConsumedPassengerMapper.insert(consumedPassenger) > 0;
if (!passengerSaveResult) {
@@ -1296,9 +1362,7 @@ public class CtripOrderServiceImpl implements ICtripOrderService {
consumedVoucher.setVoucherId(voucher.getVoucherId());
consumedVoucher.setCreateTime(LocalDateTime.now());
consumedVoucher.setUpdateTime(LocalDateTime.now());
consumedVoucher.setCreateBy("SYSTEM");
consumedVoucher.setUpdateBy("SYSTEM");
consumedVoucher.setRemark("核销凭证");
// CtripConsumedVoucher 没有 createBy, updateBy, remark 字段
boolean voucherSaveResult = ctripConsumedVoucherMapper.insert(consumedVoucher) > 0;
if (!voucherSaveResult) {
@@ -0,0 +1,47 @@
package com.central.coupon.task;
import com.central.coupon.service.ICouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 优惠券过期处理定时任务
*/
@Slf4j
@Component
public class CouponExpireTask {
@Autowired
private ICouponService couponService;
/**
* 每天凌晨2点执行过期优惠券处理
*/
@Scheduled(cron = "0 0 2 * * ?")
public void processExpiredCoupons() {
log.info("开始处理过期优惠券");
try {
couponService.updateExpiredCoupons();
log.info("过期优惠券处理完成");
} catch (Exception e) {
log.error("处理过期优惠券异常", e);
}
}
/**
* 每小时检查一次即将过期的优惠券
*/
@Scheduled(cron = "0 0 * * * ?")
public void checkExpiringCoupons() {
log.info("开始检查即将过期的优惠券");
try {
// TODO: 实现即将过期优惠券的检查和通知
// 可以发送短信或邮件通知用户
log.info("即将过期优惠券检查完成");
} catch (Exception e) {
log.error("检查即将过期优惠券异常", e);
}
}
}
@@ -10,173 +10,135 @@ public class CtripResponseCodeUtil {
* 携程响应码
*/
public static class CtripResponseCodes {
// 成功码
// 成功响应码
public static final String SUCCESS = "0000";
public static final String SUCCESS_MESSAGE = "操作成功";
// 系统错误码 (1xxx)
public static final String SYSTEM_ERROR = "1001";
public static final String SYSTEM_ERROR_MESSAGE = "系统错误";
public static final String PARAM_ERROR = "1002";
public static final String PARAM_ERROR_MESSAGE = "参数错误";
// 参数错误
public static final String PARAM_ERROR = "1001";
public static final String DATA_INVALID = "1002";
public static final String SIGN_ERROR = "1003";
public static final String SIGN_ERROR_MESSAGE = "签名验证失败";
public static final String DATA_INVALID = "1004";
public static final String DATA_INVALID_MESSAGE = "数据格式错误";
public static final String TIMEOUT_ERROR = "1005";
public static final String TIMEOUT_ERROR_MESSAGE = "请求超时";
public static final String SERVICE_UNAVAILABLE = "1006";
public static final String SERVICE_UNAVAILABLE_MESSAGE = "服务不可用";
// 业务错误码 (2xxx)
// 订单相关错误
public static final String ORDER_NOT_FOUND = "2001";
public static final String ORDER_NOT_FOUND_MESSAGE = "订单不存在";
public static final String ORDER_STATUS_ERROR = "2002";
public static final String ORDER_STATUS_ERROR_MESSAGE = "订单状态错误";
public static final String COUPON_NOT_FOUND = "2003";
public static final String COUPON_NOT_FOUND_MESSAGE = "优惠券不存在";
public static final String COUPON_ALREADY_USED = "2004";
public static final String COUPON_ALREADY_USED_MESSAGE = "优惠券已使用";
public static final String COUPON_EXPIRED = "2005";
public static final String COUPON_EXPIRED_MESSAGE = "优惠券已过期";
public static final String COUPON_INSUFFICIENT = "2006";
public static final String COUPON_INSUFFICIENT_MESSAGE = "优惠券余额不足";
public static final String USER_NOT_FOUND = "2007";
public static final String USER_NOT_FOUND_MESSAGE = "用户不存在";
public static final String PRODUCT_NOT_FOUND = "2008";
public static final String PRODUCT_NOT_FOUND_MESSAGE = "产品不存在";
public static final String INVENTORY_INSUFFICIENT = "2009";
public static final String INVENTORY_INSUFFICIENT_MESSAGE = "库存不足";
public static final String PRICE_ERROR = "2010";
public static final String PRICE_ERROR_MESSAGE = "价格错误";
public static final String CONFIRM_TIME_EXPIRED = "2011";
public static final String CONFIRM_TIME_EXPIRED_MESSAGE = "确认时间已过期";
public static final String DUPLICATE_ORDER = "2012";
public static final String DUPLICATE_ORDER_MESSAGE = "重复订单";
public static final String VOUCHER_GENERATE_ERROR = "2013";
public static final String VOUCHER_GENERATE_ERROR_MESSAGE = "凭证生成失败";
public static final String PASSENGER_INFO_ERROR = "2014";
public static final String PASSENGER_INFO_ERROR_MESSAGE = "乘客信息错误";
public static final String CONTACT_INFO_ERROR = "2015";
public static final String CONTACT_INFO_ERROR_MESSAGE = "联系人信息错误";
public static final String PAYMENT_ERROR = "2016";
public static final String PAYMENT_ERROR_MESSAGE = "支付错误";
public static final String REFUND_ERROR = "2017";
public static final String REFUND_ERROR_MESSAGE = "退款错误";
public static final String CONSUMED_ERROR = "2018";
public static final String CONSUMED_ERROR_MESSAGE = "核销错误";
public static final String CANCEL_ERROR = "2019";
public static final String CANCEL_ERROR_MESSAGE = "取消错误";
public static final String MODIFY_ERROR = "2020";
public static final String MODIFY_ERROR_MESSAGE = "修改错误";
public static final String ORDER_ALREADY_EXISTS = "2002";
public static final String ORDER_STATUS_ERROR = "2003";
public static final String ORDER_CANCEL_FAILED = "2004";
public static final String ORDER_REFUND_FAILED = "2005";
public static final String CANCEL_ERROR = "2006";
public static final String REFUND_ERROR = "2007";
public static final String CONSUMED_ERROR = "2008";
// 优惠券相关错误
public static final String COUPON_NOT_FOUND = "3001";
public static final String COUPON_EXPIRED = "3002";
public static final String COUPON_USED = "3003";
public static final String COUPON_INVALID = "3004";
public static final String COUPON_VERIFY_FAILED = "3005";
// 库存相关错误
public static final String INVENTORY_NOT_ENOUGH = "4001";
public static final String INVENTORY_LOCKED = "4002";
// 系统错误
public static final String SYSTEM_ERROR = "9999";
public static final String NETWORK_ERROR = "9998";
public static final String TIMEOUT_ERROR = "9997";
}
/**
* 根据错误码获取错误信息
* 获取错误码对应的错误信息
*/
public static String getErrorMessage(String errorCode) {
switch (errorCode) {
case CtripResponseCodes.SUCCESS:
return CtripResponseCodes.SUCCESS_MESSAGE;
case CtripResponseCodes.SYSTEM_ERROR:
return CtripResponseCodes.SYSTEM_ERROR_MESSAGE;
return "操作成功";
case CtripResponseCodes.PARAM_ERROR:
return CtripResponseCodes.PARAM_ERROR_MESSAGE;
case CtripResponseCodes.SIGN_ERROR:
return CtripResponseCodes.SIGN_ERROR_MESSAGE;
return "参数错误";
case CtripResponseCodes.DATA_INVALID:
return CtripResponseCodes.DATA_INVALID_MESSAGE;
case CtripResponseCodes.TIMEOUT_ERROR:
return CtripResponseCodes.TIMEOUT_ERROR_MESSAGE;
case CtripResponseCodes.SERVICE_UNAVAILABLE:
return CtripResponseCodes.SERVICE_UNAVAILABLE_MESSAGE;
return "数据无效";
case CtripResponseCodes.SIGN_ERROR:
return "签名验证失败";
case CtripResponseCodes.ORDER_NOT_FOUND:
return CtripResponseCodes.ORDER_NOT_FOUND_MESSAGE;
return "订单不存在";
case CtripResponseCodes.ORDER_ALREADY_EXISTS:
return "订单已存在";
case CtripResponseCodes.ORDER_STATUS_ERROR:
return CtripResponseCodes.ORDER_STATUS_ERROR_MESSAGE;
case CtripResponseCodes.COUPON_NOT_FOUND:
return CtripResponseCodes.COUPON_NOT_FOUND_MESSAGE;
case CtripResponseCodes.COUPON_ALREADY_USED:
return CtripResponseCodes.COUPON_ALREADY_USED_MESSAGE;
case CtripResponseCodes.COUPON_EXPIRED:
return CtripResponseCodes.COUPON_EXPIRED_MESSAGE;
case CtripResponseCodes.COUPON_INSUFFICIENT:
return CtripResponseCodes.COUPON_INSUFFICIENT_MESSAGE;
case CtripResponseCodes.USER_NOT_FOUND:
return CtripResponseCodes.USER_NOT_FOUND_MESSAGE;
case CtripResponseCodes.PRODUCT_NOT_FOUND:
return CtripResponseCodes.PRODUCT_NOT_FOUND_MESSAGE;
case CtripResponseCodes.INVENTORY_INSUFFICIENT:
return CtripResponseCodes.INVENTORY_INSUFFICIENT_MESSAGE;
case CtripResponseCodes.PRICE_ERROR:
return CtripResponseCodes.PRICE_ERROR_MESSAGE;
case CtripResponseCodes.CONFIRM_TIME_EXPIRED:
return CtripResponseCodes.CONFIRM_TIME_EXPIRED_MESSAGE;
case CtripResponseCodes.DUPLICATE_ORDER:
return CtripResponseCodes.DUPLICATE_ORDER_MESSAGE;
case CtripResponseCodes.VOUCHER_GENERATE_ERROR:
return CtripResponseCodes.VOUCHER_GENERATE_ERROR_MESSAGE;
case CtripResponseCodes.PASSENGER_INFO_ERROR:
return CtripResponseCodes.PASSENGER_INFO_ERROR_MESSAGE;
case CtripResponseCodes.CONTACT_INFO_ERROR:
return CtripResponseCodes.CONTACT_INFO_ERROR_MESSAGE;
case CtripResponseCodes.PAYMENT_ERROR:
return CtripResponseCodes.PAYMENT_ERROR_MESSAGE;
case CtripResponseCodes.REFUND_ERROR:
return CtripResponseCodes.REFUND_ERROR_MESSAGE;
case CtripResponseCodes.CONSUMED_ERROR:
return CtripResponseCodes.CONSUMED_ERROR_MESSAGE;
return "订单状态错误";
case CtripResponseCodes.ORDER_CANCEL_FAILED:
return "订单取消失败";
case CtripResponseCodes.ORDER_REFUND_FAILED:
return "订单退款失败";
case CtripResponseCodes.CANCEL_ERROR:
return CtripResponseCodes.CANCEL_ERROR_MESSAGE;
case CtripResponseCodes.MODIFY_ERROR:
return CtripResponseCodes.MODIFY_ERROR_MESSAGE;
return "订单取消错误";
case CtripResponseCodes.REFUND_ERROR:
return "订单退款错误";
case CtripResponseCodes.CONSUMED_ERROR:
return "订单核销错误";
case CtripResponseCodes.COUPON_NOT_FOUND:
return "优惠券不存在";
case CtripResponseCodes.COUPON_EXPIRED:
return "优惠券已过期";
case CtripResponseCodes.COUPON_USED:
return "优惠券已使用";
case CtripResponseCodes.COUPON_INVALID:
return "优惠券无效";
case CtripResponseCodes.COUPON_VERIFY_FAILED:
return "优惠券核销失败";
case CtripResponseCodes.INVENTORY_NOT_ENOUGH:
return "库存不足";
case CtripResponseCodes.INVENTORY_LOCKED:
return "库存已锁定";
case CtripResponseCodes.SYSTEM_ERROR:
return "系统错误";
case CtripResponseCodes.NETWORK_ERROR:
return "网络错误";
case CtripResponseCodes.TIMEOUT_ERROR:
return "请求超时";
default:
return "未知错误";
}
}
/**
* 判断是否为成功码
* 判断是否为成功响应码
*/
public static boolean isSuccess(String resultCode) {
return CtripResponseCodes.SUCCESS.equals(resultCode);
public static boolean isSuccess(String responseCode) {
return CtripResponseCodes.SUCCESS.equals(responseCode);
}
/**
* 判断是否为系统错误码
* 判断是否为参数错误
*/
public static boolean isSystemError(String resultCode) {
return resultCode != null && resultCode.startsWith("1");
public static boolean isParamError(String responseCode) {
return responseCode != null && responseCode.startsWith("1");
}
/**
* 判断是否为业务错误码
* 判断是否为订单错误
*/
public static boolean isBusinessError(String resultCode) {
return resultCode != null && resultCode.startsWith("2");
public static boolean isOrderError(String responseCode) {
return responseCode != null && responseCode.startsWith("2");
}
/**
* 判断是否为优惠券错误
*/
public static boolean isCouponError(String responseCode) {
return responseCode != null && responseCode.startsWith("3");
}
/**
* 判断是否为库存错误
*/
public static boolean isInventoryError(String responseCode) {
return responseCode != null && responseCode.startsWith("4");
}
/**
* 判断是否为系统错误
*/
public static boolean isSystemError(String responseCode) {
return responseCode != null && responseCode.startsWith("9");
}
}
@@ -1,81 +1,47 @@
server:
port: 8082
servlet:
context-path: /coupon-center
spring:
application:
name: coupon-center
profiles:
active: dev
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}/coupon-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true
username: ${zlt.datasource.username}
password: ${zlt.datasource.password}
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/coupon_center?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
default-property-inclusion: non_null
# 携程API配置
ctrip:
aes:
key: your-aes-key-here-16chars
iv: your-aes-iv-here-16chars
md5:
secret: your-md5-secret-here
api:
timeout: 30000
retry-times: 3
base-url: https://api.ctrip.com
# MyBatis Plus配置
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
type-aliases-package: com.central.coupon.entity
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.central.coupon.model
# configuration:
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: auto
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
springdoc:
group-configs:
- group: 'default'
paths-to-match: '/**'
packages-to-scan: com.central.coupon.controller
knife4j:
enable: true
setting:
swagger-model-name: 优惠券中心接口文档
zlt:
#多租户配置
tenant:
enable: false
ignoreTables:
ignoreSqls:
# 日志配置
logging:
level:
com.central.coupon: debug
org.springframework.web: debug
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file:
name: logs/coupon-center.log
com.central.order.controller.OrderFileController: DEBUG
# 开发环境配置
---
spring:
config:
activate:
on-profile: dev
datasource:
url: jdbc:mysql://localhost:3306/coupon_center_dev?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
# 生产环境配置
---
spring:
config:
activate:
on-profile: prod
datasource:
url: jdbc:mysql://localhost:3306/coupon_center_prod?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
profiles:
active: prod
logging:
level:
com.central.coupon: info
org.springframework.web: warn
# 携程API配置
ctrip:
aes:
key: 087b36ad0dff7942 # 请替换为实际的AES密钥
iv: 750e15a31356a99d # 请替换为实际的AES IV
sign:
key: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的签名密钥
@@ -4,10 +4,10 @@ server:
spring:
application:
name: coupon-center
cloud:
nacos:
discovery:
ip: 81.70.164.178
# cloud:
# nacos:
# discovery:
# ip: 81.70.164.178
# cloud:
# nacos:
# discovery:
@@ -1 +1,48 @@
<?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.coupon.mapper.CtripContactMapper">
<!-- 根据订单ID查询联系人列表 -->
<select id="selectByOrderId" resultType="com.central.coupon.entity.CtripContact">
SELECT
id,
order_id,
contact_name,
contact_phone,
contact_email,
contact_type,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_contact
WHERE order_id = #{orderId}
AND deleted = 0
ORDER BY id ASC
</select>
<!-- 根据订单ID和联系人类型查询联系人 -->
<select id="selectByOrderIdAndType" resultType="com.central.coupon.entity.CtripContact">
SELECT
id,
order_id,
contact_name,
contact_phone,
contact_email,
contact_type,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_contact
WHERE order_id = #{orderId}
AND contact_type = #{contactType}
AND deleted = 0
ORDER BY id ASC
</select>
</mapper>
@@ -1 +1,76 @@
<?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.coupon.mapper.CtripCouponMapper">
<!-- 根据订单ID查询优惠券列表 -->
<select id="selectByOrderId" resultType="com.central.coupon.entity.CtripCoupon">
SELECT
id,
order_id,
coupon_type,
coupon_code,
coupon_name,
coupon_amount,
currency,
coupon_status,
use_time,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_coupon
WHERE order_id = #{orderId}
AND deleted = 0
ORDER BY id ASC
</select>
<!-- 根据优惠券编码查询优惠券 -->
<select id="selectByCouponCode" resultType="com.central.coupon.entity.CtripCoupon">
SELECT
id,
order_id,
coupon_type,
coupon_code,
coupon_name,
coupon_amount,
currency,
coupon_status,
use_time,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_coupon
WHERE coupon_code = #{couponCode}
AND deleted = 0
</select>
<!-- 根据优惠券状态查询优惠券列表 -->
<select id="selectByStatus" resultType="com.central.coupon.entity.CtripCoupon">
SELECT
id,
order_id,
coupon_type,
coupon_code,
coupon_name,
coupon_amount,
currency,
coupon_status,
use_time,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_coupon
WHERE coupon_status = #{status}
AND deleted = 0
ORDER BY id ASC
</select>
</mapper>
@@ -1,18 +1,22 @@
<?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.CtripOrderItemMapper">
<mapper namespace="com.central.coupon.mapper.CtripOrderItemMapper">
<!-- 根据订单ID查询订单项列表 -->
<select id="selectByOrderId" resultType="com.central.order.entity.CtripOrderItem">
<select id="selectByOrderId" resultType="com.central.coupon.entity.CtripOrderItem">
SELECT
id,
order_id,
item_id,
item_name,
item_type,
plu,
use_start_date,
use_end_date,
price,
sale_price,
total_price,
currency,
quantity,
create_time,
update_time,
@@ -22,7 +26,63 @@
tenant_id
FROM t_ctrip_order_item
WHERE order_id = #{orderId}
AND deleted = 0
ORDER BY id ASC
</select>
<!-- 根据订单项编号查询订单项 -->
<select id="selectByItemId" resultType="com.central.coupon.entity.CtripOrderItem">
SELECT
id,
order_id,
item_id,
item_name,
item_type,
plu,
use_start_date,
use_end_date,
price,
sale_price,
total_price,
currency,
quantity,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_order_item
WHERE item_id = #{itemId}
AND deleted = 0
</select>
<!-- 根据订单ID和订单项编号查询订单项 -->
<select id="selectByOrderIdAndItemId" resultType="com.central.coupon.entity.CtripOrderItem">
SELECT
id,
order_id,
item_id,
item_name,
item_type,
plu,
use_start_date,
use_end_date,
price,
sale_price,
total_price,
currency,
quantity,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_order_item
WHERE order_id = #{orderId}
AND item_id = #{itemId}
AND deleted = 0
</select>
</mapper>
@@ -1,9 +1,9 @@
<?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.CtripOrderMapper">
<mapper namespace="com.central.coupon.mapper.CtripOrderMapper">
<!-- 根据携程订单号查询订单 -->
<select id="selectByOtaOrderId" resultType="com.central.order.entity.CtripOrder">
<select id="selectByOtaOrderId" resultType="com.central.coupon.entity.CtripOrder">
SELECT
id,
ota_order_id,
@@ -12,6 +12,8 @@
confirm_type,
order_last_confirm_time,
status,
total_amount,
currency,
create_time,
update_time,
create_by,
@@ -20,10 +22,11 @@
tenant_id
FROM t_ctrip_order
WHERE ota_order_id = #{otaOrderId}
AND deleted = 0
</select>
<!-- 根据供应商订单号查询订单 -->
<select id="selectBySupplierOrderId" resultType="com.central.order.entity.CtripOrder">
<select id="selectBySupplierOrderId" resultType="com.central.coupon.entity.CtripOrder">
SELECT
id,
ota_order_id,
@@ -32,6 +35,8 @@
confirm_type,
order_last_confirm_time,
status,
total_amount,
currency,
create_time,
update_time,
create_by,
@@ -40,6 +45,30 @@
tenant_id
FROM t_ctrip_order
WHERE supplier_order_id = #{supplierOrderId}
AND deleted = 0
</select>
<!-- 根据流水号查询订单 -->
<select id="selectBySequenceId" resultType="com.central.coupon.entity.CtripOrder">
SELECT
id,
ota_order_id,
supplier_order_id,
sequence_id,
confirm_type,
order_last_confirm_time,
status,
total_amount,
currency,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_order
WHERE sequence_id = #{sequenceId}
AND deleted = 0
</select>
</mapper>
@@ -1 +1,72 @@
<?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.coupon.mapper.CtripVoucherMapper">
<!-- 根据订单ID查询凭证列表 -->
<select id="selectByOrderId" resultType="com.central.coupon.entity.CtripVoucher">
SELECT
id,
order_id,
item_id,
voucher_id,
voucher_code,
voucher_type,
voucher_data,
voucher_seat_info,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_voucher
WHERE order_id = #{orderId}
AND deleted = 0
ORDER BY id ASC
</select>
<!-- 根据凭证编号查询凭证 -->
<select id="selectByVoucherId" resultType="com.central.coupon.entity.CtripVoucher">
SELECT
id,
order_id,
item_id,
voucher_id,
voucher_code,
voucher_type,
voucher_data,
voucher_seat_info,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_voucher
WHERE voucher_id = #{voucherId}
AND deleted = 0
</select>
<!-- 根据凭证码查询凭证 -->
<select id="selectByVoucherCode" resultType="com.central.coupon.entity.CtripVoucher">
SELECT
id,
order_id,
item_id,
voucher_id,
voucher_code,
voucher_type,
voucher_data,
voucher_seat_info,
create_time,
update_time,
create_by,
update_by,
remark,
tenant_id
FROM t_ctrip_voucher
WHERE voucher_code = #{voucherCode}
AND deleted = 0
</select>
</mapper>
@@ -0,0 +1,194 @@
package com.central.coupon.service;
import com.central.coupon.entity.Coupon;
import com.central.coupon.service.impl.CouponServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* 优惠券服务测试类
*/
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class CouponServiceTest {
@Autowired
private ICouponService couponService;
@Test
public void testCreateCouponFromCtrip() {
// 准备测试数据
String ctripCouponId = "TEST_COUPON_001";
String userPhone = "13800138000";
String couponName = "测试优惠券";
Integer couponType = 1;
BigDecimal amount = new BigDecimal("100.00");
BigDecimal minAmount = new BigDecimal("200.00");
Integer discountRate = null;
Date validStartTime = new Date();
Date validEndTime = new Date(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L); // 30天后过期
// 执行测试
boolean result = couponService.createCouponFromCtrip(ctripCouponId, userPhone, couponName,
couponType, amount, minAmount, discountRate, validStartTime, validEndTime);
// 验证结果
assertTrue(result);
// 验证数据是否正确保存
Coupon savedCoupon = couponService.getByCtripCouponId(ctripCouponId);
assertNotNull(savedCoupon);
assertEquals(userPhone, savedCoupon.getUserPhone());
assertEquals(couponName, savedCoupon.getCouponName());
assertEquals(couponType, savedCoupon.getCouponType());
assertEquals(amount, savedCoupon.getAmount());
assertEquals(minAmount, savedCoupon.getMinAmount());
assertEquals(0, savedCoupon.getStatus()); // 未使用状态
assertEquals(1, savedCoupon.getSource()); // 来源:携程
}
@Test
public void testGetAvailableCouponsByUserPhone() {
// 准备测试数据
String userPhone = "13800138000";
// 创建测试优惠券
createTestCoupon(userPhone, "TEST_COUPON_001", 0); // 未使用
createTestCoupon(userPhone, "TEST_COUPON_002", 1); // 已使用
createTestCoupon(userPhone, "TEST_COUPON_003", 0); // 未使用
// 执行测试
List<Coupon> availableCoupons = couponService.getAvailableCouponsByUserPhone(userPhone);
// 验证结果
assertEquals(2, availableCoupons.size()); // 只有未使用的优惠券
assertTrue(availableCoupons.stream().allMatch(coupon -> coupon.getStatus() == 0));
}
@Test
public void testSelectBestCoupon() {
// 准备测试数据
String userPhone = "13800138000";
BigDecimal orderAmount = new BigDecimal("300.00");
// 创建测试优惠券
createTestCoupon(userPhone, "TEST_COUPON_001", 0, new BigDecimal("50.00"), new BigDecimal("200.00")); // 满减券
createTestCoupon(userPhone, "TEST_COUPON_002", 0, new BigDecimal("100.00"), new BigDecimal("200.00")); // 满减券
createTestCoupon(userPhone, "TEST_COUPON_003", 0, new BigDecimal("30.00"), new BigDecimal("100.00")); // 满减券,金额不够
// 执行测试
Coupon bestCoupon = couponService.selectBestCoupon(userPhone, orderAmount);
// 验证结果
assertNotNull(bestCoupon);
assertEquals("TEST_COUPON_002", bestCoupon.getCtripCouponId()); // 应该选择金额最大的优惠券
assertEquals(new BigDecimal("100.00"), bestCoupon.getAmount());
}
@Test
public void testVerifyCtripCoupon() {
// 准备测试数据
String userPhone = "13800138000";
String ctripCouponId = "TEST_COUPON_001";
String orderNo = "ORDER_001";
// 创建测试优惠券
createTestCoupon(userPhone, ctripCouponId, 0);
// 执行测试
boolean result = couponService.verifyCtripCoupon(ctripCouponId, orderNo);
// 验证结果
assertTrue(result);
// 验证优惠券状态已更新
Coupon updatedCoupon = couponService.getByCtripCouponId(ctripCouponId);
assertEquals(1, updatedCoupon.getStatus()); // 已使用状态
assertEquals(orderNo, updatedCoupon.getUsedOrderNo());
}
@Test
public void testVerifyCtripCouponNotFound() {
// 执行测试
assertThrows(CouponServiceImpl.CouponNotFoundException.class, () -> {
couponService.verifyCtripCoupon("NON_EXISTENT_COUPON", "ORDER_001");
});
}
@Test
public void testVerifyCtripCouponExpired() {
// 准备测试数据
String userPhone = "13800138000";
String ctripCouponId = "TEST_COUPON_EXPIRED";
// 创建已过期的测试优惠券
createExpiredTestCoupon(userPhone, ctripCouponId);
// 执行测试
assertThrows(CouponServiceImpl.CouponExpiredException.class, () -> {
couponService.verifyCtripCoupon(ctripCouponId, "ORDER_001");
});
}
/**
* 创建测试优惠券
*/
private void createTestCoupon(String userPhone, String ctripCouponId, Integer status) {
createTestCoupon(userPhone, ctripCouponId, status, new BigDecimal("100.00"), new BigDecimal("200.00"));
}
/**
* 创建测试优惠券
*/
private void createTestCoupon(String userPhone, String ctripCouponId, Integer status,
BigDecimal amount, BigDecimal minAmount) {
Coupon coupon = new Coupon();
coupon.setCouponNo("CP" + System.currentTimeMillis());
coupon.setCouponName("测试优惠券");
coupon.setCouponType(1);
coupon.setAmount(amount);
coupon.setMinAmount(minAmount);
coupon.setStatus(status);
coupon.setUserPhone(userPhone);
coupon.setSource(1);
coupon.setCtripCouponId(ctripCouponId);
coupon.setValidStartTime(new Date());
coupon.setValidEndTime(new Date(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L));
coupon.setCreateTime(new Date());
coupon.setUpdateTime(new Date());
couponService.save(coupon);
}
/**
* 创建已过期的测试优惠券
*/
private void createExpiredTestCoupon(String userPhone, String ctripCouponId) {
Coupon coupon = new Coupon();
coupon.setCouponNo("CP" + System.currentTimeMillis());
coupon.setCouponName("已过期测试优惠券");
coupon.setCouponType(1);
coupon.setAmount(new BigDecimal("100.00"));
coupon.setMinAmount(new BigDecimal("200.00"));
coupon.setStatus(0);
coupon.setUserPhone(userPhone);
coupon.setSource(1);
coupon.setCtripCouponId(ctripCouponId);
coupon.setValidStartTime(new Date(System.currentTimeMillis() - 60 * 24 * 60 * 60 * 1000L)); // 60天前开始
coupon.setValidEndTime(new Date(System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000L)); // 30天前过期
coupon.setCreateTime(new Date());
coupon.setUpdateTime(new Date());
couponService.save(coupon);
}
}
@@ -0,0 +1 @@