!16 fix(首页统计):首页订单统计bug修复

Merge pull request !16 from Iamasoldier/feature_lsl
This commit is contained in:
2025-07-21 16:50:45 +00:00
committed by Gitee
48 changed files with 2995 additions and 410 deletions
+34 -1
View File
@@ -90,4 +90,37 @@ CREATE INDEX idx_wechat_config_serial_number_2 ON wechat_config(serial_number);
-- - serial_number:微信平台证书的序列号,用于验证回调请求的签名 -- - serial_number:微信平台证书的序列号,用于验证回调请求的签名
-- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息 -- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息
-- - 与回调请求头中的 Wechatpay-Serial 字段对应 -- - 与回调请求头中的 Wechatpay-Serial 字段对应
-- - 支持一个商户配置多个平台证书,通过序列号区分 -- - 支持一个商户配置多个平台证书,通过序列号区分
-- 创建优惠券表
CREATE TABLE IF NOT EXISTS `t_coupon` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`coupon_no` varchar(64) NOT NULL COMMENT '优惠券编号',
`coupon_name` varchar(128) NOT NULL COMMENT '优惠券名称',
`coupon_type` int(11) NOT NULL COMMENT '优惠券类型:1-满减券,2-折扣券,3-免费券',
`amount` decimal(10,2) DEFAULT NULL COMMENT '优惠券面额',
`min_amount` decimal(10,2) DEFAULT NULL COMMENT '使用门槛金额',
`discount_rate` int(11) DEFAULT NULL COMMENT '折扣率(0-100,折扣券时使用)',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '优惠券状态:0-未使用,1-已使用,2-已过期,3-已作废',
`user_phone` varchar(20) NOT NULL COMMENT '用户手机号',
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`source` int(11) NOT NULL DEFAULT '2' COMMENT '来源:1-携程,2-高飞自建',
`ctrip_coupon_id` varchar(64) DEFAULT NULL COMMENT '携程优惠券ID(来源为携程时使用)',
`valid_start_time` datetime NOT NULL COMMENT '有效期开始时间',
`valid_end_time` datetime NOT NULL COMMENT '有效期结束时间',
`used_time` datetime DEFAULT NULL COMMENT '使用时间',
`used_order_no` varchar(64) DEFAULT NULL COMMENT '使用订单号',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` varchar(64) DEFAULT NULL COMMENT '创建人',
`update_by` varchar(64) DEFAULT NULL COMMENT '更新人',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
`tenant_id` varchar(64) DEFAULT NULL COMMENT '租户ID',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_coupon_no` (`coupon_no`),
UNIQUE KEY `uk_ctrip_coupon_id` (`ctrip_coupon_id`),
KEY `idx_user_phone` (`user_phone`),
KEY `idx_status` (`status`),
KEY `idx_valid_end_time` (`valid_end_time`),
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='优惠券表';
@@ -89,13 +89,13 @@ public class ApiDeviceController {
// 2. 检查订单状态 // 2. 检查订单状态
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo); String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
if (!isValidOrderStatus(orderStatus)) { if (!isValidOrderStatus(orderStatus)) {
return Result.succeed("设备已执行"); return Result.failed("设备已处理,请关注订单详情");
} }
// 3. 构建控制消息 // 3. 构建控制消息
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId); JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
if (controlMessage == null) { if (controlMessage == null) {
return Result.succeed("暂未开放控制权限"); return Result.failed("暂未开放控制权限");
} }
// 4. 发送设备控制请求 // 4. 发送设备控制请求
@@ -160,7 +160,16 @@ public class ApiDeviceController {
if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) { if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) {
log.info("设置设备属性返回消息: message={}", requestResult.getMessage()); log.info("设置设备属性返回消息: message={}", requestResult.getMessage());
if (requestResult.getMessage().equals("Device is offline")){ if (requestResult.getMessage().equals("Device is offline")){
return Result.failed("Device is offline","设备已离线请稍后重试"); // 设备离线时自动创建退款订单
log.info("设备离线,开始自动创建退款订单: orderNo={}", orderNo);
Result refundResult = createRefundForOfflineDevice(orderNo);
if (refundResult.getResp_code() != null && refundResult.getResp_code() == 0) {
return Result.failed("设备已离线,已自动创建退款订单");
} else {
log.error("自动创建退款订单失败: orderNo={}, error={}", orderNo, refundResult.getResp_msg());
return Result.failed("设备已离线,退款处理失败,请联系客服");
}
} }
Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo); Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo);
if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) { if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) {
@@ -171,6 +180,36 @@ public class ApiDeviceController {
return Result.failed("请重试"); return Result.failed("请重试");
} }
/**
* 设备离线时自动创建退款订单
* @param orderNo 订单号
* @return 退款结果
*/
private Result createRefundForOfflineDevice(String orderNo) {
try {
// 构建退款请求体
Map<String, Object> refundBody = new HashMap<>();
refundBody.put("refundReason", "设备离线,无法提供服务");
refundBody.put("refundImgs", ""); // 可以设置为空或者添加默认图片
// 通过 OrderCenterService 调用退款接口
Result refundResult = orderCenterService.createRefundForOfflineDevice(orderNo, refundBody);
if (refundResult != null && refundResult.getResp_code() != null && refundResult.getResp_code() == 0) {
log.info("自动创建退款订单成功: orderNo={}", orderNo);
return Result.succeed("退款订单创建成功");
} else {
log.error("自动创建退款订单失败: orderNo={}, error={}", orderNo,
refundResult != null ? refundResult.getResp_msg() : "null");
return Result.failed("退款订单创建失败");
}
} catch (Exception e) {
log.error("自动创建退款订单异常: orderNo={}, error={}", orderNo, e.getMessage(), e);
return Result.failed("退款订单创建异常: " + e.getMessage());
}
}
@GetMapping("/device/wayline") @GetMapping("/device/wayline")
public Result<Map> getWayline(@RequestParam String no){ public Result<Map> getWayline(@RequestParam String no){
return Result.succeed(orderCenterService.getWaylineByOrderNo(no)); return Result.succeed(orderCenterService.getWaylineByOrderNo(no));
@@ -30,4 +30,13 @@ public interface OrderCenterService {
@GetMapping("/qrcode/wayline/{orderNo}") @GetMapping("/qrcode/wayline/{orderNo}")
Map<String,Object> getWaylineByOrderNo(@PathVariable("orderNo") String orderNo); Map<String,Object> getWaylineByOrderNo(@PathVariable("orderNo") String orderNo);
/**
* 设备离线时自动创建退款订单
* @param orderNo 订单号
* @param refundBody 退款请求体
* @return 退款结果
*/
@PostMapping("/refund/{orderNo}")
Result createRefundForOfflineDevice(@PathVariable("orderNo") String orderNo, @RequestBody Map<String, Object> refundBody);
} }
@@ -38,6 +38,12 @@ public class OrderCenterServiceFallbackFactory implements FallbackFactory<OrderC
public Map<String,Object> getWaylineByOrderNo(String orderNo) { public Map<String,Object> getWaylineByOrderNo(String orderNo) {
return null; return null;
} }
@Override
public Result createRefundForOfflineDevice(String orderNo, Map<String, Object> refundBody) {
log.error("调用订单中心退款接口失败: orderNo={}, cause={}", orderNo, cause.getMessage());
return Result.failed("退款服务调用失败");
}
}; };
} }
} }
@@ -0,0 +1,208 @@
package com.central.order.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.Result;
import com.central.common.model.PageResult;
import com.central.order.entity.Coupon;
import com.central.order.service.ICouponService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 优惠券管理控制器
*/
@Slf4j
@RestController
@RequestMapping("/coupon")
@Tag(name = "优惠券管理")
public class CouponController {
@Autowired
private ICouponService couponService;
/**
* 列表
*/
@Operation(summary = "查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult<Coupon> list(@RequestParam Map<String, Object> params) {
return couponService.findList(params);
}
/**
* 根据ID查询优惠券
*/
@Operation(summary = "根据ID查询优惠券")
@GetMapping("/{id}")
public Result<Coupon> getCouponById(@PathVariable Long id) {
Coupon coupon = couponService.getById(id);
return Result.succeed(coupon);
}
/**
* 创建优惠券
*/
@Operation(summary = "创建优惠券")
@PostMapping
public Result<Boolean> createCoupon(@RequestBody Coupon coupon) {
boolean result = couponService.createCoupon(coupon);
return Result.succeed(result);
}
/**
* 更新优惠券
*/
@Operation(summary = "更新优惠券")
@PutMapping("/{id}")
public Result<Boolean> updateCoupon(@PathVariable Long id, @RequestBody Coupon coupon) {
coupon.setId(id);
boolean result = couponService.updateCoupon(coupon);
return Result.succeed(result);
}
/**
* 删除优惠券
*/
@Operation(summary = "删除优惠券")
@DeleteMapping("/{id}")
public Result<Boolean> deleteCoupon(@PathVariable Long id) {
boolean result = couponService.deleteCoupon(id);
return Result.succeed(result);
}
/**
* 根据手机号查询用户优惠券
*/
@Operation(summary = "根据手机号查询用户优惠券")
@GetMapping("/user/{userPhone}")
public Result<List<Coupon>> getCouponsByUserPhone(@PathVariable String userPhone) {
List<Coupon> coupons = couponService.getCouponsByUserPhone(userPhone);
return Result.succeed(coupons);
}
/**
* 根据手机号查询可用优惠券
*/
@Operation(summary = "根据手机号查询可用优惠券")
@GetMapping("/user/{userPhone}/available")
public Result<List<Coupon>> getAvailableCouponsByUserPhone(@PathVariable String userPhone) {
List<Coupon> coupons = couponService.getAvailableCouponsByUserPhone(userPhone);
return Result.succeed(coupons);
}
/**
* 使用优惠券
*/
@Operation(summary = "使用优惠券")
@PostMapping("/{id}/use")
public Result<Boolean> useCoupon(@PathVariable Long id, @RequestParam String orderNo) {
boolean result = couponService.useCoupon(id, orderNo);
return Result.succeed(result);
}
/**
* 携程创建优惠券接口
*/
@Operation(summary = "携程创建优惠券接口")
@PostMapping("/ctrip/create")
public Result<Boolean> createCouponFromCtrip(
@RequestParam String ctripCouponId,
@RequestParam String userPhone,
@RequestParam String couponName,
@RequestParam Integer couponType,
@RequestParam BigDecimal amount,
@RequestParam(required = false) BigDecimal minAmount,
@RequestParam(required = false) Integer discountRate,
@RequestParam String validStartTime,
@RequestParam String validEndTime) {
// 幂等校验
if (couponService.existsByUserPhoneAndCtripCouponId(userPhone, ctripCouponId)) {
return Result.succeed(true);
}
// 时间解析
Date startTime = parseDate(validStartTime);
Date endTime = parseDate(validEndTime);
boolean result = couponService.createCouponFromCtrip(ctripCouponId, userPhone, couponName,
couponType, amount, minAmount, discountRate,
startTime, endTime);
return Result.succeed(result);
}
/**
* 携程取消优惠券接口
*/
@Operation(summary = "携程取消优惠券接口")
@PostMapping("/ctrip/cancel")
public Result<Boolean> cancelCouponFromCtrip(@RequestParam String userPhone) {
List<Coupon> coupons = couponService.getAvailableCouponsByUserPhone(userPhone);
if (coupons.isEmpty()) {
return Result.failed("无可退优惠券");
}
Coupon coupon = coupons.get(0); // 默认退第一个
coupon.setStatus(3); // 作废/退
coupon.setCancelTime(new Date());
couponService.updateCoupon(coupon);
return Result.succeed(true);
}
/**
* 优化核销携程优惠券接口,先查本地券再核销
*/
@Operation(summary = "核销携程优惠券")
@PostMapping("/ctrip/verify")
public Result<Boolean> verifyCtripCoupon(@RequestParam String userPhone, @RequestParam String orderNo) {
List<Coupon> coupons = couponService.getAvailableCouponsByUserPhone(userPhone);
if (coupons.isEmpty()) {
return Result.failed("无可用优惠券");
}
Coupon coupon = coupons.get(0);
boolean result = couponService.verifyCtripCoupon(coupon.getCtripCouponId(), orderNo);
if (result) {
coupon.setStatus(1); // 已用
coupon.setUsedTime(new Date());
couponService.updateCoupon(coupon);
return Result.succeed(true);
} else {
return Result.failed("携程核销失败");
}
}
/**
* 批量更新过期优惠券
*/
@Operation(summary = "批量更新过期优惠券")
@PostMapping("/update-expired")
public Result<Void> updateExpiredCoupons() {
couponService.updateExpiredCoupons();
return Result.succeed("批量更新过期优惠券成功");
}
// 时间解析工具
private Date parseDate(String dateStr) {
try {
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
} catch (Exception e) {
try {
return new java.text.SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
} catch (Exception ex) {
return new Date();
}
}
}
}
@@ -4,13 +4,18 @@ import com.central.common.model.Result;
import com.central.order.model.vo.DashboardStatisticsVO; import com.central.order.model.vo.DashboardStatisticsVO;
import com.central.order.service.IDashboardService; import com.central.order.service.IDashboardService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("/dashboard") @RequestMapping("/dashboard")
@@ -22,9 +27,21 @@ public class DashboardController {
@Operation(summary = "获取首页统计数据") @Operation(summary = "获取首页统计数据")
@GetMapping("/statistics") @GetMapping("/statistics")
public Result<DashboardStatisticsVO> getStatistics() { public Result<DashboardStatisticsVO> getStatistics(
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
@Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId,
@Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn,
@Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
@Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
try { try {
DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(); Map<String, Object> params = new HashMap<>();
params.put("tourismId", tourismId);
params.put("qrcodeId", qrcodeId);
params.put("deviceSn", deviceSn);
params.put("startTime", startTime);
params.put("endTime", endTime);
DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(params);
return Result.succeed(statistics, "获取首页统计数据成功"); return Result.succeed(statistics, "获取首页统计数据成功");
} catch (Exception e) { } catch (Exception e) {
log.error("获取首页统计数据失败", e); log.error("获取首页统计数据失败", e);
@@ -145,7 +145,7 @@ public class OrderController {
public PageResult<Map> listInfoByUser(@RequestParam Map<String, Object> params) { public PageResult<Map> listInfoByUser(@RequestParam Map<String, Object> params) {
LoginAppUser user = LoginUserContextHolder.getUser(); LoginAppUser user = LoginUserContextHolder.getUser();
params.put("userId", user.getId()); params.put("userId", user.getId());
List<Integer> orderStatusList = List.of(OrderStatus.COMPLETE.getId(), OrderStatus.UPLOADED.getId()); List<Integer> orderStatusList = List.of(OrderStatus.COMPLETE.getId(), OrderStatus.UPLOADING.getId(), OrderStatus.UPLOADED.getId());
params.put("orderStatusList", orderStatusList); // 查询已完成和素材上传中 params.put("orderStatusList", orderStatusList); // 查询已完成和素材上传中
String fileType = MapUtils.getString(params, "fileType"); String fileType = MapUtils.getString(params, "fileType");
if (StringUtil.isBlank(fileType)) { if (StringUtil.isBlank(fileType)) {
@@ -67,14 +67,16 @@ public class OrderStatisticsController {
@Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据") @Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据")
@Parameters({ @Parameters({
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "tourismId", description = "景区ID筛选", required = false)
}) })
@GetMapping("/tourism") @GetMapping("/tourism")
public Result<List<Map<String, Object>>> statisticsByTourism( public Result<List<Map<String, Object>>> statisticsByTourism(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
@RequestParam(required = false) String tourismId) {
try { try {
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime); List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime, tourismId);
return Result.succeed(result, "获取景区维度统计数据成功"); return Result.succeed(result, "获取景区维度统计数据成功");
} catch (Exception e) { } catch (Exception e) {
log.error("获取景区维度统计数据失败", e); log.error("获取景区维度统计数据失败", e);
@@ -85,14 +87,16 @@ public class OrderStatisticsController {
@Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据") @Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据")
@Parameters({ @Parameters({
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
@Parameter(name = "deviceSn", description = "设备编号筛选", required = false)
}) })
@GetMapping("/device") @GetMapping("/device")
public Result<List<Map<String, Object>>> statisticsByDevice( public Result<List<Map<String, Object>>> statisticsByDevice(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
@RequestParam(required = false) String deviceSn) {
try { try {
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime); List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime, deviceSn);
return Result.succeed(result, "获取设备维度统计数据成功"); return Result.succeed(result, "获取设备维度统计数据成功");
} catch (Exception e) { } catch (Exception e) {
log.error("获取设备维度统计数据失败", e); log.error("获取设备维度统计数据失败", e);
@@ -75,4 +75,20 @@ public class TourismController {
boolean result = tourismService.removeById(tourism); boolean result = tourismService.removeById(tourism);
return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败"); return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败");
} }
/**
* 获取景区设备列表
* 通过景区下的二维码信息查询二维码绑定的设备
*/
@Operation(summary = "获取景区设备列表")
@GetMapping("/{tourismId}/devices")
public Result getTourismDevices(@PathVariable("tourismId") Long tourismId) {
try {
var devices = tourismService.getDevicesByTourismId(tourismId);
return Result.succeed(devices, "获取景区设备列表成功");
} catch (Exception e) {
log.error("获取景区设备列表失败", e);
return Result.failed("获取景区设备列表失败:" + e.getMessage());
}
}
} }
@@ -0,0 +1,143 @@
package com.central.order.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;
import java.util.Date;
/**
* 优惠券实体类
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_coupon")
public class Coupon implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 优惠券编号
*/
private String couponNo;
/**
* 优惠券名称
*/
private String couponName;
/**
* 优惠券类型:1-满减券,2-折扣券,3-免费券
*/
private Integer couponType;
/**
* 优惠券面额
*/
private BigDecimal amount;
/**
* 使用门槛金额
*/
private BigDecimal minAmount;
/**
* 折扣率(0-100,折扣券时使用)
*/
private Integer discountRate;
/**
* 优惠券状态:0-未使用,1-已使用,2-已过期,3-已作废
*/
private Integer status;
/**
* 用户手机号
*/
private String userPhone;
/**
* 用户ID
*/
private Long userId;
/**
* 来源:1-携程,2-高飞自建
*/
private Integer source;
/**
* 携程优惠券ID(来源为携程时使用)
*/
private String ctripCouponId;
/**
* 有效期开始时间
*/
private Date validStartTime;
/**
* 有效期结束时间
*/
private Date validEndTime;
/**
* 使用时间
*/
private Date usedTime;
/**
* 使用订单号
*/
private String usedOrderNo;
/**
* 退券时间
*/
private Date cancelTime;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
* 租户ID
*/
private String tenantId;
/**
* 创建人
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 备注
*/
private String remark;
}
@@ -0,0 +1,52 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.order.entity.Coupon;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 优惠券Mapper接口
*/
@Mapper
public interface CouponMapper extends BaseMapper<Coupon> {
/**
* 分页查询优惠券列表
*/
IPage<Coupon> selectCouponPage(Page<Coupon> page, @Param("coupon") Coupon coupon);
/**
* 根据手机号查询用户优惠券
*/
List<Coupon> selectByUserPhone(@Param("userPhone") String userPhone);
/**
* 根据手机号查询可用优惠券
*/
List<Coupon> selectAvailableByUserPhone(@Param("userPhone") String userPhone);
/**
* 根据携程优惠券ID查询
*/
Coupon selectByCtripCouponId(@Param("ctripCouponId") String ctripCouponId);
/**
* 根据订单号查询使用的优惠券
*/
Coupon selectByUsedOrderNo(@Param("usedOrderNo") String usedOrderNo);
/**
* 更新优惠券状态为已使用
*/
int updateCouponUsed(@Param("id") Long id, @Param("usedOrderNo") String usedOrderNo);
/**
* 批量更新过期优惠券状态
*/
int updateExpiredCoupons();
}
@@ -1,52 +1,183 @@
package com.central.order.mapper; package com.central.order.mapper;
import com.central.order.model.vo.IncomeDataVO; import com.central.order.model.vo.*;
import com.central.order.model.vo.TourismRankingVO;
import com.central.order.model.vo.TrendDataVO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import java.util.List; import java.util.List;
import java.util.Map;
@Mapper @Mapper
public interface DashboardMapper { public interface DashboardMapper {
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0") // 基础订单统计(支持筛选)
Long getTotalOrders(); @Select({
"<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getTotalOrders(@Param("p") Map<String, Object> params);
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()") @Select({
Long getTodayOrders(); "<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"</script>"
})
Long getTodayOrders(@Param("p") Map<String, Object> params);
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)") @Select({
Long getYesterdayOrders(); "<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"</script>"
})
Long getYesterdayOrders(@Param("p") Map<String, Object> params);
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = #{completeStatus}") @Select({
Long getCompletedOrders(); "<script>",
"SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = 3",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getCompletedOrders(@Param("p") Map<String, Object> params);
// 对账相关统计
@Select({ @Select({
"<script>", "<script>",
"SELECT COALESCE(SUM(order_amount), 0)", "SELECT COALESCE(SUM(order_amount), 0)",
"FROM orders", "FROM orders",
"WHERE is_del = 0", "WHERE is_del = 0",
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}", "AND (order_status = 3 OR order_status = 8)",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>" "</script>"
}) })
Long getTotalIncome(); Long getTotalAmount(@Param("p") Map<String, Object> params);
@Select({ @Select({
"<script>", "<script>",
"SELECT COALESCE(SUM(order_amount), 0)", "SELECT COALESCE(SUM(platform_amount), 0)",
"FROM orders", "FROM order_statistics",
"WHERE is_del = 0", "WHERE 1=1",
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}", "<if test='p.tourismId != null'>",
"AND DATE(create_time) = CURDATE()", " AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>" "</script>"
}) })
Long getTodayIncome(); Long getPlatformAmount(@Param("p") Map<String, Object> params);
@Select({ @Select({
"<script>",
"SELECT COALESCE(SUM(tourism_amount), 0)",
"FROM order_statistics",
"WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getTourismAmount(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT COALESCE(SUM(CAST(r.refund_amount AS SIGNED)), 0)",
"FROM orders_refund r",
"JOIN orders o ON r.order_no = o.order_no",
"WHERE r.status = 8",
"<if test='p.tourismId != null'>",
" AND o.tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND r.create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND r.create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
Long getRefundAmount(@Param("p") Map<String, Object> params);
// 图表数据
@Select({
"<script>",
"SELECT", "SELECT",
" DATE_FORMAT(create_time, '%Y-%m-%d') as date,", " DATE_FORMAT(create_time, '%Y-%m-%d') as date,",
" 'orders' as type,", " 'orders' as type,",
@@ -54,38 +185,135 @@ public interface DashboardMapper {
"FROM orders", "FROM orders",
"WHERE is_del = 0", "WHERE is_del = 0",
" AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", " AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
"GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')" "<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')",
"ORDER BY date",
"</script>"
}) })
List<TrendDataVO> getOrderTrend(); List<TrendDataVO> getOrderTrend(@Param("p") Map<String, Object> params);
@Select({ @Select({
"<script>",
"SELECT", "SELECT",
" 'platform' as type,", " CASE order_status",
" SUM(platform_amount) as value", " WHEN 0 THEN '待支付'",
" WHEN 1 THEN '已支付排队中'",
" WHEN 2 THEN '已取消'",
" WHEN 3 THEN '设备执行完成'",
" WHEN 4 THEN '正在服务中'",
" WHEN 5 THEN '素材上传中'",
" WHEN 6 THEN '素材上传完成'",
" WHEN 7 THEN '退款中'",
" WHEN 8 THEN '已退款'",
" WHEN 9 THEN '退款失败'",
" ELSE '其他'",
" END as type,",
" COUNT(*) as value",
"FROM orders",
"WHERE is_del = 0",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"GROUP BY order_status",
"</script>"
})
List<DistributionDataVO> getOrderDistribution(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT",
" '平台分账' as type,",
" COALESCE(SUM(platform_amount), 0) as value",
"FROM order_statistics", "FROM order_statistics",
"WHERE DATE(create_time) = CURDATE()", "WHERE 1=1",
"<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"UNION ALL", "UNION ALL",
"SELECT", "SELECT",
" 'tourism' as type,", " '景区分账' as type,",
" SUM(tourism_amount) as value", " COALESCE(SUM(tourism_amount), 0) as value",
"FROM order_statistics", "FROM order_statistics",
"WHERE DATE(create_time) = CURDATE()" "WHERE 1=1",
}) "<if test='p.tourismId != null'>",
List<IncomeDataVO> getIncomeData(); " AND tourism_id = #{p.tourismId}",
"</if>",
@Select({ "<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND qrcode_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"UNION ALL",
"SELECT", "SELECT",
" t.id,", " '退款金额' as type,",
" t.tourism_name as name,", " COALESCE(SUM(refund_amount), 0) as value",
" COUNT(o.id) as value", "FROM order_statistics",
"FROM tourisms t", "WHERE 1=1",
"LEFT JOIN orders o ON t.id = o.tourism_id", "<if test='p.tourismId != null'>",
"WHERE t.is_del = 0", " AND tourism_id = #{p.tourismId}",
" AND o.is_del = 0", "</if>",
" AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", "<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
"GROUP BY t.id, t.tourism_name", " AND qrcode_id = #{p.qrcodeId}",
"ORDER BY value DESC", "</if>",
"LIMIT 10" "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
}) })
List<TourismRankingVO> getTourismRanking(); List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params);
// 筛选选项
@Select("SELECT id as value, tourism_name as label FROM tourisms WHERE is_del = 0 ORDER BY tourism_name")
List<FilterOptions.OptionItem> getTourismOptions();
@Select("SELECT code_id as value, CONCAT(name, ' | ', device_sn) as label FROM qrcodes WHERE is_del = 0 ORDER BY name")
List<FilterOptions.OptionItem> getQrcodeOptions();
@Select("SELECT DISTINCT device_sn as value, device_sn as label FROM orders WHERE device_sn IS NOT NULL AND device_sn != '' ORDER BY device_sn")
List<FilterOptions.OptionItem> getDeviceOptions();
} }
@@ -32,4 +32,12 @@ public interface TourismMapper extends SuperMapper<Tourism> {
// ID查询 // ID查询
Tourism getTourismById(@Param("id") Long id); Tourism getTourismById(@Param("id") Long id);
/**
* 获取景区设备列表
* 通过景区下的二维码信息查询二维码绑定的设备
* @param tourismId 景区ID
* @return 设备列表
*/
List<Map<String, Object>> getDevicesByTourismId(@Param("tourismId") Long tourismId);
} }
@@ -6,14 +6,14 @@ import lombok.Data;
import java.util.List; import java.util.List;
@Data @Data
@Schema(description = "图表统计数据") @Schema(description = "图表统计")
public class ChartStatistics { public class ChartStatistics {
@Schema(description = "订单趋势") @Schema(description = "订单趋势")
private List<TrendDataVO> orderTrend; private List<TrendDataVO> orderTrend;
@Schema(description = "设备分布") @Schema(description = "订单状态分布")
private List<DistributionDataVO> deviceDistribution; private List<DistributionDataVO> orderDistribution;
@Schema(description = "收入构成") @Schema(description = "收入构成")
private List<IncomeDataVO> incomeData; private List<IncomeDataVO> incomeBreakdown;
} }
@@ -11,18 +11,9 @@ public class DashboardStatisticsVO {
@Schema(description = "订单统计") @Schema(description = "订单统计")
private OrderStatistics orderStats; private OrderStatistics orderStats;
@Schema(description = "收入统计")
private IncomeStatistics incomeStats;
@Schema(description = "航线统计")
private WaylineStatistics waylineStats;
@Schema(description = "设备统计")
private DeviceStatistics deviceStats;
@Schema(description = "图表统计") @Schema(description = "图表统计")
private ChartStatistics chartStats; private ChartStatistics chartStats;
@Schema(description = "景区排行") @Schema(description = "筛选选项")
private List<TourismRankingVO> tourismRanking; private FilterOptions filterOptions;
} }
@@ -0,0 +1,29 @@
package com.central.order.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
@Schema(description = "筛选选项")
public class FilterOptions {
@Schema(description = "景区列表")
private List<OptionItem> tourismList;
@Schema(description = "二维码列表")
private List<OptionItem> qrcodeList;
@Schema(description = "设备列表")
private List<OptionItem> deviceList;
@Data
@Schema(description = "选项项")
public static class OptionItem {
@Schema(description = "标签")
private String label;
@Schema(description = "值")
private Object value;
}
}
@@ -6,9 +6,9 @@ import lombok.Data;
import java.math.BigDecimal; import java.math.BigDecimal;
@Data @Data
@Schema(description = "订单统计数据") @Schema(description = "订单统计")
public class OrderStatistics { public class OrderStatistics {
@Schema(description = "订单总数") @Schema(description = "总订单数")
private Long totalOrders; private Long totalOrders;
@Schema(description = "今日订单数") @Schema(description = "今日订单数")
@@ -17,6 +17,21 @@ public class OrderStatistics {
@Schema(description = "订单增长率") @Schema(description = "订单增长率")
private BigDecimal orderGrowth; private BigDecimal orderGrowth;
@Schema(description = "订单完成率") @Schema(description = "完成率")
private BigDecimal completionRate; private BigDecimal completionRate;
@Schema(description = "订单总金额(分)")
private Long totalAmount;
@Schema(description = "平台分账金额(分)")
private Long platformAmount;
@Schema(description = "景区分账金额(分)")
private Long tourismAmount;
@Schema(description = "退款金额(分)")
private Long refundAmount;
@Schema(description = "净收入(分)")
private Long netIncome;
} }
@@ -0,0 +1,80 @@
package com.central.order.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.order.entity.Coupon;
import com.central.common.model.PageResult;
import java.util.List;
import java.util.Map;
/**
* 优惠券服务接口
*/
public interface ICouponService extends IService<Coupon> {
/**
* 分页查询优惠券列表
*/
IPage<Coupon> getCouponPage(Page<Coupon> page, Coupon coupon);
/**
* 查询优惠券列表(统一风格)
*/
PageResult<Coupon> findList(Map<String, Object> params);
/**
* 创建优惠券
*/
boolean createCoupon(Coupon coupon);
/**
* 更新优惠券
*/
boolean updateCoupon(Coupon coupon);
/**
* 删除优惠券
*/
boolean deleteCoupon(Long id);
/**
* 根据手机号查询用户优惠券
*/
List<Coupon> getCouponsByUserPhone(String userPhone);
/**
* 根据手机号查询可用优惠券
*/
List<Coupon> getAvailableCouponsByUserPhone(String userPhone);
/**
* 使用优惠券
*/
boolean useCoupon(Long couponId, String orderNo);
/**
* 根据携程优惠券ID创建优惠券(携程接口调用)
*/
boolean createCouponFromCtrip(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);
/**
* 批量更新过期优惠券状态
*/
void updateExpiredCoupons();
/**
* 核销携程优惠券
*/
boolean verifyCtripCoupon(String ctripCouponId, String orderNo);
/**
* 校验手机号+携程券ID是否已存在
*/
boolean existsByUserPhoneAndCtripCouponId(String userPhone, String ctripCouponId);
}
@@ -0,0 +1,22 @@
package com.central.order.service;
/**
* 携程API服务接口
*/
public interface ICtripApiService {
/**
* 核销携程优惠券
* @param ctripCouponId 携程优惠券ID
* @param orderNo 订单号
* @return 是否核销成功
*/
boolean verifyCoupon(String ctripCouponId, String orderNo);
/**
* 查询携程优惠券状态
* @param ctripCouponId 携程优惠券ID
* @return 优惠券状态
*/
String getCouponStatus(String ctripCouponId);
}
@@ -2,9 +2,12 @@ package com.central.order.service;
import com.central.order.model.vo.DashboardStatisticsVO; import com.central.order.model.vo.DashboardStatisticsVO;
import java.util.Map;
public interface IDashboardService { public interface IDashboardService {
/** /**
* 获取首页统计数据 * 获取首页统计数据
* @param params 筛选参数
*/ */
DashboardStatisticsVO getDashboardStatistics(); DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params);
} }
@@ -38,6 +38,7 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
* 按景区维度统计 * 按景区维度统计
* @param startTime 开始时间 * @param startTime 开始时间
* @param endTime 结束时间 * @param endTime 结束时间
* @param tourismId 景区ID筛选(可选)
* @return 统计数据列表,包含: * @return 统计数据列表,包含:
* - tourismId: 景区ID * - tourismId: 景区ID
* - tourismName: 景区名称 * - tourismName: 景区名称
@@ -48,17 +49,18 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
* - paidAmountYuan: 已支付金额(元) * - paidAmountYuan: 已支付金额(元)
* - refundAmountYuan: 退款金额(元) * - refundAmountYuan: 退款金额(元)
*/ */
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime); List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId);
/** /**
* 按设备维度统计 * 按设备维度统计
* @param startTime 开始时间 * @param startTime 开始时间
* @param endTime 结束时间 * @param endTime 结束时间
* @param deviceSn 设备编号筛选(可选)
* @return 统计数据列表,包含: * @return 统计数据列表,包含:
* - deviceSn: 设备编号 * - deviceSn: 设备编号
* - totalOrders: 订单总数 * - totalOrders: 订单总数
* - totalAmountYuan: 总金额(元) * - totalAmountYuan: 总金额(元)
* - usageRate: 设备使用率 * - usageRate: 设备使用率
*/ */
List<Map<String, Object>> statisticsByDevice(String startTime, String endTime); List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn);
} }
@@ -35,5 +35,13 @@ public interface ITourismService extends ISuperService<Tourism> {
* @return * @return
*/ */
Tourism getTourismById(Long id); Tourism getTourismById(Long id);
/**
* 获取景区设备列表
* 通过景区下的二维码信息查询二维码绑定的设备
* @param tourismId 景区ID
* @return 设备列表
*/
java.util.List<java.util.Map<String, Object>> getDevicesByTourismId(Long tourismId);
} }
@@ -0,0 +1,233 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.order.entity.Coupon;
import com.central.order.mapper.CouponMapper;
import com.central.order.service.ICouponService;
import com.central.order.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;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* 优惠券服务实现类
*/
@Slf4j
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
@Autowired
private ICtripApiService ctripApiService;
@Override
public IPage<Coupon> getCouponPage(Page<Coupon> page, Coupon coupon) {
return baseMapper.selectCouponPage(page, coupon);
}
@Override
public PageResult<Coupon> findList(Map<String, Object> params) {
// 获取分页参数
Integer page = Integer.parseInt(params.getOrDefault("page", "1").toString());
Integer limit = Integer.parseInt(params.getOrDefault("limit", "10").toString());
// 构建查询条件
Coupon queryCoupon = new Coupon();
if (params.get("couponName") != null) {
queryCoupon.setCouponName(params.get("couponName").toString());
}
if (params.get("couponType") != null) {
queryCoupon.setCouponType(Integer.parseInt(params.get("couponType").toString()));
}
if (params.get("status") != null) {
queryCoupon.setStatus(Integer.parseInt(params.get("status").toString()));
}
if (params.get("userPhone") != null) {
queryCoupon.setUserPhone(params.get("userPhone").toString());
}
if (params.get("source") != null) {
queryCoupon.setSource(Integer.parseInt(params.get("source").toString()));
}
if (params.get("ctripCouponId") != null) {
queryCoupon.setCtripCouponId(params.get("ctripCouponId").toString());
}
// 执行分页查询
Page<Coupon> pageParam = new Page<>(page, limit);
IPage<Coupon> pageResult = baseMapper.selectCouponPage(pageParam, queryCoupon);
// 构建返回结果
return PageResult.<Coupon>builder()
.count(pageResult.getTotal())
.resp_code(0)
.data(pageResult.getRecords())
.build();
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean createCoupon(Coupon coupon) {
// 生成优惠券编号
if (!StringUtils.hasText(coupon.getCouponNo())) {
coupon.setCouponNo(generateCouponNo());
}
// 设置默认值
if (coupon.getStatus() == null) {
coupon.setStatus(0); // 未使用
}
if (coupon.getCreateTime() == null) {
coupon.setCreateTime(new Date());
}
if (coupon.getUpdateTime() == null) {
coupon.setUpdateTime(new Date());
}
return save(coupon);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateCoupon(Coupon coupon) {
coupon.setUpdateTime(new Date());
return updateById(coupon);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteCoupon(Long id) {
return removeById(id);
}
@Override
public List<Coupon> getCouponsByUserPhone(String userPhone) {
return baseMapper.selectByUserPhone(userPhone);
}
@Override
public List<Coupon> getAvailableCouponsByUserPhone(String userPhone) {
return baseMapper.selectAvailableByUserPhone(userPhone);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean useCoupon(Long couponId, String orderNo) {
Coupon coupon = getById(couponId);
if (coupon == null) {
log.error("优惠券不存在,couponId: {}", couponId);
return false;
}
if (coupon.getStatus() != 0) {
log.error("优惠券状态不正确,couponId: {}, status: {}", couponId, coupon.getStatus());
return false;
}
if (coupon.getValidEndTime().before(new Date())) {
log.error("优惠券已过期,couponId: {}", couponId);
return false;
}
return baseMapper.updateCouponUsed(couponId, orderNo) > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean createCouponFromCtrip(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) {
// 检查是否已存在该携程优惠券
Coupon existingCoupon = baseMapper.selectByCtripCouponId(ctripCouponId);
if (existingCoupon != null) {
log.warn("携程优惠券已存在,ctripCouponId: {}", ctripCouponId);
return true; // 已存在也算成功
}
Coupon coupon = new Coupon();
coupon.setCouponNo(generateCouponNo());
coupon.setCouponName(couponName);
coupon.setCouponType(couponType);
coupon.setAmount(amount);
coupon.setMinAmount(minAmount);
coupon.setDiscountRate(discountRate);
coupon.setStatus(0); // 未使用
coupon.setUserPhone(userPhone);
coupon.setSource(1); // 来源:携程
coupon.setCtripCouponId(ctripCouponId);
coupon.setValidStartTime(validStartTime);
coupon.setValidEndTime(validEndTime);
coupon.setCreateTime(new Date());
coupon.setUpdateTime(new Date());
coupon.setCreateBy("ctrip");
coupon.setUpdateBy("ctrip");
return save(coupon);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateExpiredCoupons() {
int count = baseMapper.updateExpiredCoupons();
log.info("批量更新过期优惠券完成,更新数量: {}", count);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean verifyCtripCoupon(String ctripCouponId, String orderNo) {
Coupon coupon = baseMapper.selectByCtripCouponId(ctripCouponId);
if (coupon == null) {
log.error("携程优惠券不存在,ctripCouponId: {}", ctripCouponId);
return false;
}
if (coupon.getStatus() != 0) {
log.error("携程优惠券状态不正确,ctripCouponId: {}, status: {}", ctripCouponId, coupon.getStatus());
return false;
}
if (coupon.getValidEndTime().before(new Date())) {
log.error("携程优惠券已过期,ctripCouponId: {}", ctripCouponId);
return false;
}
// 调用携程核销接口
boolean ctripVerifyResult = ctripApiService.verifyCoupon(ctripCouponId, orderNo);
if (!ctripVerifyResult) {
log.error("携程核销失败,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
return false;
}
// 更新本地优惠券状态
return baseMapper.updateCouponUsed(coupon.getId(), orderNo) > 0;
}
@Override
public boolean existsByUserPhoneAndCtripCouponId(String userPhone, String ctripCouponId) {
return lambdaQuery()
.eq(Coupon::getUserPhone, userPhone)
.eq(Coupon::getCtripCouponId, ctripCouponId)
.count() > 0;
}
/**
* 生成优惠券编号
*/
private String generateCouponNo() {
return "CP" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
}
}
@@ -0,0 +1,51 @@
package com.central.order.service.impl;
import com.central.order.service.ICtripApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* 携程API服务实现类
*/
@Slf4j
@Service
public class CtripApiServiceImpl implements ICtripApiService {
@Override
public boolean verifyCoupon(String ctripCouponId, String orderNo) {
// TODO: 实现具体的携程API调用逻辑
// 这里需要根据携程的API文档实现具体的调用
log.info("调用携程核销接口,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
// 模拟API调用
try {
// 这里应该调用携程的核销API
// 例如:HttpClient调用携程的核销接口
// 暂时返回true,实际需要根据API调用结果返回
return true;
} catch (Exception e) {
log.error("携程核销接口调用失败", e);
return false;
}
}
@Override
public String getCouponStatus(String ctripCouponId) {
// TODO: 实现具体的携程API调用逻辑
// 这里需要根据携程的API文档实现具体的调用
log.info("调用携程查询优惠券状态接口,ctripCouponId: {}", ctripCouponId);
// 模拟API调用
try {
// 这里应该调用携程的查询API
// 例如:HttpClient调用携程的查询接口
// 暂时返回"VALID",实际需要根据API调用结果返回
return "VALID";
} catch (Exception e) {
log.error("携程查询优惠券状态接口调用失败", e);
return "UNKNOWN";
}
}
}
@@ -10,6 +10,7 @@ import org.springframework.stereotype.Service;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.util.List; import java.util.List;
import java.util.Map;
@Slf4j @Slf4j
@Service @Service
@@ -19,21 +20,18 @@ public class DashboardServiceImpl implements IDashboardService {
private final DashboardMapper dashboardMapper; private final DashboardMapper dashboardMapper;
@Override @Override
public DashboardStatisticsVO getDashboardStatistics() { public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
DashboardStatisticsVO statistics = new DashboardStatisticsVO(); DashboardStatisticsVO statistics = new DashboardStatisticsVO();
try { try {
// 1. 获取订单统计 // 1. 获取订单统计(包含对账数据)
statistics.setOrderStats(getOrderStatistics()); statistics.setOrderStats(getOrderStatistics(params));
// 2. 获取收入统计 // 2. 获取图表统计
statistics.setIncomeStats(getIncomeStatistics()); statistics.setChartStats(getChartStatistics(params));
// 5. 获取图表统计 // 3. 获取筛选选项
statistics.setChartStats(getChartStatistics()); statistics.setFilterOptions(getFilterOptions());
// 6. 获取景区排行
statistics.setTourismRanking(getTourismRanking());
} catch (Exception e) { } catch (Exception e) {
log.error("获取仪表盘统计数据失败", e); log.error("获取仪表盘统计数据失败", e);
@@ -43,19 +41,19 @@ public class DashboardServiceImpl implements IDashboardService {
} }
/** /**
* 获取订单统计 * 获取订单统计(包含对账数据)
*/ */
private OrderStatistics getOrderStatistics() { private OrderStatistics getOrderStatistics(Map<String, Object> params) {
OrderStatistics stats = new OrderStatistics(); OrderStatistics stats = new OrderStatistics();
// 获取订单总数 // 获取订单总数
stats.setTotalOrders(dashboardMapper.getTotalOrders()); stats.setTotalOrders(dashboardMapper.getTotalOrders(params));
// 获取今日订单数 // 获取今日订单数
stats.setTodayOrders(dashboardMapper.getTodayOrders()); stats.setTodayOrders(dashboardMapper.getTodayOrders(params));
// 计算订单增长率 // 计算订单增长率
Long yesterdayOrders = dashboardMapper.getYesterdayOrders(); Long yesterdayOrders = dashboardMapper.getYesterdayOrders(params);
if (yesterdayOrders > 0) { if (yesterdayOrders > 0) {
BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders) BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders)
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP) .divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
@@ -64,7 +62,7 @@ public class DashboardServiceImpl implements IDashboardService {
} }
// 计算完成率 // 计算完成率
Long completedOrders = dashboardMapper.getCompletedOrders(); Long completedOrders = dashboardMapper.getCompletedOrders(params);
if (stats.getTotalOrders() > 0) { if (stats.getTotalOrders() > 0) {
BigDecimal completionRate = new BigDecimal(completedOrders) BigDecimal completionRate = new BigDecimal(completedOrders)
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP) .divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
@@ -72,29 +70,13 @@ public class DashboardServiceImpl implements IDashboardService {
stats.setCompletionRate(completionRate); stats.setCompletionRate(completionRate);
} }
return stats; // 获取对账相关数据
} stats.setTotalAmount(dashboardMapper.getTotalAmount(params));
stats.setRefundAmount(dashboardMapper.getRefundAmount(params));
/** // 景区收入 = 总订单金额 - 退款金额
* 获取收入统计 Long netIncome = (stats.getTotalAmount() != null ? stats.getTotalAmount() : 0)
*/ - (stats.getRefundAmount() != null ? stats.getRefundAmount() : 0);
private IncomeStatistics getIncomeStatistics() { stats.setNetIncome(netIncome);
IncomeStatistics stats = new IncomeStatistics();
// 获取总收入
stats.setTotalAmount(dashboardMapper.getTotalIncome());
// 获取今日收入
stats.setTodayAmount(dashboardMapper.getTodayIncome());
// 计算目标完成率(假设每日目标10000元)
BigDecimal targetAmount = new BigDecimal(1000000); // 100元 * 100(分)
if (stats.getTodayAmount() > 0) {
BigDecimal completion = new BigDecimal(stats.getTodayAmount())
.divide(targetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100));
stats.setTargetCompletion(completion);
}
return stats; return stats;
} }
@@ -102,22 +84,36 @@ public class DashboardServiceImpl implements IDashboardService {
/** /**
* 获取图表统计 * 获取图表统计
*/ */
private ChartStatistics getChartStatistics() { private ChartStatistics getChartStatistics(Map<String, Object> params) {
ChartStatistics stats = new ChartStatistics(); ChartStatistics stats = new ChartStatistics();
// 获取订单趋势(最近7天) // 获取订单趋势(最近7天)
stats.setOrderTrend(dashboardMapper.getOrderTrend()); stats.setOrderTrend(dashboardMapper.getOrderTrend(params));
// 获取订单状态分布
stats.setOrderDistribution(dashboardMapper.getOrderDistribution(params));
// 获取收入构成 // 获取收入构成
stats.setIncomeData(dashboardMapper.getIncomeData()); stats.setIncomeBreakdown(dashboardMapper.getIncomeBreakdown(params));
return stats; return stats;
} }
/** /**
* 获取景区排行 * 获取筛选选项
*/ */
private List<TourismRankingVO> getTourismRanking() { private FilterOptions getFilterOptions() {
return dashboardMapper.getTourismRanking(); FilterOptions options = new FilterOptions();
// 获取景区列表
options.setTourismList(dashboardMapper.getTourismOptions());
// 获取二维码列表
options.setQrcodeList(dashboardMapper.getQrcodeOptions());
// 获取设备列表
options.setDeviceList(dashboardMapper.getDeviceOptions());
return options;
} }
} }
@@ -202,15 +202,23 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
} }
@Override @Override
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime) { public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId) {
try { try {
OrderStatisticsQuery query = OrderStatisticsQuery.builder() OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
.startTime(startTime) .startTime(startTime)
.endTime(endTime) .endTime(endTime)
.groupField("o.tourism_id") .groupField("o.tourism_id");
.build();
// 如果指定了景区ID,则添加筛选条件
if (tourismId != null && !tourismId.trim().isEmpty()) {
try {
queryBuilder.tourismId(Long.parseLong(tourismId));
} catch (NumberFormatException e) {
log.warn("景区ID格式错误: {}", tourismId);
}
}
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query); List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
return processStatisticsResult(statistics); return processStatisticsResult(statistics);
} catch (Exception e) { } catch (Exception e) {
log.error("按景区维度统计失败", e); log.error("按景区维度统计失败", e);
@@ -219,15 +227,19 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
} }
@Override @Override
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime) { public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn) {
try { try {
OrderStatisticsQuery query = OrderStatisticsQuery.builder() OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
.startTime(startTime) .startTime(startTime)
.endTime(endTime) .endTime(endTime)
.groupField("o.device_sn") .groupField("o.device_sn");
.build();
// 如果指定了设备编号,则添加筛选条件
if (deviceSn != null && !deviceSn.trim().isEmpty()) {
queryBuilder.deviceSn(deviceSn);
}
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query); List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
return processStatisticsResult(statistics); return processStatisticsResult(statistics);
} catch (Exception e) { } catch (Exception e) {
log.error("按设备维度统计失败", e); log.error("按设备维度统计失败", e);
@@ -47,4 +47,9 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
return baseMapper.getTourismById(id); return baseMapper.getTourismById(id);
} }
@Override
public List<Map<String, Object>> getDevicesByTourismId(Long tourismId) {
return baseMapper.getDevicesByTourismId(tourismId);
}
} }
@@ -0,0 +1,32 @@
package com.central.order.task;
import com.central.order.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 CouponExpirationTask {
@Autowired
private ICouponService couponService;
/**
* 每天凌晨2点执行,批量更新过期优惠券状态
*/
@Scheduled(cron = "0 0 2 * * ?")
public void updateExpiredCoupons() {
log.info("开始执行优惠券过期状态更新任务");
try {
couponService.updateExpiredCoupons();
log.info("优惠券过期状态更新任务执行完成");
} catch (Exception e) {
log.error("优惠券过期状态更新任务执行失败", e);
}
}
}
@@ -0,0 +1,124 @@
<?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.CouponMapper">
<!-- 基础结果映射 -->
<resultMap id="BaseResultMap" type="com.central.order.entity.Coupon">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="coupon_no" property="couponNo" jdbcType="VARCHAR"/>
<result column="coupon_name" property="couponName" jdbcType="VARCHAR"/>
<result column="coupon_type" property="couponType" jdbcType="INTEGER"/>
<result column="amount" property="amount" jdbcType="DECIMAL"/>
<result column="min_amount" property="minAmount" jdbcType="DECIMAL"/>
<result column="discount_rate" property="discountRate" jdbcType="INTEGER"/>
<result column="status" property="status" jdbcType="INTEGER"/>
<result column="user_phone" property="userPhone" jdbcType="VARCHAR"/>
<result column="user_id" property="userId" jdbcType="BIGINT"/>
<result column="source" property="source" jdbcType="INTEGER"/>
<result column="ctrip_coupon_id" property="ctripCouponId" jdbcType="VARCHAR"/>
<result column="valid_start_time" property="validStartTime" jdbcType="TIMESTAMP"/>
<result column="valid_end_time" property="validEndTime" jdbcType="TIMESTAMP"/>
<result column="used_time" property="usedTime" jdbcType="TIMESTAMP"/>
<result column="used_order_no" property="usedOrderNo" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
<result column="create_by" property="createBy" jdbcType="VARCHAR"/>
<result column="update_by" property="updateBy" jdbcType="VARCHAR"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
<result column="tenant_id" property="tenantId" jdbcType="VARCHAR"/>
</resultMap>
<!-- 基础字段 -->
<sql id="Base_Column_List">
id, coupon_no, coupon_name, coupon_type, amount, min_amount, discount_rate, status,
user_phone, user_id, source, ctrip_coupon_id, valid_start_time, valid_end_time,
used_time, used_order_no, create_time, update_time, create_by, update_by, remark, tenant_id
</sql>
<!-- 分页查询优惠券列表 -->
<select id="selectCouponPage" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_coupon
<where>
<if test="coupon.couponName != null and coupon.couponName != ''">
AND coupon_name LIKE CONCAT('%', #{coupon.couponName}, '%')
</if>
<if test="coupon.couponType != null">
AND coupon_type = #{coupon.couponType}
</if>
<if test="coupon.status != null">
AND status = #{coupon.status}
</if>
<if test="coupon.userPhone != null and coupon.userPhone != ''">
AND user_phone = #{coupon.userPhone}
</if>
<if test="coupon.source != null">
AND source = #{coupon.source}
</if>
<if test="coupon.ctripCouponId != null and coupon.ctripCouponId != ''">
AND ctrip_coupon_id = #{coupon.ctripCouponId}
</if>
</where>
ORDER BY create_time DESC
</select>
<!-- 根据手机号查询用户优惠券 -->
<select id="selectByUserPhone" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE user_phone = #{userPhone}
ORDER BY create_time DESC
</select>
<!-- 根据手机号查询可用优惠券 -->
<select id="selectAvailableByUserPhone" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE user_phone = #{userPhone}
AND status = 0
AND valid_start_time &lt;= NOW()
AND valid_end_time &gt;= NOW()
ORDER BY create_time DESC
</select>
<!-- 根据携程优惠券ID查询 -->
<select id="selectByCtripCouponId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE ctrip_coupon_id = #{ctripCouponId}
LIMIT 1
</select>
<!-- 根据订单号查询使用的优惠券 -->
<select id="selectByUsedOrderNo" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_coupon
WHERE used_order_no = #{usedOrderNo}
LIMIT 1
</select>
<!-- 更新优惠券状态为已使用 -->
<update id="updateCouponUsed">
UPDATE t_coupon
SET status = 1,
used_time = NOW(),
used_order_no = #{usedOrderNo},
update_time = NOW()
WHERE id = #{id}
</update>
<!-- 批量更新过期优惠券状态 -->
<update id="updateExpiredCoupons">
UPDATE t_coupon
SET status = 2,
update_time = NOW()
WHERE status = 0
AND valid_end_time &lt; NOW()
</update>
</mapper>
@@ -17,4 +17,23 @@
INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone) INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone)
VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone}) VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone})
</insert> </insert>
<!-- 获取景区设备列表 -->
<select id="getDevicesByTourismId" resultType="java.util.Map">
SELECT DISTINCT
q.device_sn as deviceSn,
q.name as qrcodeName,
q.code_id as qrcodeId,
q.price as qrcodePrice,
q.status as qrcodeStatus,
q.create_time as qrcodeCreateTime,
t.tourism_name as tourismName,
t.tourism_address as tourismAddress
FROM qrcodes q
LEFT JOIN tourisms t ON q.tourism_id = t.id
WHERE q.tourism_id = #{tourismId}
AND q.is_del = 0
AND t.is_del = 0
ORDER BY q.create_time DESC
</select>
</mapper> </mapper>
@@ -20,7 +20,7 @@ public class WechatConfig {
private String tenantId; private String tenantId;
/** /**
* 配置类型:MP-公众号,MINI-小程序,PAY-支付 * 配置类型:MP-公众号,MINI-小程序,PAY-支付,MA-小程序消息
*/ */
private String type; private String type;
@@ -9,43 +9,43 @@
export default { export default {
dev: { dev: {
'/api-uaa/': { '/api-uaa/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-user/': { '/api-user/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-log/': { '/api-log/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-search/': { '/api-search/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-generator/': { '/api-generator/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-file/': { '/api-file/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-order/': { '/api-order/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-device/': { '/api-device/': {
// target: 'http://119.45.169.13:9900', target: 'http://119.45.169.13:9900',
target: 'http://127.0.0.1:9900', // target: 'http://127.0.0.1:9900',
changeOrigin: true, changeOrigin: true,
}, },
}, },
@@ -1,62 +1,76 @@
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, Progress, Typography } from 'antd'; import { Card, Row, Col, Statistic, Progress, Typography, Select, DatePicker, Space, Button } from 'antd';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { dashboard } from '@/services/orders/api'; import { dashboard } from '@/services/orders/api';
import { Area, Column, Pie } from '@ant-design/plots'; import { Area, Column, Pie } from '@ant-design/plots';
import { import {
ShoppingCartOutlined, ShoppingCartOutlined,
RocketOutlined,
MobileOutlined,
UserOutlined,
RiseOutlined,
PayCircleOutlined, PayCircleOutlined,
RiseOutlined,
FilterOutlined,
ReloadOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import styles from './Welcome.less'; import styles from './Welcome.less';
const { Title } = Typography; const { Title } = Typography;
const { RangePicker } = DatePicker;
interface Statistics { interface Statistics {
totalOrders: number; orderStats: {
todayOrders: number; totalOrders: number;
orderGrowth: number; todayOrders: number;
completionRate: number; orderGrowth: number;
totalAmount: number; completionRate: number;
todayAmount: number; // 新增对账维度
targetCompletion: number; totalAmount: number; // 订单总金额(分)
totalWaylines: number; platformAmount: number; // 平台分账金额(分)
activeWaylines: number; tourismAmount: number; // 景区分账金额(分)
waylineUsage: number; refundAmount: number; // 退款金额(分)
totalDevices: number; netIncome: number; // 净收入(分)
onlineDevices: number; };
deviceOnlineRate: number; // 移除设备和航线统计
orderTrend: { chartStats: {
date: string; orderTrend: {
type: string; date: string;
value: number; type: string;
}[]; value: number;
deviceDistribution: { }[];
type: string; orderDistribution: {
value: number; type: string;
}[]; value: number;
incomeData: { }[];
type: string; incomeBreakdown: {
value: number; type: string;
}[]; value: number;
tourismRanking: { }[];
id: string; };
name: string; // 新增筛选维度数据
value: number; filterOptions: {
}[]; tourismList: { label: string; value: number; }[];
qrcodeList: { label: string; value: string; }[];
deviceList: { label: string; value: string; }[];
};
} }
const Welcome: React.FC = () => { const Welcome: React.FC = () => {
const [loading, setLoading] = useState<boolean>(true); const [loading, setLoading] = useState<boolean>(true);
const [statistics, setStatistics] = useState<any>({}); const [statistics, setStatistics] = useState<any>({});
// 只保留景区筛选
const [selectedTourism, setSelectedTourism] = useState<number | undefined>();
// 新增平台分账比例,默认70%
const [platformRate, setPlatformRate] = useState<number>(0.7);
// 新增时间区间筛选
const [timeRange, setTimeRange] = useState<[string, string]>(['', '']);
const fetchData = async () => { const fetchData = async () => {
try { try {
setLoading(true); setLoading(true);
const result = await dashboard(); const params = {
tourismId: selectedTourism,
startTime: timeRange[0],
endTime: timeRange[1],
};
const result = await dashboard(params);
if (result.resp_code === 0) { if (result.resp_code === 0) {
setStatistics(result.data); setStatistics(result.data);
} }
@@ -69,16 +83,17 @@ const Welcome: React.FC = () => {
useEffect(() => { useEffect(() => {
fetchData(); fetchData();
const timer = setInterval(fetchData, 5 * 60 * 1000); }, [selectedTourism, timeRange]);
return () => clearInterval(timer);
}, []);
// 更新数据访问方式 // 更新数据访问方式
const orderStats = statistics.orderStats || {}; const orderStats = statistics.orderStats || {};
const incomeStats = statistics.incomeStats || {};
const waylineStats = statistics.waylineStats || {};
const deviceStats = statistics.deviceStats || {};
const chartStats = statistics.chartStats || {}; const chartStats = statistics.chartStats || {};
const filterOptions = statistics.filterOptions || {};
// 动态分账金额计算
const netIncome = orderStats.netIncome || 0;
const platformAmount = Math.round(netIncome * platformRate);
const tourismAmount = netIncome - platformAmount;
// 订单趋势配置 // 订单趋势配置
const orderTrendConfig = { const orderTrendConfig = {
@@ -96,9 +111,9 @@ const Welcome: React.FC = () => {
}, },
}; };
// 设备分布配置 // 订单分布配置
const deviceDistConfig = { const orderDistConfig = {
data: chartStats.deviceDistribution || [], data: chartStats.orderDistribution || [],
angleField: 'value', angleField: 'value',
colorField: 'type', colorField: 'type',
radius: 0.8, radius: 0.8,
@@ -108,9 +123,13 @@ const Welcome: React.FC = () => {
}, },
}; };
// 收入统计配置 // 收入构成图表数据
const incomeConfig = { const incomeConfig = {
data: chartStats.incomeData || [], data: [
{ type: '平台分账', value: platformAmount / 100 },
{ type: '景区分账', value: tourismAmount / 100 },
{ type: '退款金额', value: (orderStats.refundAmount || 0) / 100 },
],
xField: 'type', xField: 'type',
yField: 'value', yField: 'value',
label: { label: {
@@ -124,9 +143,59 @@ const Welcome: React.FC = () => {
return ( return (
<PageContainer className={styles.container}> <PageContainer className={styles.container}>
{/* 筛选条件 */}
<Card style={{ marginBottom: 16 }}>
<Space size="large">
<span>筛选条件:</span>
<Select
placeholder="选择景区"
style={{ width: 200 }}
allowClear
options={filterOptions.tourismList || []}
value={selectedTourism}
onChange={setSelectedTourism}
/>
{/* 新增平台分账比例选择 */}
<span>平台分账比例:</span>
<Select
style={{ width: 120 }}
value={platformRate}
onChange={setPlatformRate}
options={[
{ label: '70%', value: 0.7 },
{ label: '60%', value: 0.6 },
{ label: '50%', value: 0.5 },
]}
/>
{/* 新增时间区间筛选 */}
<RangePicker
placeholder={['开始时间', '结束时间']}
onChange={(dates) => {
if (dates) {
setTimeRange([
dates[0]?.format('YYYY-MM-DD HH:mm:ss') || '',
dates[1]?.format('YYYY-MM-DD HH:mm:ss') || ''
]);
} else {
setTimeRange(['', '']);
}
}}
showTime
style={{ width: 300 }}
/>
<Button
icon={<ReloadOutlined />}
onClick={fetchData}
type="primary"
>
刷新
</Button>
</Space>
</Card>
{/* 核心指标 */} {/* 核心指标 */}
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
<Col xs={24} sm={12} md={6}> <Col xs={24} sm={12} md={8}>
<Card className={styles.statCard} loading={loading}> <Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}> <div className={styles.statHeader}>
<ShoppingCartOutlined className={styles.iconOrders} /> <ShoppingCartOutlined className={styles.iconOrders} />
@@ -152,65 +221,59 @@ const Welcome: React.FC = () => {
</Card> </Card>
</Col> </Col>
<Col xs={24} sm={12} md={6}> <Col xs={24} sm={12} md={8}>
<Card className={styles.statCard} loading={loading}> <Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}> <div className={styles.statHeader}>
<PayCircleOutlined className={styles.iconIncome} /> <PayCircleOutlined className={styles.iconIncome} />
<span>收入统计</span> <span>收入统计</span>
</div> </div>
<Statistic <Statistic
title="总收入" title="订单总金额"
value={(incomeStats.totalAmount || 0) / 100} value={(orderStats.totalAmount || 0) / 100}
precision={2} precision={2}
prefix="¥" prefix="¥"
/> />
<div className={styles.subStats}> <div className={styles.subStats}>
<Statistic <Statistic
title="今日收入" title="景区净收入"
value={(incomeStats.todayAmount || 0) / 100} value={netIncome / 100}
precision={2}
prefix="¥"
/>
<Statistic
title="退款金额"
value={(orderStats.refundAmount || 0) / 100}
precision={2}
prefix="¥"
/>
</div>
</Card>
</Col>
<Col xs={24} sm={12} md={8}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<PayCircleOutlined className={styles.iconIncome} />
<span>分账明细</span>
</div>
<Statistic
title="平台分账"
value={platformAmount / 100}
precision={2}
prefix="¥"
/>
<div className={styles.subStats}>
<Statistic
title="景区分账"
value={tourismAmount / 100}
precision={2} precision={2}
prefix="¥" prefix="¥"
/> />
<Progress <Progress
percent={incomeStats.targetCompletion || 0} percent={netIncome > 0 ? (tourismAmount / netIncome * 100) : 0}
size="small"
status="active"
/>
</div>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<RocketOutlined className={styles.iconWayline} />
<span>航线概况</span>
</div>
<Statistic title="航线总数" value={waylineStats.totalWaylines || 0} />
<div className={styles.subStats}>
<Statistic title="活跃航线" value={waylineStats.activeWaylines || 0} />
<Progress
percent={waylineStats.waylineUsage || 0}
size="small"
status="active"
/>
</div>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className={styles.statCard} loading={loading}>
<div className={styles.statHeader}>
<MobileOutlined className={styles.iconDevice} />
<span>设备状态</span>
</div>
<Statistic title="设备总数" value={deviceStats.totalDevices || 0} />
<div className={styles.subStats}>
<Statistic title="在线设备" value={deviceStats.onlineDevices || 0} />
<Progress
percent={deviceStats.deviceOnlineRate || 0}
size="small" size="small"
status="active" status="active"
format={(percent) => `分账率 ${percent?.toFixed(1)}%`}
/> />
</div> </div>
</Card> </Card>
@@ -225,34 +288,19 @@ const Welcome: React.FC = () => {
</Card> </Card>
</Col> </Col>
<Col xs={24} lg={8}> <Col xs={24} lg={8}>
<Card title="设备分布" loading={loading}> <Card title="订单状态分布" loading={loading}>
<Pie {...deviceDistConfig} height={300} /> <Pie {...orderDistConfig} height={300} />
</Card> </Card>
</Col> </Col>
</Row> </Row>
{/* 业务数据 */} {/* 收入构成 */}
<Row gutter={[16, 16]} className={styles.businessRow}> <Row gutter={[16, 16]}>
<Col xs={24} lg={12}> <Col xs={24}>
<Card title="收入统计" loading={loading}> <Card title="收入构成分析" loading={loading}>
<Column {...incomeConfig} height={300} /> <Column {...incomeConfig} height={300} />
</Card> </Card>
</Col> </Col>
<Col xs={24} lg={12}>
<Card title="景区排名" loading={loading}>
<div className={styles.rankList}>
{statistics.tourismRanking?.map((item: { id: string; name: string; value: number }, index: number) => (
<div key={item.id} className={styles.rankItem}>
<span className={`${styles.rankNum} ${index < 3 ? 'topThree' : ''}`}>
{index + 1}
</span>
<span className={styles.rankName}>{item.name}</span>
<span className={styles.rankValue}>{item.value}</span>
</div>
))}
</div>
</Card>
</Col>
</Row> </Row>
</PageContainer> </PageContainer>
); );
@@ -0,0 +1,449 @@
import React, { useState, useEffect } from 'react';
import {
Card,
Table,
Button,
Space,
Modal,
Form,
Input,
Select,
DatePicker,
InputNumber,
message,
Popconfirm,
Tag,
Tooltip,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { getCouponList, createCoupon, updateCoupon, deleteCoupon, getCouponById } from '@/services/orders/api';
import moment from 'moment';
const { Option } = Select;
const { RangePicker } = DatePicker;
const CouponManagement: React.FC = () => {
const [loading, setLoading] = useState(false);
const [dataSource, setDataSource] = useState<ORDERS.Coupon[]>([]);
const [total, setTotal] = useState(0);
const [current, setCurrent] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [modalVisible, setModalVisible] = useState(false);
const [editingCoupon, setEditingCoupon] = useState<ORDERS.Coupon | null>(null);
const [form] = Form.useForm();
// 优惠券类型选项
const couponTypeOptions = [
{ label: '满减券', value: 1 },
{ label: '折扣券', value: 2 },
{ label: '免费券', value: 3 },
];
// 优惠券状态选项
const statusOptions = [
{ label: '未使用', value: 0 },
{ label: '已使用', value: 1 },
{ label: '已过期', value: 2 },
{ label: '已作废', value: 3 },
];
// 来源选项
const sourceOptions = [
{ label: '携程', value: 1 },
{ label: '高飞自建', value: 2 },
];
// 获取优惠券列表
const fetchCouponList = async (params?: any) => {
setLoading(true);
try {
const result = await getCouponList({
current: params?.current || current,
pageSize: params?.pageSize || pageSize,
...params,
});
setDataSource(result.data || []);
setTotal(result.total || 0);
} catch (error) {
message.error('获取优惠券列表失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchCouponList();
}, []);
// 表格列定义
const columns = [
{
title: '优惠券编号',
dataIndex: 'couponNo',
key: 'couponNo',
width: 150,
},
{
title: '优惠券名称',
dataIndex: 'couponName',
key: 'couponName',
width: 200,
},
{
title: '优惠券类型',
dataIndex: 'couponType',
key: 'couponType',
width: 100,
render: (type: number) => {
const option = couponTypeOptions.find(item => item.value === type);
return option ? option.label : '-';
},
},
{
title: '面额/折扣',
key: 'amount',
width: 120,
render: (record: ORDERS.Coupon) => {
if (record.couponType === 2) {
return `${record.discountRate}%`;
}
return `¥${record.amount}`;
},
},
{
title: '使用门槛',
dataIndex: 'minAmount',
key: 'minAmount',
width: 100,
render: (amount: number) => amount ? `¥${amount}` : '-',
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
render: (status: number) => {
const option = statusOptions.find(item => item.value === status);
const color = status === 0 ? 'green' : status === 1 ? 'blue' : status === 2 ? 'orange' : 'red';
return option ? <Tag color={color}>{option.label}</Tag> : '-';
},
},
{
title: '用户手机号',
dataIndex: 'userPhone',
key: 'userPhone',
width: 130,
},
{
title: '来源',
dataIndex: 'source',
key: 'source',
width: 100,
render: (source: number) => {
const option = sourceOptions.find(item => item.value === source);
return option ? option.label : '-';
},
},
{
title: '有效期',
key: 'validTime',
width: 200,
render: (record: ORDERS.Coupon) => (
<div>
<div>{moment(record.validStartTime).format('YYYY-MM-DD HH:mm')}</div>
<div>至</div>
<div>{moment(record.validEndTime).format('YYYY-MM-DD HH:mm')}</div>
</div>
),
},
{
title: '创建时间',
dataIndex: 'createTime',
key: 'createTime',
width: 150,
render: (time: string) => time ? moment(time).format('YYYY-MM-DD HH:mm') : '-',
},
{
title: '操作',
key: 'action',
width: 150,
fixed: 'right' as const,
render: (record: ORDERS.Coupon) => (
<Space size="small">
<Tooltip title="查看详情">
<Button
type="link"
size="small"
icon={<EyeOutlined />}
onClick={() => handleView(record)}
/>
</Tooltip>
<Tooltip title="编辑">
<Button
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
/>
</Tooltip>
<Popconfirm
title="确定要删除这个优惠券吗?"
onConfirm={() => handleDelete(record.id)}
okText="确定"
cancelText="取消"
>
<Tooltip title="删除">
<Button
type="link"
size="small"
danger
icon={<DeleteOutlined />}
/>
</Tooltip>
</Popconfirm>
</Space>
),
},
];
// 查看详情
const handleView = (record: ORDERS.Coupon) => {
setEditingCoupon(record);
setModalVisible(true);
};
// 编辑
const handleEdit = (record: ORDERS.Coupon) => {
setEditingCoupon(record);
form.setFieldsValue({
...record,
validTime: [moment(record.validStartTime), moment(record.validEndTime)],
});
setModalVisible(true);
};
// 删除
const handleDelete = async (id: number) => {
try {
await deleteCoupon(id);
message.success('删除成功');
fetchCouponList();
} catch (error) {
message.error('删除失败');
}
};
// 新增
const handleAdd = () => {
setEditingCoupon(null);
form.resetFields();
setModalVisible(true);
};
// 提交表单
const handleSubmit = async () => {
try {
const values = await form.validateFields();
const [validStartTime, validEndTime] = values.validTime;
const couponData = {
...values,
validStartTime: validStartTime.format('YYYY-MM-DD HH:mm:ss'),
validEndTime: validEndTime.format('YYYY-MM-DD HH:mm:ss'),
};
if (editingCoupon) {
await updateCoupon(editingCoupon.id, couponData);
message.success('更新成功');
} else {
await createCoupon(couponData);
message.success('创建成功');
}
setModalVisible(false);
fetchCouponList();
} catch (error) {
message.error('操作失败');
}
};
// 表格分页变化
const handleTableChange = (pagination: any) => {
setCurrent(pagination.current);
setPageSize(pagination.pageSize);
fetchCouponList({
current: pagination.current,
pageSize: pagination.pageSize,
});
};
return (
<Card title="优惠券管理" extra={
<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
新增优惠券
</Button>
}>
<Table
columns={columns}
dataSource={dataSource}
loading={loading}
rowKey="id"
pagination={{
current,
pageSize,
total,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total) => `共 ${total} 条记录`,
}}
onChange={handleTableChange}
scroll={{ x: 1500 }}
/>
<Modal
title={editingCoupon ? '编辑优惠券' : '新增优惠券'}
open={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
width={600}
destroyOnClose
>
<Form
form={form}
layout="vertical"
initialValues={{
couponType: 1,
status: 0,
source: 2,
}}
>
<Form.Item
name="couponName"
label="优惠券名称"
rules={[{ required: true, message: '请输入优惠券名称' }]}
>
<Input placeholder="请输入优惠券名称" />
</Form.Item>
<Form.Item
name="couponType"
label="优惠券类型"
rules={[{ required: true, message: '请选择优惠券类型' }]}
>
<Select placeholder="请选择优惠券类型">
{couponTypeOptions.map(option => (
<Option key={option.value} value={option.value}>
{option.label}
</Option>
))}
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) => prevValues.couponType !== currentValues.couponType}
>
{({ getFieldValue }) => {
const couponType = getFieldValue('couponType');
return couponType === 2 ? (
<Form.Item
name="discountRate"
label="折扣率(%)"
rules={[{ required: true, message: '请输入折扣率' }]}
>
<InputNumber
min={1}
max={99}
placeholder="请输入折扣率"
style={{ width: '100%' }}
/>
</Form.Item>
) : (
<Form.Item
name="amount"
label="优惠券面额"
rules={[{ required: true, message: '请输入优惠券面额' }]}
>
<InputNumber
min={0}
placeholder="请输入优惠券面额"
style={{ width: '100%' }}
/>
</Form.Item>
);
}}
</Form.Item>
<Form.Item
name="minAmount"
label="使用门槛金额"
>
<InputNumber
min={0}
placeholder="请输入使用门槛金额"
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item
name="userPhone"
label="用户手机号"
rules={[{ required: true, message: '请输入用户手机号' }]}
>
<Input placeholder="请输入用户手机号" />
</Form.Item>
<Form.Item
name="source"
label="来源"
rules={[{ required: true, message: '请选择来源' }]}
>
<Select placeholder="请选择来源">
{sourceOptions.map(option => (
<Option key={option.value} value={option.value}>
{option.label}
</Option>
))}
</Select>
</Form.Item>
<Form.Item
name="ctripCouponId"
label="携程优惠券ID"
>
<Input placeholder="请输入携程优惠券ID" />
</Form.Item>
<Form.Item
name="validTime"
label="有效期"
rules={[{ required: true, message: '请选择有效期' }]}
>
<RangePicker
showTime
format="YYYY-MM-DD HH:mm:ss"
placeholder={['开始时间', '结束时间']}
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item
name="remark"
label="备注"
>
<Input.TextArea rows={3} placeholder="请输入备注" />
</Form.Item>
<Form.Item
name="tenantId"
label="租户ID"
>
<Input placeholder="请输入租户ID" />
</Form.Item>
</Form>
</Modal>
</Card>
);
};
export default CouponManagement;
@@ -124,6 +124,15 @@ const TableList: React.FC = () => {
); );
}; };
// 处理删除
const handleDelete = async (record: ORDERS.Qrcode) => {
return handleApiRequest(
() => deleteQrcode(record.id),
'正在删除',
'删除成功'
);
};
const handleTableAction = useCallback(async ( const handleTableAction = useCallback(async (
action: 'add' | 'edit' | 'delete', action: 'add' | 'edit' | 'delete',
record?: ORDERS.Qrcode, record?: ORDERS.Qrcode,
@@ -79,6 +79,15 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
/> />
</ProForm.Group> </ProForm.Group>
<ProForm.Group>
<ProFormText
name="tenantId"
label="租户ID"
width="md"
placeholder="请输入租户ID"
/>
</ProForm.Group>
<ProForm.Group> <ProForm.Group>
<ProFormTextArea <ProFormTextArea
name="tourismDesc" name="tourismDesc"
@@ -142,6 +142,12 @@ const TableList: React.FC = () => {
dataIndex: 'tourismPhone', dataIndex: 'tourismPhone',
copyable: true, copyable: true,
}, },
{
title: '租户ID',
dataIndex: 'tenantId',
copyable: true,
hideInSearch: true,
},
{ {
title: '状态', title: '状态',
dataIndex: 'status', dataIndex: 'status',
@@ -259,6 +265,15 @@ const TableList: React.FC = () => {
/> />
</ProForm.Group> </ProForm.Group>
<ProForm.Group>
<ProFormText
name="tenantId"
label="租户ID"
width="md"
placeholder="请输入租户ID(可选,不填将自动获取当前租户)"
/>
</ProForm.Group>
<ProForm.Group> <ProForm.Group>
<ProFormTextArea <ProFormTextArea
name="tourismDesc" name="tourismDesc"
@@ -1,6 +1,6 @@
// 设备维度统计组件 // 设备维度统计组件
import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react'; import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react';
import { ProForm, ProFormDateRangePicker, ProTable } from '@ant-design/pro-components'; import { ProForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, message } from 'antd'; import { Card, Row, Col, Statistic, message } from 'antd';
import { Column } from '@ant-design/plots'; import { Column } from '@ant-design/plots';
import moment from 'moment'; import moment from 'moment';
@@ -24,9 +24,12 @@ interface DeviceStatisticsItem {
interface DeviceStatisticsProps { interface DeviceStatisticsProps {
refreshKey: number; refreshKey: number;
deviceOptions: { label: string; value: string; }[];
deviceSn?: string;
onDeviceChange: (deviceSn: string) => void;
} }
const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref) => { const DeviceStatistics = forwardRef(({ refreshKey, deviceOptions, deviceSn, onDeviceChange }: DeviceStatisticsProps, ref) => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([ const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([
moment().startOf('month'), moment().startOf('month'),
@@ -41,6 +44,7 @@ const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref)
const params = { const params = {
startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'), startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'), endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
deviceSn: deviceSn,
}; };
const res = await getDeviceStatistics(params); const res = await getDeviceStatistics(params);
@@ -191,8 +195,8 @@ const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref)
submitter={false} submitter={false}
initialValues={{ timeRange }} initialValues={{ timeRange }}
> >
<Row> <Row gutter={16}>
<Col span={24}> <Col span={12}>
<ProFormDateRangePicker <ProFormDateRangePicker
name="timeRange" name="timeRange"
label="统计时间" label="统计时间"
@@ -208,6 +212,19 @@ const DeviceStatistics = forwardRef(({ refreshKey }: DeviceStatisticsProps, ref)
}} }}
/> />
</Col> </Col>
<Col span={12}>
<ProFormSelect
name="deviceSn"
label="选择设备"
fieldProps={{
value: deviceSn,
onChange: onDeviceChange,
options: deviceOptions,
placeholder: '请选择设备',
allowClear: true,
}}
/>
</Col>
</Row> </Row>
</ProForm> </ProForm>
</Card> </Card>
@@ -1,5 +1,5 @@
import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react'; import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react';
import { ProForm, ProFormDateRangePicker, ProTable } from '@ant-design/pro-components'; import { ProForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, message } from 'antd'; import { Card, Row, Col, Statistic, message } from 'antd';
import { Column } from '@ant-design/plots'; import { Column } from '@ant-design/plots';
import moment from 'moment'; import moment from 'moment';
@@ -23,9 +23,12 @@ interface TourismStatisticsItem {
interface TourismStatisticsProps { interface TourismStatisticsProps {
refreshKey: number; refreshKey: number;
tourismOptions: { label: string; value: string; }[];
tourismId?: string;
onTourismChange: (tourismId: string) => void;
} }
const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, ref) => { const TourismStatistics = forwardRef(({ refreshKey, tourismOptions, tourismId, onTourismChange }: TourismStatisticsProps, ref) => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([ const [timeRange, setTimeRange] = useState<[moment.Moment, moment.Moment]>([
moment().startOf('month'), moment().startOf('month'),
@@ -40,6 +43,7 @@ const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, re
const params = { const params = {
startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'), startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'), endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
tourismId: tourismId,
}; };
const res = await getTourismStatistics(params); const res = await getTourismStatistics(params);
@@ -191,8 +195,8 @@ const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, re
submitter={false} submitter={false}
initialValues={{ timeRange }} initialValues={{ timeRange }}
> >
<Row> <Row gutter={16}>
<Col span={24}> <Col span={12}>
<ProFormDateRangePicker <ProFormDateRangePicker
name="timeRange" name="timeRange"
label="统计时间" label="统计时间"
@@ -208,6 +212,19 @@ const TourismStatistics = forwardRef(({ refreshKey }: TourismStatisticsProps, re
}} }}
/> />
</Col> </Col>
<Col span={12}>
<ProFormSelect
name="tourismId"
label="选择景区"
fieldProps={{
value: tourismId,
onChange: onTourismChange,
options: tourismOptions,
placeholder: '请选择景区',
allowClear: true,
}}
/>
</Col>
</Row> </Row>
</ProForm> </ProForm>
</Card> </Card>
@@ -3,7 +3,7 @@ import { PageContainer } from '@ant-design/pro-components';
import { Card, Tabs, Button, message, Modal, DatePicker } from 'antd'; import { Card, Tabs, Button, message, Modal, DatePicker } from 'antd';
import { ReloadOutlined, DownloadOutlined, LineChartOutlined } from '@ant-design/icons'; import { ReloadOutlined, DownloadOutlined, LineChartOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd'; import type { TabsProps } from 'antd';
import { getQrcodeList, generateStatistics } from '@/services/statistics/api'; import { getQrcodeList, getDeviceList, getTourismList, generateStatistics } from '@/services/statistics/api';
import QrcodeStatistics from './components/QrcodeStatistics'; import QrcodeStatistics from './components/QrcodeStatistics';
import DeviceStatistics from './components/DeviceStatistics'; import DeviceStatistics from './components/DeviceStatistics';
import TourismStatistics from './components/TourismStatistics'; import TourismStatistics from './components/TourismStatistics';
@@ -13,7 +13,11 @@ const { RangePicker } = DatePicker;
const Statistics: React.FC = () => { const Statistics: React.FC = () => {
const [qrcodeOptions, setQrcodeOptions] = useState<{ label: string; value: string; }[]>([]); const [qrcodeOptions, setQrcodeOptions] = useState<{ label: string; value: string; }[]>([]);
const [deviceOptions, setDeviceOptions] = useState<{ label: string; value: string; }[]>([]);
const [tourismOptions, setTourismOptions] = useState<{ label: string; value: string; }[]>([]);
const [qrcodeId, setQrcodeId] = useState<string>(); const [qrcodeId, setQrcodeId] = useState<string>();
const [deviceSn, setDeviceSn] = useState<string>();
const [tourismId, setTourismId] = useState<string>();
const [refreshKey, setRefreshKey] = useState(0); const [refreshKey, setRefreshKey] = useState(0);
const [generateModalVisible, setGenerateModalVisible] = useState(false); const [generateModalVisible, setGenerateModalVisible] = useState(false);
const [generateTimeRange, setGenerateTimeRange] = useState<[moment.Moment, moment.Moment]>([ const [generateTimeRange, setGenerateTimeRange] = useState<[moment.Moment, moment.Moment]>([
@@ -27,24 +31,79 @@ const Statistics: React.FC = () => {
const fetchQrcodeList = async () => { const fetchQrcodeList = async () => {
try { try {
const res = await getQrcodeList({ page: 1, limit: 100 }); const res = await getQrcodeList({ page: 1, limit: 100 });
console.log('二维码列表响应:', res); // 添加调试日志
if (res.resp_code === 0 && res.data) { if (res.resp_code === 0 && res.data) {
const options = res.data.map((item: any) => ({ const options = res.data.map((item: any) => ({
label: `${item.name || item.qrcode} | ${item.deviceSn || '无设备'} | ${((item.price || 0) / 100).toFixed(2)}元`, label: `${item.name || item.codeId} | ${item.deviceSn || '无设备'} | ${((item.price || 0) / 100).toFixed(2)}元`,
value: item.codeId, value: item.codeId,
})); }));
console.log('二维码选项:', options); // 添加调试日志
setQrcodeOptions(options); setQrcodeOptions(options);
if (options.length > 0) { if (options.length > 0) {
setQrcodeId(options[0].value); setQrcodeId(options[0].value);
} }
} }
} catch (error) { } catch (error) {
console.error('获取二维码列表失败:', error); // 添加错误日志
message.error('获取二维码列表失败'); message.error('获取二维码列表失败');
} }
}; };
// 获取设备列表
const fetchDeviceList = async () => {
try {
const res = await getDeviceList({ page: 1, limit: 100 });
console.log('设备列表响应:', res);
if (res.resp_code === 0 && res.data) {
const options = res.data.map((item: any) => ({
label: `${item.deviceSn || '未知设备'} | ${item.deviceName || '无名称'}`,
value: item.deviceSn,
}));
console.log('设备选项:', options);
setDeviceOptions(options);
if (options.length > 0) {
setDeviceSn(options[0].value);
}
}
} catch (error) {
console.error('获取设备列表失败:', error);
message.error('获取设备列表失败');
}
};
// 获取景区列表
const fetchTourismList = async () => {
try {
const res = await getTourismList({ page: 1, limit: 100 });
console.log('景区列表响应:', res);
if (res.resp_code === 0 && res.data) {
const options = res.data.map((item: any) => ({
label: `${item.name || '未知景区'} | ${item.address || '无地址'}`,
value: item.id?.toString(),
}));
console.log('景区选项:', options);
setTourismOptions(options);
if (options.length > 0) {
setTourismId(options[0].value);
}
}
} catch (error) {
console.error('获取景区列表失败:', error);
message.error('获取景区列表失败');
}
};
// 初始化加载 // 初始化加载
useEffect(() => { useEffect(() => {
console.log('页面初始化,开始加载数据...');
console.log('当前 activeTab:', activeTab);
// 立即执行数据加载
fetchQrcodeList(); fetchQrcodeList();
fetchDeviceList();
fetchTourismList();
console.log('数据加载函数已调用');
}, []); }, []);
// 生成统计数据 // 生成统计数据
@@ -158,6 +217,9 @@ const Statistics: React.FC = () => {
children: ( children: (
<DeviceStatistics <DeviceStatistics
ref={deviceRef} ref={deviceRef}
deviceOptions={deviceOptions}
deviceSn={deviceSn}
onDeviceChange={setDeviceSn}
refreshKey={refreshKey} refreshKey={refreshKey}
/> />
), ),
@@ -168,6 +230,9 @@ const Statistics: React.FC = () => {
children: ( children: (
<TourismStatistics <TourismStatistics
ref={tourismRef} ref={tourismRef}
tourismOptions={tourismOptions}
tourismId={tourismId}
onTourismChange={setTourismId}
refreshKey={refreshKey} refreshKey={refreshKey}
/> />
), ),
@@ -74,8 +74,14 @@ const TableList: React.FC = () => {
MP: { text: '公众号' }, MP: { text: '公众号' },
MINI: { text: '小程序' }, MINI: { text: '小程序' },
PAY: { text: '支付' }, PAY: { text: '支付' },
MA: { text: '小程序消息' },
}, },
}, },
{
title: '租户ID',
dataIndex: 'tenantId',
copyable: true,
},
{ {
title: '商户ID', title: '商户ID',
dataIndex: 'merchantId', dataIndex: 'merchantId',
@@ -86,6 +92,28 @@ const TableList: React.FC = () => {
dataIndex: 'appId', dataIndex: 'appId',
copyable: true, copyable: true,
}, },
{
title: '服务商模式',
dataIndex: 'isServiceMode',
valueType: 'select',
valueEnum: {
true: { text: '服务商' },
false: { text: '普通商户' },
},
render: (_, record) => (
<Tag color={record.isServiceMode ? 'blue' : 'default'}>
{record.isServiceMode ? '服务商' : '普通商户'}
</Tag>
),
},
{
title: '服务商商户号',
dataIndex: 'serviceMchId',
},
{
title: '子商户号',
dataIndex: 'subMchId',
},
{ {
title: '状态', title: '状态',
dataIndex: 'status', dataIndex: 'status',
@@ -101,12 +129,12 @@ const TableList: React.FC = () => {
), ),
}, },
{ {
title: '分账功能', title: '分账',
dataIndex: 'profitSharingEnabled', dataIndex: 'profitSharingEnabled',
valueType: 'switch', valueType: 'switch',
}, },
{ {
title: '异步处理', title: '异步',
dataIndex: 'asyncEnabled', dataIndex: 'asyncEnabled',
valueType: 'switch', valueType: 'switch',
}, },
@@ -122,6 +150,11 @@ const TableList: React.FC = () => {
valueType: 'dateTime', valueType: 'dateTime',
sorter: true, sorter: true,
}, },
{
title: '备注',
dataIndex: 'remark',
ellipsis: true,
},
{ {
title: '操作', title: '操作',
dataIndex: 'option', dataIndex: 'option',
@@ -160,110 +193,163 @@ const TableList: React.FC = () => {
// 表单字段定义 // 表单字段定义
const renderModalContent = () => ( const renderModalContent = () => (
<ProForm.Group> <>
<ProFormSelect <ProForm.Group>
rules={[{ required: true, message: '配置类型不能为空' }]} <ProFormSelect
width="md" rules={[{ required: true, message: '配置类型不能为空' }]}
name="type" width="md"
label="配置类型" name="type"
options={TYPE_OPTIONS} label="配置类型"
/> options={TYPE_OPTIONS}
<ProFormText />
rules={[{ required: true, message: '商户ID不能为空' }]} <ProFormText
width="md" width="md"
name="merchantId" name="tenantId"
label="商户ID" label="租户ID"
/> />
<ProFormText <ProFormText
rules={[{ required: true, message: '应用ID不能为空' }]} rules={[{ required: true, message: '商户ID不能为空' }]}
width="md" width="md"
name="appId" name="merchantId"
label="应用ID" label="商户ID"
/> />
<ProFormText <ProFormText
rules={[{ required: true, message: '应用密钥不能为空' }]} rules={[{ required: true, message: '应用ID不能为空' }]}
width="md" width="md"
name="appSecret" name="appId"
label="应用密钥" label="应用ID"
/> />
<ProFormText <ProFormText
width="md" rules={[{ required: true, message: '应用密钥不能为空' }]}
name="mchKey" width="md"
label="商户API密钥" name="appSecret"
/> label="应用密钥"
<ProFormText />
width="md" <ProFormText
name="mchSerialNo" width="md"
label="商户证书序列号" name="mchKey"
/> label="商户API密钥"
<ProFormText />
width="md" <ProFormText
name="privateKeyPath" width="md"
label="商户私钥文件路径" name="mchSerialNo"
/> label="商户证书序列号"
<ProFormText />
width="md" <ProFormText
name="apiV3Key" width="md"
label="APIv3密钥" name="serialNumber"
/> label="微信平台证书序列号"
<ProFormText />
width="md" <ProFormText
name="notifyUrl" width="md"
label="支付回调地址" name="privateKeyPath"
/> label="商户私钥文件路径"
<ProFormText />
width="md" <ProFormText
name="token" width="md"
label="微信公众号token" name="privateKey"
/> label="商户私钥"
<ProFormText />
width="md" <ProFormText
name="aesKey" width="md"
label="微信公众号aesKey" name="apiV3Key"
/> label="APIv3密钥"
<ProFormText />
width="md" <ProFormText
name="paymentSuccessTemplateId" width="md"
label="支付成功通知模板ID" name="notifyUrl"
/> label="支付回调地址"
<ProFormText />
width="md" <ProFormText
name="videoCompleteTemplateId" width="md"
label="视频处理完成通知模板ID" name="token"
/> label="微信公众号token"
<ProFormText />
width="md" <ProFormText
name="videoFailTemplateId" width="md"
label="视频处理失败通知模板ID" name="aesKey"
/> label="微信公众号aesKey"
<ProFormSwitch />
name="profitSharingEnabled" <ProFormText
label="启用分账" width="md"
/> name="paymentSuccessTemplateId"
<ProFormSwitch label="支付成功通知模板ID"
name="asyncEnabled" />
label="启用异步处理" <ProFormText
/> width="md"
<ProFormDigit name="videoCompleteTemplateId"
name="asyncPoolSize" label="视频处理完成通知模板ID"
label="异步处理线程池大小" />
min={1} <ProFormText
max={100} width="md"
/> name="videoFailTemplateId"
<ProFormSelect label="视频处理失败通知模板ID"
rules={[{ required: true, message: '状态不能为空' }]} />
width="md" <ProFormSwitch
name="status" name="profitSharingEnabled"
label="状态" label="启用分账"
options={STATUS_OPTIONS} />
initialValue={1} <ProFormSwitch
/> name="asyncEnabled"
<ProFormText label="启用异步处理"
width="md" />
name="remark" <ProFormDigit
label="备注" name="asyncPoolSize"
/> label="异步处理线程池大小"
</ProForm.Group> min={1}
max={100}
/>
<ProFormSelect
rules={[{ required: true, message: '状态不能为空' }]}
width="md"
name="status"
label="状态"
options={STATUS_OPTIONS}
initialValue={1}
/>
<ProFormText
width="md"
name="remark"
label="备注"
/>
</ProForm.Group>
<ProForm.Group title="服务商模式相关">
<ProFormSwitch
name="isServiceMode"
label="服务商模式"
/>
<ProFormText
width="md"
name="serviceAppId"
label="服务商应用ID"
/>
<ProFormText
width="md"
name="serviceMchId"
label="服务商商户号"
/>
<ProFormText
width="md"
name="subMchId"
label="子商户号"
/>
<ProFormText
width="md"
name="subAppId"
label="子商户应用ID"
/>
<ProFormText
width="md"
name="subMchName"
label="子商户名称"
/>
<ProFormText
width="md"
name="subMchDescription"
label="子商户描述"
/>
</ProForm.Group>
</>
); );
return ( return (
@@ -296,7 +382,6 @@ const TableList: React.FC = () => {
searchKey: params.searchKey, searchKey: params.searchKey,
searchValue: params.searchValue, searchValue: params.searchValue,
}) as any; }) as any;
return { return {
data: res.data || [], data: res.data || [],
success: res.resp_code === 0, success: res.resp_code === 0,
@@ -184,9 +184,16 @@ export async function getOrderDetail(orderNo: string) {
} }
/** 获取首页统计数据 GET /api-order/dashboard/statistics */ /** 获取首页统计数据 GET /api-order/dashboard/statistics */
export async function dashboard() { export async function dashboard(params?: {
tourismId?: number;
qrcodeId?: string;
deviceSn?: string;
startTime?: string;
endTime?: string;
}) {
return request('/api-order/dashboard/statistics', { return request('/api-order/dashboard/statistics', {
method: 'GET', method: 'GET',
params,
}); });
} }
@@ -332,3 +339,97 @@ export async function getWxMessageStatistics(params: {
}); });
} }
// 优惠券相关接口
export async function getCouponList(params?: { [key: string]: string | number }) {
const { current, pageSize, ...rest } = params ?? {};
const result = await request<SYSTEM.Page<ORDERS.Coupon>>('/api-order/coupon', {
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: result.data, total: result.count };
}
export async function getCouponById(id: number) {
const result = await request<API.Result<ORDERS.Coupon>>(`/api-order/coupon/${id}`, {
method: 'GET',
});
return result;
}
export async function createCoupon(data: ORDERS.Coupon) {
const result = await request<API.Result<boolean>>('/api-order/coupon', {
method: 'POST',
data,
});
return result;
}
export async function updateCoupon(id: number, data: ORDERS.Coupon) {
const result = await request<API.Result<boolean>>(`/api-order/coupon/${id}`, {
method: 'PUT',
data,
});
return result;
}
export async function deleteCoupon(id: number) {
const result = await request<API.Result<boolean>>(`/api-order/coupon/${id}`, {
method: 'DELETE',
});
return result;
}
export async function getCouponsByUserPhone(userPhone: string) {
const result = await request<API.Result<ORDERS.Coupon[]>>(`/api-order/coupon/user/${userPhone}`, {
method: 'GET',
});
return result;
}
export async function getAvailableCouponsByUserPhone(userPhone: string) {
const result = await request<API.Result<ORDERS.Coupon[]>>(`/api-order/coupon/user/${userPhone}/available`, {
method: 'GET',
});
return result;
}
export async function useCoupon(id: number, orderNo: string) {
const result = await request<API.Result<boolean>>(`/api-order/coupon/${id}/use`, {
method: 'POST',
params: { orderNo },
});
return result;
}
export async function createCouponFromCtrip(params: {
ctripCouponId: string;
userPhone: string;
couponName: string;
couponType: number;
amount: number;
minAmount?: number;
discountRate?: number;
validStartTime: string;
validEndTime: string;
}) {
const result = await request<API.Result<boolean>>('/api-order/coupon/ctrip/create', {
method: 'POST',
params,
});
return result;
}
export async function verifyCtripCoupon(ctripCouponId: string, orderNo: string) {
const result = await request<API.Result<boolean>>('/api-order/coupon/ctrip/verify', {
method: 'POST',
params: { ctripCouponId, orderNo },
});
return result;
}
export async function updateExpiredCoupons() {
const result = await request<API.Result<void>>('/api-order/coupon/update-expired', {
method: 'POST',
});
return result;
}
@@ -98,7 +98,31 @@ declare namespace ORDERS {
approveReason: string; approveReason: string;
createTime?: string; createTime?: string;
tenantId?: string; tenantId?: string;
}
type Coupon = {
id: number;
couponNo: string;
couponName: string;
couponType: number; // 1-满减券,2-折扣券,3-免费券
amount: number;
minAmount?: number;
discountRate?: number;
status: number; // 0-未使用,1-已使用,2-已过期,3-已作废
userPhone: string;
userId?: number;
source: number; // 1-携程,2-高飞自建
ctripCouponId?: string;
validStartTime: string;
validEndTime: string;
usedTime?: string;
usedOrderNo?: string;
createTime?: string;
updateTime?: string; updateTime?: string;
tenantId?: string;
createBy?: string;
updateBy?: string;
remark?: string;
} }
// 添加 Dashboard 相关类型 // 添加 Dashboard 相关类型
@@ -108,21 +132,12 @@ declare namespace ORDERS {
todayOrders: number; todayOrders: number;
orderGrowth: number; orderGrowth: number;
completionRate: number; completionRate: number;
}; // 对账相关字段
incomeStats: { totalAmount: number; // 订单总金额(分)
totalAmount: number; platformAmount: number; // 平台分账金额(分)
todayAmount: number; tourismAmount: number; // 景区分账金额(分)
targetCompletion: number; refundAmount: number; // 退款金额(分)
}; netIncome: number; // 净收入(分)
waylineStats: {
totalWaylines: number;
activeWaylines: number;
waylineUsage: number;
};
deviceStats: {
totalDevices: number;
onlineDevices: number;
deviceOnlineRate: number;
}; };
chartStats: { chartStats: {
orderTrend: Array<{ orderTrend: Array<{
@@ -130,20 +145,29 @@ declare namespace ORDERS {
type: string; type: string;
value: number; value: number;
}>; }>;
deviceDistribution: Array<{ orderDistribution: Array<{
type: string; type: string;
value: number; value: number;
}>; }>;
incomeData: Array<{ incomeBreakdown: Array<{
type: string; type: string;
value: number; value: number;
}>; }>;
}; };
tourismRanking: Array<{ filterOptions: {
id: string; tourismList: Array<{
name: string; label: string;
value: number; value: number;
}>; }>;
qrcodeList: Array<{
label: string;
value: string;
}>;
deviceList: Array<{
label: string;
value: string;
}>;
};
} }
interface ProfitSharing { interface ProfitSharing {
@@ -14,6 +14,34 @@ export async function getQrcodeList(params: QrcodeListParams = { page: 1, limit:
}); });
} }
/** 获取设备列表参数 */
interface DeviceListParams {
page: number;
limit: number;
}
/** 获取设备列表 */
export async function getDeviceList(params: DeviceListParams = { page: 1, limit: 100 }) {
return request('/api-device/device', {
method: 'GET',
params,
});
}
/** 获取景区列表参数 */
interface TourismListParams {
page: number;
limit: number;
}
/** 获取景区列表 */
export async function getTourismList(params: TourismListParams = { page: 1, limit: 100 }) {
return request('/api-order/tourism', {
method: 'GET',
params,
});
}
/** 时间维度类型 */ /** 时间维度类型 */
type TimeType = 'hour' | 'day' | 'month'; type TimeType = 'hour' | 'day' | 'month';
@@ -46,6 +74,7 @@ export async function getTimeStatistics(params: TimeStatisticsParams) {
interface DeviceStatisticsParams { interface DeviceStatisticsParams {
startTime: string; startTime: string;
endTime: string; endTime: string;
deviceSn?: string;
} }
/** 获取设备维度统计数据 */ /** 获取设备维度统计数据 */
@@ -56,11 +85,15 @@ export async function getDeviceStatistics(params: DeviceStatisticsParams) {
}); });
} }
/** 获取景区维度统计数据 */ /** 获取景区维度统计数据参数 */
export async function getTourismStatistics(params: { interface TourismStatisticsParams {
startTime: string; startTime: string;
endTime: string; endTime: string;
}) { tourismId?: string;
}
/** 获取景区维度统计数据 */
export async function getTourismStatistics(params: TourismStatisticsParams) {
return request('/api-order/statistics/tourism', { return request('/api-order/statistics/tourism', {
method: 'GET', method: 'GET',
params, params,
@@ -254,15 +254,26 @@ export async function getMiniAppList(params: {
searchKey?: string; searchKey?: string;
searchValue?: string; searchValue?: string;
}) { }) {
return request<{ // 适配微信配置管理后台接口
data: SYSTEM.MiniApp[]; const res = await request<{
count: number; data: {
data: SYSTEM.MiniApp[];
count: number;
resp_code: number;
resp_msg?: string;
};
resp_code: number; resp_code: number;
resp_msg?: string; resp_msg?: string;
}>('/api-user/wechat/config', { }>('/api-user/wechat/config/list', {
method: 'GET', method: 'GET',
params, params,
}); });
return {
data: res.data?.data || [],
count: res.data?.count || 0,
resp_code: res.resp_code,
resp_msg: res.resp_msg,
};
} }
export async function saveMiniApp(data: SYSTEM.MiniApp) { export async function saveMiniApp(data: SYSTEM.MiniApp) {
@@ -111,7 +111,9 @@ declare namespace SYSTEM {
appSecret: string; appSecret: string;
mchKey?: string; mchKey?: string;
mchSerialNo?: string; mchSerialNo?: string;
serialNumber?: string;
privateKeyPath?: string; privateKeyPath?: string;
privateKey?: string;
apiV3Key?: string; apiV3Key?: string;
notifyUrl?: string; notifyUrl?: string;
token?: string; token?: string;
@@ -124,6 +126,13 @@ declare namespace SYSTEM {
asyncPoolSize?: number; asyncPoolSize?: number;
status: number; status: number;
remark?: string; remark?: string;
isServiceMode?: boolean;
serviceAppId?: string;
serviceMchId?: string;
subMchId?: string;
subAppId?: string;
subMchName?: string;
subMchDescription?: string;
createTime?: string; createTime?: string;
updateTime?: string; updateTime?: string;
} }
+175
View File
@@ -0,0 +1,175 @@
# 优惠券管理功能说明
## 功能概述
根据携程优惠券兑换流程图,实现了完整的优惠券管理功能,包括:
1. **优惠券基础管理**:创建、编辑、删除、查询优惠券
2. **携程集成**:携程创建优惠券接口、核销接口
3. **用户优惠券查询**:根据手机号查询用户优惠券
4. **自动过期处理**:定时任务自动更新过期优惠券状态
## 数据库设计
### 优惠券表 (t_coupon)
| 字段名 | 类型 | 说明 |
|--------|------|------|
| id | bigint | 主键ID |
| coupon_no | varchar(64) | 优惠券编号(唯一) |
| coupon_name | varchar(128) | 优惠券名称 |
| coupon_type | int | 优惠券类型:1-满减券,2-折扣券,3-免费券 |
| amount | decimal(10,2) | 优惠券面额 |
| min_amount | decimal(10,2) | 使用门槛金额 |
| discount_rate | int | 折扣率(0-100,折扣券时使用) |
| status | int | 优惠券状态:0-未使用,1-已使用,2-已过期,3-已作废 |
| user_phone | varchar(20) | 用户手机号 |
| user_id | bigint | 用户ID |
| source | int | 来源:1-携程,2-高飞自建 |
| ctrip_coupon_id | varchar(64) | 携程优惠券ID(来源为携程时使用) |
| valid_start_time | datetime | 有效期开始时间 |
| valid_end_time | datetime | 有效期结束时间 |
| used_time | datetime | 使用时间 |
| used_order_no | varchar(64) | 使用订单号 |
| create_time | datetime | 创建时间 |
| update_time | datetime | 更新时间 |
| create_by | varchar(64) | 创建人 |
| update_by | varchar(64) | 更新人 |
| remark | varchar(255) | 备注 |
| tenant_id | varchar(64) | 租户ID |
## 后端API接口
### 1. 优惠券基础管理
- `GET /api-order/coupon/page` - 分页查询优惠券列表
- `GET /api-order/coupon/{id}` - 根据ID查询优惠券
- `POST /api-order/coupon` - 创建优惠券
- `PUT /api-order/coupon/{id}` - 更新优惠券
- `DELETE /api-order/coupon/{id}` - 删除优惠券
### 2. 用户优惠券查询
- `GET /api-order/coupon/user/{userPhone}` - 根据手机号查询用户优惠券
- `GET /api-order/coupon/user/{userPhone}/available` - 根据手机号查询可用优惠券
### 3. 优惠券使用
- `POST /api-order/coupon/{id}/use` - 使用优惠券
### 4. 携程集成接口
- `POST /api-order/coupon/ctrip/create` - 携程创建优惠券接口
- `POST /api-order/coupon/ctrip/verify` - 核销携程优惠券
### 5. 系统管理
- `POST /api-order/coupon/update-expired` - 批量更新过期优惠券
## 前端功能
### 优惠券管理页面
位置:`/pages/orders/CouponManagement.tsx`
功能:
- 优惠券列表展示(支持分页、筛选)
- 新增优惠券
- 编辑优惠券
- 删除优惠券
- 查看优惠券详情
### 主要特性
1. **响应式表格**:支持横向滚动,适配不同屏幕尺寸
2. **智能表单**:根据优惠券类型动态显示不同字段
3. **状态管理**:不同状态用不同颜色标签显示
4. **时间处理**:使用moment.js处理时间格式化
## 业务流程
### 1. 携程优惠券创建流程
```
用户在携程购券 → 携程调用高飞创建优惠券接口 → 高飞创建本地优惠券记录
```
### 2. 用户下单优惠券使用流程
```
用户扫码进入下单页 → 查询用户绑定手机号 → 通过手机号查询高飞用户优惠券记录 →
有可用优惠券自动带出 → 用户选择是否核销 → 调用携程核销接口 → 进入支付流程
```
### 3. 优惠券过期处理流程
```
定时任务每天凌晨2点执行 → 查询所有未使用且已过期的优惠券 → 批量更新状态为已过期
```
## 定时任务
### 优惠券过期处理任务
- **类名**:`CouponExpirationTask`
- **执行时间**:每天凌晨2点
- **功能**:批量更新过期优惠券状态
## 携程API集成
### 携程API服务
- **接口**:`ICtripApiService`
- **实现**:`CtripApiServiceImpl`
### 待实现功能
1. **核销接口**:`verifyCoupon(String ctripCouponId, String orderNo)`
2. **状态查询**:`getCouponStatus(String ctripCouponId)`
### 集成说明
目前携程API调用为模拟实现,需要根据携程提供的API文档进行实际集成:
1. 配置携程API密钥和接口地址
2. 实现HTTP客户端调用
3. 处理API响应和错误
4. 添加重试机制和日志记录
## 部署说明
### 1. 数据库迁移
执行 `database_migration.sql` 中的优惠券表创建语句。
### 2. 后端部署
确保以下组件已正确配置:
- MyBatis Plus配置
- 定时任务配置(@EnableScheduling)
- 数据库连接配置
### 3. 前端部署
确保以下依赖已安装:
- Ant Design
- moment.js
- TypeScript类型定义
## 注意事项
1. **优惠券编号唯一性**:系统自动生成优惠券编号,确保唯一性
2. **携程优惠券ID唯一性**:同一携程优惠券ID只能创建一次
3. **时间处理**:所有时间字段使用UTC时间存储
4. **状态管理**:优惠券状态变更需要记录操作日志
5. **API安全**:携程集成接口需要添加适当的认证和授权
## 扩展功能
### 可扩展的功能点
1. **优惠券模板**:支持创建优惠券模板,批量生成优惠券
2. **优惠券统计**:优惠券使用情况统计和分析
3. **优惠券推送**:向用户推送优惠券到期提醒
4. **优惠券分享**:支持优惠券分享功能
5. **多平台集成**:支持其他平台的优惠券集成
+133
View File
@@ -0,0 +1,133 @@
# 携程优惠券对接接口文档
本文件描述我方对接携程的优惠券相关接口,包括创建、取消、核销等业务场景。
---
## 1. 创建用户优惠券接口
- **接口地址**:`POST /coupon/ctrip/create`
- **用途**:携程下单后回调,创建用户优惠券(手机号+携程券ID唯一,幂等)。
- **请求参数**:
| 参数名 | 类型 | 必填 | 说明 |
|----------------|-----------|------|------------------------|
| ctripCouponId | string | 是 | 携程券ID(唯一) |
| userPhone | string | 是 | 用户手机号 |
| couponName | string | 是 | 优惠券名称 |
| couponType | integer | 是 | 优惠券类型 |
| amount | number | 是 | 优惠券面额 |
| minAmount | number | 否 | 使用门槛金额 |
| discountRate | integer | 否 | 折扣率 |
| validStartTime | string | 是 | 有效期开始时间(yyyy-MM-dd或yyyy-MM-dd HH:mm:ss)|
| validEndTime | string | 是 | 有效期结束时间(yyyy-MM-dd或yyyy-MM-dd HH:mm:ss)|
- **返回示例**:
```json
{
"code": 0,
"data": true,
"resp_msg": "success"
}
```
---
## 2. 取消用户优惠券接口
- **接口地址**:`POST /coupon/ctrip/cancel`
- **用途**:携程退券回调,取消用户优惠券(默认退第一个未用券)。
- **请求参数**:
| 参数名 | 类型 | 必填 | 说明 |
|-----------|--------|------|-----------|
| userPhone | string | 是 | 用户手机号 |
- **返回示例**:
```json
{
"code": 0,
"data": true,
"resp_msg": "success"
}
```
如无可退券:
```json
{
"code": 1,
"data": null,
"resp_msg": "无可退优惠券"
}
```
---
## 3. 核销用户优惠券接口
- **接口地址**:`POST /coupon/ctrip/verify`
- **用途**:用户下单时,先查本地券,再调用携程核销接口,核销成功后本地状态设为已用。
- **请求参数**:
| 参数名 | 类型 | 必填 | 说明 |
|-----------|--------|------|-----------|
| userPhone | string | 是 | 用户手机号 |
| orderNo | string | 是 | 订单号 |
- **返回示例**:
```json
{
"code": 0,
"data": true,
"resp_msg": "success"
}
```
如无可用券或核销失败:
```json
{
"code": 1,
"data": null,
"resp_msg": "无可用优惠券" // 或 "携程核销失败"
}
```
---
## 4. 业务说明
- **幂等性**:所有接口均需保证幂等,创建时手机号+携程券ID唯一。
- **状态同步**:本地与携程券状态需保持一致。
- **时间格式**:支持`yyyy-MM-dd`或`yyyy-MM-dd HH:mm:ss`。
- **安全性**:建议所有接口加签名校验。
- **返回结构**:统一为 `{ code, data, resp_msg }`,便于携程方解析。
---
## 5. 示例请求
### 创建优惠券
```http
POST /coupon/ctrip/create
Content-Type: application/x-www-form-urlencoded
ctripCouponId=CT123456&userPhone=13800000000&couponName=xxx&couponType=1&amount=100&validStartTime=2024-05-01&validEndTime=2024-06-01
```
### 取消优惠券
```http
POST /coupon/ctrip/cancel
Content-Type: application/x-www-form-urlencoded
userPhone=13800000000
```
### 核销优惠券
```http
POST /coupon/ctrip/verify
Content-Type: application/x-www-form-urlencoded
userPhone=13800000000&orderNo=ORDER123
```
---
如需OpenAPI YAML、签名校验、错误码说明等补充,请联系技术支持。