diff --git a/ruoyi-system/pom.xml b/ruoyi-system/pom.xml index fe76162..4ccc12a 100644 --- a/ruoyi-system/pom.xml +++ b/ruoyi-system/pom.xml @@ -7,6 +7,18 @@ com.ruoyi 3.8.9 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + + + + 4.0.0 ruoyi-system diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppletController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppletController.java index 5c11b44..ff446f8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppletController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppletController.java @@ -23,6 +23,7 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.text.DateFormat; +import java.time.LocalDate; import java.util.*; import java.text.SimpleDateFormat; import java.util.stream.Collectors; @@ -134,8 +135,6 @@ public class AppletController extends BaseController { private IGoodsOrderCursorService goodsOrderCursorService; - - // /** // * 创建服务订单 // * @@ -272,7 +271,7 @@ public class AppletController extends BaseController { // 构建查询条件:状态启用且类型为服务 ServiceCate serviceCateQuery = new ServiceCate(); serviceCateQuery.setStatus(1L); // 启用状态 - // serviceCateQuery.setType(1L); // 服务类型 + // serviceCateQuery.setType(1L); // 服务类型 // 查询分类列表 List categoryList = serviceCateService.selectServiceCateList(serviceCateQuery); @@ -978,7 +977,7 @@ public class AppletController extends BaseController { orderData.put("status_text", getOrderStatusText(order.getStatus())); // 状态文本 orderData.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); orderData.put("num", order.getNum()); - if (order.getSku()!=null) { + if (order.getSku() != null) { orderData.put("sku", order.getSku()); } else { orderData.put("sku", null); @@ -1194,6 +1193,7 @@ public class AppletController extends BaseController { // return error("查询商品详情失败:" + e.getMessage()); // } // } + /** * 获取服务商品详细信息 * @@ -1235,6 +1235,7 @@ public class AppletController extends BaseController { return AppletControllerUtil.appletError("查询商品详情失败:" + e.getMessage()); } } + /** * 获取广告图片列表 * @@ -1478,8 +1479,14 @@ public class AppletController extends BaseController { } // 其他业务字段 - userInfo.put("commission","0.00"); - //userInfo.put("commission", user.getCommission().toString() != null ? user.getCommission().toString() : "0.00"); + //userInfo.put("commission","0.00"); + if (user.getType().equals("2")) { + userInfo.put("commission", user.getCommission().toString() != null ? user.getCommission().toString() : "0.00"); + userInfo.put("total_comm", user.getTotalComm().toString() != null ? user.getTotalComm().toString() : "0.00"); + userInfo.put("propose", user.getPropose().toString() != null ? user.getPropose().toString() : "0.00"); + } + + userInfo.put("integral", user.getIntegral() != null ? user.getIntegral() : 0); userInfo.put("is_stop", user.getIsStop() != null ? user.getIsStop() : 1); userInfo.put("job_number", user.getJobNumber()); @@ -1490,12 +1497,12 @@ public class AppletController extends BaseController { userInfo.put("openid", user.getOpenid()); userInfo.put("prohibit_time", user.getProhibitTime()); userInfo.put("prohibit_time_str", null); - userInfo.put("propose", user.getPropose().toString() != null ? user.getPropose().toString() : "0.00"); + userInfo.put("remember_token", user.getRememberToken()); userInfo.put("status", user.getStatus() != null ? user.getStatus() : 1); userInfo.put("tpd", 0); // 默认值 - userInfo.put("total_comm","0.00"); - // userInfo.put("total_comm", user.getTotalComm().toString() != null ? user.getTotalComm().toString() : "0.00"); + // userInfo.put("total_comm","0.00"); + // userInfo.put("total_comm", user.getTotalComm().toString() != null ? user.getTotalComm().toString() : "0.00"); userInfo.put("total_integral", user.getTotalIntegral() != null ? user.getTotalIntegral() : 100); userInfo.put("type", user.getType() != null ? user.getType().toString() : "1"); userInfo.put("worker_time", user.getWorkerTime()); @@ -2029,7 +2036,7 @@ public class AppletController extends BaseController { } WechatPayUtil wechatPayUtil = new WechatPayUtil(); // 2. 创建代付订单 - Map payForResult = wechatPayUtil.unifiedOrder(params.get("payerOpenid").toString(), params.get("orderNo").toString(),Integer.valueOf(params.get("totalFee").toString()), params.get("body").toString(), params.get("notifyUrl").toString(), params.get("remark").toString()); + Map payForResult = wechatPayUtil.unifiedOrder(params.get("payerOpenid").toString(), params.get("orderNo").toString(), Integer.valueOf(params.get("totalFee").toString()), params.get("body").toString(), params.get("notifyUrl").toString(), params.get("remark").toString()); // 3. 返回结果 boolean success = (Boolean) payForResult.get("success"); @@ -2368,6 +2375,7 @@ public class AppletController extends BaseController { } } + /** * 查询用户优惠券列表 * @@ -2377,1979 +2385,2053 @@ public class AppletController extends BaseController { */ @PostMapping("/api/coupon/my/lst") public AjaxResult getMyCouponList(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 解析查询参数 - Long status = parseParamToLong(params.get("status"), "状态参数格式错误"); - Long productId = parseParamToLong(params.get("product_id"), "商品ID参数格式错误"); - Integer price = parseParamToInteger(params.get("price"), "价格参数格式错误"); - - // 4. 查询用户的所有优惠券 - CouponUser couponUserQuery = new CouponUser(); - couponUserQuery.setUid(user.getId()); - List couponUserList = couponUserService.selectCouponUserList(couponUserQuery); - - // 5. 根据状态筛选优惠券 - long currentTime = System.currentTimeMillis() / 1000; // 当前时间戳(秒) - List filteredList = new ArrayList<>(); - - if (status == null) { - // 如果未指定状态,返回所有优惠券 - filteredList = couponUserList; - } else if (status == 1L) { - // 未使用的优惠券 - for (CouponUser coupon : couponUserList) { - if (coupon.getStatus() != 2L && !isExpired(coupon, currentTime)) { - filteredList.add(coupon); - } - } - } else if (status == 2L) { - // 已使用的优惠券 - for (CouponUser coupon : couponUserList) { - if (coupon.getStatus() != null && coupon.getStatus() == 2L) { - filteredList.add(coupon); - } - } - } else if (status == 3L) { - // 已过期的优惠券 - for (CouponUser coupon : couponUserList) { - if (isExpired(coupon, currentTime)) { - filteredList.add(coupon); - } - } - } else if (status == 4L) { - // 待领取的优惠券 - 只返回手动领取(type=2)且剩余数量大于0的优惠券 - Coupons couponsQuery = new Coupons(); - couponsQuery.setStatus(1L); // 启用状态 - couponsQuery.setType(2L); // 手动领取类型 - List availableCoupons = couponsService.selectCouponsList(couponsQuery); - - for (Coupons coupon : availableCoupons) { - // 检查剩余数量大于0且用户可领取 - if (coupon.getCount() != null && coupon.getCount() > 0 && - isCouponAvailableToReceive(coupon, user.getId(), currentTime)) { - // 创建一个临时的CouponUser对象,包含完整的优惠券信息 - CouponUser tempCouponUser = new CouponUser(); - tempCouponUser.setCouponId(coupon.getId()); - tempCouponUser.setUid(user.getId()); - tempCouponUser.setStatus(0L); // 待领取状态 - tempCouponUser.setCouponTitle(coupon.getTitle()); - tempCouponUser.setCouponPrice(coupon.getPrice() != null ? coupon.getPrice().intValue() : 0); - tempCouponUser.setMinPrice(coupon.getMinPrice() != null ? coupon.getMinPrice().longValue() : 0L); - tempCouponUser.setCateId(coupon.getCateId()); - tempCouponUser.setProductId(coupon.getProductId()); - tempCouponUser.setReceiveType(coupon.getReceiveType() != null ? coupon.getReceiveType().toString() : "1"); - - // 设置有效期 - if (coupon.getCouponTime() != null) { - // 如果有固定的有效期天数,计算失效时间 - long loseTime = currentTime + (coupon.getCouponTime() * 24 * 60 * 60); - tempCouponUser.setLoseTime(String.valueOf(loseTime)); - } else if (coupon.getEndTime() != null) { - // 如果有结束时间,使用结束时间作为失效时间 - tempCouponUser.setLoseTime(String.valueOf(coupon.getEndTime())); - } - - filteredList.add(tempCouponUser); - } - } - } - - // 6. 商品ID筛选 - if (productId != null) { - filteredList = filteredList.stream() - .filter(coupon -> productId.equals(coupon.getProductId())) - .collect(Collectors.toList()); - } - - // 7. 价格筛选 - List priceFilteredList = AppletControllerUtil.filterCouponsByPrice(filteredList, price); - - // 8. 使用工具类处理数据格式化 - List> resultList = AppletControllerUtil.buildCouponUserList( - priceFilteredList, serviceCateService); - - return success(resultList); - - } catch (Exception e) { - System.err.println("查询用户优惠券列表异常:" + e.getMessage()); - return error("查询优惠券列表失败:" + e.getMessage()); + // 3. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); } + + // 4. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + Long userId = user.getId(); // 获取当前用户id + Integer status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : null; + String productId = params.get("product_id") != null ? params.get("product_id").toString() : null; + BigDecimal totalPrice = params.get("price") != null ? new BigDecimal(params.get("price").toString()) : null; + // 过期的优惠券标记为已过期 + CouponUser couponUser = new CouponUser(); + couponUser.setStatus(1L); + couponUser.setUid(user.getId()); + List couponUserList = couponUserService.selectCouponUserNoList(couponUser); + for (CouponUser c: couponUserList){ + c.setStatus(3L); + couponUserService.updateCouponUser(c); + } + //安状态进行赋值 + //待领取优惠券 + if (status==4){ + Coupons coupons = new Coupons(); + coupons.setSearchValue("12"); + List couponsList = couponsService.selectCouponsList(coupons); + if (!couponsList.isEmpty()){ + return AppletControllerUtil.appletSuccess(AppletControllerUtil.buildCouponDataList(couponsList,serviceCateService,serviceGoodsService)); + } + }else{ + CouponUser couponUserData = new CouponUser(); + couponUserData.setStatus(Long.valueOf(status)); + couponUserData.setUid(user.getId()); +// if (productIdStr!=null){ +// couponUserData.setProductId(productIdStr); +// } +// if (totalPrice!=null){ +// couponUserData.setMinPrice(totalPrice); +// } + +// List couponUserList, +// IServiceCateService serviceCateService, IServiceGoodsService serviceGoodsService,Long productId,Long totalPrice + + List couponUserDataList = couponUserService.selectCouponUserList(couponUserData); + if (couponUserDataList!=null){ + return AppletControllerUtil.appletSuccess(AppletControllerUtil.buildCouponUserList(couponUserDataList,serviceCateService,serviceGoodsService,productId,totalPrice)); + } + + + } + // 按is_use排序 + + return AjaxResult.success(); } - /** - * 解析参数为Long类型 - */ - private Long parseParamToLong(Object param, String errorMsg) { - if (param == null) return null; - if (param instanceof Integer) { - return ((Integer) param).longValue(); - } else if (param instanceof String && !((String) param).trim().isEmpty()) { + + +// ... existing code ... +// /** +// * 查询用户优惠券列表 +// * +// * @param params 请求参数,包含status(优惠券状态)、product_id(指定商品ID)、price(最低价格) +// * @param request HTTP请求对象 +// * @return 返回用户优惠券列表 +// */ +// @PostMapping("/api/coupon/my/lst") +// public AjaxResult getMyCouponList(@RequestBody Map params, HttpServletRequest request) { +// try { +// // 1. 验证用户登录状态 +// String token = request.getHeader("token"); +// Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); +// if (!(Boolean) userValidation.get("valid")) { +// return error("用户未登录或token无效"); +// } + +// // 2. 获取用户信息 +// Users user = (Users) userValidation.get("user"); +// if (user == null) { +// return error("用户信息获取失败"); +// } + +// // 3. 解析查询参数 +// Long status = parseParamToLong(params.get("status"), "状态参数格式错误"); +// Long productId = parseParamToLong(params.get("product_id"), "商品ID参数格式错误"); +// Integer price = parseParamToInteger(params.get("price"), "价格参数格式错误"); + +// // 4. 查询用户的所有优惠券 +// CouponUser couponUserQuery = new CouponUser(); +// couponUserQuery.setUid(user.getId()); +// List couponUserList = couponUserService.selectCouponUserList(couponUserQuery); + +// // 5. 根据状态筛选优惠券 +// long currentTime = System.currentTimeMillis() / 1000; // 当前时间戳(秒) +// List filteredList = new ArrayList<>(); + +// if (status == null) { +// // 如果未指定状态,返回所有优惠券 +// filteredList = couponUserList; +// } else if (status == 1L) { +// // 未使用的优惠券 +// for (CouponUser coupon : couponUserList) { +// if (coupon.getStatus() != 2L && !isExpired(coupon, currentTime)) { +// filteredList.add(coupon); +// } +// } +// } else if (status == 2L) { +// // 已使用的优惠券 +// for (CouponUser coupon : couponUserList) { +// if (coupon.getStatus() != null && coupon.getStatus() == 2L) { +// filteredList.add(coupon); +// } +// } +// } else if (status == 3L) { +// // 已过期的优惠券 +// for (CouponUser coupon : couponUserList) { +// if (isExpired(coupon, currentTime)) { +// filteredList.add(coupon); +// } +// } +// } else if (status == 4L) { +// // 待领取的优惠券 - 只返回手动领取(type=2)且剩余数量大于0的优惠券 +// Coupons couponsQuery = new Coupons(); +// couponsQuery.setStatus(1L); // 启用状态 +// couponsQuery.setType(2L); // 手动领取类型 +// List availableCoupons = couponsService.selectCouponsList(couponsQuery); + +// for (Coupons coupon : availableCoupons) { +// // 检查剩余数量大于0且用户可领取 +// if (coupon.getCount() != null && coupon.getCount() > 0 && +// isCouponAvailableToReceive(coupon, user.getId(), currentTime)) { +// // 创建一个临时的CouponUser对象,包含完整的优惠券信息 +// CouponUser tempCouponUser = new CouponUser(); +// tempCouponUser.setCouponId(coupon.getId()); +// tempCouponUser.setUid(user.getId()); +// tempCouponUser.setStatus(0L); // 待领取状态 +// tempCouponUser.setCouponTitle(coupon.getTitle()); +// tempCouponUser.setCouponPrice(coupon.getPrice() != null ? coupon.getPrice().intValue() : 0); +// tempCouponUser.setMinPrice(coupon.getMinPrice() != null ? coupon.getMinPrice().longValue() : 0L); +// tempCouponUser.setCateId(coupon.getCateId()); +// tempCouponUser.setProductId(coupon.getProductId()); +// tempCouponUser.setReceiveType(coupon.getReceiveType() != null ? coupon.getReceiveType().toString() : "1"); + +// // 设置有效期 +// if (coupon.getCouponTime() != null) { +// // 如果有固定的有效期天数,计算失效时间 +// long loseTime = currentTime + (coupon.getCouponTime() * 24 * 60 * 60); +// tempCouponUser.setLoseTime(String.valueOf(loseTime)); +// } else if (coupon.getEndTime() != null) { +// // 如果有结束时间,使用结束时间作为失效时间 +// tempCouponUser.setLoseTime(String.valueOf(coupon.getEndTime())); +// } + +// filteredList.add(tempCouponUser); +// } +// } +// } + +// // 6. 商品ID筛选 +// if (productId != null) { +// filteredList = filteredList.stream() +// .filter(coupon -> productId.equals(coupon.getProductId())) +// .collect(Collectors.toList()); +// } + +// // 7. 价格筛选 +// List priceFilteredList = AppletControllerUtil.filterCouponsByPrice(filteredList, price); + +// // 8. 使用工具类处理数据格式化 +// List> resultList = AppletControllerUtil.buildCouponUserList( +// priceFilteredList, serviceCateService); + +// return success(resultList); + +// } catch (Exception e) { +// System.err.println("查询用户优惠券列表异常:" + e.getMessage()); +// return error("查询优惠券列表失败:" + e.getMessage()); +// } +// } + +/** + * 解析参数为Long类型 + */ +private Long parseParamToLong(Object param, String errorMsg) { + if (param == null) return null; + + if (param instanceof Integer) { + return ((Integer) param).longValue(); + } else if (param instanceof String && !((String) param).trim().isEmpty()) { + try { + return Long.parseLong((String) param); + } catch (NumberFormatException e) { + throw new RuntimeException(errorMsg); + } + } + return null; +} + +/** + * 解析参数为Integer类型 + */ +private Integer parseParamToInteger(Object param, String errorMsg) { + if (param == null) return null; + + if (param instanceof Integer) { + return (Integer) param; + } else if (param instanceof String && !((String) param).trim().isEmpty()) { + try { + return Integer.parseInt((String) param); + } catch (NumberFormatException e) { + throw new RuntimeException(errorMsg); + } + } + return null; +} + +/** + * 查询用户积分日志列表 + * + * @param params 请求参数,包含limit(每页数量)、page(页码) + * @param request HTTP请求对象 + * @return 返回分页的积分日志列表 + */ +@PostMapping("/api/integral/user/log/lst") +public AjaxResult getUserIntegralLogList(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 获取分页参数 + int page = params.get("page") != null ? (Integer) params.get("page") : 1; + int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; + + // 2. 验证分页参数 + Map pageValidation = PageUtil.validatePageParams(page, limit); + if (!(Boolean) pageValidation.get("valid")) { + return error((String) pageValidation.get("message")); + } + + // 3. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 4. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 5. 设置分页参数 + PageHelper.startPage(page, limit); + + // 6. 构建查询条件并查询 + IntegralLog integralLogQuery = new IntegralLog(); + integralLogQuery.setUid(user.getId()); + List integralLogList = integralLogService.selectIntegralLogList(integralLogQuery); + + // 7. 构建分页信息 + PageInfo pageInfo = new PageInfo<>(integralLogList); + + // 8. 使用工具类处理数据格式化 + List> formattedLogList = AppletControllerUtil.buildIntegralLogList(integralLogList); + Map paginationData = AppletControllerUtil.buildPaginationResponse( + pageInfo, formattedLogList, "https://www.huafurenjia.cn/api/integral/user/log/lst"); + Map userData = AppletControllerUtil.buildUserDataInfo(user); + + // 9. 构建最终返回数据结构 + Map responseData = new HashMap<>(); + responseData.put("data", paginationData); + responseData.put("user", userData); + responseData.put("msg", "OK"); + + return success(responseData); + + } catch (Exception e) { + System.err.println("查询用户积分日志列表异常:" + e.getMessage()); + return error("查询积分日志列表失败:" + e.getMessage()); + } +} + +/** + * 查询用户积分商城订单列表 + * + * @param params 请求参数,包含limit(每页数量)、page(页码)、status(订单状态) + * @param request HTTP请求对象 + * @return 返回分页的积分商城订单列表 + */ +@PostMapping("/api/integral/user/order") +public AjaxResult getUserIntegralOrderList(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 获取分页参数 + int page = params.get("page") != null ? (Integer) params.get("page") : 1; + int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; + String status = params.get("status") != null ? params.get("status").toString() : null; + + // 2. 验证分页参数 + Map pageValidation = PageUtil.validatePageParams(page, limit); + if (!(Boolean) pageValidation.get("valid")) { + return error((String) pageValidation.get("message")); + } + + // 3. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 4. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 5. 设置分页参数 + PageHelper.startPage(page, limit); + + // 6. 构建查询条件并查询 + IntegralOrder integralOrderQuery = new IntegralOrder(); + integralOrderQuery.setUid(user.getId()); + if (status != null && !status.trim().isEmpty()) { + integralOrderQuery.setStatus(status.trim()); + } + List integralOrderList = integralOrderService.selectIntegralOrderList(integralOrderQuery); + + // 7. 构建分页信息 + PageInfo pageInfo = new PageInfo<>(integralOrderList); + + // 8. 使用工具类处理数据格式化 + List> formattedOrderList = AppletControllerUtil.buildIntegralOrderList( + integralOrderList, integralProductService); + Map responseData = AppletControllerUtil.buildPaginationResponse( + pageInfo, formattedOrderList, "https://www.huafurenjia.cn/api/integral/user/order"); + + return success(responseData); + + } catch (Exception e) { + System.err.println("查询用户积分商城订单列表异常:" + e.getMessage()); + return error("查询积分商城订单列表失败:" + e.getMessage()); + } +} + +/** + * 查询积分订单详情 + * + * @param id 订单ID + * @param request HTTP请求对象 + * @return 返回积分订单详细信息 + */ +@GetMapping("/api/integral/user/order/info/{id}") +public AjaxResult getIntegralOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { + try { + // 1. 参数验证 + if (id == null || id <= 0) { + return error("订单ID无效"); + } + + // 2. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 3. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 4. 查询积分订单信息 + IntegralOrder integralOrder = integralOrderService.selectIntegralOrderById(id); + if (integralOrder == null) { + return error("订单不存在"); + } + + // 5. 验证订单归属权 + if (!integralOrder.getUid().equals(user.getId())) { + return error("无权访问该订单信息"); + } + + // 6. 使用工具类构建订单详情数据 + Map orderData = AppletControllerUtil.buildIntegralOrderDetail( + integralOrder, integralProductService, integralOrderLogService); + + return success(orderData); + + } catch (Exception e) { + System.err.println("查询积分订单详情异常:" + e.getMessage()); + return error("查询订单详情失败:" + e.getMessage()); + } +} + +/** + * 查询积分商品分类列表 + * + * @param request HTTP请求对象 + * @return 返回积分商品分类列表 + *

+ * 功能说明: + * - 获取所有启用状态的积分商品分类 + * - 返回分类的ID和名称 + * - 用于积分商城分类展示 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": [ + * { + * "id": 4, + * "title": "家清商品" + * } + * ] + * } + */ +@GetMapping("/api/integral/product/cate") +public AjaxResult getIntegralProductCateList(HttpServletRequest request) { + try { + // 1. 构建查询条件:查询启用状态的积分商品分类 + IntegralCate integralCateQuery = new IntegralCate(); + integralCateQuery.setStatus(1L); // 启用状态 + + // 2. 查询积分商品分类列表 + List integralCateList = integralCateService.selectIntegralCateList(integralCateQuery); + + // 3. 构建返回数据格式 + List> resultList = new ArrayList<>(); + for (IntegralCate integralCate : integralCateList) { + Map cateData = new HashMap<>(); + cateData.put("id", integralCate.getId()); + cateData.put("title", integralCate.getTitle()); + resultList.add(cateData); + } + + return success(resultList); + + } catch (Exception e) { + System.err.println("查询积分商品分类列表异常:" + e.getMessage()); + return error("查询分类列表失败:" + e.getMessage()); + } +} + +/** + * 查询积分商品列表 + * + * @param params 请求参数,包含limit(每页数量)、page(页码)、type(分类ID) + * @param request HTTP请求对象 + * @return 返回分页的积分商品列表 + *

+ * 功能说明: + * - 获取积分商品列表,支持分页 + * - 支持按分类筛选 + * - 返回商品详细信息和分页信息 + * - 按创建时间倒序排列 + *

+ * 请求参数格式: + * { + * "limit": 15, // 每页显示数量 + * "page": 1, // 页码 + * "type": "1" // 分类ID(可选) + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "current_page": 1, + * "data": [ + * { + * "id": 7, + * "title": "全无码食品火锅", + * "image": "https://img.huafurenjia.cn/images/cb03ed40d32282bb47235568219ca26.png", + * "num": 11, + * "price": "53.90", + * "sales": 568, + * "tags": [] + * } + * ], + * "from": 1, + * "last_page": 1, + * "per_page": 15, + * "to": 2, + * "total": 2 + * } + * } + */ +@PostMapping("/api/integral/product/lst") +public AjaxResult getIntegralProductList(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 获取分页参数 + int page = params.get("page") != null ? (Integer) params.get("page") : 1; + int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; + String type = params.get("type") != null ? params.get("type").toString() : null; + + // 2. 验证分页参数 + Map pageValidation = PageUtil.validatePageParams(page, limit); + if (!(Boolean) pageValidation.get("valid")) { + return error((String) pageValidation.get("message")); + } + + // 3. 设置分页参数 + PageHelper.startPage(page, limit); + + // 4. 构建查询条件 + IntegralProduct integralProductQuery = new IntegralProduct(); + integralProductQuery.setStatus(1L); // 只查询启用状态的商品 + + // 如果有分类参数,添加分类筛选 + if (type != null && !type.trim().isEmpty()) { try { - return Long.parseLong((String) param); + Long cateId = Long.parseLong(type.trim()); + integralProductQuery.setCateId(cateId); } catch (NumberFormatException e) { - throw new RuntimeException(errorMsg); + return error("分类参数格式错误"); } } - return null; + + // 5. 查询积分商品列表 + List integralProductList = integralProductService.selectIntegralProductList(integralProductQuery); + + // 6. 构建分页信息 + PageInfo pageInfo = new PageInfo<>(integralProductList); + + // 7. 使用工具类处理数据格式化 + List> formattedProductList = AppletControllerUtil.buildIntegralProductList(integralProductList); + Map responseData = AppletControllerUtil.buildPaginationResponse( + pageInfo, formattedProductList, "https://www.huafurenjia.cn/api/integral/product/lst"); + + return success(responseData); + + } catch (Exception e) { + System.err.println("查询积分商品列表异常:" + e.getMessage()); + return error("查询积分商品列表失败:" + e.getMessage()); } +} - /** - * 解析参数为Integer类型 - */ - private Integer parseParamToInteger(Object param, String errorMsg) { - if (param == null) return null; +/** + * 查询积分商品详情 + * + * @param id 商品ID + * @param request HTTP请求对象 + * @return 返回积分商品详细信息 + *

+ * 功能说明: + * - 根据商品ID获取积分商品详细信息 + * - 返回完整的商品数据包括图片、规格、库存等 + * - 自动处理图片URL添加CDN前缀 + * - 格式化轮播图和标签为数组格式 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "id": 7, + * "title": "全无码食品火锅", + * "cate_id": 4, + * "contetnt": "

", + * "created_at": "2024-07-17 14:59:44", + * "image": "https://img.huafurenjia.cn/images/cb03ed40d32282bb47235568219ca26.png", + * "images": ["https://img.huafurenjia.cn/images/..."], + * "num": 11, + * "price": "53.90", + * "sales": 568, + * "sku": {"type": "single"}, + * "sku_type": 1, + * "sort": 1, + * "status": 1, + * "stock": 120, + * "tags": [], + * "updated_at": "2024-08-16 15:03:33" + * } + * } + */ +@GetMapping("/api/integral/product/info/{id}") +public AjaxResult getIntegralProductInfo(@PathVariable("id") Long id, HttpServletRequest request) { + try { + // 1. 参数验证 + if (id == null || id <= 0) { + return error("商品ID无效"); + } - if (param instanceof Integer) { - return (Integer) param; - } else if (param instanceof String && !((String) param).trim().isEmpty()) { - try { - return Integer.parseInt((String) param); - } catch (NumberFormatException e) { - throw new RuntimeException(errorMsg); + // 2. 查询积分商品信息 + IntegralProduct integralProduct = integralProductService.selectIntegralProductById(id); + if (integralProduct == null) { + return error("商品不存在"); + } + + // 3. 验证商品状态(只返回启用状态的商品) + if (integralProduct.getStatus() == null || integralProduct.getStatus() != 1) { + return error("商品已下架或不可用"); + } + + // 4. 使用工具类构建商品详情数据 + Map productDetail = AppletControllerUtil.buildIntegralProductDetail(integralProduct); + + return success(productDetail); + + } catch (Exception e) { + System.err.println("查询积分商品详情异常:" + e.getMessage()); + return error("查询商品详情失败:" + e.getMessage()); + } +} + +/** + * 获取用户默认收货地址 + * + * @param request HTTP请求对象 + * @return 默认地址信息 + *

+ * 接口说明: + * - 查询用户的默认收货地址(is_default = 1) + * - 如果没有默认地址,返回用户地址列表的第一条数据 + * - 验证用户登录状态和地址归属权 + * - 返回AddressApple格式的地址数据 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "操作成功", + * "data": { + * "id": 160, + * "uid": 302, + * "name": "赵先生", + * "phone": "18709185987", + * "latitude": "34.15643", + * "longitude": "108.86683", + * "address_name": "陕西省西安市长安区榆林北段与建设大道交叉口处北侧", + * "address_info": "陕西省西安市长安区榆林北段与建设大道交叉口处", + * "info": "14号楼2302", + * "is_default": 1, + * "created_at": null, + * "updated_at": null + * } + * } + */ +@GetMapping("/api/user/address/default") +public AjaxResult getUserDefaultAddress(HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 首先查询用户的默认地址 + UserAddress userAddressQuery = new UserAddress(); + userAddressQuery.setUid(user.getId()); + userAddressQuery.setIsDefault(1L); // 查询默认地址 + List defaultAddressList = userAddressService.selectUserAddressList(userAddressQuery); + + UserAddress targetAddress = null; + + if (!defaultAddressList.isEmpty()) { + // 找到默认地址 + targetAddress = defaultAddressList.get(0); + } else { + // 没有默认地址,查询用户的第一条地址 + UserAddress allAddressQuery = new UserAddress(); + allAddressQuery.setUid(user.getId()); + List allAddressList = userAddressService.selectUserAddressList(allAddressQuery); + + if (!allAddressList.isEmpty()) { + targetAddress = allAddressList.get(0); + } else { + return error("用户暂无收货地址"); } } - return null; - } - /** - * 查询用户积分日志列表 - * - * @param params 请求参数,包含limit(每页数量)、page(页码) - * @param request HTTP请求对象 - * @return 返回分页的积分日志列表 - */ - @PostMapping("/api/integral/user/log/lst") - public AjaxResult getUserIntegralLogList(@RequestBody Map params, HttpServletRequest request) { + // 4. 转换为AddressApple格式并返回 + AddressApple addressApple = AddressApple.fromUserAddress(targetAddress); + + return success(addressApple); + + } catch (Exception e) { + System.err.println("查询用户默认地址异常:" + e.getMessage()); + return error("查询默认地址失败:" + e.getMessage()); + } +} + +/** + * 获取用户小程序通知订阅状态 + * + * @param request HTTP请求对象 + * @return 用户通知订阅状态 + *

+ * 接口说明: + * - 查询用户对小程序消息模板的订阅状态 + * - 返回三个消息模板的订阅配置信息 + * - 支持不同业务场景的消息通知配置 + * - 验证用户登录状态 + *

+ * 消息模板说明: + * - pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M: 积分相关通知模板 + * - YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8: 操作成功通知模板 + * - 5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU: 工作人员通知模板 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "integral": ["pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"], + * "make_success": ["YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8", "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"], + * "is": "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU", + * "new_success": ["pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"], + * "s": "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M", + * "workers": ["5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"], + * "a": "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" + * } + * } + */ +@GetMapping("/api/user/notification/status") +public AjaxResult getUserNotificationStatus(HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 直接返回固定的消息模板配置数据 + Map notificationStatus = AppletControllerUtil.buildMiniProgramNotificationStatus(user); + + return success(notificationStatus); + + } catch (Exception e) { + System.err.println("查询用户通知订阅状态异常:" + e.getMessage()); + return error("查询通知订阅状态失败:" + e.getMessage()); + } +} + +/** + * 用户订阅消息授权接口 + * + * @param params 请求参数,包含tmplIds(模板ID数组) + * @param request HTTP请求对象 + * @return 授权结果 + *

+ * 接口说明: + * - 处理用户对消息模板的订阅授权 + * - 记录用户的授权状态 + * - 支持批量处理多个模板ID + *

+ * 请求参数格式: + * { + * "tmplIds": ["pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M", "YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8"] + * } + */ +@PostMapping("/api/user/notification/subscribe") +public AjaxResult subscribeNotification(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 获取模板ID列表 + List tmplIds = (List) params.get("tmplIds"); + if (tmplIds == null || tmplIds.isEmpty()) { + return error("模板ID列表不能为空"); + } + + // 4. 验证模板ID的有效性 + List validTemplateIds = new ArrayList<>(); + validTemplateIds.add("pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"); + validTemplateIds.add("YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8"); + validTemplateIds.add("5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"); + + for (String tmplId : tmplIds) { + if (!validTemplateIds.contains(tmplId)) { + return error("无效的模板ID:" + tmplId); + } + } + + // 5. 处理订阅逻辑(这里可以记录到数据库或调用微信API) + Map subscribeResult = new HashMap<>(); + subscribeResult.put("user_id", user.getId()); + subscribeResult.put("template_ids", tmplIds); + subscribeResult.put("subscribe_time", new Date()); + subscribeResult.put("status", "success"); + + // 6. 这里可以将订阅状态保存到数据库 + // 例如:userNotificationService.saveSubscribeStatus(user.getId(), tmplIds); + + return success(subscribeResult); + + } catch (Exception e) { + System.err.println("用户订阅消息异常:" + e.getMessage()); + return error("订阅消息失败:" + e.getMessage()); + } +} + + +/** + * 小程序下单时用户订阅消息推送接口(前端不传值,后端返回固定结构) + * + * @return 订阅消息推送ID分类结果 + */ +@GetMapping("/api/public/massge/notice") +public Map subscribeMessageNotice() { + Map data = new HashMap<>(); + data.put("make_success", Arrays.asList( + "YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8", + "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" + )); + data.put("pay_success", Arrays.asList( + "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M" + )); + data.put("integral", Arrays.asList( + "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M" + )); + data.put("worker", Arrays.asList( + "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" + )); + Map result = new HashMap<>(); + result.put("code", 200); + result.put("msg", "OK"); + result.put("data", data); + return result; +} + + +/** + * 积分商品兑换接口 + * + * @param params 请求参数,包含id(积分商品ID)、address_id(收货地址ID)、num(购买数量)、sku(规格)、mark(备注) + * @param request HTTP请求对象 + * @return 兑换结果 + *

+ * 接口说明: + * - 使用积分兑换积分商品 + * - 验证用户积分是否足够支付 + * - 创建积分订单并扣除用户积分 + * - 记录积分变动日志 + *

+ * 请求参数格式: + * { + * "id": 7, // 积分商品ID + * "num": 1, // 购买数量 + * "sku": "", // 商品规格(可选) + * "address_id": 2151, // 收货地址ID + * "mark": "" // 备注(可选) + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "操作成功", + * "data": { + * "order_id": "JF20241217143055", + * "message": "积分商品兑换成功" + * } + * } + */ +@PostMapping("/api/integral/user/exchange") +public AjaxResult exchangeIntegralProduct(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 验证请求参数 + String validationResult = AppletControllerUtil.validateIntegralExchangeParams(params); + if (validationResult != null) { + return error(validationResult); + } + + // 4. 获取并验证积分商品信息 + Long productId = Long.valueOf(params.get("id").toString()); + IntegralProduct product = integralProductService.selectIntegralProductById(productId); + if (product == null) { + return error("积分商品不存在"); + } + + if (product.getStatus() == null || product.getStatus() != 1) { + return error("积分商品已下架或不可用"); + } + + // 5. 获取并验证收货地址信息 + Long addressId = Long.valueOf(params.get("address_id").toString()); + UserAddress address = userAddressService.selectUserAddressById(addressId); + if (address == null) { + return error("收货地址不存在"); + } + + if (!address.getUid().equals(user.getId())) { + return error("无权使用该收货地址"); + } + + // 6. 计算所需积分并验证库存 + Integer num = Integer.valueOf(params.get("num").toString()); + if (product.getStock() != null && product.getStock() < num) { + return error("商品库存不足"); + } + + Long totalIntegral = product.getNum() * num; + + // 7. 验证用户积分是否足够 + if (!AppletControllerUtil.checkUserIntegralSufficient(user, totalIntegral)) { + // 积分不足,返回422状态码 + return AppletControllerUtil.appletWarning("积分不足"); + } + + // 8. 创建积分订单 + IntegralOrder order = AppletControllerUtil.buildIntegralOrder(params, user, product, address); + int orderResult = integralOrderService.insertIntegralOrder(order); + + if (orderResult <= 0) { + return error("订单创建失败"); + } + + // 9. 扣除用户积分 + Users updateUser = new Users(); + updateUser.setId(user.getId()); + updateUser.setIntegral(user.getIntegral() - totalIntegral); + int updateResult = usersService.updateUsers(updateUser); + + if (updateResult <= 0) { + return error("扣除积分失败"); + } + + // 10. 记录积分变动日志 + IntegralLog integralLog = AppletControllerUtil.buildIntegralLog( + user, -totalIntegral, order.getOrderId(), product.getTitle()); + integralLogService.insertIntegralLog(integralLog); + + // 11. 更新商品库存(如果有库存管理) + if (product.getStock() != null) { + IntegralProduct updateProduct = new IntegralProduct(); + updateProduct.setId(product.getId()); + updateProduct.setStock(product.getStock() - num); + updateProduct.setSales(product.getSales() != null ? product.getSales() + num : num.longValue()); + integralProductService.updateIntegralProduct(updateProduct); + } + // 12. 构建返回结果 + return AppletControllerUtil.appletSuccess("兑换成功"); + } catch (Exception e) { + System.err.println("积分商品兑换异常:" + e.getMessage()); + return AppletControllerUtil.appletError("积分商品兑换失败:" + e.getMessage()); + } +} + +/** + * 获取服务订单详情 + * + * @param id 订单ID + * @param request HTTP请求对象 + * @return 服务订单详细信息 + *

+ * 接口说明: + * - 根据订单ID获取服务订单完整信息 + * - 包含订单基本信息、订单日志和商品信息 + * - 验证用户登录状态和订单归属权 + * - 返回完整的订单详情数据 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * // 订单基本信息 + * "id": 260, + * "order_id": "B831770908583777", + * // ... 其他订单字段 + * "log": [ + * // 订单日志数组 + * ], + * "product": { + * // 商品信息 + * } + * } + * } + */ +@GetMapping("/api/service/order/info/{id}") +public AjaxResult getServiceOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { + try { + // 1. 参数验证 + if (id == null || id <= 0) { + return AppletControllerUtil.appletWarning("订单ID无效"); + } + + // 2. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + + // 3. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + + // 4. 查询订单信息并验证归属权 + Order order = orderService.selectOrderById(id); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + + // 5. 验证订单归属权 + if (!order.getUid().equals(user.getId())) { + return AppletControllerUtil.appletWarning("无权访问该订单信息"); + } + + // 6. 使用工具类构建订单详情数据 + Map orderDetail = AppletControllerUtil.buildServiceOrderDetail( + order, orderLogService, serviceGoodsService); + + return AppletControllerUtil.appletSuccess(orderDetail); + + } catch (Exception e) { + System.err.println("查询服务订单详情异常:" + e.getMessage()); + return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); + } +} + +/** + * 获取城市列表接口 + * + * @param request HTTP请求对象 + * @return 城市列表数据 + *

+ * 接口说明: + * - 获取所有启用状态的城市列表 + * - 返回城市的ID、名称和父级ID + * - 用于小程序城市选择功能 + * - 无需用户登录验证 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": [ + * { + * "id": 1, + * "title": "西安市", + * "pid": 0 + * } + * ] + * } + */ +@GetMapping(value = "/api/public/diy/city") +public AjaxResult getDiyCityList(HttpServletRequest request) { + try { + // 查询所有城市列表 + List cityList = diyCityService.selectDiyCityList(null); + + // 构建树状结构数据 + List> resultList = AppletControllerUtil.buildCityTree(cityList); + + return AppletControllerUtil.appletSuccess(resultList); + } catch (Exception e) { + System.err.println("获取城市列表异常:" + e.getMessage()); + return AppletControllerUtil.appletError("获取城市列表失败:" + e.getMessage()); + } +} + +/** + * 获取技能列表接口 + * + * @param request HTTP请求对象 + * @return 技能列表数据 + *

+ * 接口说明: + * - 获取所有技能列表数据 + * - 返回技能的ID、名称、排序、状态等信息 + * - 用于小程序技能选择功能 + * - 无需用户登录验证 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": [ + * { + * "id": 47, + * "title": "燃气灶维修", + * "sort": 43, + * "status": 1, + * "created_at": "2025-04-10 09:36:35", + * "updated_at": "2025-04-10 09:36:35" + * } + * ] + * } + */ +@GetMapping(value = "/api/form/skill/lst") +public AjaxResult getSkillList(HttpServletRequest request) { + try { + // 查询技能列表 + List skillList = siteSkillService.selectSiteSkillList(null); + + // 构建返回数据格式 + List> resultList = new ArrayList<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + for (SiteSkill skill : skillList) { + Map skillData = new HashMap<>(); + skillData.put("id", skill.getId()); + skillData.put("title", skill.getTitle()); + skillData.put("sort", skill.getSort()); + skillData.put("status", skill.getStatus()); + + // 格式化时间字段 + if (skill.getCreatedAt() != null) { + skillData.put("created_at", sdf.format(skill.getCreatedAt())); + } else { + skillData.put("created_at", null); + } + + if (skill.getUpdatedAt() != null) { + skillData.put("updated_at", sdf.format(skill.getUpdatedAt())); + } else { + skillData.put("updated_at", null); + } + + resultList.add(skillData); + } + + return AppletControllerUtil.appletSuccess(resultList); + } catch (Exception e) { + System.err.println("获取技能列表异常:" + e.getMessage()); + return AppletControllerUtil.appletError("获取技能列表失败:" + e.getMessage()); + } +} + +/** + * 文件上传接口 + * + * @param file 上传的文件 + * @param request HTTP请求对象 + * @return 上传结果 + *

+ * 接口说明: + * - 支持图片和文档文件上传 + * - 优先使用七牛云上传,未启用时使用本地上传 + * - 自动验证文件格式和大小 + * - 无需用户登录验证(public 接口) + *

+ * 支持的文件格式: + * - 图片:jpg, jpeg, png, gif, bmp, webp, svg + * - 文档:doc, docx, xls, xlsx, ppt, pptx, txt, pdf + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "path": "images/2025-06-11/zvsZHNoFYlFkMCePQs1624hKwBSCozL9XM7pEUmo.jpg", + * "full_path": "http://img.huafurenjia.cn/images/2025-06-11/zvsZHNoFYlFkMCePQs1624hKwBSCozL9XM7pEUmo.jpg" + * } + * } + */ +@PostMapping(value = "/api/public/upload/file") +public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) { + try { + // 1. 验证文件是否为空 + if (file == null || file.isEmpty()) { + return AppletControllerUtil.appletWarning("上传文件不能为空"); + } + + // 2. 验证文件格式 + String[] allowedTypes = { + // 图片格式 + "jpg", "jpeg", "png", "gif", "bmp", "webp", "svg", + // 文档格式 + "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf" + }; + + if (!QiniuUploadUtil.isValidFileType(file.getOriginalFilename(), allowedTypes)) { + return AppletControllerUtil.appletWarning("不支持的文件格式"); + } + + // 3. 验证文件大小(10MB) + long maxSize = 10 * 1024 * 1024; + if (!QiniuUploadUtil.isFileSizeValid(file.getSize(), maxSize)) { + return AppletControllerUtil.appletWarning("文件大小不能超过10MB"); + } + + String fileUrl; + String filePath; + + // 4. 检查是否启用七牛云上传 + if (qiniuConfig.isEnabled()) { + // 使用七牛云上传 + fileUrl = QiniuUploadUtil.uploadFile(file); + // 从完整URL中提取路径部分 + filePath = AppletControllerUtil.extractPathFromUrl(fileUrl, "https://" + qiniuConfig.getDomain() + "/"); + } else { + // 使用本地上传(这里需要集成本地上传逻辑) + return AppletControllerUtil.appletError("本地上传功能暂未在此接口中实现,请启用七牛云上传"); + } + + // 5. 构建返回数据 + Map uploadResult = new HashMap<>(); + uploadResult.put("path", filePath); + uploadResult.put("full_path", fileUrl); + + return AppletControllerUtil.appletSuccess(uploadResult); + + } catch (Exception e) { + System.err.println("文件上传异常:" + e.getMessage()); + return AppletControllerUtil.appletError("文件上传失败:" + e.getMessage()); + } +} + + +/** + * 获取服务预约时间段接口 + * + * @param params 请求参数,包含day(预约日期) + * @param request HTTP请求对象 + * @return 时间段列表数据 + *

+ * 接口说明: + * - 根据指定日期获取可预约的时间段列表 + * - 返回每个时间段的可用状态和剩余数量 + * - 支持动态时间段配置 + * - 无需用户登录验证 + *

+ * 请求参数格式: + * { + * "day": "2025-06-11" + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": [ + * { + * "click": true, + * "value": "8:00-10:00", + * "prove": "可预约", + * "residue_num": 99 + * } + * ] + * } + */ +@PostMapping(value = "/api/service/make/time") +public AjaxResult getServiceMakeTime(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 参数验证 + if (params == null || params.get("day") == null) { + return AppletControllerUtil.appletWarning("日期参数不能为空"); + } + + String day = params.get("day").toString().trim(); + if (day.isEmpty()) { + return AppletControllerUtil.appletWarning("日期参数不能为空"); + } + + // 2. 验证日期格式 + if (!AppletControllerUtil.isValidDateFormat(day)) { + return AppletControllerUtil.appletWarning("日期格式错误,请使用yyyy-MM-dd格式"); + } + + // 3. 检查日期是否为过去时间 + if (AppletControllerUtil.isPastDate(day)) { + return AppletControllerUtil.appletWarning("不能预约过去的日期"); + } + + // 4. 构建时间段列表 + List> timeSlotList = AppletControllerUtil.buildTimeSlotList(day); + + return AppletControllerUtil.appletSuccess(timeSlotList); + + } catch (Exception e) { + System.err.println("获取服务预约时间段异常:" + e.getMessage()); + return AppletControllerUtil.appletError("获取时间段失败:" + e.getMessage()); + } +} + + +/** + * 添加商品到购物车接口 + * + * @param params 请求参数,包含good_id(商品ID)、sku(商品规格) + * @param request HTTP请求对象 + * @return 添加结果 + *

+ * 接口说明: + * - 将指定商品添加到用户购物车 + * - 验证商品是否存在和可用 + * - 支持商品规格选择 + * - 需要用户登录验证 + *

+ * 请求参数格式: + * { + * "good_id": 86, + * "sku": "" + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "操作成功", + * "data": "商品已添加到购物车" + * } + */ +@PostMapping(value = "/api/cart/add") +public AjaxResult addToCart(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + + // 3. 验证请求参数 + if (params == null || params.get("good_id") == null) { + return AppletControllerUtil.appletWarning("商品ID不能为空"); + } + + Long goodId; try { - // 1. 获取分页参数 - int page = params.get("page") != null ? (Integer) params.get("page") : 1; - int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; - - // 2. 验证分页参数 - Map pageValidation = PageUtil.validatePageParams(page, limit); - if (!(Boolean) pageValidation.get("valid")) { - return error((String) pageValidation.get("message")); + goodId = Long.valueOf(params.get("good_id").toString()); + if (goodId <= 0) { + return AppletControllerUtil.appletWarning("商品ID无效"); } - - // 3. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 4. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 5. 设置分页参数 - PageHelper.startPage(page, limit); - - // 6. 构建查询条件并查询 - IntegralLog integralLogQuery = new IntegralLog(); - integralLogQuery.setUid(user.getId()); - List integralLogList = integralLogService.selectIntegralLogList(integralLogQuery); - - // 7. 构建分页信息 - PageInfo pageInfo = new PageInfo<>(integralLogList); - - // 8. 使用工具类处理数据格式化 - List> formattedLogList = AppletControllerUtil.buildIntegralLogList(integralLogList); - Map paginationData = AppletControllerUtil.buildPaginationResponse( - pageInfo, formattedLogList, "https://www.huafurenjia.cn/api/integral/user/log/lst"); - Map userData = AppletControllerUtil.buildUserDataInfo(user); - - // 9. 构建最终返回数据结构 - Map responseData = new HashMap<>(); - responseData.put("data", paginationData); - responseData.put("user", userData); - responseData.put("msg", "OK"); - - return success(responseData); - - } catch (Exception e) { - System.err.println("查询用户积分日志列表异常:" + e.getMessage()); - return error("查询积分日志列表失败:" + e.getMessage()); + } catch (NumberFormatException e) { + return AppletControllerUtil.appletWarning("商品ID格式错误"); } - } - /** - * 查询用户积分商城订单列表 - * - * @param params 请求参数,包含limit(每页数量)、page(页码)、status(订单状态) - * @param request HTTP请求对象 - * @return 返回分页的积分商城订单列表 - */ - @PostMapping("/api/integral/user/order") - public AjaxResult getUserIntegralOrderList(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 获取分页参数 - int page = params.get("page") != null ? (Integer) params.get("page") : 1; - int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; - String status = params.get("status") != null ? params.get("status").toString() : null; - - // 2. 验证分页参数 - Map pageValidation = PageUtil.validatePageParams(page, limit); - if (!(Boolean) pageValidation.get("valid")) { - return error((String) pageValidation.get("message")); - } - - // 3. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 4. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 5. 设置分页参数 - PageHelper.startPage(page, limit); - - // 6. 构建查询条件并查询 - IntegralOrder integralOrderQuery = new IntegralOrder(); - integralOrderQuery.setUid(user.getId()); - if (status != null && !status.trim().isEmpty()) { - integralOrderQuery.setStatus(status.trim()); - } - List integralOrderList = integralOrderService.selectIntegralOrderList(integralOrderQuery); - - // 7. 构建分页信息 - PageInfo pageInfo = new PageInfo<>(integralOrderList); - - // 8. 使用工具类处理数据格式化 - List> formattedOrderList = AppletControllerUtil.buildIntegralOrderList( - integralOrderList, integralProductService); - Map responseData = AppletControllerUtil.buildPaginationResponse( - pageInfo, formattedOrderList, "https://www.huafurenjia.cn/api/integral/user/order"); - - return success(responseData); - - } catch (Exception e) { - System.err.println("查询用户积分商城订单列表异常:" + e.getMessage()); - return error("查询积分商城订单列表失败:" + e.getMessage()); - } - } - - /** - * 查询积分订单详情 - * - * @param id 订单ID - * @param request HTTP请求对象 - * @return 返回积分订单详细信息 - */ - @GetMapping("/api/integral/user/order/info/{id}") - public AjaxResult getIntegralOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { - try { - // 1. 参数验证 - if (id == null || id <= 0) { - return error("订单ID无效"); - } - - // 2. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 3. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 4. 查询积分订单信息 - IntegralOrder integralOrder = integralOrderService.selectIntegralOrderById(id); - if (integralOrder == null) { - return error("订单不存在"); - } - - // 5. 验证订单归属权 - if (!integralOrder.getUid().equals(user.getId())) { - return error("无权访问该订单信息"); - } - - // 6. 使用工具类构建订单详情数据 - Map orderData = AppletControllerUtil.buildIntegralOrderDetail( - integralOrder, integralProductService, integralOrderLogService); - - return success(orderData); - - } catch (Exception e) { - System.err.println("查询积分订单详情异常:" + e.getMessage()); - return error("查询订单详情失败:" + e.getMessage()); - } - } - - /** - * 查询积分商品分类列表 - * - * @param request HTTP请求对象 - * @return 返回积分商品分类列表 - *

- * 功能说明: - * - 获取所有启用状态的积分商品分类 - * - 返回分类的ID和名称 - * - 用于积分商城分类展示 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": [ - * { - * "id": 4, - * "title": "家清商品" - * } - * ] - * } - */ - @GetMapping("/api/integral/product/cate") - public AjaxResult getIntegralProductCateList(HttpServletRequest request) { - try { - // 1. 构建查询条件:查询启用状态的积分商品分类 - IntegralCate integralCateQuery = new IntegralCate(); - integralCateQuery.setStatus(1L); // 启用状态 - - // 2. 查询积分商品分类列表 - List integralCateList = integralCateService.selectIntegralCateList(integralCateQuery); - - // 3. 构建返回数据格式 - List> resultList = new ArrayList<>(); - for (IntegralCate integralCate : integralCateList) { - Map cateData = new HashMap<>(); - cateData.put("id", integralCate.getId()); - cateData.put("title", integralCate.getTitle()); - resultList.add(cateData); - } - - return success(resultList); - - } catch (Exception e) { - System.err.println("查询积分商品分类列表异常:" + e.getMessage()); - return error("查询分类列表失败:" + e.getMessage()); - } - } - - /** - * 查询积分商品列表 - * - * @param params 请求参数,包含limit(每页数量)、page(页码)、type(分类ID) - * @param request HTTP请求对象 - * @return 返回分页的积分商品列表 - *

- * 功能说明: - * - 获取积分商品列表,支持分页 - * - 支持按分类筛选 - * - 返回商品详细信息和分页信息 - * - 按创建时间倒序排列 - *

- * 请求参数格式: - * { - * "limit": 15, // 每页显示数量 - * "page": 1, // 页码 - * "type": "1" // 分类ID(可选) - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "current_page": 1, - * "data": [ - * { - * "id": 7, - * "title": "全无码食品火锅", - * "image": "https://img.huafurenjia.cn/images/cb03ed40d32282bb47235568219ca26.png", - * "num": 11, - * "price": "53.90", - * "sales": 568, - * "tags": [] - * } - * ], - * "from": 1, - * "last_page": 1, - * "per_page": 15, - * "to": 2, - * "total": 2 - * } - * } - */ - @PostMapping("/api/integral/product/lst") - public AjaxResult getIntegralProductList(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 获取分页参数 - int page = params.get("page") != null ? (Integer) params.get("page") : 1; - int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; - String type = params.get("type") != null ? params.get("type").toString() : null; - - // 2. 验证分页参数 - Map pageValidation = PageUtil.validatePageParams(page, limit); - if (!(Boolean) pageValidation.get("valid")) { - return error((String) pageValidation.get("message")); - } - - // 3. 设置分页参数 - PageHelper.startPage(page, limit); - - // 4. 构建查询条件 - IntegralProduct integralProductQuery = new IntegralProduct(); - integralProductQuery.setStatus(1L); // 只查询启用状态的商品 - - // 如果有分类参数,添加分类筛选 - if (type != null && !type.trim().isEmpty()) { + // 4. 获取商品规格参数 + // String sku = params.get("sku") != null ? params.get("sku").toString().trim() : ""; + String sku = null; + if (params.get("sku") != null) { + Object skuParam = params.get("sku"); + if (skuParam instanceof Map) { + // 如果前端传递的是Map对象,转换为JSON字符串 try { - Long cateId = Long.parseLong(type.trim()); - integralProductQuery.setCateId(cateId); - } catch (NumberFormatException e) { - return error("分类参数格式错误"); + sku = com.alibaba.fastjson2.JSON.toJSONString(skuParam); + } catch (Exception e) { + System.err.println("SKU转换JSON失败:" + e.getMessage()); + sku = skuParam.toString(); } - } - - // 5. 查询积分商品列表 - List integralProductList = integralProductService.selectIntegralProductList(integralProductQuery); - - // 6. 构建分页信息 - PageInfo pageInfo = new PageInfo<>(integralProductList); - - // 7. 使用工具类处理数据格式化 - List> formattedProductList = AppletControllerUtil.buildIntegralProductList(integralProductList); - Map responseData = AppletControllerUtil.buildPaginationResponse( - pageInfo, formattedProductList, "https://www.huafurenjia.cn/api/integral/product/lst"); - - return success(responseData); - - } catch (Exception e) { - System.err.println("查询积分商品列表异常:" + e.getMessage()); - return error("查询积分商品列表失败:" + e.getMessage()); - } - } - - /** - * 查询积分商品详情 - * - * @param id 商品ID - * @param request HTTP请求对象 - * @return 返回积分商品详细信息 - *

- * 功能说明: - * - 根据商品ID获取积分商品详细信息 - * - 返回完整的商品数据包括图片、规格、库存等 - * - 自动处理图片URL添加CDN前缀 - * - 格式化轮播图和标签为数组格式 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "id": 7, - * "title": "全无码食品火锅", - * "cate_id": 4, - * "contetnt": "

", - * "created_at": "2024-07-17 14:59:44", - * "image": "https://img.huafurenjia.cn/images/cb03ed40d32282bb47235568219ca26.png", - * "images": ["https://img.huafurenjia.cn/images/..."], - * "num": 11, - * "price": "53.90", - * "sales": 568, - * "sku": {"type": "single"}, - * "sku_type": 1, - * "sort": 1, - * "status": 1, - * "stock": 120, - * "tags": [], - * "updated_at": "2024-08-16 15:03:33" - * } - * } - */ - @GetMapping("/api/integral/product/info/{id}") - public AjaxResult getIntegralProductInfo(@PathVariable("id") Long id, HttpServletRequest request) { - try { - // 1. 参数验证 - if (id == null || id <= 0) { - return error("商品ID无效"); - } - - // 2. 查询积分商品信息 - IntegralProduct integralProduct = integralProductService.selectIntegralProductById(id); - if (integralProduct == null) { - return error("商品不存在"); - } - - // 3. 验证商品状态(只返回启用状态的商品) - if (integralProduct.getStatus() == null || integralProduct.getStatus() != 1) { - return error("商品已下架或不可用"); - } - - // 4. 使用工具类构建商品详情数据 - Map productDetail = AppletControllerUtil.buildIntegralProductDetail(integralProduct); - - return success(productDetail); - - } catch (Exception e) { - System.err.println("查询积分商品详情异常:" + e.getMessage()); - return error("查询商品详情失败:" + e.getMessage()); - } - } - - /** - * 获取用户默认收货地址 - * - * @param request HTTP请求对象 - * @return 默认地址信息 - *

- * 接口说明: - * - 查询用户的默认收货地址(is_default = 1) - * - 如果没有默认地址,返回用户地址列表的第一条数据 - * - 验证用户登录状态和地址归属权 - * - 返回AddressApple格式的地址数据 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "操作成功", - * "data": { - * "id": 160, - * "uid": 302, - * "name": "赵先生", - * "phone": "18709185987", - * "latitude": "34.15643", - * "longitude": "108.86683", - * "address_name": "陕西省西安市长安区榆林北段与建设大道交叉口处北侧", - * "address_info": "陕西省西安市长安区榆林北段与建设大道交叉口处", - * "info": "14号楼2302", - * "is_default": 1, - * "created_at": null, - * "updated_at": null - * } - * } - */ - @GetMapping("/api/user/address/default") - public AjaxResult getUserDefaultAddress(HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 首先查询用户的默认地址 - UserAddress userAddressQuery = new UserAddress(); - userAddressQuery.setUid(user.getId()); - userAddressQuery.setIsDefault(1L); // 查询默认地址 - List defaultAddressList = userAddressService.selectUserAddressList(userAddressQuery); - - UserAddress targetAddress = null; - - if (!defaultAddressList.isEmpty()) { - // 找到默认地址 - targetAddress = defaultAddressList.get(0); } else { - // 没有默认地址,查询用户的第一条地址 - UserAddress allAddressQuery = new UserAddress(); - allAddressQuery.setUid(user.getId()); - List allAddressList = userAddressService.selectUserAddressList(allAddressQuery); - - if (!allAddressList.isEmpty()) { - targetAddress = allAddressList.get(0); - } else { - return error("用户暂无收货地址"); - } + // 如果前端传递的是字符串,直接使用 + sku = skuParam.toString().trim(); } - - // 4. 转换为AddressApple格式并返回 - AddressApple addressApple = AddressApple.fromUserAddress(targetAddress); - - return success(addressApple); - - } catch (Exception e) { - System.err.println("查询用户默认地址异常:" + e.getMessage()); - return error("查询默认地址失败:" + e.getMessage()); + } else { + sku = null; } - } - - /** - * 获取用户小程序通知订阅状态 - * - * @param request HTTP请求对象 - * @return 用户通知订阅状态 - *

- * 接口说明: - * - 查询用户对小程序消息模板的订阅状态 - * - 返回三个消息模板的订阅配置信息 - * - 支持不同业务场景的消息通知配置 - * - 验证用户登录状态 - *

- * 消息模板说明: - * - pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M: 积分相关通知模板 - * - YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8: 操作成功通知模板 - * - 5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU: 工作人员通知模板 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "integral": ["pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"], - * "make_success": ["YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8", "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"], - * "is": "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU", - * "new_success": ["pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"], - * "s": "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M", - * "workers": ["5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"], - * "a": "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" - * } - * } - */ - @GetMapping("/api/user/notification/status") - public AjaxResult getUserNotificationStatus(HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 直接返回固定的消息模板配置数据 - Map notificationStatus = AppletControllerUtil.buildMiniProgramNotificationStatus(user); - - return success(notificationStatus); - - } catch (Exception e) { - System.err.println("查询用户通知订阅状态异常:" + e.getMessage()); - return error("查询通知订阅状态失败:" + e.getMessage()); + // 5. 查询商品信息并验证 + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodId); + if (serviceGoods == null) { + return AppletControllerUtil.appletWarning("商品不存在"); } - } - /** - * 用户订阅消息授权接口 - * - * @param params 请求参数,包含tmplIds(模板ID数组) - * @param request HTTP请求对象 - * @return 授权结果 - *

- * 接口说明: - * - 处理用户对消息模板的订阅授权 - * - 记录用户的授权状态 - * - 支持批量处理多个模板ID - *

- * 请求参数格式: - * { - * "tmplIds": ["pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M", "YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8"] - * } - */ - @PostMapping("/api/user/notification/subscribe") - public AjaxResult subscribeNotification(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 获取模板ID列表 - List tmplIds = (List) params.get("tmplIds"); - if (tmplIds == null || tmplIds.isEmpty()) { - return error("模板ID列表不能为空"); - } - - // 4. 验证模板ID的有效性 - List validTemplateIds = new ArrayList<>(); - validTemplateIds.add("pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"); - validTemplateIds.add("YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8"); - validTemplateIds.add("5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"); - - for (String tmplId : tmplIds) { - if (!validTemplateIds.contains(tmplId)) { - return error("无效的模板ID:" + tmplId); - } - } - - // 5. 处理订阅逻辑(这里可以记录到数据库或调用微信API) - Map subscribeResult = new HashMap<>(); - subscribeResult.put("user_id", user.getId()); - subscribeResult.put("template_ids", tmplIds); - subscribeResult.put("subscribe_time", new Date()); - subscribeResult.put("status", "success"); - - // 6. 这里可以将订阅状态保存到数据库 - // 例如:userNotificationService.saveSubscribeStatus(user.getId(), tmplIds); - - return success(subscribeResult); - - } catch (Exception e) { - System.err.println("用户订阅消息异常:" + e.getMessage()); - return error("订阅消息失败:" + e.getMessage()); - } - } - - - - /** - * 小程序下单时用户订阅消息推送接口(前端不传值,后端返回固定结构) - * @return 订阅消息推送ID分类结果 - */ - @GetMapping("/api/public/massge/notice") - public Map subscribeMessageNotice() { - Map data = new HashMap<>(); - data.put("make_success", Arrays.asList( - "YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8", - "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" - )); - data.put("pay_success", Arrays.asList( - "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M" - )); - data.put("integral", Arrays.asList( - "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M" - )); - data.put("worker", Arrays.asList( - "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" - )); - Map result = new HashMap<>(); - result.put("code", 200); - result.put("msg", "OK"); - result.put("data", data); - return result; - } - - - /** - * 积分商品兑换接口 - * - * @param params 请求参数,包含id(积分商品ID)、address_id(收货地址ID)、num(购买数量)、sku(规格)、mark(备注) - * @param request HTTP请求对象 - * @return 兑换结果 - *

- * 接口说明: - * - 使用积分兑换积分商品 - * - 验证用户积分是否足够支付 - * - 创建积分订单并扣除用户积分 - * - 记录积分变动日志 - *

- * 请求参数格式: - * { - * "id": 7, // 积分商品ID - * "num": 1, // 购买数量 - * "sku": "", // 商品规格(可选) - * "address_id": 2151, // 收货地址ID - * "mark": "" // 备注(可选) - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "操作成功", - * "data": { - * "order_id": "JF20241217143055", - * "message": "积分商品兑换成功" - * } - * } - */ - @PostMapping("/api/integral/user/exchange") - public AjaxResult exchangeIntegralProduct(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 验证请求参数 - String validationResult = AppletControllerUtil.validateIntegralExchangeParams(params); - if (validationResult != null) { - return error(validationResult); - } - - // 4. 获取并验证积分商品信息 - Long productId = Long.valueOf(params.get("id").toString()); - IntegralProduct product = integralProductService.selectIntegralProductById(productId); - if (product == null) { - return error("积分商品不存在"); - } - - if (product.getStatus() == null || product.getStatus() != 1) { - return error("积分商品已下架或不可用"); - } - - // 5. 获取并验证收货地址信息 - Long addressId = Long.valueOf(params.get("address_id").toString()); - UserAddress address = userAddressService.selectUserAddressById(addressId); - if (address == null) { - return error("收货地址不存在"); - } - - if (!address.getUid().equals(user.getId())) { - return error("无权使用该收货地址"); - } - - // 6. 计算所需积分并验证库存 - Integer num = Integer.valueOf(params.get("num").toString()); - if (product.getStock() != null && product.getStock() < num) { - return error("商品库存不足"); - } - - Long totalIntegral = product.getNum() * num; - - // 7. 验证用户积分是否足够 - if (!AppletControllerUtil.checkUserIntegralSufficient(user, totalIntegral)) { - // 积分不足,返回422状态码 - return AppletControllerUtil.appletWarning("积分不足"); - } - - // 8. 创建积分订单 - IntegralOrder order = AppletControllerUtil.buildIntegralOrder(params, user, product, address); - int orderResult = integralOrderService.insertIntegralOrder(order); - - if (orderResult <= 0) { - return error("订单创建失败"); - } - - // 9. 扣除用户积分 - Users updateUser = new Users(); - updateUser.setId(user.getId()); - updateUser.setIntegral(user.getIntegral() - totalIntegral); - int updateResult = usersService.updateUsers(updateUser); - - if (updateResult <= 0) { - return error("扣除积分失败"); - } - - // 10. 记录积分变动日志 - IntegralLog integralLog = AppletControllerUtil.buildIntegralLog( - user, -totalIntegral, order.getOrderId(), product.getTitle()); - integralLogService.insertIntegralLog(integralLog); - - // 11. 更新商品库存(如果有库存管理) - if (product.getStock() != null) { - IntegralProduct updateProduct = new IntegralProduct(); - updateProduct.setId(product.getId()); - updateProduct.setStock(product.getStock() - num); - updateProduct.setSales(product.getSales() != null ? product.getSales() + num : num.longValue()); - integralProductService.updateIntegralProduct(updateProduct); - } - // 12. 构建返回结果 - return AppletControllerUtil.appletSuccess("兑换成功"); - } catch (Exception e) { - System.err.println("积分商品兑换异常:" + e.getMessage()); - return AppletControllerUtil.appletError("积分商品兑换失败:" + e.getMessage()); - } - } - - /** - * 获取服务订单详情 - * - * @param id 订单ID - * @param request HTTP请求对象 - * @return 服务订单详细信息 - *

- * 接口说明: - * - 根据订单ID获取服务订单完整信息 - * - 包含订单基本信息、订单日志和商品信息 - * - 验证用户登录状态和订单归属权 - * - 返回完整的订单详情数据 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * // 订单基本信息 - * "id": 260, - * "order_id": "B831770908583777", - * // ... 其他订单字段 - * "log": [ - * // 订单日志数组 - * ], - * "product": { - * // 商品信息 - * } - * } - * } - */ - @GetMapping("/api/service/order/info/{id}") - public AjaxResult getServiceOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { - try { - // 1. 参数验证 - if (id == null || id <= 0) { - return AppletControllerUtil.appletWarning("订单ID无效"); - } - - // 2. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - - // 3. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - - // 4. 查询订单信息并验证归属权 - Order order = orderService.selectOrderById(id); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - - // 5. 验证订单归属权 - if (!order.getUid().equals(user.getId())) { - return AppletControllerUtil.appletWarning("无权访问该订单信息"); - } - - // 6. 使用工具类构建订单详情数据 - Map orderDetail = AppletControllerUtil.buildServiceOrderDetail( - order, orderLogService, serviceGoodsService); - - return AppletControllerUtil.appletSuccess(orderDetail); - - } catch (Exception e) { - System.err.println("查询服务订单详情异常:" + e.getMessage()); - return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); - } - } - - /** - * 获取城市列表接口 - * - * @param request HTTP请求对象 - * @return 城市列表数据 - *

- * 接口说明: - * - 获取所有启用状态的城市列表 - * - 返回城市的ID、名称和父级ID - * - 用于小程序城市选择功能 - * - 无需用户登录验证 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": [ - * { - * "id": 1, - * "title": "西安市", - * "pid": 0 - * } - * ] - * } - */ - @GetMapping(value = "/api/public/diy/city") - public AjaxResult getDiyCityList(HttpServletRequest request) { - try { - // 查询所有城市列表 - List cityList = diyCityService.selectDiyCityList(null); - - // 构建树状结构数据 - List> resultList = AppletControllerUtil.buildCityTree(cityList); - - return AppletControllerUtil.appletSuccess(resultList); - } catch (Exception e) { - System.err.println("获取城市列表异常:" + e.getMessage()); - return AppletControllerUtil.appletError("获取城市列表失败:" + e.getMessage()); - } - } - - /** - * 获取技能列表接口 - * - * @param request HTTP请求对象 - * @return 技能列表数据 - *

- * 接口说明: - * - 获取所有技能列表数据 - * - 返回技能的ID、名称、排序、状态等信息 - * - 用于小程序技能选择功能 - * - 无需用户登录验证 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": [ - * { - * "id": 47, - * "title": "燃气灶维修", - * "sort": 43, - * "status": 1, - * "created_at": "2025-04-10 09:36:35", - * "updated_at": "2025-04-10 09:36:35" - * } - * ] - * } - */ - @GetMapping(value = "/api/form/skill/lst") - public AjaxResult getSkillList(HttpServletRequest request) { - try { - // 查询技能列表 - List skillList = siteSkillService.selectSiteSkillList(null); - - // 构建返回数据格式 - List> resultList = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - for (SiteSkill skill : skillList) { - Map skillData = new HashMap<>(); - skillData.put("id", skill.getId()); - skillData.put("title", skill.getTitle()); - skillData.put("sort", skill.getSort()); - skillData.put("status", skill.getStatus()); - - // 格式化时间字段 - if (skill.getCreatedAt() != null) { - skillData.put("created_at", sdf.format(skill.getCreatedAt())); - } else { - skillData.put("created_at", null); - } - - if (skill.getUpdatedAt() != null) { - skillData.put("updated_at", sdf.format(skill.getUpdatedAt())); - } else { - skillData.put("updated_at", null); - } - - resultList.add(skillData); - } - - return AppletControllerUtil.appletSuccess(resultList); - } catch (Exception e) { - System.err.println("获取技能列表异常:" + e.getMessage()); - return AppletControllerUtil.appletError("获取技能列表失败:" + e.getMessage()); - } - } - - /** - * 文件上传接口 - * - * @param file 上传的文件 - * @param request HTTP请求对象 - * @return 上传结果 - *

- * 接口说明: - * - 支持图片和文档文件上传 - * - 优先使用七牛云上传,未启用时使用本地上传 - * - 自动验证文件格式和大小 - * - 无需用户登录验证(public 接口) - *

- * 支持的文件格式: - * - 图片:jpg, jpeg, png, gif, bmp, webp, svg - * - 文档:doc, docx, xls, xlsx, ppt, pptx, txt, pdf - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "path": "images/2025-06-11/zvsZHNoFYlFkMCePQs1624hKwBSCozL9XM7pEUmo.jpg", - * "full_path": "http://img.huafurenjia.cn/images/2025-06-11/zvsZHNoFYlFkMCePQs1624hKwBSCozL9XM7pEUmo.jpg" - * } - * } - */ - @PostMapping(value = "/api/public/upload/file") - public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) { - try { - // 1. 验证文件是否为空 - if (file == null || file.isEmpty()) { - return AppletControllerUtil.appletWarning("上传文件不能为空"); - } - - // 2. 验证文件格式 - String[] allowedTypes = { - // 图片格式 - "jpg", "jpeg", "png", "gif", "bmp", "webp", "svg", - // 文档格式 - "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf" - }; - - if (!QiniuUploadUtil.isValidFileType(file.getOriginalFilename(), allowedTypes)) { - return AppletControllerUtil.appletWarning("不支持的文件格式"); - } - - // 3. 验证文件大小(10MB) - long maxSize = 10 * 1024 * 1024; - if (!QiniuUploadUtil.isFileSizeValid(file.getSize(), maxSize)) { - return AppletControllerUtil.appletWarning("文件大小不能超过10MB"); - } - - String fileUrl; - String filePath; - - // 4. 检查是否启用七牛云上传 - if (qiniuConfig.isEnabled()) { - // 使用七牛云上传 - fileUrl = QiniuUploadUtil.uploadFile(file); - // 从完整URL中提取路径部分 - filePath = AppletControllerUtil.extractPathFromUrl(fileUrl, "https://" + qiniuConfig.getDomain() + "/"); - } else { - // 使用本地上传(这里需要集成本地上传逻辑) - return AppletControllerUtil.appletError("本地上传功能暂未在此接口中实现,请启用七牛云上传"); - } - - // 5. 构建返回数据 - Map uploadResult = new HashMap<>(); - uploadResult.put("path", filePath); - uploadResult.put("full_path", fileUrl); - - return AppletControllerUtil.appletSuccess(uploadResult); - - } catch (Exception e) { - System.err.println("文件上传异常:" + e.getMessage()); - return AppletControllerUtil.appletError("文件上传失败:" + e.getMessage()); - } - } - - - /** - * 获取服务预约时间段接口 - * - * @param params 请求参数,包含day(预约日期) - * @param request HTTP请求对象 - * @return 时间段列表数据 - *

- * 接口说明: - * - 根据指定日期获取可预约的时间段列表 - * - 返回每个时间段的可用状态和剩余数量 - * - 支持动态时间段配置 - * - 无需用户登录验证 - *

- * 请求参数格式: - * { - * "day": "2025-06-11" - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": [ - * { - * "click": true, - * "value": "8:00-10:00", - * "prove": "可预约", - * "residue_num": 99 - * } - * ] - * } - */ - @PostMapping(value = "/api/service/make/time") - public AjaxResult getServiceMakeTime(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 参数验证 - if (params == null || params.get("day") == null) { - return AppletControllerUtil.appletWarning("日期参数不能为空"); - } - - String day = params.get("day").toString().trim(); - if (day.isEmpty()) { - return AppletControllerUtil.appletWarning("日期参数不能为空"); - } - - // 2. 验证日期格式 - if (!AppletControllerUtil.isValidDateFormat(day)) { - return AppletControllerUtil.appletWarning("日期格式错误,请使用yyyy-MM-dd格式"); - } - - // 3. 检查日期是否为过去时间 - if (AppletControllerUtil.isPastDate(day)) { - return AppletControllerUtil.appletWarning("不能预约过去的日期"); - } - - // 4. 构建时间段列表 - List> timeSlotList = AppletControllerUtil.buildTimeSlotList(day); - - return AppletControllerUtil.appletSuccess(timeSlotList); - - } catch (Exception e) { - System.err.println("获取服务预约时间段异常:" + e.getMessage()); - return AppletControllerUtil.appletError("获取时间段失败:" + e.getMessage()); - } - } - - - /** - * 添加商品到购物车接口 - * - * @param params 请求参数,包含good_id(商品ID)、sku(商品规格) - * @param request HTTP请求对象 - * @return 添加结果 - *

- * 接口说明: - * - 将指定商品添加到用户购物车 - * - 验证商品是否存在和可用 - * - 支持商品规格选择 - * - 需要用户登录验证 - *

- * 请求参数格式: - * { - * "good_id": 86, - * "sku": "" - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "操作成功", - * "data": "商品已添加到购物车" - * } - */ - @PostMapping(value = "/api/cart/add") - public AjaxResult addToCart(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - - // 3. 验证请求参数 - if (params == null || params.get("good_id") == null) { - return AppletControllerUtil.appletWarning("商品ID不能为空"); - } - - Long goodId; - try { - goodId = Long.valueOf(params.get("good_id").toString()); - if (goodId <= 0) { - return AppletControllerUtil.appletWarning("商品ID无效"); - } - } catch (NumberFormatException e) { - return AppletControllerUtil.appletWarning("商品ID格式错误"); - } - - // 4. 获取商品规格参数 - // String sku = params.get("sku") != null ? params.get("sku").toString().trim() : ""; - String sku = null; - if (params.get("sku") != null) { - Object skuParam = params.get("sku"); - if (skuParam instanceof Map) { - // 如果前端传递的是Map对象,转换为JSON字符串 - try { - sku = com.alibaba.fastjson2.JSON.toJSONString(skuParam); - } catch (Exception e) { - System.err.println("SKU转换JSON失败:" + e.getMessage()); - sku = skuParam.toString(); - } - } else { - // 如果前端传递的是字符串,直接使用 - sku = skuParam.toString().trim(); - } - }else{ - sku = null; - } - // 5. 查询商品信息并验证 - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodId); - if (serviceGoods == null) { - return AppletControllerUtil.appletWarning("商品不存在"); - } - - // 6. 验证商品状态 + // 6. 验证商品状态 // if (serviceGoods.getStatus() == null || !serviceGoods.getStatus().equals(1L)) { // return AppletControllerUtil.appletWarning("商品已下架或不可用"); // } - // 7. 检查商品库存(如果有库存管理) + // 7. 检查商品库存(如果有库存管理) // if (serviceGoods.getStock() != null && serviceGoods.getStock() <= 0L) { // return AppletControllerUtil.appletWarning("商品库存不足"); // } - // 8. 检查购物车中是否已存在该商品 - GoodsCart existingCartItem = AppletControllerUtil.findExistingCartItem(user.getId(), goodId, sku, goodsCartService); + // 8. 检查购物车中是否已存在该商品 + GoodsCart existingCartItem = AppletControllerUtil.findExistingCartItem(user.getId(), goodId, sku, goodsCartService); - if (existingCartItem != null) { - // 如果已存在,更新数量 - return AppletControllerUtil.updateCartItemQuantity(existingCartItem, serviceGoods, goodsCartService); - } else { - // 如果不存在,新增购物车记录 - return AppletControllerUtil.addNewCartItem(user, serviceGoods, sku, goodsCartService); - } - - } catch (Exception e) { - System.err.println("添加购物车异常:" + e.getMessage()); - return AppletControllerUtil.appletError("添加购物车失败:" + e.getMessage()); + if (existingCartItem != null) { + // 如果已存在,更新数量 + return AppletControllerUtil.updateCartItemQuantity(existingCartItem, serviceGoods, goodsCartService); + } else { + // 如果不存在,新增购物车记录 + return AppletControllerUtil.addNewCartItem(user, serviceGoods, sku, goodsCartService); } + + } catch (Exception e) { + System.err.println("添加购物车异常:" + e.getMessage()); + return AppletControllerUtil.appletError("添加购物车失败:" + e.getMessage()); } +} - /** - * 查询购物车列表接口 - * - * @param params 请求参数,包含limit(每页数量)、page(页码) - * @param request HTTP请求对象 - * @return 购物车列表数据 - *

- * 接口说明: - * - 获取当前登录用户的购物车商品列表 - * - 支持分页查询 - * - 返回完整的商品信息 - * - 需要用户登录验证 - *

- * 请求参数格式: - * { - * "limit": 15, - * "page": 1 - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "current_page": 1, - * "data": [ - * { - * "id": 248, - * "uid": 302, - * "good_id": 86, - * "good_num": 1, - * "sku": null, - * "created_at": "2025-06-11 10:05:37", - * "updated_at": "2025-06-11 10:05:37", - * "good": { - * "id": 86, - * "title": "马桶漏水", - * "price": "0.00", - * "icon": "https://img.huafurenjia.cn/images/...", - * "stock": 232, - * "type": 1 - * } - * } - * ], - * "from": 1, - * "last_page": 1, - * "per_page": 15, - * "to": 1, - * "total": 1 - * } - * } - */ - @PostMapping(value = "/api/cart/lst") - public AjaxResult getCartList(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - - // 3. 获取分页参数 - int page = params.get("page") != null ? (Integer) params.get("page") : 1; - int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; - - // 4. 验证分页参数 - Map pageValidation = PageUtil.validatePageParams(page, limit); - if (!(Boolean) pageValidation.get("valid")) { - return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); - } - - // 5. 设置分页参数 - PageHelper.startPage(page, limit); - - // 6. 构建查询条件 - GoodsCart queryCart = new GoodsCart(); - queryCart.setUid(user.getId()); - - // 7. 查询购物车列表 - List cartList = goodsCartService.selectGoodsCartList(queryCart); - - // 8. 为每个购物车项目填充商品信息 - List> resultList = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - for (GoodsCart cart : cartList) { - Map cartData = new HashMap<>(); - - // 基本购物车信息 - cartData.put("id", cart.getId()); - cartData.put("uid", cart.getUid()); - cartData.put("good_id", cart.getGoodId()); - cartData.put("good_num", cart.getGoodNum()); - if (cart.getSku() != null||cart.getSku() != "") { - cartData.put("sku", JSONObject.parseObject(cart.getSku())); - }else{ - cartData.put("sku", null); - } - - - // 格式化时间字段 - cartData.put("created_at", cart.getCreatedAt() != null ? - sdf.format(cart.getCreatedAt()) : null); - cartData.put("updated_at", cart.getUpdatedAt() != null ? - sdf.format(cart.getUpdatedAt()) : null); - - // 查询并添加商品详细信息 - Map goodInfo = AppletControllerUtil.getGoodDetailForCart(cart.getGoodId(), serviceGoodsService); - cartData.put("good", goodInfo); - - resultList.add(cartData); - } - - // 9. 构建分页信息 - PageInfo pageInfo = new PageInfo<>(cartList); - - // 10. 构建返回数据格式 - Map responseData = new HashMap<>(); - responseData.put("current_page", pageInfo.getPageNum()); - responseData.put("data", resultList); - responseData.put("from", pageInfo.getStartRow()); - responseData.put("last_page", pageInfo.getPages()); - responseData.put("per_page", pageInfo.getPageSize()); - responseData.put("to", pageInfo.getEndRow()); - responseData.put("total", pageInfo.getTotal()); - - // 构建分页链接信息 - String baseUrl = "https://www.huafurenjia.cn/api/cart/lst"; - responseData.put("first_page_url", baseUrl + "?page=1"); - responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); - responseData.put("next_page_url", pageInfo.isHasNextPage() ? - baseUrl + "?page=" + pageInfo.getNextPage() : null); - responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? - baseUrl + "?page=" + pageInfo.getPrePage() : null); - responseData.put("path", baseUrl); - - // 构建links数组 - List> links = new ArrayList<>(); - Map prevLink = new HashMap<>(); - prevLink.put("url", pageInfo.isHasPreviousPage() ? - baseUrl + "?page=" + pageInfo.getPrePage() : null); - prevLink.put("label", "« Previous"); - prevLink.put("active", false); - links.add(prevLink); - - Map nextLink = new HashMap<>(); - nextLink.put("url", pageInfo.isHasNextPage() ? - baseUrl + "?page=" + pageInfo.getNextPage() : null); - nextLink.put("label", "Next »"); - nextLink.put("active", false); - links.add(nextLink); - - responseData.put("links", links); - - return AppletControllerUtil.appletSuccess(responseData); - - } catch (Exception e) { - System.err.println("查询购物车列表异常:" + e.getMessage()); - return AppletControllerUtil.appletError("查询购物车列表失败:" + e.getMessage()); +/** + * 查询购物车列表接口 + * + * @param params 请求参数,包含limit(每页数量)、page(页码) + * @param request HTTP请求对象 + * @return 购物车列表数据 + *

+ * 接口说明: + * - 获取当前登录用户的购物车商品列表 + * - 支持分页查询 + * - 返回完整的商品信息 + * - 需要用户登录验证 + *

+ * 请求参数格式: + * { + * "limit": 15, + * "page": 1 + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "current_page": 1, + * "data": [ + * { + * "id": 248, + * "uid": 302, + * "good_id": 86, + * "good_num": 1, + * "sku": null, + * "created_at": "2025-06-11 10:05:37", + * "updated_at": "2025-06-11 10:05:37", + * "good": { + * "id": 86, + * "title": "马桶漏水", + * "price": "0.00", + * "icon": "https://img.huafurenjia.cn/images/...", + * "stock": 232, + * "type": 1 + * } + * } + * ], + * "from": 1, + * "last_page": 1, + * "per_page": 15, + * "to": 1, + * "total": 1 + * } + * } + */ +@PostMapping(value = "/api/cart/lst") +public AjaxResult getCartList(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); } - } - - /** - * 服务/商品搜索接口 - * - * @param params 请求参数,包含limit(每页数量)、page(页码)、keywords(搜索关键词) - * @param request HTTP请求对象 - * @return 搜索结果列表 - *

- * 接口说明: - * - 根据关键词搜索服务商品 - * - 支持按商品标题进行模糊查询 - * - 支持分页查询 - * - 无需用户登录验证 - *

- * 请求参数格式: - * { - * "limit": 15, - * "page": 1, - * "keywords": "3" - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "current_page": 1, - * "data": [ - * { - * "id": 161, - * "title": "238元套餐", - * "icon": "https://img.huafurenjia.cn/images/238元套餐.png", - * "cate_id": 8, - * "price": "238.00", - * "price_zn": "元起", - * "sales": 66, - * "stock": 942, - * "sub_title": "咖啡机(咖啡)冷台·洗衣机(空调)烘", - * "title": "238元套餐", - * "type": 1 - * } - * ], - * "from": 1, - * "last_page": 1, - * "per_page": 15, - * "to": 2, - * "total": 2 - * } - * } - */ - @PostMapping(value = "/api/service/search") - public AjaxResult searchServices(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 获取搜索参数 - int page = params.get("page") != null ? (Integer) params.get("page") : 1; - int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; - String keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : ""; - - // 2. 验证分页参数 - Map pageValidation = PageUtil.validatePageParams(page, limit); - if (!(Boolean) pageValidation.get("valid")) { - return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); - } - - // 3. 设置分页参数 - PageHelper.startPage(page, limit); - - // 4. 构建查询条件 - ServiceGoods queryGoods = new ServiceGoods(); - - // 如果有关键词,设置标题模糊查询 - if (!keywords.isEmpty()) { - queryGoods.setTitle(keywords); // 这里依赖mapper中的like查询实现 - } - - // 5. 查询商品列表 - List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); - - // 6. 构建返回数据 - List> resultList = new ArrayList<>(); - for (ServiceGoods goods : goodsList) { - Map goodsData = AppletControllerUtil.buildServiceGoodsData(goods); - resultList.add(goodsData); - } - - // 7. 构建分页信息 - PageInfo pageInfo = new PageInfo<>(goodsList); - - // 8. 构建返回数据格式 - Map responseData = new HashMap<>(); - responseData.put("current_page", pageInfo.getPageNum()); - responseData.put("data", resultList); - responseData.put("from", pageInfo.getStartRow()); - responseData.put("last_page", pageInfo.getPages()); - responseData.put("per_page", pageInfo.getPageSize()); - responseData.put("to", pageInfo.getEndRow()); - responseData.put("total", pageInfo.getTotal()); - - // 构建分页链接信息 - String baseUrl = "https://www.huafurenjia.cn/api/service/search"; - responseData.put("first_page_url", baseUrl + "?page=1"); - responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); - responseData.put("next_page_url", pageInfo.isHasNextPage() ? - baseUrl + "?page=" + pageInfo.getNextPage() : null); - responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? - baseUrl + "?page=" + pageInfo.getPrePage() : null); - responseData.put("path", baseUrl); - - // 构建links数组 - List> links = new ArrayList<>(); - Map prevLink = new HashMap<>(); - prevLink.put("url", pageInfo.isHasPreviousPage() ? - baseUrl + "?page=" + pageInfo.getPrePage() : null); - prevLink.put("label", "« Previous"); - prevLink.put("active", false); - links.add(prevLink); - - Map nextLink = new HashMap<>(); - nextLink.put("url", pageInfo.isHasNextPage() ? - baseUrl + "?page=" + pageInfo.getNextPage() : null); - nextLink.put("label", "Next »"); - nextLink.put("active", false); - links.add(nextLink); - - responseData.put("links", links); - - return AppletControllerUtil.appletSuccess(responseData); - - } catch (Exception e) { - System.err.println("搜索服务商品异常:" + e.getMessage()); - return AppletControllerUtil.appletError("搜索失败:" + e.getMessage()); + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); } - } - /** - * 获取商品订单详情接口 - * - * @param id 订单ID - * @param request HTTP请求对象 - * @return 订单详细信息 - *

- * 接口说明: - * - 根据订单ID获取商品订单完整信息 - * - 包含订单基本信息、用户地址、商品信息等 - * - 验证用户登录状态和订单归属权 - * - 返回完整的订单详情数据 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "id": 2, - * "type": 2, - * "main_order_id": "WXBB08452049418556", - * "order_id": "BB08452049567554", - * // ... 其他订单字段 - * "address": { - * // 地址信息 - * }, - * "product": { - * // 商品信息 - * }, - * "comment": [], - * "delivery": [] - * } - * } - */ - @GetMapping("/api/goods/order/info/{id}") - public AjaxResult getGoodsOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { - try { - // 1. 参数验证 - if (id == null || id <= 0) { - return AppletControllerUtil.appletWarning("订单ID无效"); - } + // 3. 获取分页参数 + int page = params.get("page") != null ? (Integer) params.get("page") : 1; + int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; - // 2. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - - // 3. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - - // 4. 查询订单信息并验证归属权 - GoodsOrder order = goodsOrderService.selectGoodsOrderById(id); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - - // 5. 验证订单归属权 - if (!order.getUid().equals(user.getId())) { - return AppletControllerUtil.appletWarning("无权访问该订单信息"); - } - - // 6. 构建订单详情数据 - Map orderDetail = buildGoodsOrderDetail(order); - - return AppletControllerUtil.appletSuccess(orderDetail); - - } catch (Exception e) { - System.err.println("查询商品订单详情异常:" + e.getMessage()); - return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); + // 4. 验证分页参数 + Map pageValidation = PageUtil.validatePageParams(page, limit); + if (!(Boolean) pageValidation.get("valid")) { + return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } - } - /** - * 构建商品订单详情数据 - * - * @param order 订单信息 - * @return 格式化的订单详情 - */ - private Map buildGoodsOrderDetail(GoodsOrder order) { - Map orderDetail = new HashMap<>(); + // 5. 设置分页参数 + PageHelper.startPage(page, limit); + + // 6. 构建查询条件 + GoodsCart queryCart = new GoodsCart(); + queryCart.setUid(user.getId()); + + // 7. 查询购物车列表 + List cartList = goodsCartService.selectGoodsCartList(queryCart); + + // 8. 为每个购物车项目填充商品信息 + List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - // 订单基本信息 - orderDetail.put("id", order.getId()); - orderDetail.put("type", order.getType()); - orderDetail.put("main_order_id", order.getMainOrderId()); - orderDetail.put("order_id", order.getOrderId()); - orderDetail.put("transaction_id", order.getTransactionId() != null ? order.getTransactionId() : ""); - orderDetail.put("uid", order.getUid()); - orderDetail.put("product_id", order.getProductId()); - orderDetail.put("name", order.getName()); - orderDetail.put("phone", order.getPhone()); - orderDetail.put("num", order.getNum()); - orderDetail.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); - orderDetail.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); - orderDetail.put("service_price", order.getServicePrice()); - orderDetail.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); - orderDetail.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); - orderDetail.put("postage", order.getPostage()); - orderDetail.put("pay_time", order.getPayTime() != null ? sdf.format(order.getPayTime()) : null); - orderDetail.put("status", order.getStatus()); - orderDetail.put("delivery_id", order.getDeliveryId()); - orderDetail.put("delivery_num", order.getDeliveryNum() != null ? order.getDeliveryNum() : ""); - orderDetail.put("send_time", order.getSendTime() != null ? sdf.format(order.getSendTime()) : null); - orderDetail.put("mark", order.getMark()); - orderDetail.put("address_id", order.getAddressId()); - orderDetail.put("sku", order.getSku()); + for (GoodsCart cart : cartList) { + Map cartData = new HashMap<>(); - // 时间字段格式化 - orderDetail.put("created_at", order.getCreatedAt() != null ? sdf.format(order.getCreatedAt()) : null); - orderDetail.put("updated_at", order.getUpdatedAt() != null ? sdf.format(order.getUpdatedAt()) : null); - orderDetail.put("deleted_at", order.getDeletedAt() != null ? sdf.format(order.getDeletedAt()) : null); - - // 查询并添加地址信息 - if (order.getAddressId() != null) { - UserAddress address = userAddressService.selectUserAddressById(order.getAddressId()); - if (address != null) { - Map addressInfo = new HashMap<>(); - addressInfo.put("id", address.getId()); - addressInfo.put("uid", address.getUid()); - addressInfo.put("name", address.getName()); - addressInfo.put("phone", address.getPhone()); - addressInfo.put("latitude", address.getLatitude()); - addressInfo.put("longitude", address.getLongitude()); - addressInfo.put("address_name", address.getAddressName()); - addressInfo.put("address_info", address.getAddressInfo()); - addressInfo.put("info", address.getInfo()); - addressInfo.put("is_default", address.getIsDefault()); - addressInfo.put("created_at", address.getCreatedAt() != null ? sdf.format(address.getCreatedAt()) : null); - addressInfo.put("updated_at", address.getUpdatedAt() != null ? sdf.format(address.getUpdatedAt()) : null); - addressInfo.put("deleted_at", null); // UserAddress可能没有deletedAt字段 - - orderDetail.put("address", addressInfo); + // 基本购物车信息 + cartData.put("id", cart.getId()); + cartData.put("uid", cart.getUid()); + cartData.put("good_id", cart.getGoodId()); + cartData.put("good_num", cart.getGoodNum()); + if (cart.getSku() != null || cart.getSku() != "") { + cartData.put("sku", JSONObject.parseObject(cart.getSku())); + } else { + cartData.put("sku", null); } + + + // 格式化时间字段 + cartData.put("created_at", cart.getCreatedAt() != null ? + sdf.format(cart.getCreatedAt()) : null); + cartData.put("updated_at", cart.getUpdatedAt() != null ? + sdf.format(cart.getUpdatedAt()) : null); + + // 查询并添加商品详细信息 + Map goodInfo = AppletControllerUtil.getGoodDetailForCart(cart.getGoodId(), serviceGoodsService); + cartData.put("good", goodInfo); + + resultList.add(cartData); } - // 查询并添加商品信息 - if (order.getProductId() != null) { - ServiceGoods product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - if (product != null) { - Map productInfo = new HashMap<>(); - productInfo.put("id", product.getId()); - productInfo.put("title", product.getTitle()); - productInfo.put("sub_title", product.getSubTitle()); - productInfo.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); + // 9. 构建分页信息 + PageInfo pageInfo = new PageInfo<>(cartList); - orderDetail.put("product", productInfo); - } + // 10. 构建返回数据格式 + Map responseData = new HashMap<>(); + responseData.put("current_page", pageInfo.getPageNum()); + responseData.put("data", resultList); + responseData.put("from", pageInfo.getStartRow()); + responseData.put("last_page", pageInfo.getPages()); + responseData.put("per_page", pageInfo.getPageSize()); + responseData.put("to", pageInfo.getEndRow()); + responseData.put("total", pageInfo.getTotal()); + + // 构建分页链接信息 + String baseUrl = "https://www.huafurenjia.cn/api/cart/lst"; + responseData.put("first_page_url", baseUrl + "?page=1"); + responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); + responseData.put("next_page_url", pageInfo.isHasNextPage() ? + baseUrl + "?page=" + pageInfo.getNextPage() : null); + responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? + baseUrl + "?page=" + pageInfo.getPrePage() : null); + responseData.put("path", baseUrl); + + // 构建links数组 + List> links = new ArrayList<>(); + Map prevLink = new HashMap<>(); + prevLink.put("url", pageInfo.isHasPreviousPage() ? + baseUrl + "?page=" + pageInfo.getPrePage() : null); + prevLink.put("label", "« Previous"); + prevLink.put("active", false); + links.add(prevLink); + + Map nextLink = new HashMap<>(); + nextLink.put("url", pageInfo.isHasNextPage() ? + baseUrl + "?page=" + pageInfo.getNextPage() : null); + nextLink.put("label", "Next »"); + nextLink.put("active", false); + links.add(nextLink); + + responseData.put("links", links); + + return AppletControllerUtil.appletSuccess(responseData); + + } catch (Exception e) { + System.err.println("查询购物车列表异常:" + e.getMessage()); + return AppletControllerUtil.appletError("查询购物车列表失败:" + e.getMessage()); + } +} + + +/** + * 服务/商品搜索接口 + * + * @param params 请求参数,包含limit(每页数量)、page(页码)、keywords(搜索关键词) + * @param request HTTP请求对象 + * @return 搜索结果列表 + *

+ * 接口说明: + * - 根据关键词搜索服务商品 + * - 支持按商品标题进行模糊查询 + * - 支持分页查询 + * - 无需用户登录验证 + *

+ * 请求参数格式: + * { + * "limit": 15, + * "page": 1, + * "keywords": "3" + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "current_page": 1, + * "data": [ + * { + * "id": 161, + * "title": "238元套餐", + * "icon": "https://img.huafurenjia.cn/images/238元套餐.png", + * "cate_id": 8, + * "price": "238.00", + * "price_zn": "元起", + * "sales": 66, + * "stock": 942, + * "sub_title": "咖啡机(咖啡)冷台·洗衣机(空调)烘", + * "title": "238元套餐", + * "type": 1 + * } + * ], + * "from": 1, + * "last_page": 1, + * "per_page": 15, + * "to": 2, + * "total": 2 + * } + * } + */ +@PostMapping(value = "/api/service/search") +public AjaxResult searchServices(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 获取搜索参数 + int page = params.get("page") != null ? (Integer) params.get("page") : 1; + int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; + String keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : ""; + + // 2. 验证分页参数 + Map pageValidation = PageUtil.validatePageParams(page, limit); + if (!(Boolean) pageValidation.get("valid")) { + return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } - // 添加评论和配送信息(暂时为空数组,后续可以扩展) - orderDetail.put("comment", new ArrayList<>()); - orderDetail.put("delivery", new ArrayList<>()); + // 3. 设置分页参数 + PageHelper.startPage(page, limit); - return orderDetail; + // 4. 构建查询条件 + ServiceGoods queryGoods = new ServiceGoods(); + + // 如果有关键词,设置标题模糊查询 + if (!keywords.isEmpty()) { + queryGoods.setTitle(keywords); // 这里依赖mapper中的like查询实现 + } + + // 5. 查询商品列表 + List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); + + // 6. 构建返回数据 + List> resultList = new ArrayList<>(); + for (ServiceGoods goods : goodsList) { + Map goodsData = AppletControllerUtil.buildServiceGoodsData(goods); + resultList.add(goodsData); + } + + // 7. 构建分页信息 + PageInfo pageInfo = new PageInfo<>(goodsList); + + // 8. 构建返回数据格式 + Map responseData = new HashMap<>(); + responseData.put("current_page", pageInfo.getPageNum()); + responseData.put("data", resultList); + responseData.put("from", pageInfo.getStartRow()); + responseData.put("last_page", pageInfo.getPages()); + responseData.put("per_page", pageInfo.getPageSize()); + responseData.put("to", pageInfo.getEndRow()); + responseData.put("total", pageInfo.getTotal()); + + // 构建分页链接信息 + String baseUrl = "https://www.huafurenjia.cn/api/service/search"; + responseData.put("first_page_url", baseUrl + "?page=1"); + responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); + responseData.put("next_page_url", pageInfo.isHasNextPage() ? + baseUrl + "?page=" + pageInfo.getNextPage() : null); + responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? + baseUrl + "?page=" + pageInfo.getPrePage() : null); + responseData.put("path", baseUrl); + + // 构建links数组 + List> links = new ArrayList<>(); + Map prevLink = new HashMap<>(); + prevLink.put("url", pageInfo.isHasPreviousPage() ? + baseUrl + "?page=" + pageInfo.getPrePage() : null); + prevLink.put("label", "« Previous"); + prevLink.put("active", false); + links.add(prevLink); + + Map nextLink = new HashMap<>(); + nextLink.put("url", pageInfo.isHasNextPage() ? + baseUrl + "?page=" + pageInfo.getNextPage() : null); + nextLink.put("label", "Next »"); + nextLink.put("active", false); + links.add(nextLink); + + responseData.put("links", links); + + return AppletControllerUtil.appletSuccess(responseData); + + } catch (Exception e) { + System.err.println("搜索服务商品异常:" + e.getMessage()); + return AppletControllerUtil.appletError("搜索失败:" + e.getMessage()); + } +} + +/** + * 获取商品订单详情接口 + * + * @param id 订单ID + * @param request HTTP请求对象 + * @return 订单详细信息 + *

+ * 接口说明: + * - 根据订单ID获取商品订单完整信息 + * - 包含订单基本信息、用户地址、商品信息等 + * - 验证用户登录状态和订单归属权 + * - 返回完整的订单详情数据 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "id": 2, + * "type": 2, + * "main_order_id": "WXBB08452049418556", + * "order_id": "BB08452049567554", + * // ... 其他订单字段 + * "address": { + * // 地址信息 + * }, + * "product": { + * // 商品信息 + * }, + * "comment": [], + * "delivery": [] + * } + * } + */ +@GetMapping("/api/goods/order/info/{id}") +public AjaxResult getGoodsOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { + try { + // 1. 参数验证 + if (id == null || id <= 0) { + return AppletControllerUtil.appletWarning("订单ID无效"); + } + + // 2. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + + // 3. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + + // 4. 查询订单信息并验证归属权 + GoodsOrder order = goodsOrderService.selectGoodsOrderById(id); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + + // 5. 验证订单归属权 + if (!order.getUid().equals(user.getId())) { + return AppletControllerUtil.appletWarning("无权访问该订单信息"); + } + + // 6. 构建订单详情数据 + Map orderDetail = buildGoodsOrderDetail(order); + + return AppletControllerUtil.appletSuccess(orderDetail); + + } catch (Exception e) { + System.err.println("查询商品订单详情异常:" + e.getMessage()); + return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); + } +} + +/** + * 构建商品订单详情数据 + * + * @param order 订单信息 + * @return 格式化的订单详情 + */ +private Map buildGoodsOrderDetail(GoodsOrder order) { + Map orderDetail = new HashMap<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + // 订单基本信息 + orderDetail.put("id", order.getId()); + orderDetail.put("type", order.getType()); + orderDetail.put("main_order_id", order.getMainOrderId()); + orderDetail.put("order_id", order.getOrderId()); + orderDetail.put("transaction_id", order.getTransactionId() != null ? order.getTransactionId() : ""); + orderDetail.put("uid", order.getUid()); + orderDetail.put("product_id", order.getProductId()); + orderDetail.put("name", order.getName()); + orderDetail.put("phone", order.getPhone()); + orderDetail.put("num", order.getNum()); + orderDetail.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); + orderDetail.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); + orderDetail.put("service_price", order.getServicePrice()); + orderDetail.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); + orderDetail.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); + orderDetail.put("postage", order.getPostage()); + orderDetail.put("pay_time", order.getPayTime() != null ? sdf.format(order.getPayTime()) : null); + orderDetail.put("status", order.getStatus()); + orderDetail.put("delivery_id", order.getDeliveryId()); + orderDetail.put("delivery_num", order.getDeliveryNum() != null ? order.getDeliveryNum() : ""); + orderDetail.put("send_time", order.getSendTime() != null ? sdf.format(order.getSendTime()) : null); + orderDetail.put("mark", order.getMark()); + orderDetail.put("address_id", order.getAddressId()); + orderDetail.put("sku", order.getSku()); + + // 时间字段格式化 + orderDetail.put("created_at", order.getCreatedAt() != null ? sdf.format(order.getCreatedAt()) : null); + orderDetail.put("updated_at", order.getUpdatedAt() != null ? sdf.format(order.getUpdatedAt()) : null); + orderDetail.put("deleted_at", order.getDeletedAt() != null ? sdf.format(order.getDeletedAt()) : null); + + // 查询并添加地址信息 + if (order.getAddressId() != null) { + UserAddress address = userAddressService.selectUserAddressById(order.getAddressId()); + if (address != null) { + Map addressInfo = new HashMap<>(); + addressInfo.put("id", address.getId()); + addressInfo.put("uid", address.getUid()); + addressInfo.put("name", address.getName()); + addressInfo.put("phone", address.getPhone()); + addressInfo.put("latitude", address.getLatitude()); + addressInfo.put("longitude", address.getLongitude()); + addressInfo.put("address_name", address.getAddressName()); + addressInfo.put("address_info", address.getAddressInfo()); + addressInfo.put("info", address.getInfo()); + addressInfo.put("is_default", address.getIsDefault()); + addressInfo.put("created_at", address.getCreatedAt() != null ? sdf.format(address.getCreatedAt()) : null); + addressInfo.put("updated_at", address.getUpdatedAt() != null ? sdf.format(address.getUpdatedAt()) : null); + addressInfo.put("deleted_at", null); // UserAddress可能没有deletedAt字段 + + orderDetail.put("address", addressInfo); + } } - /** - * 获取用户优惠券数量统计接口 - * - * @param request HTTP请求对象 - * @return 优惠券数量统计信息 - *

- * 接口说明: - * - 统计当前登录用户的优惠券数量 - * - 包含未使用、已使用、已过期、待领取数量 - * - 需要用户登录验证 - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": { - * "one": 1, // 未使用数量 - * "two": 0, // 已使用数量 - * "three": 0, // 已过期数量 - * "four": 13 // 待领取数量 - * } - * } - */ - @GetMapping("/api/coupon/my/count") - public AjaxResult getMyCouponCount(HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } + // 查询并添加商品信息 + if (order.getProductId() != null) { + ServiceGoods product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + if (product != null) { + Map productInfo = new HashMap<>(); + productInfo.put("id", product.getId()); + productInfo.put("title", product.getTitle()); + productInfo.put("sub_title", product.getSubTitle()); + productInfo.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } + orderDetail.put("product", productInfo); + } + } - // 3. 查询用户的所有优惠券 - CouponUser couponUserQuery = new CouponUser(); - couponUserQuery.setUid(user.getId()); - List userCouponList = couponUserService.selectCouponUserList(couponUserQuery); + // 添加评论和配送信息(暂时为空数组,后续可以扩展) + orderDetail.put("comment", new ArrayList<>()); + orderDetail.put("delivery", new ArrayList<>()); - // 4. 统计各种状态的优惠券数量 - int unusedCount = 0; // 未使用数量 (one) - int usedCount = 0; // 已使用数量 (two) - int expiredCount = 0; // 已过期数量 (three) + return orderDetail; +} - long currentTime = System.currentTimeMillis() / 1000; // 当前时间戳(秒) +/** + * 获取用户优惠券数量统计接口 + * + * @param request HTTP请求对象 + * @return 优惠券数量统计信息 + *

+ * 接口说明: + * - 统计当前登录用户的优惠券数量 + * - 包含未使用、已使用、已过期、待领取数量 + * - 需要用户登录验证 + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": { + * "one": 1, // 未使用数量 + * "two": 0, // 已使用数量 + * "three": 0, // 已过期数量 + * "four": 13 // 待领取数量 + * } + * } + */ +@GetMapping("/api/coupon/my/count") +public AjaxResult getMyCouponCount(HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } - for (CouponUser couponUser : userCouponList) { - // 检查是否已使用 - if (couponUser.getStatus() != null && couponUser.getStatus() == 2L) { - usedCount++; + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + + // 3. 查询用户的所有优惠券 + CouponUser couponUserQuery = new CouponUser(); + couponUserQuery.setUid(user.getId()); + List userCouponList = couponUserService.selectCouponUserList(couponUserQuery); + + // 4. 统计各种状态的优惠券数量 + int unusedCount = 0; // 未使用数量 (one) + int usedCount = 0; // 已使用数量 (two) + int expiredCount = 0; // 已过期数量 (three) + + long currentTime = System.currentTimeMillis() / 1000; // 当前时间戳(秒) + + for (CouponUser couponUser : userCouponList) { + // 检查是否已使用 + if (couponUser.getStatus() != null && couponUser.getStatus() == 2L) { + usedCount++; + } else { + // 检查是否已过期 + if (isExpired(couponUser, currentTime)) { + expiredCount++; } else { - // 检查是否已过期 - if (isExpired(couponUser, currentTime)) { - expiredCount++; - } else { - // 未使用且未过期 - unusedCount++; - } + // 未使用且未过期 + unusedCount++; } } + } - // 5. 查询可领取的优惠券数量 - Coupons couponsQuery = new Coupons(); - couponsQuery.setStatus(1L); // 启用状态 - List availableCoupons = couponsService.selectCouponsList(couponsQuery); + // 5. 查询可领取的优惠券数量 + Coupons couponsQuery = new Coupons(); + couponsQuery.setStatus(1L); // 启用状态 + List availableCoupons = couponsService.selectCouponsList(couponsQuery); - int availableToReceiveCount = 0; // 待领取数量 (four) - for (Coupons coupon : availableCoupons) { - if (isCouponAvailableToReceive(coupon, user.getId(), currentTime)) { - availableToReceiveCount++; - } + int availableToReceiveCount = 0; // 待领取数量 (four) + for (Coupons coupon : availableCoupons) { + if (isCouponAvailableToReceive(coupon, user.getId(), currentTime)) { + availableToReceiveCount++; } + } - // 6. 构建返回数据 - Map countData = new HashMap<>(); - countData.put("one", unusedCount); // 未使用数量 - countData.put("two", usedCount); // 已使用数量 - countData.put("three", expiredCount); // 已过期数量 - countData.put("four", availableToReceiveCount); // 待领取数量 + // 6. 构建返回数据 + Map countData = new HashMap<>(); + countData.put("one", unusedCount); // 未使用数量 + countData.put("two", usedCount); // 已使用数量 + countData.put("three", expiredCount); // 已过期数量 + countData.put("four", availableToReceiveCount); // 待领取数量 - return AppletControllerUtil.appletSuccess(countData); + return AppletControllerUtil.appletSuccess(countData); - } catch (Exception e) { - System.err.println("查询用户优惠券数量统计异常:" + e.getMessage()); - return AppletControllerUtil.appletError("查询优惠券数量统计失败:" + e.getMessage()); + } catch (Exception e) { + System.err.println("查询用户优惠券数量统计异常:" + e.getMessage()); + return AppletControllerUtil.appletError("查询优惠券数量统计失败:" + e.getMessage()); + } +} + +/** + * 判断优惠券是否已过期 + * + * @param couponUser 用户优惠券 + * @param currentTime 当前时间戳(秒) + * @return 是否过期 + */ +private boolean isExpired(CouponUser couponUser, long currentTime) { + // 检查lose_time字段(失效时间),这是一个字符串时间戳 + if (couponUser.getLoseTime() != null && !couponUser.getLoseTime().isEmpty()) { + try { + long loseTimeStamp = Long.parseLong(couponUser.getLoseTime()); + return currentTime > loseTimeStamp; + } catch (NumberFormatException e) { + // 如果解析失败,假设为日期格式,暂时认为未过期 + System.err.println("解析失效时间失败:" + couponUser.getLoseTime()); } } - /** - * 判断优惠券是否已过期 - * - * @param couponUser 用户优惠券 - * @param currentTime 当前时间戳(秒) - * @return 是否过期 - */ - private boolean isExpired(CouponUser couponUser, long currentTime) { - // 检查lose_time字段(失效时间),这是一个字符串时间戳 - if (couponUser.getLoseTime() != null && !couponUser.getLoseTime().isEmpty()) { - try { - long loseTimeStamp = Long.parseLong(couponUser.getLoseTime()); - return currentTime > loseTimeStamp; - } catch (NumberFormatException e) { - // 如果解析失败,假设为日期格式,暂时认为未过期 - System.err.println("解析失效时间失败:" + couponUser.getLoseTime()); - } - } - - // 如果状态为3,表示已失效 - if (couponUser.getStatus() != null && couponUser.getStatus() == 3L) { - return true; - } - - // 如果都没有设置,认为未过期 - return false; - } - - /** - * 判断优惠券是否可以领取 - * - * @param coupon 优惠券 - * @param userId 用户ID - * @param currentTime 当前时间戳(秒) - * @return 是否可以领取 - */ - private boolean isCouponAvailableToReceive(Coupons coupon, Long userId, long currentTime) { - // 检查优惠券状态 - if (coupon.getStatus() == null || coupon.getStatus() != 1L) { - return false; - } - - // 检查领取时间范围 - if (coupon.getStartTime() != null && currentTime < coupon.getStartTime()) { - return false; // 还未到领取时间 - } - - if (coupon.getEndTime() != null && currentTime > coupon.getEndTime()) { - return false; // 已过领取时间 - } - - // 检查数量限制(如果不是无限领取) - if (coupon.getIsPermanent() == null || coupon.getIsPermanent() != 1L) { - if (coupon.getCount() != null && coupon.getCount() <= 0) { - return false; // 数量已用完 - } - } - - // 检查用户是否已经领取过此优惠券(如果有限制的话) - // 这里可以根据业务规则进一步完善 - + // 如果状态为3,表示已失效 + if (couponUser.getStatus() != null && couponUser.getStatus() == 3L) { return true; } + // 如果都没有设置,认为未过期 + return false; +} + +/** + * 判断优惠券是否可以领取 + * + * @param coupon 优惠券 + * @param userId 用户ID + * @param currentTime 当前时间戳(秒) + * @return 是否可以领取 + */ +private boolean isCouponAvailableToReceive(Coupons coupon, Long userId, long currentTime) { + // 检查优惠券状态 + if (coupon.getStatus() == null || coupon.getStatus() != 1L) { + return false; + } + + // 检查领取时间范围 + if (coupon.getStartTime() != null && currentTime < coupon.getStartTime()) { + return false; // 还未到领取时间 + } + + if (coupon.getEndTime() != null && currentTime > coupon.getEndTime()) { + return false; // 已过领取时间 + } + + // 检查数量限制(如果不是无限领取) + if (coupon.getIsPermanent() == null || coupon.getIsPermanent() != 1L) { + if (coupon.getCount() != null && coupon.getCount() <= 0) { + return false; // 数量已用完 + } + } + + // 检查用户是否已经领取过此优惠券(如果有限制的话) + // 这里可以根据业务规则进一步完善 + + return true; +} // /** @@ -4427,267 +4509,517 @@ public class AppletController extends BaseController { // } +/** + * 创建服务订单(支持多商品批量下单) + * + * @param params 请求参数,包含多个商品信息、地址信息和预约时间 + * @param request HTTP请求对象 + * @return 返回创建结果 + */ +@PostMapping("/api/service/create/order") +public AjaxResult createServiceOrder(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + // 3. 验证订单参数 + if (params == null || params.isEmpty()) { + return error("订单参数不能为空"); + } - /** - * 创建服务订单(支持多商品批量下单) - * - * @param params 请求参数,包含多个商品信息、地址信息和预约时间 - * @param request HTTP请求对象 - * @return 返回创建结果 - */ - @PostMapping("/api/service/create/order") - public AjaxResult createServiceOrder(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); + // 4. 生成主订单号 + String mainOrderId = GenerateCustomCode.generCreateOrder("WXB"); + + // 5. 存储所有订单信息 + List> orderList = new ArrayList<>(); + BigDecimal totalAmount = BigDecimal.ZERO; // 总金额 + + // 6. 遍历所有订单项 + for (String key : params.keySet()) { + // 跳过非数字键 + if (!key.matches("\\d+")) { + continue; } - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); + Map orderParams = (Map) params.get(key); + + // 验证必要参数 + if (orderParams.get("product_id") == null || orderParams.get("address_id") == null) { + return error("商品ID或地址ID不能为空"); } - // 3. 验证订单参数 - if (params == null || params.isEmpty()) { - return error("订单参数不能为空"); + Long productId = Long.valueOf(orderParams.get("product_id").toString()); + Long addressId = Long.valueOf(orderParams.get("address_id").toString()); + Long num = orderParams.get("num") != null ? Long.valueOf(orderParams.get("num").toString()) : 1L; + + // 处理SKU参数 + String sku = AppletControllerUtil.processSkuParam(orderParams.get("sku")); + + // 查询商品信息 + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId); + if (serviceGoods == null) { + return error("商品ID " + productId + " 不存在"); } - // 4. 生成主订单号 - String mainOrderId =GenerateCustomCode.generCreateOrder("WXB"); + // 查询地址信息(只需要查询一次,假设所有订单使用相同地址) + UserAddress userAddress = userAddressService.selectUserAddressById(addressId); + if (userAddress == null) { + return error("地址不存在"); + } + + // 计算单个订单金额 + BigDecimal itemPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); + totalAmount = totalAmount.add(itemPrice); + + // 判断商品类型并创建相应订单 + if (serviceGoods.getType() == 2) { + // 创建服务订单 + String coupon_id = orderParams.get("coupon_id") != null ? orderParams.get("coupon_id").toString() : ""; + if (coupon_id!=null){ + CouponUser coupon = couponUserService.selectCouponUserById(Long.valueOf(coupon_id)); + if (coupon==null){ + return AppletControllerUtil.appletWarning("优惠券不存在"); + } - // 5. 存储所有订单信息 - List> orderList = new ArrayList<>(); - BigDecimal totalAmount = BigDecimal.ZERO; // 总金额 - // 6. 遍历所有订单项 - for (String key : params.keySet()) { - // 跳过非数字键 - if (!key.matches("\\d+")) { - continue; } - Map orderParams = (Map) params.get(key); + // 创建商品订单 + GoodsOrder goodsOrder = new GoodsOrder(); + goodsOrder.setType(2); + goodsOrder.setMainOrderId(mainOrderId); + goodsOrder.setOrderId(GenerateCustomCode.generCreateOrder("B")); // 独立订单号 + goodsOrder.setUid(user.getId()); + goodsOrder.setProductId(productId); + goodsOrder.setName(userAddress.getName()); + goodsOrder.setPhone(userAddress.getPhone()); + goodsOrder.setAddress(userAddress.getAddressName()); + goodsOrder.setNum(num); + goodsOrder.setTotalPrice(itemPrice); + goodsOrder.setGoodPrice(serviceGoods.getPrice()); + goodsOrder.setPayPrice(itemPrice); + goodsOrder.setDeduction(new BigDecimal(0)); + goodsOrder.setStatus(1L); // 待支付状态 + goodsOrder.setAddressId(addressId); + goodsOrder.setSku(sku); - // 验证必要参数 - if (orderParams.get("product_id") == null || orderParams.get("address_id") == null) { - return error("商品ID或地址ID不能为空"); + // 保存商品订单 + int insertResult = goodsOrderService.insertGoodsOrder(goodsOrder); + if (insertResult <= 0) { + return error("商品订单创建失败,请稍后重试"); } - Long productId = Long.valueOf(orderParams.get("product_id").toString()); - Long addressId = Long.valueOf(orderParams.get("address_id").toString()); - Long num = orderParams.get("num") != null ? Long.valueOf(orderParams.get("num").toString()) : 1L; + // 添加到订单列表 + Map orderInfo = new HashMap<>(); + orderInfo.put("type", "goods"); + orderInfo.put("orderId", goodsOrder.getId()); + orderInfo.put("orderNo", goodsOrder.getOrderId()); + orderInfo.put("productName", serviceGoods.getTitle()); + orderInfo.put("price", itemPrice.toString()); + orderList.add(orderInfo); - // 处理SKU参数 - String sku = AppletControllerUtil.processSkuParam(orderParams.get("sku")); + } else { + // 创建服务订单 + String makeTime = orderParams.get("make_time") != null ? orderParams.get("make_time").toString() : ""; - // 查询商品信息 - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId); - if (serviceGoods == null) { - return error("商品ID " + productId + " 不存在"); - } + Order order = new Order(); + order.setType(1); // 1:服务项目 + order.setCreateType(1); // 1:用户自主下单 + order.setUid(user.getId()); + order.setUname(user.getName()); + order.setProductId(productId); + order.setProductName(serviceGoods.getTitle()); + order.setName(userAddress.getName()); + order.setPhone(userAddress.getPhone()); + order.setAddress(userAddress.getAddressInfo()); + order.setAddressId(addressId); + order.setSku(sku); + order.setMainOrderId(mainOrderId); + order.setOrderId(GenerateCustomCode.generCreateOrder("B")); // 独立订单号 - // 查询地址信息(只需要查询一次,假设所有订单使用相同地址) - UserAddress userAddress = userAddressService.selectUserAddressById(addressId); - if (userAddress == null) { - return error("地址不存在"); - } - - // 计算单个订单金额 - BigDecimal itemPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); - totalAmount = totalAmount.add(itemPrice); - - // 判断商品类型并创建相应订单 - if (serviceGoods.getType() == 2) { - // 创建商品订单 - GoodsOrder goodsOrder = new GoodsOrder(); - goodsOrder.setType(2); - goodsOrder.setMainOrderId(mainOrderId); - goodsOrder.setOrderId(GenerateCustomCode.generCreateOrder("B")); // 独立订单号 - goodsOrder.setUid(user.getId()); - goodsOrder.setProductId(productId); - goodsOrder.setName(userAddress.getName()); - goodsOrder.setPhone(userAddress.getPhone()); - goodsOrder.setAddress(userAddress.getAddressName()); - goodsOrder.setNum(num); - goodsOrder.setTotalPrice(itemPrice); - goodsOrder.setGoodPrice(serviceGoods.getPrice()); - goodsOrder.setPayPrice(itemPrice); - goodsOrder.setDeduction(new BigDecimal(0)); - goodsOrder.setStatus(1L); // 待支付状态 - goodsOrder.setAddressId(addressId); - goodsOrder.setSku(sku); - - // 保存商品订单 - int insertResult = goodsOrderService.insertGoodsOrder(goodsOrder); - if (insertResult <= 0) { - return error("商品订单创建失败,请稍后重试"); - } - - // 添加到订单列表 - Map orderInfo = new HashMap<>(); - orderInfo.put("type", "goods"); - orderInfo.put("orderId", goodsOrder.getId()); - orderInfo.put("orderNo", goodsOrder.getOrderId()); - orderInfo.put("productName", serviceGoods.getTitle()); - orderInfo.put("price", itemPrice.toString()); - orderList.add(orderInfo); - - } else { - // 创建服务订单 - String makeTime = orderParams.get("make_time") != null ? orderParams.get("make_time").toString() : ""; - - Order order = new Order(); - order.setType(1); // 1:服务项目 - order.setCreateType(1); // 1:用户自主下单 - order.setUid(user.getId()); - order.setUname(user.getName()); - order.setProductId(productId); - order.setProductName(serviceGoods.getTitle()); - order.setName(userAddress.getName()); - order.setPhone(userAddress.getPhone()); - order.setAddress(userAddress.getAddressInfo()); - order.setAddressId(addressId); - order.setSku(sku); - order.setMainOrderId(mainOrderId); - order.setOrderId(GenerateCustomCode.generCreateOrder("B")); // 独立订单号 - - // 处理预约时间 - if (makeTime != null && !makeTime.isEmpty()) { - String[] makeTimeArr = makeTime.split(" "); - if (makeTimeArr.length == 2) { - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Date date = sdf.parse(makeTimeArr[0]); - order.setMakeTime(date.getTime() / 1000); - order.setMakeHour(makeTimeArr[1]); - } catch (Exception e) { - logger.warn("预约时间格式错误: " + makeTime); - } + // 处理预约时间 + if (makeTime != null && !makeTime.isEmpty()) { + String[] makeTimeArr = makeTime.split(" "); + if (makeTimeArr.length == 2) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date = sdf.parse(makeTimeArr[0]); + order.setMakeTime(date.getTime() / 1000); + order.setMakeHour(makeTimeArr[1]); + } catch (Exception e) { + logger.warn("预约时间格式错误: " + makeTime); } } - - order.setNum(num); - order.setTotalPrice(itemPrice); - order.setGoodPrice(serviceGoods.getPrice()); - order.setServicePrice(BigDecimal.ZERO); - order.setPayPrice(itemPrice); - order.setStatus(1L); // 1:待接单 - order.setReceiveType(1L); // 1:自由抢单 - order.setIsAccept(0); - order.setIsComment(0); - order.setIsPause(1); - order.setDeduction(new BigDecimal(0)); - - // 保存服务订单 - int result = orderService.insertOrder(order); - if (result <= 0) { - return error("服务订单创建失败,请稍后重试"); - } - - // 添加订单日志 - OrderLog orderLog = new OrderLog(); - orderLog.setOid(order.getId()); - orderLog.setOrderId(order.getOrderId()); - orderLog.setTitle("订单生成"); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("name", "预约成功,将尽快为主人派单"); - orderLog.setType(new BigDecimal(1.0)); - orderLog.setContent(jsonObject.toString()); - orderLogService.insertOrderLog(orderLog); - - // 系统派单和消息通知逻辑 - Order orderNewData = orderService.selectOrderById(order.getId()); - String wxsendmsg = WXsendMsgUtil.sendMsgForUserInfo(user.getOpenid(), orderNewData, serviceGoods); - Users worker = AppletControllerUtil.creatWorkerForOrder(orderNewData); - - if (worker != null) { - // 更新订单状态为已派单 - orderNewData.setWorkerId(worker.getId()); - orderNewData.setStatus(2l); - orderNewData.setIsPause(1); - orderNewData.setReceiveTime(new Date()); - orderNewData.setReceiveType(3l); - orderNewData.setLogStatus(9); - JSONObject jSONObject = new JSONObject(); - jSONObject.put("type", 9); - orderNewData.setLogJson(jSONObject.toJSONString()); - orderService.updateOrder(orderNewData); - - // 添加派单日志 - OrderLog orderLognew = new OrderLog(); - orderLognew.setOid(orderNewData.getId()); - orderLognew.setOrderId(orderNewData.getOrderId()); - orderLognew.setTitle("平台派单"); - orderLognew.setType(new BigDecimal(1.1)); - JSONObject jSONObject1 = new JSONObject(); - jSONObject1.put("name", "师傅收到派单信息"); - orderLognew.setContent(jSONObject1.toJSONString()); - orderLognew.setWorkerId(worker.getId()); - orderLognew.setWorkerLogId(worker.getId()); - orderLogService.insertOrderLog(orderLognew); - - // 发送通知 - WXsendMsgUtil.sendMsgForWorkerInfo(worker.getOpenid(), orderNewData, serviceGoods); - YunXinPhoneUtilAPI.httpsAxbTransfer(worker.getPhone()); - } - - // 添加到订单列表 - Map orderInfo = new HashMap<>(); - orderInfo.put("type", "service"); - orderInfo.put("orderId", order.getId()); - orderInfo.put("orderNo", order.getOrderId()); - orderInfo.put("productName", serviceGoods.getTitle()); - orderInfo.put("price", itemPrice.toString()); - orderList.add(orderInfo); } + + order.setNum(num); + order.setTotalPrice(itemPrice); + order.setGoodPrice(serviceGoods.getPrice()); + order.setServicePrice(BigDecimal.ZERO); + order.setPayPrice(itemPrice); + order.setStatus(1L); // 1:待接单 + order.setReceiveType(1L); // 1:自由抢单 + order.setIsAccept(0); + order.setIsComment(0); + order.setIsPause(1); + order.setDeduction(new BigDecimal(0)); + + // 保存服务订单 + int result = orderService.insertOrder(order); + if (result <= 0) { + return error("服务订单创建失败,请稍后重试"); + } + + // 添加订单日志 + OrderLog orderLog = new OrderLog(); + orderLog.setOid(order.getId()); + orderLog.setOrderId(order.getOrderId()); + orderLog.setTitle("订单生成"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", "预约成功,将尽快为主人派单"); + orderLog.setType(new BigDecimal(1.0)); + orderLog.setContent(jsonObject.toString()); + orderLogService.insertOrderLog(orderLog); + + // 系统派单和消息通知逻辑 + Order orderNewData = orderService.selectOrderById(order.getId()); + String wxsendmsg = WXsendMsgUtil.sendMsgForUserInfo(user.getOpenid(), orderNewData, serviceGoods); + Users worker = AppletControllerUtil.creatWorkerForOrder(orderNewData); + + if (worker != null) { + // 更新订单状态为已派单 + orderNewData.setWorkerId(worker.getId()); + orderNewData.setStatus(2l); + orderNewData.setIsPause(1); + orderNewData.setReceiveTime(new Date()); + orderNewData.setReceiveType(3l); + orderNewData.setLogStatus(9); + JSONObject jSONObject = new JSONObject(); + jSONObject.put("type", 9); + orderNewData.setLogJson(jSONObject.toJSONString()); + orderService.updateOrder(orderNewData); + + // 添加派单日志 + OrderLog orderLognew = new OrderLog(); + orderLognew.setOid(orderNewData.getId()); + orderLognew.setOrderId(orderNewData.getOrderId()); + orderLognew.setTitle("平台派单"); + orderLognew.setType(new BigDecimal(1.1)); + JSONObject jSONObject1 = new JSONObject(); + jSONObject1.put("name", "师傅收到派单信息"); + orderLognew.setContent(jSONObject1.toJSONString()); + orderLognew.setWorkerId(worker.getId()); + orderLognew.setWorkerLogId(worker.getId()); + orderLogService.insertOrderLog(orderLognew); + + // 发送通知 + WXsendMsgUtil.sendMsgForWorkerInfo(worker.getOpenid(), orderNewData, serviceGoods); + YunXinPhoneUtilAPI.httpsAxbTransfer(worker.getPhone()); + } + + // 添加到订单列表 + Map orderInfo = new HashMap<>(); + orderInfo.put("type", "service"); + orderInfo.put("orderId", order.getId()); + orderInfo.put("orderNo", order.getOrderId()); + orderInfo.put("productName", serviceGoods.getTitle()); + orderInfo.put("price", itemPrice.toString()); + orderList.add(orderInfo); } + } - // 7. 如果有商品订单,需要发起微信支付 - boolean hasGoodsOrder = orderList.stream().anyMatch(order -> "goods".equals(order.get("type"))); + // 7. 如果有商品订单,需要发起微信支付 + boolean hasGoodsOrder = orderList.stream().anyMatch(order -> "goods".equals(order.get("type"))); - if (hasGoodsOrder && totalAmount.compareTo(BigDecimal.ZERO) > 0) { - // 使用工具类简化微信支付参数组装 - Map payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), mainOrderId, new BigDecimal(0.01), orderList.size(),"https://4d983d7f.r3.cpolar.top/api/goods/pay/notify"); - //Map payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), mainOrderId, totalAmount, orderList.size()); - if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { - Map responseData = new HashMap<>(); - responseData.put("mainOrderId", mainOrderId); - responseData.put("orderList", orderList); - responseData.put("totalAmount", totalAmount.toString()); - responseData.put("prepayId", payResult.get("prepayId")); - // 直接合并所有支付参数 - responseData.putAll(payResult); - return AppletControllerUtil.appletSuccess(responseData); - } else { - String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; - return error("支付下单失败:" + errorMsg); - } - } else { - // 没有商品订单,只有服务订单,直接返回成功 + if (hasGoodsOrder && totalAmount.compareTo(BigDecimal.ZERO) > 0) { + // 使用工具类简化微信支付参数组装 + Map payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), mainOrderId, new BigDecimal(0.01), orderList.size(), "https://2d684c7a.r5.cpolar.xyz/api/goods/pay/notify"); + //Map payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), mainOrderId, totalAmount, orderList.size()); + if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { Map responseData = new HashMap<>(); responseData.put("mainOrderId", mainOrderId); responseData.put("orderList", orderList); responseData.put("totalAmount", totalAmount.toString()); + responseData.put("prepayId", payResult.get("prepayId")); + // 直接合并所有支付参数 + responseData.putAll(payResult); return AppletControllerUtil.appletSuccess(responseData); + } else { + String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; + return error("支付下单失败:" + errorMsg); } + } else { + // 没有商品订单,只有服务订单,直接返回成功 + Map responseData = new HashMap<>(); + responseData.put("mainOrderId", mainOrderId); + responseData.put("orderList", orderList); + responseData.put("totalAmount", totalAmount.toString()); + return AppletControllerUtil.appletSuccess(responseData); + } - } catch (Exception e) { - logger.error("创建订单异常:", e); - return error("创建订单失败:" + e.getMessage()); + } catch (Exception e) { + logger.error("创建订单异常:", e); + return error("创建订单失败:" + e.getMessage()); + } +} + +/** + * 尾款结算 + */ +@PostMapping("api/service/order/pay/total/price") +public AjaxResult apiServiceOrderPayTotalPprice(@RequestBody Map params, HttpServletRequest request) { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 验证必要参数 + if (params == null || params.get("order_id") == null || params.get("worker_id") == null) { + return error("参数不能为空"); + } + Long worker_id = Long.valueOf(params.get("worker_id").toString()); + String order_id = params.get("order_id").toString(); + Order order = orderService.selectOrderByOrderId(order_id); + // 2. 查询订单日志(取type=5评估报价,或最新一条) + List logList = orderLogService.selectOrderLogByOrderId(order.getOrderId()); + OrderLog log = null; + for (OrderLog l : logList) { + if (l.getType() != null && l.getType().intValue() == 5) { + log = l; + break; } } - /** - * 尾款结算 - * - */ - @PostMapping("api/service/order/pay/total/price") - public AjaxResult apiServiceOrderPayTotalPprice(@RequestBody Map params, HttpServletRequest request) { + if (log == null && !logList.isEmpty()) { + log = logList.get(0); + } + if (log == null) { + return error("未找到订单日志"); + } + + Map payResult = wechatPayUtil.createBatchOrderAndPay( + user.getOpenid(), + String.valueOf(order_id), + new BigDecimal(0.01), + 1, + "https://2d684c7a.r5.cpolar.xyz/api/order/amount/pay/notify"); + if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { + Map responseData = new HashMap<>(); + responseData.put("mainOrderId", order_id); + //responseData.put("orderList", orderList); + responseData.put("totalAmount", log.getPrice()); + responseData.put("prepayId", payResult.get("prepayId")); + // 直接合并所有支付参数 + responseData.putAll(payResult); + return AppletControllerUtil.appletSuccess(responseData); + } else { + String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; + return error("支付下单失败:" + errorMsg); + } + + +} + +/** + * 上门费支付接口 + */ + +@PostMapping("api/service/order/pay_fee") +public AjaxResult apiServiceOrderPayFee(@RequestBody Map params, HttpServletRequest request) { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 验证必要参数 + if (params == null || params.get("id") == null) { + return error("参数不能为空"); + } + Long orderId = Long.valueOf(params.get("id").toString()); + OrderLog orderLog = orderLogService.selectOrderLogById(orderId); + if (orderLog != null) { + + Map payResult = wechatPayUtil.createBatchOrderAndPay( + user.getOpenid(), + String.valueOf(orderLog.getId()), + new BigDecimal(0.01), + 1, + "https://2d684c7a.r5.cpolar.xyz/api/door/fee/pay/notify"); + if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { + Map responseData = new HashMap<>(); + responseData.put("mainOrderId", String.valueOf(orderLog.getId())); + //responseData.put("orderList", orderList); + responseData.put("totalAmount", orderLog.getPrice()); + responseData.put("prepayId", payResult.get("prepayId")); + // 直接合并所有支付参数 + responseData.putAll(payResult); + return AppletControllerUtil.appletSuccess(responseData); + } else { + String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; + return error("支付下单失败:" + errorMsg); + } + + } + + + return error("支付失败"); +} + + +/** + * 定金支付接口 + */ + +@PostMapping("/api/service/order/pay/deposit") +public AjaxResult apiServiceOrderPaydeposit(@RequestBody Map params, HttpServletRequest request) { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 验证必要参数 + if (params == null || params.get("id") == null) { + return error("参数不能为空"); + } + Long orderId = Long.valueOf(params.get("id").toString()); + OrderLog orderLog = orderLogService.selectOrderLogById(orderId); + if (orderLog != null) { + + Map payResult = wechatPayUtil.createBatchOrderAndPay( + user.getOpenid(), + String.valueOf(orderLog.getId()), + new BigDecimal(0.01), + 1, + "https://2d684c7a.r5.cpolar.xyz/api/deposit/pay/notify"); + if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { + Map responseData = new HashMap<>(); + responseData.put("mainOrderId", String.valueOf(orderLog.getId())); + //responseData.put("orderList", orderList); + responseData.put("totalAmount", orderLog.getPrice()); + responseData.put("prepayId", payResult.get("prepayId")); + // 直接合并所有支付参数 + responseData.putAll(payResult); + return AppletControllerUtil.appletSuccess(responseData); + } else { + String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; + return error("支付下单失败:" + errorMsg); + } + + } + + + return error("支付失败"); +} + + +/** + * 单个商品支付 + */ +@PostMapping("api/goods/order/once_pay") +public AjaxResult apiGoodsOrderOncePay(@RequestBody Map params, HttpServletRequest request) { + // 1. 验证用户登录状态 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return error("用户未登录或token无效"); + } + + // 2. 获取用户信息 + Users user = (Users) userValidation.get("user"); + if (user == null) { + return error("用户信息获取失败"); + } + + // 3. 验证必要参数 + if (params == null || params.get("id") == null) { + return error("参数不能为空"); + } + Long orderId = Long.valueOf(params.get("id").toString()); + GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId); + logger.info("orderId:{}", orderId); + logger.info("goodsOrder:{}", goodsOrder); + if (goodsOrder != null) { + goodsOrder.setMainOrderId(GenerateCustomCode.generCreateOrder("WXB")); + int flg = goodsOrderService.updateGoodsOrder(goodsOrder); + //修改成功就开始走支付功能 + if (flg > 0) { + goodsOrder.setMainOrderId(goodsOrder.getMainOrderId()); + Map payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), goodsOrder.getMainOrderId(), new BigDecimal(0.01), 1, "https://2d684c7a.r5.cpolar.xyz/api/goods/pay/notify"); + if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { + Map responseData = new HashMap<>(); + responseData.put("mainOrderId", goodsOrder.getMainOrderId()); + //responseData.put("orderList", orderList); + responseData.put("totalAmount", goodsOrder.getTotalPrice()); + responseData.put("prepayId", payResult.get("prepayId")); + // 直接合并所有支付参数 + responseData.putAll(payResult); + return AppletControllerUtil.appletSuccess(responseData); + } else { + String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; + return error("支付下单失败:" + errorMsg); + } + + } + + + } + return error("支付失败"); +} + +/** + * 生成订单号 + * 格式:年月日时分秒 + 4位随机数 + */ +private String generateOrderId() { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + String timeStr = sdf.format(new Date()); + int random = (int) ((Math.random() * 9 + 1) * 1000); + return timeStr + random; +} + +/** + * 取消服务订单 + * + * @param params 请求参数,包含订单ID和取消原因 + * @param request HTTP请求对象 + * @return 返回取消结果 + */ +@PostMapping("/api/service/cancel/order") +public AjaxResult cancelServiceOrder(@RequestBody Map params, HttpServletRequest request) { + try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); @@ -4702,14 +5034,507 @@ public class AppletController extends BaseController { } // 3. 验证必要参数 - if (params == null || params.get("id") == null ) { + if (params == null || params.get("id") == null || params.get("content") == null) { return error("参数不能为空"); } - Long worker_id = Long.valueOf(params.get("worker_id").toString()); - String order_id = params.get("order_id").toString(); - Order order = orderService.selectOrderByOrderId(order_id); + Long orderId = Long.valueOf(params.get("id").toString()); + String cancelReason = params.get("content").toString(); + + // 4. 查询订单信息 + Order orderQuery = new Order(); + orderQuery.setId(orderId); + orderQuery.setUid(user.getId()); // 确保是用户自己的订单 + List orders = orderService.selectOrderList(orderQuery); + + if (orders == null || orders.isEmpty()) { + return error("订单不存在"); + } + Order order = orders.get(0); + + // 5. 验证订单状态是否可以取消 + if (order.getStatus() != 1L) { + return error("当前订单状态不可取消"); + } + + // 6. 更新订单状态为已取消(5) + Order updateOrder = new Order(); + updateOrder.setId(orderId); + updateOrder.setStatus(5L); + int result = orderService.updateOrder(updateOrder); + + if (result > 0) { + // 7. 添加订单日志 + OrderLog orderLog = new OrderLog(); + orderLog.setOid(orderId); + orderLog.setOrderId(order.getOrderId()); + orderLog.setTitle("订单取消"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", "用户取消订单,原因:" + cancelReason); + orderLog.setType(new BigDecimal(9.0)); + orderLog.setContent(jsonObject.toString()); + orderLogService.insertOrderLog(orderLog); + + return success("取消成功"); + } else { + return error("取消失败,请稍后重试"); + } + + } catch (Exception e) { + return error("取消失败:" + e.getMessage()); + } +} + +/** + * 师傅接单接口 + * 参考OrderController+OrderUtil+OrderLogHandler的json_status=2分支 + */ +@GetMapping("/api/worker/accept/order/{id}") +public AjaxResult workerAcceptOrder(@PathVariable("id") Long id, HttpServletRequest request) { + try { + // 1. 校验token并获取师傅信息 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users worker = (Users) userValidation.get("user"); + if (worker == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + // 2. 查询订单 + Order order = orderService.selectOrderById(id); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + // 3. 仅允许待服务状态接单 + if (order.getStatus() == null || order.getStatus() != 2L) { + return AppletControllerUtil.appletWarning("当前订单状态不可接单"); + } + // 4. 设置接单相关字段 + order.setWorkerId(worker.getId()); + order.setWorkerPhone(worker.getPhone()); + order.setIsPause(1); // 1:未暂停 + order.setReceiveType(3L); // 3:平台派单 + order.setReceiveTime(new Date()); + order.setIsAccept(1); // 1:已接单 + order.setJsonStatus(2); // 服务进度:2=接单 + order.setStatus(2l); + order.setLogStatus(9); + JSONObject json = new JSONObject(); + json.put("type", 1); + order.setLogJson(json.toJSONString()); + orderService.updateOrder(order); + + // 5. 写入日志 + OrderLog orderLog = new OrderLog(); + orderLog.setOid(order.getId()); + orderLog.setOrderId(order.getOrderId()); + orderLog.setTitle("师傅接单"); + orderLog.setType(new BigDecimal(2.0)); + JSONObject js = new JSONObject(); + js.put("name", "同意系统配单"); + orderLog.setContent(js.toJSONString()); + orderLog.setWorkerId(order.getWorkerId()); + orderLog.setWorkerLogId(order.getWorkerId()); + orderLogService.insertOrderLog(orderLog); +// OrderUtil orderUtil = new OrderUtil(); +// orderUtil.SaveOrderLog(order); + //绑定号码 + Map bindmap = OrderBindWorkerUtil.getOrderBindWorker(order.getId()); + //发送微信推送通知客户师傅已接单 + + + // 6. 返回成功 + return AjaxResult.success("接单成功"); + } catch (Exception e) { + return AppletControllerUtil.appletError("师傅接单失败:" + e.getMessage()); + } +} + +/** + * 师傅端订单列表接口 + * 查询worker_id为当前师傅的订单,支持状态和预约日期筛选 + * + * @param params {"limit":10,"page":1,"status":0,"day":""} + * @param request HttpServletRequest + * @return AjaxResult 带分页的订单列表,结构与json.txt一致 + */ +@PostMapping("/api/worker/order/lst") +public AjaxResult getWorkerOrderList(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 校验token并获取师傅信息 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + // 2. 解析分页和筛选参数 + int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; + int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 10; + int status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : 0; + String day = params.get("day") != null ? params.get("day").toString() : ""; + + // 3. 构建查询条件 + Order query = new Order(); + query.setWorkerId(user.getId()); + // 状态筛选 + if (status == 2) { + query.setStatus(2L); // 待服务 + } else if (status == 3) { + query.setStatus(3L); // 服务中 + } else if (status == 4) { + query.setStatus(5L); // 已结束 + } else if (status == 5) { + query.setStatus(6L); // 已取消 + } // status=0查全部 + + PageHelper.startPage(page, limit); + List orderList = orderService.selectOrderList(query); + List> resultList = new ArrayList<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date today = new Date(); + Date tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000); + int todayCount = 0; + int tomorrowCount = 0; + for (Order order : orderList) { + // day筛选逻辑 + if (status == 2 && day != null && !day.isEmpty()) { + String orderDay = order.getMakeTime() != null ? sdf.format(new Date(order.getMakeTime() * 1000)) : ""; + if ("today".equals(day) && !orderDay.equals(sdf.format(today))) continue; + if ("tomorrow".equals(day) && !orderDay.equals(sdf.format(tomorrow))) continue; + } + // 统计今日/明日待服务订单数 + if (order.getStatus() != null && order.getStatus() == 2L && order.getMakeTime() != null) { + String orderDay = sdf.format(new Date(order.getMakeTime() * 1000)); + if (orderDay.equals(sdf.format(today))) todayCount++; + if (orderDay.equals(sdf.format(tomorrow))) tomorrowCount++; + } + Map map = new HashMap<>(); + map.put("id", order.getId()); + map.put("type", order.getType()); + map.put("main_order_id", order.getMainOrderId()); + map.put("order_id", order.getOrderId()); + map.put("transaction_id", order.getTransactionId()); + map.put("create_type", order.getCreateType()); + map.put("create_phone", order.getCreatePhone()); + map.put("uid", order.getUid()); + map.put("product_id", order.getProductId()); + map.put("name", order.getName()); + map.put("phone", order.getPhone()); + // make_time格式化 + if (order.getMakeTime() != null && order.getMakeHour() != null) { + map.put("make_time", sdf.format(new Date(order.getMakeTime() * 1000)) + " " + order.getMakeHour()); + } else { + map.put("make_time", null); + } + map.put("make_hour", order.getMakeHour()); + map.put("num", order.getNum()); + map.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); + map.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); + map.put("service_price", order.getServicePrice()); + map.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); + map.put("coupon_id", order.getCouponId()); + map.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); + map.put("pay_time", order.getPayTime()); + map.put("status", order.getStatus()); + map.put("is_pause", order.getIsPause()); + map.put("mark", order.getMark()); + map.put("address_id", order.getAddressId()); + map.put("sku", order.getSku()); + map.put("worker_id", order.getWorkerId()); + map.put("first_worker_id", order.getFirstWorkerId()); + map.put("receive_time", order.getReceiveTime()); + map.put("is_comment", order.getIsComment()); + map.put("receive_type", order.getReceiveType()); + map.put("is_accept", order.getIsAccept()); + map.put("middle_phone", order.getMiddlePhone()); + map.put("user_phone", order.getUserPhone()); + map.put("worker_phone", order.getWorkerPhone()); + map.put("address_en", order.getAddressEn()); + map.put("uid_admin", order.getUidAdmin()); + map.put("address_admin", order.getAddressAdmin()); + map.put("log_status", order.getLogStatus()); + map.put("log_json", order.getLogJson()); + map.put("json_status", order.getJsonStatus()); + map.put("log_images", order.getLogImages()); + map.put("created_at", order.getCreatedAt() != null ? sdfFull.format(order.getCreatedAt()) : null); + map.put("updated_at", order.getUpdatedAt() != null ? sdfFull.format(order.getUpdatedAt()) : null); + map.put("deleted_at", order.getDeletedAt()); + //map.put("log_type", 1.1); + // 兼容log_type + + // address/address_has + UserAddress address = null; + if (order.getAddressId() != null) { + address = userAddressService.selectUserAddressById(order.getAddressId()); + } + map.put("address", address); + map.put("address_has", address); + // product + ServiceGoods product = null; + if (order.getProductId() != null) { + product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + } + if (product != null) { + Map productMap = new HashMap<>(); + productMap.put("id", product.getId()); + productMap.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); + productMap.put("title", product.getTitle()); + productMap.put("price", product.getPrice() != null ? product.getPrice().toString() : "0.00"); + productMap.put("sku_type", product.getSkuType()); + productMap.put("price_zn", product.getPriceZn()); + map.put("product", productMap); + } else { + map.put("product", null); + } + resultList.add(map); + } + PageInfo pageInfo = new PageInfo<>(orderList); + Map dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, "/api/worker/order/lst"); + // 外层data结构 + Map outerData = new HashMap<>(); + outerData.put("data", dataPage); + Map totalMap = new HashMap<>(); + totalMap.put("today", todayCount); + totalMap.put("tomorrow", tomorrowCount); + outerData.put("total", totalMap); + return AjaxResult.success(outerData); + } catch (Exception e) { + return AppletControllerUtil.appletError("查询师傅订单列表失败:" + e.getMessage()); + } +} + +/** + * 获取师傅工作台统计数据 + * 返回格式见json.txt + */ +@GetMapping("/api/worker/stat") +public AjaxResult getWorkerStat(HttpServletRequest request) { + try { + // 1. 校验token并获取用户 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + // 2. 查询config_one配置 + SiteConfig configQuery = new SiteConfig(); + configQuery.setName("config_one"); + List configList = siteConfigService.selectSiteConfigList(configQuery); + Object configObj = null; + if (configList != null && !configList.isEmpty()) { + String configValue = configList.get(0).getValue(); + if (configValue != null && !configValue.trim().isEmpty()) { + configObj = JSONObject.parse(configValue); + } + } + // 3. 判断今日是否签到 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String todayStr = sdf.format(new Date()); + WorkerSign signQuery = new WorkerSign(); + signQuery.setUid(String.valueOf(user.getId())); + signQuery.setTime(sdf.parse(todayStr)); + boolean signed = false; + List signList = workerSignService.selectWorkerSignList(signQuery); + if (signList != null && !signList.isEmpty()) { + signed = true; + } + // 4. 构建user数据 + Map userMap = buildUserInfoResponse(user); + // 5. 构建返回结构 + Map data = new HashMap<>(); + data.put("day_count", 0); + data.put("mouth_count", 0); + data.put("income", 0); + data.put("user", userMap); + data.put("sign", signed); + data.put("config", configObj); + Map result = new HashMap<>(); + result.put("code", 200); + result.put("msg", "OK"); + result.put("data", data); + return AjaxResult.success(result); + } catch (Exception e) { + return AppletControllerUtil.appletError("获取师傅统计数据失败:" + e.getMessage()); + } +} + +/** + * 师傅端订单详情接口 + * 返回结构见json.txt + */ +@GetMapping("/api/worker/order/info/{id}") +public AjaxResult getWorkerOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { + try { + // 4. 处理时间字段 + java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + // 1. 校验token并获取师傅信息 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users worker = (Users) userValidation.get("user"); + if (worker == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + // 2. 查询订单 + Order order = orderService.selectOrderById(id); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + // 3. 查询用户信息 + Users user = usersService.selectUsersById(order.getUid()); + // 4. 查询地址信息 + UserAddress address = null; + if (order.getAddressId() != null) { + address = userAddressService.selectUserAddressById(order.getAddressId()); + } + // 5. 查询商品信息 + ServiceGoods product = null; + if (order.getProductId() != null) { + product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + } + // 6. 查询订单日志 + OrderLog logQuery = new OrderLog(); + logQuery.setOid(order.getId()); + List logList = orderLogService.selectOrderLogList(logQuery); + List> logArr = new ArrayList<>(); + for (OrderLog log : logList) { + Map logMap = new HashMap<>(); + logMap.put("id", log.getId()); + logMap.put("oid", log.getOid()); + logMap.put("order_id", log.getOrderId()); + logMap.put("log_order_id", log.getLogOrderId()); + logMap.put("title", log.getTitle()); + logMap.put("type", log.getType()); + // content字段为json字符串,需转为对象 + Object contentObj = null; + try { + if (log.getContent() != null) { + contentObj = JSONObject.parse(log.getContent()); + } + } catch (Exception e) { + + if (AppletControllerUtil.canParseToJSONArray(log.getContent())) { + contentObj = JSONArray.parseArray(log.getContent()); + } else { + contentObj = log.getContent(); + } + + } + logMap.put("content", contentObj); + logMap.put("deposit", log.getDeposit()); + logMap.put("dep_paid", log.getDepPaid()); + logMap.put("dep_pay_time", log.getDepPayTime()); + logMap.put("dep_log_id", log.getDepLogId()); + logMap.put("price", log.getPrice()); + logMap.put("paid", log.getPaid()); + logMap.put("pay_time", log.getPayTime()); + logMap.put("log_id", log.getLogId()); + logMap.put("worker_id", log.getWorkerId()); + logMap.put("first_worker_id", log.getFirstWorkerId()); + logMap.put("give_up", log.getGiveUp()); + logMap.put("worker_cost", log.getWorkerCost()); + logMap.put("reduction_price", log.getReductionPrice()); + logMap.put("is_pause", log.getIsPause()); + logMap.put("coupon_id", log.getCouponId()); + logMap.put("deduction", log.getDeduction()); + logMap.put("worker_log_id", log.getWorkerLogId()); + logMap.put("created_at", log.getCreatedAt() != null ? dateFormat.format(log.getCreatedAt()) : null); + logMap.put("updated_at", log.getUpdatedAt() != null ? dateFormat.format(log.getUpdatedAt()) : null); + logMap.put("deleted_at", log.getDeletedAt()); + logArr.add(logMap); + } + // 7. 构建返回数据 + Map data = new HashMap<>(); + data.put("id", order.getId()); + data.put("type", order.getType()); + data.put("main_order_id", order.getMainOrderId()); + data.put("order_id", order.getOrderId()); + data.put("transaction_id", order.getTransactionId()); + data.put("create_type", order.getCreateType()); + data.put("create_phone", order.getCreatePhone()); + data.put("uid", order.getUid()); + data.put("product_id", order.getProductId()); + data.put("name", order.getName()); + data.put("phone", order.getPhone()); + data.put("address", address); + data.put("make_time", AppletControllerUtil.timeStamp2Date(order)); + data.put("make_hour", order.getMakeHour()); + data.put("num", order.getNum()); + data.put("total_price", order.getTotalPrice()); + data.put("good_price", order.getGoodPrice()); + data.put("service_price", order.getServicePrice()); + data.put("pay_price", order.getPayPrice()); + data.put("coupon_id", order.getCouponId()); + data.put("deduction", order.getDeduction()); + data.put("pay_time", order.getPayTime()); + data.put("status", order.getStatus()); + data.put("is_pause", order.getIsPause()); + data.put("mark", order.getMark()); + data.put("address_id", order.getAddressId()); + data.put("sku", order.getSku()); + data.put("worker_id", order.getWorkerId()); + data.put("first_worker_id", order.getFirstWorkerId()); + data.put("receive_time", order.getReceiveTime() != null ? dateFormat.format(order.getReceiveTime()) : null); + data.put("is_comment", order.getIsComment()); + data.put("receive_type", order.getReceiveType()); + data.put("is_accept", order.getIsAccept()); + data.put("middle_phone", order.getMiddlePhone()); + data.put("user_phone", order.getUserPhone()); + data.put("worker_phone", order.getWorkerPhone()); + data.put("address_en", order.getAddressEn()); + data.put("uid_admin", order.getUidAdmin()); + data.put("address_admin", order.getAddressAdmin()); + data.put("log_status", order.getLogStatus()); + data.put("log_json", order.getLogJson()); + data.put("json_status", order.getJsonStatus()); + data.put("log_images", order.getLogImages()); + data.put("created_at", order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); + data.put("updated_at", order.getUpdatedAt() != null ? dateFormat.format(order.getUpdatedAt()) : null); + data.put("deleted_at", order.getDeletedAt() != null ? dateFormat.format(order.getDeletedAt()) : null); + data.put("phone_xx", order.getPhone()); // 可脱敏处理 + data.put("user", user); + data.put("product", product); + data.put("log", logArr); + return AjaxResult.success(data); + } catch (Exception e) { + return AppletControllerUtil.appletError("查询师傅订单详情失败:" + e.getMessage()); + } +} + + +/** + * 支付尾款回调到页面的数据 + * 返回结构见json.txt + */ +@PostMapping("/api/service/order/pay/total/price/info") +public AjaxResult getOrderPayLastInfo(@RequestBody Map params) { + try { + String orderId = (String) params.get("order_id"); + if (StringUtils.isEmpty(orderId)) { + return error("订单号不能为空"); + } + + // 1. 查询订单 + Order order = orderService.selectOrderByOrderId(orderId); + if (order == null) { + return error("订单不存在"); + } + // 2. 查询订单日志(取type=5评估报价,或最新一条) - List logList = orderLogService.selectOrderLogByOrderId(order.getOrderId()); + List logList = orderLogService.selectOrderLogByOrderId(orderId); OrderLog log = null; for (OrderLog l : logList) { if (l.getType() != null && l.getType().intValue() == 5) { @@ -4724,820 +5549,401 @@ public class AppletController extends BaseController { return error("未找到订单日志"); } - Map payResult = wechatPayUtil.createBatchOrderAndPay( - user.getOpenid(), - String.valueOf(order_id), - new BigDecimal(0.01), - 1, - "https://4d983d7f.r3.cpolar.top/api/order/amount/pay/notify"); - if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { - Map responseData = new HashMap<>(); - responseData.put("mainOrderId", order_id); - //responseData.put("orderList", orderList); - responseData.put("totalAmount",log.getPrice()); - responseData.put("prepayId", payResult.get("prepayId")); - // 直接合并所有支付参数 - responseData.putAll(payResult); - return AppletControllerUtil.appletSuccess(responseData); - } else { - String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; - return error("支付下单失败:" + errorMsg); + // 3. 组装content字段 + JSONObject contentJson; + try { + contentJson = JSONObject.parseObject(log.getContent()); + } catch (Exception e) { + contentJson = new JSONObject(); } + // 4. 组装返回数据 + Map data = new HashMap<>(); + data.put("id", log.getId()); + data.put("oid", log.getOid()); + data.put("order_id", log.getOrderId()); + data.put("log_order_id", log.getLogOrderId()); + data.put("title", log.getTitle()); + data.put("type", log.getType() != null ? log.getType().intValue() : null); + data.put("content", contentJson); + data.put("deposit", log.getDeposit() != null ? log.getDeposit().toString() : "0.00"); + data.put("dep_paid", log.getDepPaid()); + data.put("dep_pay_time", log.getDepPayTime()); + data.put("dep_log_id", log.getDepLogId()); + data.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); + data.put("paid", log.getPaid()); + data.put("pay_time", log.getPayTime() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(log.getPayTime() * 1000)) : null); + data.put("log_id", log.getLogId()); + data.put("worker_id", log.getWorkerId()); + data.put("first_worker_id", log.getFirstWorkerId()); + data.put("give_up", log.getGiveUp()); + data.put("worker_cost", log.getWorkerCost()); + data.put("reduction_price", log.getReductionPrice() != null ? log.getReductionPrice().toString() : "0.00"); + data.put("is_pause", log.getIsPause()); + data.put("coupon_id", log.getCouponId()); + data.put("deduction", log.getDeduction()); + data.put("worker_log_id", log.getWorkerLogId()); + data.put("created_at", log.getCreatedAt() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getCreatedAt()) : null); + data.put("updated_at", log.getUpdatedAt() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getUpdatedAt()) : null); + data.put("deleted_at", log.getDeletedAt()); + return success(data); + } catch (Exception e) { + return error("查询失败:" + e.getMessage()); } - /** - * 上门费支付接口 - * - */ +} - @PostMapping("api/service/order/pay_fee") - public AjaxResult apiServiceOrderPayFee(@RequestBody Map params, HttpServletRequest request) { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); + +/** + * 师傅列表接口 + * 返回结构见json.txt + */ +@PostMapping("/api/worker/user/lst") +public AjaxResult getWorkerUserList(@RequestBody Map params) { + try { + int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; + int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; + String keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : null; + // 查询type=2的师傅 + Users query = new Users(); + query.setType("2"); + if (keywords != null && !keywords.isEmpty()) { + query.setName(keywords); } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 验证必要参数 - if (params == null || params.get("id") == null ) { - return error("参数不能为空"); - } - Long orderId = Long.valueOf(params.get("id").toString()); - OrderLog orderLog = orderLogService.selectOrderLogById(orderId); - if (orderLog != null) { - - Map payResult = wechatPayUtil.createBatchOrderAndPay( - user.getOpenid(), - String.valueOf(orderLog.getId()), - new BigDecimal(0.01), - 1, - "https://4d983d7f.r3.cpolar.top/api/door/fee/pay/notify"); - if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { - Map responseData = new HashMap<>(); - responseData.put("mainOrderId", String.valueOf(orderLog.getId())); - //responseData.put("orderList", orderList); - responseData.put("totalAmount",orderLog.getPrice()); - responseData.put("prepayId", payResult.get("prepayId")); - // 直接合并所有支付参数 - responseData.putAll(payResult); - return AppletControllerUtil.appletSuccess(responseData); + PageHelper.startPage(page, limit); + List userList = usersService.selectUsersList(query); + PageInfo pageInfo = new PageInfo<>(userList); + List> resultList = new ArrayList<>(); + for (Users user : userList) { + Map map = new HashMap<>(); + map.put("id", user.getId()); + map.put("name", user.getName()); + // 头像处理 + String avatar = user.getAvatar(); + if (avatar != null && !avatar.isEmpty()) { + if (!avatar.startsWith("http")) { + avatar = "https://img.huafurenjia.cn/" + avatar.replaceFirst("^/+", ""); + } } else { - String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; - return error("支付下单失败:" + errorMsg); + avatar = "https://img.huafurenjia.cn//default/user_avatar.jpeg"; } - - } - - - return error("支付失败"); - } - - - - - - /** - * 定金支付接口 - * - */ - - @PostMapping("/api/service/order/pay/deposit") - public AjaxResult apiServiceOrderPaydeposit(@RequestBody Map params, HttpServletRequest request) { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 验证必要参数 - if (params == null || params.get("id") == null ) { - return error("参数不能为空"); - } - Long orderId = Long.valueOf(params.get("id").toString()); - OrderLog orderLog = orderLogService.selectOrderLogById(orderId); - if (orderLog != null) { - - Map payResult = wechatPayUtil.createBatchOrderAndPay( - user.getOpenid(), - String.valueOf(orderLog.getId()), - new BigDecimal(0.01), - 1, - "https://4d983d7f.r3.cpolar.top/api/deposit/pay/notify"); - if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { - Map responseData = new HashMap<>(); - responseData.put("mainOrderId", String.valueOf(orderLog.getId())); - //responseData.put("orderList", orderList); - responseData.put("totalAmount",orderLog.getPrice()); - responseData.put("prepayId", payResult.get("prepayId")); - // 直接合并所有支付参数 - responseData.putAll(payResult); - return AppletControllerUtil.appletSuccess(responseData); - } else { - String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; - return error("支付下单失败:" + errorMsg); - } - - } - - - return error("支付失败"); - } - - - /** - * 单个商品支付 - * - */ - @PostMapping("api/goods/order/once_pay") - public AjaxResult apiGoodsOrderOncePay(@RequestBody Map params, HttpServletRequest request) { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 验证必要参数 - if (params == null || params.get("id") == null ) { - return error("参数不能为空"); - } - Long orderId = Long.valueOf(params.get("id").toString()); - GoodsOrder goodsOrder= goodsOrderService.selectGoodsOrderById(orderId); - logger.info("orderId:{}",orderId); - logger.info("goodsOrder:{}",goodsOrder); - if (goodsOrder != null) { - goodsOrder.setMainOrderId(GenerateCustomCode.generCreateOrder("WXB")); - int flg=goodsOrderService.updateGoodsOrder(goodsOrder); - //修改成功就开始走支付功能 - if(flg>0){ - goodsOrder.setMainOrderId(goodsOrder.getMainOrderId()); - Map payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), goodsOrder.getMainOrderId(), new BigDecimal(0.01), 1, "https://4d983d7f.r3.cpolar.top/api/goods/pay/notify"); - if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) { - Map responseData = new HashMap<>(); - responseData.put("mainOrderId", goodsOrder.getMainOrderId()); - //responseData.put("orderList", orderList); - responseData.put("totalAmount", goodsOrder.getTotalPrice()); - responseData.put("prepayId", payResult.get("prepayId")); - // 直接合并所有支付参数 - responseData.putAll(payResult); - return AppletControllerUtil.appletSuccess(responseData); - } else { - String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败"; - return error("支付下单失败:" + errorMsg); - } - - } - - - } - return error("支付失败"); - } - - /** - * 生成订单号 - * 格式:年月日时分秒 + 4位随机数 - */ - private String generateOrderId() { - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); - String timeStr = sdf.format(new Date()); - int random = (int) ((Math.random() * 9 + 1) * 1000); - return timeStr + random; - } - - /** - * 取消服务订单 - * - * @param params 请求参数,包含订单ID和取消原因 - * @param request HTTP请求对象 - * @return 返回取消结果 - */ - @PostMapping("/api/service/cancel/order") - public AjaxResult cancelServiceOrder(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 验证用户登录状态 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return error("用户未登录或token无效"); - } - - // 2. 获取用户信息 - Users user = (Users) userValidation.get("user"); - if (user == null) { - return error("用户信息获取失败"); - } - - // 3. 验证必要参数 - if (params == null || params.get("id") == null || params.get("content") == null) { - return error("参数不能为空"); - } - Long orderId = Long.valueOf(params.get("id").toString()); - String cancelReason = params.get("content").toString(); - - // 4. 查询订单信息 - Order orderQuery = new Order(); - orderQuery.setId(orderId); - orderQuery.setUid(user.getId()); // 确保是用户自己的订单 - List orders = orderService.selectOrderList(orderQuery); - - if (orders == null || orders.isEmpty()) { - return error("订单不存在"); - } - Order order = orders.get(0); - - // 5. 验证订单状态是否可以取消 - if (order.getStatus() != 1L) { - return error("当前订单状态不可取消"); - } - - // 6. 更新订单状态为已取消(5) - Order updateOrder = new Order(); - updateOrder.setId(orderId); - updateOrder.setStatus(5L); - int result = orderService.updateOrder(updateOrder); - - if (result > 0) { - // 7. 添加订单日志 - OrderLog orderLog = new OrderLog(); - orderLog.setOid(orderId); - orderLog.setOrderId(order.getOrderId()); - orderLog.setTitle("订单取消"); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("name", "用户取消订单,原因:" + cancelReason); - orderLog.setType(new BigDecimal(9.0)); - orderLog.setContent(jsonObject.toString()); - orderLogService.insertOrderLog(orderLog); - - return success("取消成功"); - } else { - return error("取消失败,请稍后重试"); - } - - } catch (Exception e) { - return error("取消失败:" + e.getMessage()); - } - } - - /** - * 师傅接单接口 - * 参考OrderController+OrderUtil+OrderLogHandler的json_status=2分支 - */ - @GetMapping("/api/worker/accept/order/{id}") - public AjaxResult workerAcceptOrder(@PathVariable("id") Long id, HttpServletRequest request) { - try { - // 1. 校验token并获取师傅信息 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users worker = (Users) userValidation.get("user"); - if (worker == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - // 2. 查询订单 - Order order = orderService.selectOrderById(id); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - // 3. 仅允许待服务状态接单 - if (order.getStatus() == null || order.getStatus() != 2L) { - return AppletControllerUtil.appletWarning("当前订单状态不可接单"); - } - // 4. 设置接单相关字段 - order.setWorkerId(worker.getId()); - order.setWorkerPhone(worker.getPhone()); - order.setIsPause(1); // 1:未暂停 - order.setReceiveType(3L); // 3:平台派单 - order.setReceiveTime(new Date()); - order.setIsAccept(1); // 1:已接单 - order.setJsonStatus(2); // 服务进度:2=接单 - order.setStatus(2l); - order.setLogStatus(9); - JSONObject json=new JSONObject(); - json.put("type",1); - order.setLogJson(json.toJSONString()); - orderService.updateOrder(order); - - // 5. 写入日志 - OrderLog orderLog=new OrderLog(); - orderLog.setOid(order.getId()); - orderLog.setOrderId(order.getOrderId()); - orderLog.setTitle("师傅接单"); - orderLog.setType(new BigDecimal(2.0)); - JSONObject js=new JSONObject(); - js.put("name", "同意系统配单"); - orderLog.setContent(js.toJSONString()); - orderLog.setWorkerId(order.getWorkerId()); - orderLog.setWorkerLogId(order.getWorkerId()); - orderLogService.insertOrderLog(orderLog); -// OrderUtil orderUtil = new OrderUtil(); -// orderUtil.SaveOrderLog(order); - //绑定号码 - Map bindmap= OrderBindWorkerUtil.getOrderBindWorker(order.getId()); - //发送微信推送通知客户师傅已接单 - - - // 6. 返回成功 - return AjaxResult.success("接单成功"); - } catch (Exception e) { - return AppletControllerUtil.appletError("师傅接单失败:" + e.getMessage()); - } - } - - /** - * 师傅端订单列表接口 - * 查询worker_id为当前师傅的订单,支持状态和预约日期筛选 - * - * @param params {"limit":10,"page":1,"status":0,"day":""} - * @param request HttpServletRequest - * @return AjaxResult 带分页的订单列表,结构与json.txt一致 - */ - @PostMapping("/api/worker/order/lst") - public AjaxResult getWorkerOrderList(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 校验token并获取师傅信息 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - // 2. 解析分页和筛选参数 - int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; - int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 10; - int status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : 0; - String day = params.get("day") != null ? params.get("day").toString() : ""; - - // 3. 构建查询条件 - Order query = new Order(); - query.setWorkerId(user.getId()); - // 状态筛选 - if (status == 2) { - query.setStatus(2L); // 待服务 - } else if (status == 3) { - query.setStatus(3L); // 服务中 - } else if (status == 4) { - query.setStatus(5L); // 已结束 - } else if (status == 5) { - query.setStatus(6L); // 已取消 - } // status=0查全部 - - PageHelper.startPage(page, limit); - List orderList = orderService.selectOrderList(query); - List> resultList = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date today = new Date(); - Date tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000); - int todayCount = 0; - int tomorrowCount = 0; - for (Order order : orderList) { - // day筛选逻辑 - if (status == 2 && day != null && !day.isEmpty()) { - String orderDay = order.getMakeTime() != null ? sdf.format(new Date(order.getMakeTime() * 1000)) : ""; - if ("today".equals(day) && !orderDay.equals(sdf.format(today))) continue; - if ("tomorrow".equals(day) && !orderDay.equals(sdf.format(tomorrow))) continue; - } - // 统计今日/明日待服务订单数 - if (order.getStatus() != null && order.getStatus() == 2L && order.getMakeTime() != null) { - String orderDay = sdf.format(new Date(order.getMakeTime() * 1000)); - if (orderDay.equals(sdf.format(today))) todayCount++; - if (orderDay.equals(sdf.format(tomorrow))) tomorrowCount++; - } - Map map = new HashMap<>(); - map.put("id", order.getId()); - map.put("type", order.getType()); - map.put("main_order_id", order.getMainOrderId()); - map.put("order_id", order.getOrderId()); - map.put("transaction_id", order.getTransactionId()); - map.put("create_type", order.getCreateType()); - map.put("create_phone", order.getCreatePhone()); - map.put("uid", order.getUid()); - map.put("product_id", order.getProductId()); - map.put("name", order.getName()); - map.put("phone", order.getPhone()); - // make_time格式化 - if (order.getMakeTime() != null && order.getMakeHour() != null) { - map.put("make_time", sdf.format(new Date(order.getMakeTime() * 1000)) + " " + order.getMakeHour()); - } else { - map.put("make_time", null); - } - map.put("make_hour", order.getMakeHour()); - map.put("num", order.getNum()); - map.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); - map.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); - map.put("service_price", order.getServicePrice()); - map.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); - map.put("coupon_id", order.getCouponId()); - map.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); - map.put("pay_time", order.getPayTime()); - map.put("status", order.getStatus()); - map.put("is_pause", order.getIsPause()); - map.put("mark", order.getMark()); - map.put("address_id", order.getAddressId()); - map.put("sku", order.getSku()); - map.put("worker_id", order.getWorkerId()); - map.put("first_worker_id", order.getFirstWorkerId()); - map.put("receive_time", order.getReceiveTime()); - map.put("is_comment", order.getIsComment()); - map.put("receive_type", order.getReceiveType()); - map.put("is_accept", order.getIsAccept()); - map.put("middle_phone", order.getMiddlePhone()); - map.put("user_phone", order.getUserPhone()); - map.put("worker_phone", order.getWorkerPhone()); - map.put("address_en", order.getAddressEn()); - map.put("uid_admin", order.getUidAdmin()); - map.put("address_admin", order.getAddressAdmin()); - map.put("log_status", order.getLogStatus()); - map.put("log_json", order.getLogJson()); - map.put("json_status", order.getJsonStatus()); - map.put("log_images", order.getLogImages()); - map.put("created_at", order.getCreatedAt() != null ? sdfFull.format(order.getCreatedAt()) : null); - map.put("updated_at", order.getUpdatedAt() != null ? sdfFull.format(order.getUpdatedAt()) : null); - map.put("deleted_at", order.getDeletedAt()); - //map.put("log_type", 1.1); - // 兼容log_type - - // address/address_has - UserAddress address = null; - if (order.getAddressId() != null) { - address = userAddressService.selectUserAddressById(order.getAddressId()); - } - map.put("address", address); - map.put("address_has", address); - // product - ServiceGoods product = null; - if (order.getProductId() != null) { - product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - } - if (product != null) { - Map productMap = new HashMap<>(); - productMap.put("id", product.getId()); - productMap.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); - productMap.put("title", product.getTitle()); - productMap.put("price", product.getPrice() != null ? product.getPrice().toString() : "0.00"); - productMap.put("sku_type", product.getSkuType()); - productMap.put("price_zn", product.getPriceZn()); - map.put("product", productMap); - } else { - map.put("product", null); - } - resultList.add(map); - } - PageInfo pageInfo = new PageInfo<>(orderList); - Map dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, "/api/worker/order/lst"); - // 外层data结构 - Map outerData = new HashMap<>(); - outerData.put("data", dataPage); - Map totalMap = new HashMap<>(); - totalMap.put("today", todayCount); - totalMap.put("tomorrow", tomorrowCount); - outerData.put("total", totalMap); - return AjaxResult.success(outerData); - } catch (Exception e) { - return AppletControllerUtil.appletError("查询师傅订单列表失败:" + e.getMessage()); - } - } - - /** - * 获取师傅工作台统计数据 - * 返回格式见json.txt - */ - @GetMapping("/api/worker/stat") - public AjaxResult getWorkerStat(HttpServletRequest request) { - try { - // 1. 校验token并获取用户 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - // 2. 查询config_one配置 - SiteConfig configQuery = new SiteConfig(); - configQuery.setName("config_one"); - List configList = siteConfigService.selectSiteConfigList(configQuery); - Object configObj = null; - if (configList != null && !configList.isEmpty()) { - String configValue = configList.get(0).getValue(); - if (configValue != null && !configValue.trim().isEmpty()) { - configObj = JSONObject.parse(configValue); - } - } - // 3. 判断今日是否签到 - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - String todayStr = sdf.format(new Date()); - WorkerSign signQuery = new WorkerSign(); - signQuery.setUid(String.valueOf(user.getId())); - signQuery.setTime(sdf.parse(todayStr)); - boolean signed = false; - List signList = workerSignService.selectWorkerSignList(signQuery); - if (signList != null && !signList.isEmpty()) { - signed = true; - } - // 4. 构建user数据 - Map userMap = buildUserInfoResponse(user); - // 5. 构建返回结构 - Map data = new HashMap<>(); - data.put("day_count", 0); - data.put("mouth_count", 0); - data.put("income", 0); - data.put("user", userMap); - data.put("sign", signed); - data.put("config", configObj); - Map result = new HashMap<>(); - result.put("code", 200); - result.put("msg", "OK"); - result.put("data", data); - return AjaxResult.success(result); - } catch (Exception e) { - return AppletControllerUtil.appletError("获取师傅统计数据失败:" + e.getMessage()); - } - } - - /** - * 师傅端订单详情接口 - * 返回结构见json.txt - */ - @GetMapping("/api/worker/order/info/{id}") - public AjaxResult getWorkerOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { - try { - // 4. 处理时间字段 - java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - // 1. 校验token并获取师傅信息 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users worker = (Users) userValidation.get("user"); - if (worker == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - // 2. 查询订单 - Order order = orderService.selectOrderById(id); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - // 3. 查询用户信息 - Users user = usersService.selectUsersById(order.getUid()); - // 4. 查询地址信息 - UserAddress address = null; - if (order.getAddressId() != null) { - address = userAddressService.selectUserAddressById(order.getAddressId()); - } - // 5. 查询商品信息 - ServiceGoods product = null; - if (order.getProductId() != null) { - product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - } - // 6. 查询订单日志 - OrderLog logQuery = new OrderLog(); - logQuery.setOid(order.getId()); - List logList = orderLogService.selectOrderLogList(logQuery); - List> logArr = new ArrayList<>(); - for (OrderLog log : logList) { - Map logMap = new HashMap<>(); - logMap.put("id", log.getId()); - logMap.put("oid", log.getOid()); - logMap.put("order_id", log.getOrderId()); - logMap.put("log_order_id", log.getLogOrderId()); - logMap.put("title", log.getTitle()); - logMap.put("type", log.getType()); - // content字段为json字符串,需转为对象 - Object contentObj = null; + map.put("avatar", avatar); + map.put("phone", user.getPhone()); + map.put("service_city_ids", user.getServiceCityIds()); + map.put("skill_ids", user.getSkillIds()); + // city名称数组 + List cityNames = new ArrayList<>(); + List cityIds = AppletControllerUtil.parseStringToList(user.getServiceCityIds()); + for (String cityIdStr : cityIds) { try { - if (log.getContent() != null) { - contentObj = JSONObject.parse(log.getContent()); + if (cityIdStr != null && !cityIdStr.trim().isEmpty()) { + Integer cityId = Integer.valueOf(cityIdStr); + DiyCity city = diyCityService.selectDiyCityById(cityId); + if (city != null && city.getTitle() != null) { + cityNames.add(city.getTitle()); + } } - } catch (Exception e) { - - if (AppletControllerUtil.canParseToJSONArray(log.getContent())) { - contentObj = JSONArray.parseArray(log.getContent()); - } else { - contentObj = log.getContent(); - } - + } catch (Exception ignore) { } - logMap.put("content", contentObj); - logMap.put("deposit", log.getDeposit()); - logMap.put("dep_paid", log.getDepPaid()); - logMap.put("dep_pay_time", log.getDepPayTime()); - logMap.put("dep_log_id", log.getDepLogId()); - logMap.put("price", log.getPrice()); - logMap.put("paid", log.getPaid()); - logMap.put("pay_time", log.getPayTime()); - logMap.put("log_id", log.getLogId()); - logMap.put("worker_id", log.getWorkerId()); - logMap.put("first_worker_id", log.getFirstWorkerId()); - logMap.put("give_up", log.getGiveUp()); - logMap.put("worker_cost", log.getWorkerCost()); - logMap.put("reduction_price", log.getReductionPrice()); - logMap.put("is_pause", log.getIsPause()); - logMap.put("coupon_id", log.getCouponId()); - logMap.put("deduction", log.getDeduction()); - logMap.put("worker_log_id", log.getWorkerLogId()); - logMap.put("created_at", log.getCreatedAt() != null ? dateFormat.format(log.getCreatedAt()) : null); - logMap.put("updated_at", log.getUpdatedAt() != null ? dateFormat.format(log.getUpdatedAt()) : null); - logMap.put("deleted_at", log.getDeletedAt()); - logArr.add(logMap); } - // 7. 构建返回数据 - Map data = new HashMap<>(); - data.put("id", order.getId()); - data.put("type", order.getType()); - data.put("main_order_id", order.getMainOrderId()); - data.put("order_id", order.getOrderId()); - data.put("transaction_id", order.getTransactionId()); - data.put("create_type", order.getCreateType()); - data.put("create_phone", order.getCreatePhone()); - data.put("uid", order.getUid()); - data.put("product_id", order.getProductId()); - data.put("name", order.getName()); - data.put("phone", order.getPhone()); - data.put("address", address); - data.put("make_time", AppletControllerUtil.timeStamp2Date(order)); - data.put("make_hour", order.getMakeHour()); - data.put("num", order.getNum()); - data.put("total_price", order.getTotalPrice()); - data.put("good_price", order.getGoodPrice()); - data.put("service_price", order.getServicePrice()); - data.put("pay_price", order.getPayPrice()); - data.put("coupon_id", order.getCouponId()); - data.put("deduction", order.getDeduction()); - data.put("pay_time", order.getPayTime()); - data.put("status", order.getStatus()); - data.put("is_pause", order.getIsPause()); - data.put("mark", order.getMark()); - data.put("address_id", order.getAddressId()); - data.put("sku", order.getSku()); - data.put("worker_id", order.getWorkerId()); - data.put("first_worker_id", order.getFirstWorkerId()); - data.put("receive_time",order.getReceiveTime() != null ? dateFormat.format(order.getReceiveTime()) : null); - data.put("is_comment", order.getIsComment()); - data.put("receive_type", order.getReceiveType()); - data.put("is_accept", order.getIsAccept()); - data.put("middle_phone", order.getMiddlePhone()); - data.put("user_phone", order.getUserPhone()); - data.put("worker_phone", order.getWorkerPhone()); - data.put("address_en", order.getAddressEn()); - data.put("uid_admin", order.getUidAdmin()); - data.put("address_admin", order.getAddressAdmin()); - data.put("log_status", order.getLogStatus()); - data.put("log_json", order.getLogJson()); - data.put("json_status", order.getJsonStatus()); - data.put("log_images", order.getLogImages()); - data.put("created_at",order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); - data.put("updated_at",order.getUpdatedAt() != null ? dateFormat.format(order.getUpdatedAt()) : null); - data.put("deleted_at",order.getDeletedAt() != null ? dateFormat.format(order.getDeletedAt()) : null); - data.put("phone_xx", order.getPhone()); // 可脱敏处理 - data.put("user", user); - data.put("product", product); - data.put("log", logArr); - return AjaxResult.success(data); - } catch (Exception e) { - return AppletControllerUtil.appletError("查询师傅订单详情失败:" + e.getMessage()); + map.put("city", cityNames); + // skill名称数组 + List skillNames = new ArrayList<>(); + List skillIds = AppletControllerUtil.parseStringToList(user.getSkillIds()); + for (String skillIdStr : skillIds) { + try { + if (skillIdStr != null && !skillIdStr.trim().isEmpty()) { + Long skillId = Long.valueOf(skillIdStr); + SiteSkill skill = siteSkillService.selectSiteSkillById(skillId); + if (skill != null && skill.getTitle() != null) { + skillNames.add(skill.getTitle()); + } + } + } catch (Exception ignore) { + } + } + map.put("skill", skillNames); + resultList.add(map); } + // 构建分页数据 + Map data = new HashMap<>(); + data.put("current_page", pageInfo.getPageNum()); + data.put("data", resultList); + data.put("first_page_url", "https://www.huafurenjia.cn/api/worker/user/lst?page=1"); + data.put("from", pageInfo.getStartRow()); + data.put("last_page", pageInfo.getPages()); + data.put("last_page_url", "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPages()); + // 构建links + List> links = new ArrayList<>(); + Map prevLink = new HashMap<>(); + prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null); + prevLink.put("label", "« Previous"); + prevLink.put("active", false); + links.add(prevLink); + for (int i = 1; i <= pageInfo.getPages(); i++) { + Map link = new HashMap<>(); + link.put("url", "https://www.huafurenjia.cn/api/worker/user/lst?page=" + i); + link.put("label", String.valueOf(i)); + link.put("active", i == pageInfo.getPageNum()); + links.add(link); + } + Map nextLink = new HashMap<>(); + nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null); + nextLink.put("label", "Next »"); + nextLink.put("active", false); + links.add(nextLink); + data.put("links", links); + data.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null); + data.put("path", "https://www.huafurenjia.cn/api/worker/user/lst"); + data.put("per_page", pageInfo.getPageSize()); + data.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null); + data.put("to", pageInfo.getEndRow()); + data.put("total", pageInfo.getTotal()); + return AjaxResult.success(data); + } catch (Exception e) { + return AjaxResult.error("查询师傅列表失败:" + e.getMessage()); } +} - - - - - /** - * 支付尾款回调到页面的数据 - * 返回结构见json.txt - */ - @PostMapping("/api/service/order/pay/total/price/info") - public AjaxResult getOrderPayLastInfo(@RequestBody Map params) { - try { - String orderId = (String) params.get("order_id"); - if (StringUtils.isEmpty(orderId)) { - return error("订单号不能为空"); - } - - // 1. 查询订单 - Order order = orderService.selectOrderByOrderId(orderId); - if (order == null) { - return error("订单不存在"); - } - - // 2. 查询订单日志(取type=5评估报价,或最新一条) - List logList = orderLogService.selectOrderLogByOrderId(orderId); - OrderLog log = null; +/** + * 师傅转单接口 + * + * @param orderId 订单ID + * @param newWorkerId 新师傅ID + * @return 操作结果 + */ +@GetMapping("/api/worker/change/order/{orderId}") +public AjaxResult changeWorkerOrder(@PathVariable("orderId") Long orderId, @RequestParam("id") Long newWorkerId) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + // 1. 查询订单 + Order order = orderService.selectOrderById(orderId); + if (order == null) { + return AjaxResult.error("订单不存在"); + } + // 2. 查询新师傅信息 + Users newWorker = usersService.selectUsersById(newWorkerId); + if (newWorker == null) { + return AjaxResult.error("新师傅不存在"); + } + // 3. 查询原师傅信息 + Users oldWorker = null; + if (order.getWorkerId() != null) { + oldWorker = usersService.selectUsersById(order.getWorkerId()); + } + // 4. 修改订单的师傅id + order.setWorkerId(newWorkerId); + int updateOrder = orderService.updateOrder(order); + if (updateOrder <= 0) { + return AjaxResult.error("订单更新失败"); + } + //查询最新的订单日志 + OrderLog log = orderLogService.selectDataTheFirstNew(order.getId()); + OrderLog log1 = new OrderLog(); + log1.setOid(order.getId()); + //原订单日志下所有师傅id需更换为新的师傅id + List logList = orderLogService.selectOrderLogList(log1); + if (!logList.isEmpty()) { for (OrderLog l : logList) { - if (l.getType() != null && l.getType().intValue() == 5) { - log = l; - break; + if (l.getWorkerId() != null) { + l.setWorkerId(newWorkerId); + orderLogService.updateOrderLog(l); } } - if (log == null && !logList.isEmpty()) { - log = logList.get(0); - } - if (log == null) { - return error("未找到订单日志"); - } - - // 3. 组装content字段 - JSONObject contentJson; - try { - contentJson = JSONObject.parseObject(log.getContent()); - } catch (Exception e) { - contentJson = new JSONObject(); - } - - // 4. 组装返回数据 - Map data = new HashMap<>(); - data.put("id", log.getId()); - data.put("oid", log.getOid()); - data.put("order_id", log.getOrderId()); - data.put("log_order_id", log.getLogOrderId()); - data.put("title", log.getTitle()); - data.put("type", log.getType() != null ? log.getType().intValue() : null); - data.put("content", contentJson); - data.put("deposit", log.getDeposit() != null ? log.getDeposit().toString() : "0.00"); - data.put("dep_paid", log.getDepPaid()); - data.put("dep_pay_time", log.getDepPayTime()); - data.put("dep_log_id", log.getDepLogId()); - data.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); - data.put("paid", log.getPaid()); - data.put("pay_time", log.getPayTime() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(log.getPayTime() * 1000)) : null); - data.put("log_id", log.getLogId()); - data.put("worker_id", log.getWorkerId()); - data.put("first_worker_id", log.getFirstWorkerId()); - data.put("give_up", log.getGiveUp()); - data.put("worker_cost", log.getWorkerCost()); - data.put("reduction_price", log.getReductionPrice() != null ? log.getReductionPrice().toString() : "0.00"); - data.put("is_pause", log.getIsPause()); - data.put("coupon_id", log.getCouponId()); - data.put("deduction", log.getDeduction()); - data.put("worker_log_id", log.getWorkerLogId()); - data.put("created_at", log.getCreatedAt() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getCreatedAt()) : null); - data.put("updated_at", log.getUpdatedAt() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getUpdatedAt()) : null); - data.put("deleted_at", log.getDeletedAt()); - - return success(data); - } catch (Exception e) { - return error("查询失败:" + e.getMessage()); } - } + //如果订单状态为6就继续做 + if (log.getType().compareTo(new BigDecimal("6.0")) == 0) { + // 2. 组装日志内容为数组格式 + Map logItem = new LinkedHashMap<>(); - - /** - * 师傅列表接口 - * 返回结构见json.txt - */ - @PostMapping("/api/worker/user/lst") - public AjaxResult getWorkerUserList(@RequestBody Map params) { - try { - int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; - int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; - String keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : null; - // 查询type=2的师傅 - Users query = new Users(); - query.setType("2"); - if (keywords != null && !keywords.isEmpty()) { - query.setName(keywords); + JSONArray jsonArray = JSONArray.parseArray(log.getContent()); + logItem.put("name", "师傅" + newWorker.getName() + "将继续为您服务 不需要预约时间"); + logItem.put("name", "暂停服务"); + logItem.put("image", ""); + logItem.put("reson", "由于订单师傅更换,自动暂停服务"); + logItem.put("next_time", ""); + logItem.put("type", 2); + logItem.put("date", sdf.format(new Date())); + jsonArray.add(logItem); + if (log != null) { + log.setIsPause(2); + log.setContent(jsonArray.toJSONString()); + orderLogService.updateOrderLog(log); + order.setIsPause(2); + order.setWorkerId(newWorkerId); + orderService.updateOrder(order); } - PageHelper.startPage(page, limit); - List userList = usersService.selectUsersList(query); - PageInfo pageInfo = new PageInfo<>(userList); - List> resultList = new ArrayList<>(); - for (Users user : userList) { - Map map = new HashMap<>(); - map.put("id", user.getId()); - map.put("name", user.getName()); - // 头像处理 - String avatar = user.getAvatar(); + + } else { + // 5. 插入转单日志 + OrderLog newlog = new OrderLog(); + if (log.getType().compareTo(new BigDecimal("5.0")) == 0) { + newlog.setType(new BigDecimal(6.0)); + } else { + newlog.setType(new BigDecimal(1.1)); + } + JSONObject jsonObjectnew = new JSONObject(); + jsonObjectnew.put("name", "师傅" + newWorker.getName() + "将继续为您服务 不需要预约时间"); + jsonObjectnew.put("convert", oldWorker.getName() + "将订单转给" + newWorker.getName()); + newlog.setContent(jsonObjectnew.toJSONString()); + newlog.setOid(order.getId()); + newlog.setOrderId(order.getOrderId()); + newlog.setWorkerId(newWorkerId); + newlog.setWorkerLogId(newWorkerId); + newlog.setIsPause(2); + orderLogService.insertOrderLog(newlog); + //需要解绑原订单上原师傅和客户的虚拟号 + VoiceResponseResult resultObj = YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone()); + if (resultObj.getResult().equals("000000")) { + order.setWorkerPhone(null); + order.setUserPhone(null); + order.setMiddlePhone(null); + orderService.updateOrder(order); + } + //给新师傅进行电话通知 + YunXinPhoneUtilAPI.httpsAxbTransfer(newWorker.getPhone()); + } + return AjaxResult.success("转单成功"); + } catch (Exception e) { + return AjaxResult.error("转单失败:" + e.getMessage()); + } +} + +/** + * 师傅首页接口 + * 返回结构见json.txt + */ +@PostMapping("/api/worker/index") +public AjaxResult getWorkerIndex(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 校验token并获取师傅信息 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + // 2. 查询等级信息 + Object levelInfo = null; + String levelImg = null; + if (user.getLevel() != null) { + WorkerLevel level = workerLevelService.selectWorkerLevelById(Long.valueOf(user.getLevel())); + if (level != null) { + Map levelMap = new HashMap<>(); + levelMap.put("id", level.getId()); + levelMap.put("image", level.getImage()); + levelImg = level.getImage(); + levelMap.put("title", level.getTitle()); + levelInfo = levelMap; + } + } + // 3. 查询技能数组 + List> skillArr = new ArrayList<>(); + List skillIds = AppletControllerUtil.parseStringToList(user.getSkillIds()); + for (String skillIdStr : skillIds) { + try { + if (skillIdStr != null && !skillIdStr.trim().isEmpty()) { + Long skillId = Long.valueOf(skillIdStr); + SiteSkill skill = siteSkillService.selectSiteSkillById(skillId); + if (skill != null) { + Map skillMap = new HashMap<>(); + skillMap.put("id", skill.getId()); + skillMap.put("title", skill.getTitle()); + skillArr.add(skillMap); + } + } + } catch (Exception ignore) { + } + } + // 4. 查询服务城市数组 + List> cityArr = new ArrayList<>(); + List cityIds = AppletControllerUtil.parseStringToList(user.getServiceCityIds()); + for (String cityIdStr : cityIds) { + try { + if (cityIdStr != null && !cityIdStr.trim().isEmpty()) { + Integer cityId = Integer.valueOf(cityIdStr); + DiyCity city = diyCityService.selectDiyCityById(cityId); + if (city != null) { + Map cityMap = new HashMap<>(); + cityMap.put("id", city.getId()); + cityMap.put("title", city.getTitle()); + cityArr.add(cityMap); + } + } + } catch (Exception ignore) { + } + } + // 5. 统计评价 + OrderComment commentQuery = new OrderComment(); + commentQuery.setWorkerId(user.getId()); + List commentList = orderCommentService.selectOrderCommentList(commentQuery); + int one = 0, two = 0, three = 0; + for (OrderComment c : commentList) { + if (c.getNumType() != null) { + if (c.getNumType() == 1L) one++; + else if (c.getNumType() == 2L) two++; + else if (c.getNumType() == 3L) three++; + } + } + int total = commentList.size(); + Map commentStat = new HashMap<>(); + commentStat.put("one", one); + commentStat.put("two", two); + commentStat.put("three", three); + commentStat.put("total", total); + // 6. 构建user数据 + Map userMap = buildUserInfoResponse(user); + userMap.put("level_info", levelInfo); + userMap.put("skill_arr", skillArr); + userMap.put("service_city_arr", cityArr); + userMap.put("level_img", levelImg); + // 7. 处理分页和type筛选,默认参数 + int page = 1; + int limit = 15; + int type = 0; + List filteredList = new ArrayList<>(); + if (params != null) { + params = new HashMap<>(); + page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; + limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; + type = params.get("type") != null ? Integer.parseInt(params.get("type").toString()) : 0; + // 过滤type + for (OrderComment c : commentList) { + if (type == 0 || (type == 1 && c.getNumType() != null && c.getNumType() == 1L) + || (type == 2 && c.getNumType() != null && c.getNumType() == 2L) + || (type == 3 && c.getNumType() != null && c.getNumType() == 3L)) { + filteredList.add(c); + } + } + } else { + filteredList.addAll(commentList); + } + int totalCount = filteredList.size(); + int from = (page - 1) * limit; + int to = Math.min(from + limit, totalCount); + List> commentArr = new ArrayList<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日"); + for (int i = from; i < to; i++) { + OrderComment c = filteredList.get(i); + Map cMap = new HashMap<>(); + cMap.put("id", c.getId()); + cMap.put("uid", c.getUid()); + cMap.put("images", c.getImages()); + cMap.put("content", c.getContent()); + cMap.put("num", c.getNum()); + cMap.put("created_at", c.getCreatedAt() != null ? sdf.format(c.getCreatedAt()) : null); + cMap.put("time", c.getCreatedAt() != null ? sdf2.format(c.getCreatedAt()) : null); + // 查询用户信息 + Map uMap = new HashMap<>(); + Users u = usersService.selectUsersById(c.getUid()); + if (u != null) { + uMap.put("id", u.getId()); + uMap.put("name", u.getName()); + String avatar = u.getAvatar(); if (avatar != null && !avatar.isEmpty()) { if (!avatar.startsWith("http")) { avatar = "https://img.huafurenjia.cn/" + avatar.replaceFirst("^/+", ""); @@ -5545,729 +5951,405 @@ public class AppletController extends BaseController { } else { avatar = "https://img.huafurenjia.cn//default/user_avatar.jpeg"; } - map.put("avatar", avatar); - map.put("phone", user.getPhone()); - map.put("service_city_ids", user.getServiceCityIds()); - map.put("skill_ids", user.getSkillIds()); - // city名称数组 - List cityNames = new ArrayList<>(); - List cityIds = AppletControllerUtil.parseStringToList(user.getServiceCityIds()); - for (String cityIdStr : cityIds) { - try { - if (cityIdStr != null && !cityIdStr.trim().isEmpty()) { - Integer cityId = Integer.valueOf(cityIdStr); - DiyCity city = diyCityService.selectDiyCityById(cityId); - if (city != null && city.getTitle() != null) { - cityNames.add(city.getTitle()); - } - } - } catch (Exception ignore) { - } - } - map.put("city", cityNames); - // skill名称数组 - List skillNames = new ArrayList<>(); - List skillIds = AppletControllerUtil.parseStringToList(user.getSkillIds()); - for (String skillIdStr : skillIds) { - try { - if (skillIdStr != null && !skillIdStr.trim().isEmpty()) { - Long skillId = Long.valueOf(skillIdStr); - SiteSkill skill = siteSkillService.selectSiteSkillById(skillId); - if (skill != null && skill.getTitle() != null) { - skillNames.add(skill.getTitle()); - } - } - } catch (Exception ignore) { - } - } - map.put("skill", skillNames); - resultList.add(map); + uMap.put("avatar", avatar); } - // 构建分页数据 - Map data = new HashMap<>(); - data.put("current_page", pageInfo.getPageNum()); - data.put("data", resultList); - data.put("first_page_url", "https://www.huafurenjia.cn/api/worker/user/lst?page=1"); - data.put("from", pageInfo.getStartRow()); - data.put("last_page", pageInfo.getPages()); - data.put("last_page_url", "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPages()); - // 构建links - List> links = new ArrayList<>(); - Map prevLink = new HashMap<>(); - prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null); - prevLink.put("label", "« Previous"); - prevLink.put("active", false); - links.add(prevLink); - for (int i = 1; i <= pageInfo.getPages(); i++) { - Map link = new HashMap<>(); - link.put("url", "https://www.huafurenjia.cn/api/worker/user/lst?page=" + i); - link.put("label", String.valueOf(i)); - link.put("active", i == pageInfo.getPageNum()); - links.add(link); - } - Map nextLink = new HashMap<>(); - nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null); - nextLink.put("label", "Next »"); - nextLink.put("active", false); - links.add(nextLink); - data.put("links", links); - data.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null); - data.put("path", "https://www.huafurenjia.cn/api/worker/user/lst"); - data.put("per_page", pageInfo.getPageSize()); - data.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null); - data.put("to", pageInfo.getEndRow()); - data.put("total", pageInfo.getTotal()); - return AjaxResult.success(data); - } catch (Exception e) { - return AjaxResult.error("查询师傅列表失败:" + e.getMessage()); + cMap.put("user", uMap); + commentArr.add(cMap); } - } - - /** - * 师傅转单接口 - * - * @param orderId 订单ID - * @param newWorkerId 新师傅ID - * @return 操作结果 - */ - @GetMapping("/api/worker/change/order/{orderId}") - public AjaxResult changeWorkerOrder(@PathVariable("orderId") Long orderId, @RequestParam("id") Long newWorkerId) { - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - // 1. 查询订单 - Order order = orderService.selectOrderById(orderId); - if (order == null) { - return AjaxResult.error("订单不存在"); - } - // 2. 查询新师傅信息 - Users newWorker = usersService.selectUsersById(newWorkerId); - if (newWorker == null) { - return AjaxResult.error("新师傅不存在"); - } - // 3. 查询原师傅信息 - Users oldWorker = null; - if (order.getWorkerId() != null) { - oldWorker = usersService.selectUsersById(order.getWorkerId()); - } - // 4. 修改订单的师傅id - order.setWorkerId(newWorkerId); - int updateOrder = orderService.updateOrder(order); - if (updateOrder <= 0) { - return AjaxResult.error("订单更新失败"); - } - //查询最新的订单日志 - OrderLog log = orderLogService.selectDataTheFirstNew(order.getId()); - OrderLog log1=new OrderLog(); - log1.setOid(order.getId()); - //原订单日志下所有师傅id需更换为新的师傅id - List logList = orderLogService.selectOrderLogList(log1); - if (!logList.isEmpty()) { - for (OrderLog l : logList){ - if (l.getWorkerId()!=null){ - l.setWorkerId(newWorkerId); - orderLogService.updateOrderLog(l); - } - } - } - //如果订单状态为6就继续做 - if (log.getType().compareTo(new BigDecimal("6.0"))==0) { - // 2. 组装日志内容为数组格式 - Map logItem = new LinkedHashMap<>(); - - JSONArray jsonArray = JSONArray.parseArray(log.getContent()); - logItem.put("name", "师傅"+newWorker.getName()+"将继续为您服务 不需要预约时间"); - logItem.put("name", "暂停服务"); - logItem.put("image", ""); - logItem.put("reson", "由于订单师傅更换,自动暂停服务"); - logItem.put("next_time", ""); - logItem.put("type", 2); - logItem.put("date", sdf.format(new Date())); - jsonArray.add(logItem); - if (log != null) { - log.setIsPause(2); - log.setContent(jsonArray.toJSONString()); - orderLogService.updateOrderLog(log); - order.setIsPause(2); - order.setWorkerId(newWorkerId); - orderService.updateOrder(order); - } - - }else{ - // 5. 插入转单日志 - OrderLog newlog = new OrderLog(); - if(log.getType().compareTo(new BigDecimal("5.0"))==0){ - newlog.setType(new BigDecimal(6.0)); - }else{ - newlog.setType(new BigDecimal(1.1)); - } - JSONObject jsonObjectnew=new JSONObject(); - jsonObjectnew.put("name", "师傅"+newWorker.getName()+"将继续为您服务 不需要预约时间"); - jsonObjectnew.put("convert", oldWorker.getName()+"将订单转给"+newWorker.getName()); - newlog.setContent(jsonObjectnew.toJSONString()); - newlog.setOid(order.getId()); - newlog.setOrderId(order.getOrderId()); - newlog.setWorkerId(newWorkerId); - newlog.setWorkerLogId(newWorkerId); - newlog.setIsPause(2); - orderLogService.insertOrderLog(newlog); - //需要解绑原订单上原师傅和客户的虚拟号 - VoiceResponseResult resultObj=YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone()); - if (resultObj.getResult().equals("000000")){ - order.setWorkerPhone(null); - order.setUserPhone(null); - order.setMiddlePhone(null); - orderService.updateOrder(order); - } - //给新师傅进行电话通知 - YunXinPhoneUtilAPI.httpsAxbTransfer(newWorker.getPhone()); - } - return AjaxResult.success("转单成功"); - } catch (Exception e) { - return AjaxResult.error("转单失败:" + e.getMessage()); + // 8. 构建分页结构 + Map pageData = new HashMap<>(); + pageData.put("current_page", page); + pageData.put("data", commentArr); + pageData.put("first_page_url", "https://www.huafurenjia.cn/api/worker/index?page=1"); + pageData.put("from", totalCount == 0 ? null : from + 1); + int lastPage = (int) Math.ceil((double) totalCount / limit); + pageData.put("last_page", lastPage); + pageData.put("last_page_url", "https://www.huafurenjia.cn/api/worker/index?page=" + lastPage); + // links + List> links = new ArrayList<>(); + Map prevLink = new HashMap<>(); + prevLink.put("url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null); + prevLink.put("label", "« Previous"); + prevLink.put("active", false); + links.add(prevLink); + for (int i = 1; i <= lastPage; i++) { + Map link = new HashMap<>(); + link.put("url", "https://www.huafurenjia.cn/api/worker/index?page=" + i); + link.put("label", String.valueOf(i)); + link.put("active", i == page); + links.add(link); } + Map nextLink = new HashMap<>(); + nextLink.put("url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null); + nextLink.put("label", "Next »"); + nextLink.put("active", false); + links.add(nextLink); + pageData.put("links", links); + pageData.put("next_page_url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null); + pageData.put("path", "https://www.huafurenjia.cn/api/worker/index"); + pageData.put("per_page", String.valueOf(limit)); + pageData.put("prev_page_url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null); + pageData.put("to", totalCount == 0 ? null : to); + pageData.put("total", totalCount); + // 9. 构建最终返回结构 + Map data = new HashMap<>(); + data.put("user", userMap); + data.put("data", pageData); + data.put("comment", commentStat); + return AjaxResult.success(data); + } catch (Exception e) { + return AppletControllerUtil.appletError("获取师傅首页数据失败:" + e.getMessage()); } +} - /** - * 师傅首页接口 - * 返回结构见json.txt - */ - @PostMapping("/api/worker/index") - public AjaxResult getWorkerIndex(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 校验token并获取师傅信息 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - // 2. 查询等级信息 - Object levelInfo = null; - String levelImg = null; - if (user.getLevel() != null) { - WorkerLevel level = workerLevelService.selectWorkerLevelById(Long.valueOf(user.getLevel())); - if (level != null) { - Map levelMap = new HashMap<>(); - levelMap.put("id", level.getId()); - levelMap.put("image", level.getImage()); - levelImg = level.getImage(); - levelMap.put("title", level.getTitle()); - levelInfo = levelMap; - } - } - // 3. 查询技能数组 - List> skillArr = new ArrayList<>(); - List skillIds = AppletControllerUtil.parseStringToList(user.getSkillIds()); - for (String skillIdStr : skillIds) { - try { - if (skillIdStr != null && !skillIdStr.trim().isEmpty()) { - Long skillId = Long.valueOf(skillIdStr); - SiteSkill skill = siteSkillService.selectSiteSkillById(skillId); - if (skill != null) { - Map skillMap = new HashMap<>(); - skillMap.put("id", skill.getId()); - skillMap.put("title", skill.getTitle()); - skillArr.add(skillMap); - } - } - } catch (Exception ignore) { - } - } - // 4. 查询服务城市数组 - List> cityArr = new ArrayList<>(); - List cityIds = AppletControllerUtil.parseStringToList(user.getServiceCityIds()); - for (String cityIdStr : cityIds) { - try { - if (cityIdStr != null && !cityIdStr.trim().isEmpty()) { - Integer cityId = Integer.valueOf(cityIdStr); - DiyCity city = diyCityService.selectDiyCityById(cityId); - if (city != null) { - Map cityMap = new HashMap<>(); - cityMap.put("id", city.getId()); - cityMap.put("title", city.getTitle()); - cityArr.add(cityMap); - } - } - } catch (Exception ignore) { - } - } - // 5. 统计评价 - OrderComment commentQuery = new OrderComment(); - commentQuery.setWorkerId(user.getId()); - List commentList = orderCommentService.selectOrderCommentList(commentQuery); - int one = 0, two = 0, three = 0; - for (OrderComment c : commentList) { - if (c.getNumType() != null) { - if (c.getNumType() == 1L) one++; - else if (c.getNumType() == 2L) two++; - else if (c.getNumType() == 3L) three++; - } - } - int total = commentList.size(); - Map commentStat = new HashMap<>(); - commentStat.put("one", one); - commentStat.put("two", two); - commentStat.put("three", three); - commentStat.put("total", total); - // 6. 构建user数据 - Map userMap = buildUserInfoResponse(user); - userMap.put("level_info", levelInfo); - userMap.put("skill_arr", skillArr); - userMap.put("service_city_arr", cityArr); - userMap.put("level_img", levelImg); - // 7. 处理分页和type筛选,默认参数 - int page = 1; - int limit = 15; - int type = 0; - List filteredList = new ArrayList<>(); - if (params != null) { - params = new HashMap<>(); - page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; - limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; - type = params.get("type") != null ? Integer.parseInt(params.get("type").toString()) : 0; - // 过滤type - for (OrderComment c : commentList) { - if (type == 0 || (type == 1 && c.getNumType() != null && c.getNumType() == 1L) - || (type == 2 && c.getNumType() != null && c.getNumType() == 2L) - || (type == 3 && c.getNumType() != null && c.getNumType() == 3L)) { - filteredList.add(c); - } - } - }else{ - filteredList.addAll(commentList); - } - int totalCount = filteredList.size(); - int from = (page - 1) * limit; - int to = Math.min(from + limit, totalCount); - List> commentArr = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日"); - for (int i = from; i < to; i++) { - OrderComment c = filteredList.get(i); - Map cMap = new HashMap<>(); - cMap.put("id", c.getId()); - cMap.put("uid", c.getUid()); - cMap.put("images", c.getImages()); - cMap.put("content", c.getContent()); - cMap.put("num", c.getNum()); - cMap.put("created_at", c.getCreatedAt() != null ? sdf.format(c.getCreatedAt()) : null); - cMap.put("time", c.getCreatedAt() != null ? sdf2.format(c.getCreatedAt()) : null); - // 查询用户信息 - Map uMap = new HashMap<>(); - Users u = usersService.selectUsersById(c.getUid()); - if (u != null) { - uMap.put("id", u.getId()); - uMap.put("name", u.getName()); - String avatar = u.getAvatar(); - if (avatar != null && !avatar.isEmpty()) { - if (!avatar.startsWith("http")) { - avatar = "https://img.huafurenjia.cn/" + avatar.replaceFirst("^/+", ""); - } - } else { - avatar = "https://img.huafurenjia.cn//default/user_avatar.jpeg"; - } - uMap.put("avatar", avatar); - } - cMap.put("user", uMap); - commentArr.add(cMap); - } - // 8. 构建分页结构 - Map pageData = new HashMap<>(); - pageData.put("current_page", page); - pageData.put("data", commentArr); - pageData.put("first_page_url", "https://www.huafurenjia.cn/api/worker/index?page=1"); - pageData.put("from", totalCount == 0 ? null : from + 1); - int lastPage = (int) Math.ceil((double) totalCount / limit); - pageData.put("last_page", lastPage); - pageData.put("last_page_url", "https://www.huafurenjia.cn/api/worker/index?page=" + lastPage); - // links - List> links = new ArrayList<>(); - Map prevLink = new HashMap<>(); - prevLink.put("url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null); - prevLink.put("label", "« Previous"); - prevLink.put("active", false); - links.add(prevLink); - for (int i = 1; i <= lastPage; i++) { - Map link = new HashMap<>(); - link.put("url", "https://www.huafurenjia.cn/api/worker/index?page=" + i); - link.put("label", String.valueOf(i)); - link.put("active", i == page); - links.add(link); - } - Map nextLink = new HashMap<>(); - nextLink.put("url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null); - nextLink.put("label", "Next »"); - nextLink.put("active", false); - links.add(nextLink); - pageData.put("links", links); - pageData.put("next_page_url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null); - pageData.put("path", "https://www.huafurenjia.cn/api/worker/index"); - pageData.put("per_page", String.valueOf(limit)); - pageData.put("prev_page_url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null); - pageData.put("to", totalCount == 0 ? null : to); - pageData.put("total", totalCount); - // 9. 构建最终返回结构 - Map data = new HashMap<>(); - data.put("user", userMap); - data.put("data", pageData); - data.put("comment", commentStat); - return AjaxResult.success(data); - } catch (Exception e) { - return AppletControllerUtil.appletError("获取师傅首页数据失败:" + e.getMessage()); +/** + * 师傅签到日志接口 + * + * @param params {year: "2025", month: "06"} + * @param request + * @return 签到日志列表 + */ +@PostMapping("/api/worker/sign/log") +public AjaxResult getWorkerSignLog(@RequestBody Map params, HttpServletRequest request) { + try { + // 校验token并获取用户 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); } - } - - /** - * 师傅签到日志接口 - * - * @param params {year: "2025", month: "06"} - * @param request - * @return 签到日志列表 - */ - @PostMapping("/api/worker/sign/log") - public AjaxResult getWorkerSignLog(@RequestBody Map params, HttpServletRequest request) { - try { - // 校验token并获取用户 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - if (params == null || !params.containsKey("year") || !params.containsKey("month")) { - return AppletControllerUtil.appletWarning("参数year和month不能为空"); - } - String year = params.get("year").toString(); - String month = params.get("month").toString(); - // 构造当月起止日期 - String startDate = year + "-" + month + "-01"; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Date start = sdf.parse(startDate); - Calendar cal = Calendar.getInstance(); - cal.setTime(start); - cal.set(Calendar.DAY_OF_MONTH, 1); - int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); - cal.set(Calendar.DAY_OF_MONTH, maxDay); - Date end = cal.getTime(); - // 查询签到记录 - WorkerSign query = new WorkerSign(); - query.setUid(String.valueOf(user.getId())); - List allList = workerSignService.selectWorkerSignList(query); - List> result = new ArrayList<>(); - for (WorkerSign sign : allList) { - if (sign.getTime() != null && !sign.getTime().before(start) && !sign.getTime().after(end)) { - Map map = new HashMap<>(); - map.put("id", sign.getId()); - map.put("date", sdf.format(sign.getTime())); - map.put("info", sign.getUname()); - result.add(map); - } - } - return AjaxResult.success(result); - } catch (Exception e) { - return AjaxResult.error("查询签到日志失败:" + e.getMessage()); + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); } - } - - /** - * 师傅质保金日志接口 - * - * @param params {"limit":15,"page":1} - * @param request - * @return 质保金日志分页数据和师傅信息 - */ - @PostMapping("/api/worker/mergin/log") - public AjaxResult getWorkerMarginLog(@RequestBody Map params, HttpServletRequest request) { - try { - // 校验token并获取用户 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; - int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; - // 查询质保金日志 - WorkerMarginLog query = new WorkerMarginLog(); - query.setUid(user.getId()); - PageHelper.startPage(page, limit); - List logList = workerMarginLogService.selectWorkerMarginLogList(query); - PageInfo pageInfo = new PageInfo<>(logList); - List> resultList = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - for (WorkerMarginLog log : logList) { + if (params == null || !params.containsKey("year") || !params.containsKey("month")) { + return AppletControllerUtil.appletWarning("参数year和month不能为空"); + } + String year = params.get("year").toString(); + String month = params.get("month").toString(); + // 构造当月起止日期 + String startDate = year + "-" + month + "-01"; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date start = sdf.parse(startDate); + Calendar cal = Calendar.getInstance(); + cal.setTime(start); + cal.set(Calendar.DAY_OF_MONTH, 1); + int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); + cal.set(Calendar.DAY_OF_MONTH, maxDay); + Date end = cal.getTime(); + // 查询签到记录 + WorkerSign query = new WorkerSign(); + query.setUid(String.valueOf(user.getId())); + List allList = workerSignService.selectWorkerSignList(query); + List> result = new ArrayList<>(); + for (WorkerSign sign : allList) { + if (sign.getTime() != null && !sign.getTime().before(start) && !sign.getTime().after(end)) { Map map = new HashMap<>(); - map.put("id", log.getId()); - map.put("uid", log.getUid()); - map.put("oid", log.getOid()); - map.put("order_id", log.getOrderId()); - map.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); - map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); - map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); - resultList.add(map); + map.put("id", sign.getId()); + map.put("date", sdf.format(sign.getTime())); + map.put("info", sign.getUname()); + result.add(map); } - // 构建分页结构 - Map dataPage = new HashMap<>(); - dataPage.put("current_page", pageInfo.getPageNum()); - dataPage.put("data", resultList); - dataPage.put("first_page_url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=1"); - dataPage.put("from", pageInfo.getStartRow()); - dataPage.put("last_page", pageInfo.getPages()); - dataPage.put("last_page_url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPages()); - // links - List> links = new ArrayList<>(); - Map prevLink = new HashMap<>(); - prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null); - prevLink.put("label", "« Previous"); - prevLink.put("active", false); - links.add(prevLink); - for (int i = 1; i <= pageInfo.getPages(); i++) { - Map link = new HashMap<>(); - link.put("url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + i); - link.put("label", String.valueOf(i)); - link.put("active", i == pageInfo.getPageNum()); - links.add(link); - } - Map nextLink = new HashMap<>(); - nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null); - nextLink.put("label", "Next »"); - nextLink.put("active", false); - links.add(nextLink); - dataPage.put("links", links); - dataPage.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null); - dataPage.put("path", "https://www.huafurenjia.cn/api/worker/mergin/log"); - dataPage.put("per_page", limit); - dataPage.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null); - dataPage.put("to", pageInfo.getEndRow()); - dataPage.put("total", pageInfo.getTotal()); - // 构建user信息 - Map userMap = buildUserInfoResponse(user); - // 最终返回结构 - Map data = new HashMap<>(); - data.put("data", dataPage); - data.put("user", userMap); - return AjaxResult.success(data); - } catch (Exception e) { - return AjaxResult.error("查询质保金日志失败:" + e.getMessage()); } + return AjaxResult.success(result); + } catch (Exception e) { + return AjaxResult.error("查询签到日志失败:" + e.getMessage()); } +} - /** - * 师傅收益明细接口 - * - * @param params {"limit":15,"page":1,"type":"1"} - * @param request - * @return 收益明细分页数据 - */ - @PostMapping("/api/worker/money/log") - public AjaxResult getWorkerMoneyLog(@RequestBody Map params, HttpServletRequest request) { - try { - // 校验token并获取用户 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; - int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; - String type = params.get("type") != null ? params.get("type").toString() : null; - // 查询收益明细 - WorkerMoneyLog query = new WorkerMoneyLog(); - query.setWorkerId(user.getId()); - if (type != null && !type.isEmpty()) { - query.setType(Integer.valueOf(type)); - } - PageHelper.startPage(page, limit); - List logList = workerMoneyLogService.selectWorkerMoneyLogList(query); - PageInfo pageInfo = new PageInfo<>(logList); - List> resultList = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - for (WorkerMoneyLog log : logList) { - Map map = new HashMap<>(); - map.put("id", log.getId()); - map.put("worker_id", log.getWorkerId()); - map.put("oid", log.getOid()); - map.put("order_id", log.getOrderId()); - map.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); - map.put("type", log.getType()); - map.put("service_price", log.getServicePrice() != null ? log.getServicePrice().toString() : "0.00"); - map.put("reduction_price", log.getReductionPrice() != null ? log.getReductionPrice().toString() : "0.00"); - map.put("cr", log.getCr()); - map.put("mergin", log.getMergin() != null ? log.getMergin().toString() : "0.00"); - map.put("door_price", log.getDoorPrice() != null ? log.getDoorPrice().toString() : null); - map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); - map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); - resultList.add(map); - } - // 构建分页结构 - Map dataPage = new HashMap<>(); - dataPage.put("current_page", pageInfo.getPageNum()); - dataPage.put("data", resultList); - dataPage.put("first_page_url", "https://www.huafurenjia.cn/api/worker/money/log?page=1"); - dataPage.put("from", pageInfo.getStartRow()); - dataPage.put("last_page", pageInfo.getPages()); - dataPage.put("last_page_url", "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPages()); - // links - List> links = new ArrayList<>(); - Map prevLink = new HashMap<>(); - prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null); - prevLink.put("label", "« Previous"); - prevLink.put("active", false); - links.add(prevLink); - for (int i = 1; i <= pageInfo.getPages(); i++) { - Map link = new HashMap<>(); - link.put("url", "https://www.huafurenjia.cn/api/worker/money/log?page=" + i); - link.put("label", String.valueOf(i)); - link.put("active", i == pageInfo.getPageNum()); - links.add(link); - } - Map nextLink = new HashMap<>(); - nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null); - nextLink.put("label", "Next »"); - nextLink.put("active", false); - links.add(nextLink); - dataPage.put("links", links); - dataPage.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null); - dataPage.put("path", "https://www.huafurenjia.cn/api/worker/money/log"); - dataPage.put("per_page", limit); - dataPage.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null); - dataPage.put("to", pageInfo.getEndRow()); - dataPage.put("total", pageInfo.getTotal()); - return AjaxResult.success(dataPage); - } catch (Exception e) { - return AjaxResult.error("查询收益明细失败:" + e.getMessage()); +/** + * 师傅质保金日志接口 + * + * @param params {"limit":15,"page":1} + * @param request + * @return 质保金日志分页数据和师傅信息 + */ +@PostMapping("/api/worker/mergin/log") +public AjaxResult getWorkerMarginLog(@RequestBody Map params, HttpServletRequest request) { + try { + // 校验token并获取用户 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; + int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; + // 查询质保金日志 + WorkerMarginLog query = new WorkerMarginLog(); + query.setUid(user.getId()); + PageHelper.startPage(page, limit); + List logList = workerMarginLogService.selectWorkerMarginLogList(query); + PageInfo pageInfo = new PageInfo<>(logList); + List> resultList = new ArrayList<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + for (WorkerMarginLog log : logList) { + Map map = new HashMap<>(); + map.put("id", log.getId()); + map.put("uid", log.getUid()); + map.put("oid", log.getOid()); + map.put("order_id", log.getOrderId()); + map.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); + map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); + map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); + resultList.add(map); + } + // 构建分页结构 + Map dataPage = new HashMap<>(); + dataPage.put("current_page", pageInfo.getPageNum()); + dataPage.put("data", resultList); + dataPage.put("first_page_url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=1"); + dataPage.put("from", pageInfo.getStartRow()); + dataPage.put("last_page", pageInfo.getPages()); + dataPage.put("last_page_url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPages()); + // links + List> links = new ArrayList<>(); + Map prevLink = new HashMap<>(); + prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null); + prevLink.put("label", "« Previous"); + prevLink.put("active", false); + links.add(prevLink); + for (int i = 1; i <= pageInfo.getPages(); i++) { + Map link = new HashMap<>(); + link.put("url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + i); + link.put("label", String.valueOf(i)); + link.put("active", i == pageInfo.getPageNum()); + links.add(link); + } + Map nextLink = new HashMap<>(); + nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null); + nextLink.put("label", "Next »"); + nextLink.put("active", false); + links.add(nextLink); + dataPage.put("links", links); + dataPage.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null); + dataPage.put("path", "https://www.huafurenjia.cn/api/worker/mergin/log"); + dataPage.put("per_page", limit); + dataPage.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null); + dataPage.put("to", pageInfo.getEndRow()); + dataPage.put("total", pageInfo.getTotal()); + // 构建user信息 + Map userMap = buildUserInfoResponse(user); + // 最终返回结构 + Map data = new HashMap<>(); + data.put("data", dataPage); + data.put("user", userMap); + return AjaxResult.success(data); + } catch (Exception e) { + return AjaxResult.error("查询质保金日志失败:" + e.getMessage()); } +} - /** - * 师傅提现记录接口 - * 查询当前师傅的提现记录,支持分页和类型筛选 - * - * @param params {"limit":15,"page":1,"type":2} - * @param request HttpServletRequest - * @return AjaxResult 分页提现记录 - */ - @PostMapping("/api/worker/withdraw_log") - public AjaxResult getWorkerWithdrawLog(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 校验token并获取用户 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - // 2. 解析分页和筛选参数 - int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; - int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; +/** + * 师傅收益明细接口 + * + * @param params {"limit":15,"page":1,"type":"1"} + * @param request + * @return 收益明细分页数据 + */ +@PostMapping("/api/worker/money/log") +public AjaxResult getWorkerMoneyLog(@RequestBody Map params, HttpServletRequest request) { + try { + // 校验token并获取用户 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; + int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; + String type = params.get("type") != null ? params.get("type").toString() : null; + // 查询收益明细 + WorkerMoneyLog query = new WorkerMoneyLog(); + query.setWorkerId(user.getId()); + if (type != null && !type.isEmpty()) { + query.setType(Integer.valueOf(type)); + } + PageHelper.startPage(page, limit); + List logList = workerMoneyLogService.selectWorkerMoneyLogList(query); + PageInfo pageInfo = new PageInfo<>(logList); + List> resultList = new ArrayList<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + for (WorkerMoneyLog log : logList) { + Map map = new HashMap<>(); + map.put("id", log.getId()); + map.put("worker_id", log.getWorkerId()); + map.put("oid", log.getOid()); + map.put("order_id", log.getOrderId()); + map.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); + map.put("type", log.getType()); + map.put("service_price", log.getServicePrice() != null ? log.getServicePrice().toString() : "0.00"); + map.put("reduction_price", log.getReductionPrice() != null ? log.getReductionPrice().toString() : "0.00"); + map.put("cr", log.getCr()); + map.put("mergin", log.getMergin() != null ? log.getMergin().toString() : "0.00"); + map.put("door_price", log.getDoorPrice() != null ? log.getDoorPrice().toString() : null); + map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); + map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); + resultList.add(map); + } + // 构建分页结构 + Map dataPage = new HashMap<>(); + dataPage.put("current_page", pageInfo.getPageNum()); + dataPage.put("data", resultList); + dataPage.put("first_page_url", "https://www.huafurenjia.cn/api/worker/money/log?page=1"); + dataPage.put("from", pageInfo.getStartRow()); + dataPage.put("last_page", pageInfo.getPages()); + dataPage.put("last_page_url", "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPages()); + // links + List> links = new ArrayList<>(); + Map prevLink = new HashMap<>(); + prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null); + prevLink.put("label", "« Previous"); + prevLink.put("active", false); + links.add(prevLink); + for (int i = 1; i <= pageInfo.getPages(); i++) { + Map link = new HashMap<>(); + link.put("url", "https://www.huafurenjia.cn/api/worker/money/log?page=" + i); + link.put("label", String.valueOf(i)); + link.put("active", i == pageInfo.getPageNum()); + links.add(link); + } + Map nextLink = new HashMap<>(); + nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null); + nextLink.put("label", "Next »"); + nextLink.put("active", false); + links.add(nextLink); + dataPage.put("links", links); + dataPage.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null); + dataPage.put("path", "https://www.huafurenjia.cn/api/worker/money/log"); + dataPage.put("per_page", limit); + dataPage.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null); + dataPage.put("to", pageInfo.getEndRow()); + dataPage.put("total", pageInfo.getTotal()); + return AjaxResult.success(dataPage); + } catch (Exception e) { + return AjaxResult.error("查询收益明细失败:" + e.getMessage()); + } +} + +/** + * 师傅提现记录接口 + * 查询当前师傅的提现记录,支持分页和类型筛选 + * + * @param params {"limit":15,"page":1,"type":2} + * @param request HttpServletRequest + * @return AjaxResult 分页提现记录 + */ +@PostMapping("/api/worker/withdraw_log") +public AjaxResult getWorkerWithdrawLog(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 校验token并获取用户 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + // 2. 解析分页和筛选参数 + int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; + int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; // Long type = null; // if (params.get("type") != null) { // try { type = Long.valueOf(params.get("type").toString()); } catch (Exception ignore) {} // } - // 3. 构建查询条件 - WechatTransfer query = new WechatTransfer(); - query.setUid(user.getId()); - //if (type != null) query.setStatus(type); - PageHelper.startPage(page, limit); - List logList = wechatTransferService.selectWechatTransferList(query); - PageInfo pageInfo = new PageInfo<>(logList); - // 4. 数据组装 - List> resultList = new ArrayList<>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - for (WechatTransfer log : logList) { - Map map = new HashMap<>(); - map.put("id", log.getId()); - map.put("uid", log.getUid()); - map.put("batch_id", log.getBatchId()); - map.put("money", log.getMoney() != null ? log.getMoney().toString() : "0.00"); - map.put("status", log.getStatus()); - map.put("order_id", log.getOrderId()); - map.put("openid", log.getOpenid()); - map.put("paid", log.getPaid()); - map.put("pay_time", log.getPayTime() != null ? sdf.format(log.getPayTime()) : null); - map.put("time", log.getTime()); - map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); - map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); - resultList.add(map); - } - // 5. 构建分页响应结构 - String baseUrl = "https://www.huafurenjia.cn/api/worker/withdraw_log"; - Map dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, baseUrl); - return AjaxResult.success(dataPage); - } catch (Exception e) { - return AppletControllerUtil.appletError("查询提现记录失败:" + e.getMessage()); + // 3. 构建查询条件 + WechatTransfer query = new WechatTransfer(); + query.setUid(user.getId()); + //if (type != null) query.setStatus(type); + PageHelper.startPage(page, limit); + List logList = wechatTransferService.selectWechatTransferList(query); + PageInfo pageInfo = new PageInfo<>(logList); + // 4. 数据组装 + List> resultList = new ArrayList<>(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + for (WechatTransfer log : logList) { + Map map = new HashMap<>(); + map.put("id", log.getId()); + map.put("uid", log.getUid()); + map.put("batch_id", log.getBatchId()); + map.put("money", log.getMoney() != null ? log.getMoney().toString() : "0.00"); + map.put("status", log.getStatus()); + map.put("order_id", log.getOrderId()); + map.put("openid", log.getOpenid()); + map.put("paid", log.getPaid()); + map.put("pay_time", log.getPayTime() != null ? sdf.format(log.getPayTime()) : null); + map.put("time", log.getTime()); + map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); + map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); + resultList.add(map); } + // 5. 构建分页响应结构 + String baseUrl = "https://www.huafurenjia.cn/api/worker/withdraw_log"; + Map dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, baseUrl); + return AjaxResult.success(dataPage); + } catch (Exception e) { + return AppletControllerUtil.appletError("查询提现记录失败:" + e.getMessage()); } +} - /** - * 师傅设置上门费接口 - * 参数:{"id":订单id,"price":金额} - * 逻辑:查找订单最新日志,设置workerCost和price,并设置paid=1 - */ - @PostMapping("/api/worker/set/price") - public AjaxResult setWorkerPrice(@RequestBody Map params,HttpServletRequest request) { - try { - // 1. 校验token并获取用户 - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletUnauthorized(); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } +/** + * 师傅设置上门费接口 + * 参数:{"id":订单id,"price":金额} + * 逻辑:查找订单最新日志,设置workerCost和price,并设置paid=1 + */ +@PostMapping("/api/worker/set/price") +public AjaxResult setWorkerPrice(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 校验token并获取用户 + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletUnauthorized(); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } - Long orderId = params.get("id") != null ? Long.parseLong(params.get("id").toString()) : null; - String priceStr = params.get("price") != null ? params.get("price").toString() : null; - if (orderId == null || StringUtils.isEmpty(priceStr)) { - return AppletControllerUtil.appletWarning("参数错误"); - } - BigDecimal price = new BigDecimal(priceStr); - // 查询订单 - Order order = orderService.selectOrderById(orderId); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - // 查询最新订单日志 - OrderLog neworderLog = orderLogService.selectDataTheFirstNew(order.getId()); - System.out.println("######################"+order.getId()); - System.out.println("^^^^^^^^^^^^^^^^^^^^^^"+neworderLog.getId()); - if (neworderLog!=null){ - //修改订单日志添加费用 - neworderLog.setPrice(price); - neworderLog.setPaid(1L); - neworderLog.setWorkerCost(price); - neworderLog.setLogId(GenerateCustomCode.generCreateOrder("FEE")); - //修改订单状态 - order.setJsonStatus(3); - JSONObject jsonObject3 = new JSONObject(); - jsonObject3.put("type", 2); - order.setLogJson(jsonObject3.toJSONString()); - orderLogService.updateOrderLog(neworderLog); - orderService.updateOrder(order); - Users userinfo = usersService.selectUsersById(order.getUid()); - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - //给用户发送微信推送消息 - WXsendMsgUtil.sendMsgForUserDoorMoney(userinfo.getOpenid(),order,serviceGoods); - } + Long orderId = params.get("id") != null ? Long.parseLong(params.get("id").toString()) : null; + String priceStr = params.get("price") != null ? params.get("price").toString() : null; + if (orderId == null || StringUtils.isEmpty(priceStr)) { + return AppletControllerUtil.appletWarning("参数错误"); + } + BigDecimal price = new BigDecimal(priceStr); + // 查询订单 + Order order = orderService.selectOrderById(orderId); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + // 查询最新订单日志 + OrderLog neworderLog = orderLogService.selectDataTheFirstNew(order.getId()); + System.out.println("######################" + order.getId()); + System.out.println("^^^^^^^^^^^^^^^^^^^^^^" + neworderLog.getId()); + if (neworderLog != null) { + //修改订单日志添加费用 + neworderLog.setPrice(price); + neworderLog.setPaid(1L); + neworderLog.setWorkerCost(price); + neworderLog.setLogId(GenerateCustomCode.generCreateOrder("FEE")); + //修改订单状态 + order.setJsonStatus(3); + JSONObject jsonObject3 = new JSONObject(); + jsonObject3.put("type", 2); + order.setLogJson(jsonObject3.toJSONString()); + orderLogService.updateOrderLog(neworderLog); + orderService.updateOrder(order); + Users userinfo = usersService.selectUsersById(order.getUid()); + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + //给用户发送微信推送消息 + WXsendMsgUtil.sendMsgForUserDoorMoney(userinfo.getOpenid(), order, serviceGoods); + } // List logList = orderLogService.selectOrderLogByOrderId(order.getOrderId()); // if (logList == null || logList.isEmpty()) { // return AppletControllerUtil.appletWarning("订单日志不存在"); @@ -6277,39 +6359,39 @@ public class AppletController extends BaseController { // latestLog.setPrice(price); // latestLog.setPaid(1L); // orderLogService.updateOrderLog(latestLog); - return AjaxResult.success("设置上门费成功"); - } catch (Exception e) { - return AppletControllerUtil.appletError("设置上门费失败:" + e.getMessage()); - } + return AjaxResult.success("设置上门费成功"); + } catch (Exception e) { + return AppletControllerUtil.appletError("设置上门费失败:" + e.getMessage()); } +} - /** - * 师傅设置出发上门 - * GET /api/worker/start/door/{id} - * 逻辑参考OrderController的edit接口中jsonStatus=4的流程 - */ - @GetMapping("/api/worker/start/door/{id}") - public AjaxResult workerStartDoor(@PathVariable("id") Long id, HttpServletRequest request) throws Exception { - // 1. 获取当前登录师傅ID(token在header) - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletWarning("未登录或token无效"); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - Long workerId = user.getId(); +/** + * 师傅设置出发上门 + * GET /api/worker/start/door/{id} + * 逻辑参考OrderController的edit接口中jsonStatus=4的流程 + */ +@GetMapping("/api/worker/start/door/{id}") +public AjaxResult workerStartDoor(@PathVariable("id") Long id, HttpServletRequest request) throws Exception { + // 1. 获取当前登录师傅ID(token在header) + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletWarning("未登录或token无效"); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + Long workerId = user.getId(); - // 2. 获取订单 - Order order = orderService.selectOrderById(id); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - if (!workerId.equals(order.getWorkerId())) { - return AppletControllerUtil.appletWarning("您不是该订单的师傅"); - } + // 2. 获取订单 + Order order = orderService.selectOrderById(id); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + if (!workerId.equals(order.getWorkerId())) { + return AppletControllerUtil.appletWarning("您不是该订单的师傅"); + } // if (order.getStatus() == null || order.getStatus() != 2L) { // return error("订单状态不正确"); // } @@ -6317,1202 +6399,1319 @@ public class AppletController extends BaseController { // return error("订单进度不正确"); // } - order.setJsonStatus(4); // 出发上门 - JSONObject typeJson = new JSONObject(); - typeJson.put("type", 3); - order.setLogJson(typeJson.toJSONString()); - // 5. 保存 - orderService.updateOrder(order); - // 4. 写订单日志 - OrderLog orderLog = new OrderLog(); - orderLog.setOid(order.getId()); - orderLog.setOrderId(order.getOrderId()); - orderLog.setWorkerId(workerId); - orderLog.setWorkerLogId(workerId); - orderLog.setTitle("出发上门"); - JSONObject typeJson1 = new JSONObject(); - typeJson1.put("name", "师傅收到派单信息准备出发"); - orderLog.setType(new BigDecimal("3.0")); - orderLog.setContent(typeJson1.toJSONString()); - orderLogService.insertOrderLog(orderLog); - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - //小程序推送给用户师傅已经出发 - WXsendMsgUtil.sendStartDoorMoney(user.getOpenid(),order,serviceGoods); - return AppletControllerUtil.appletSuccess("出发上门成功"); + order.setJsonStatus(4); // 出发上门 + JSONObject typeJson = new JSONObject(); + typeJson.put("type", 3); + order.setLogJson(typeJson.toJSONString()); + // 5. 保存 + orderService.updateOrder(order); + // 4. 写订单日志 + OrderLog orderLog = new OrderLog(); + orderLog.setOid(order.getId()); + orderLog.setOrderId(order.getOrderId()); + orderLog.setWorkerId(workerId); + orderLog.setWorkerLogId(workerId); + orderLog.setTitle("出发上门"); + JSONObject typeJson1 = new JSONObject(); + typeJson1.put("name", "师傅收到派单信息准备出发"); + orderLog.setType(new BigDecimal("3.0")); + orderLog.setContent(typeJson1.toJSONString()); + orderLogService.insertOrderLog(orderLog); + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + //小程序推送给用户师傅已经出发 + WXsendMsgUtil.sendStartDoorMoney(user.getOpenid(), order, serviceGoods); + return AppletControllerUtil.appletSuccess("出发上门成功"); +} + +/** + * 师傅确认到达(新版,校验手机号后两位) + * POST /api/worker/confirm/door + * 参数:{id: 订单id, phone_two: 用户手机号后两位} + */ +@PostMapping("/api/worker/confirm/door") +public AjaxResult workerConfirmDoor(@RequestBody Map params, HttpServletRequest request) throws Exception { + // 1. 获取参数 + if (params == null || !params.containsKey("id") || !params.containsKey("phone_two")) { + return AppletControllerUtil.appletWarning("参数不完整"); + } + Long id; + try { + id = Long.valueOf(params.get("id").toString()); + } catch (Exception e) { + return AppletControllerUtil.appletWarning("订单ID格式错误"); + } + String phoneTwo = params.get("phone_two").toString(); + if (phoneTwo.length() != 2) { + return AppletControllerUtil.appletWarning("请输入手机号后两位"); } - /** - * 师傅确认到达(新版,校验手机号后两位) - * POST /api/worker/confirm/door - * 参数:{id: 订单id, phone_two: 用户手机号后两位} - */ - @PostMapping("/api/worker/confirm/door") - public AjaxResult workerConfirmDoor(@RequestBody Map params, HttpServletRequest request) throws Exception { - // 1. 获取参数 - if (params == null || !params.containsKey("id") || !params.containsKey("phone_two")) { - return AppletControllerUtil.appletWarning("参数不完整"); - } - Long id; + // 2. 获取当前登录师傅ID(token在header) + String token = request.getHeader("token"); + Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); + if (!(Boolean) userValidation.get("valid")) { + return AppletControllerUtil.appletWarning("未登录或token无效"); + } + Users user = (Users) userValidation.get("user"); + if (user == null) { + return AppletControllerUtil.appletWarning("用户信息获取失败"); + } + Long workerId = user.getId(); + + // 3. 获取订单 + Order order = orderService.selectOrderById(id); + if (order == null) { + return AppletControllerUtil.appletWarning("订单不存在"); + } + if (!workerId.equals(order.getWorkerId())) { + return AppletControllerUtil.appletWarning("您不是该订单的师傅"); + } + // 校验用户手机号后两位 + String userPhone = order.getPhone(); + if (userPhone == null || userPhone.length() < 2) { + return AppletControllerUtil.appletWarning("用户手机号无效"); + } + String lastTwo = userPhone.substring(userPhone.length() - 2); + if (!phoneTwo.equals(lastTwo)) { + return AppletControllerUtil.appletWarning("手机号后两位不正确"); + } + + //解绑订单虚拟号 + YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone()); + + + // 4. 更新订单状态 + order.setJsonStatus(5); // 确认到达 + JSONObject typeJson = new JSONObject(); + typeJson.put("type", 4); + order.setLogJson(typeJson.toJSONString()); + // 6. 保存 + orderService.updateOrder(order); + + // 5. 写订单日志 + OrderLog orderLog = new OrderLog(); + orderLog.setOid(order.getId()); + orderLog.setOrderId(order.getOrderId()); + orderLog.setWorkerId(workerId); + orderLog.setWorkerLogId(workerId); + orderLog.setTitle("师傅到达"); + orderLog.setType(new BigDecimal("4.0")); + JSONObject content = new JSONObject(); + content.put("name", "师傅到达服务地点"); + orderLog.setContent(content.toJSONString()); + // 6. 保存 + orderLogService.insertOrderLog(orderLog); + + // 小程序推送给用户师傅已经到达 + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + WXsendMsgUtil.sendMsgForWorkerInfo(user.getOpenid(), order, serviceGoods); + return AppletControllerUtil.appletSuccess("师傅已经上门"); +} + +/** + * 获取基检项目 + * GET /api/worker/basic/project/{id} + * 返回格式参考用户图片 + */ +@GetMapping("/api/worker/basic/project/{id}") +public AjaxResult getWorkerBasicProject(@PathVariable("id") Long id) { + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(id); + if (serviceGoods == null) { + return AppletControllerUtil.appletError("商品不存在"); + } + String basic = serviceGoods.getBasic(); + List basicList = new ArrayList<>(); + if (basic != null && !basic.trim().isEmpty()) { try { - id = Long.valueOf(params.get("id").toString()); + JSONArray jsonArray = JSONArray.parseArray(basic); + for (int i = 0; i < jsonArray.size(); i++) { + String item = jsonArray.getString(i); + if (item != null && !item.trim().isEmpty()) { + basicList.add(item.trim()); + } + } } catch (Exception e) { - return AppletControllerUtil.appletWarning("订单ID格式错误"); - } - String phoneTwo = params.get("phone_two").toString(); - if (phoneTwo.length() != 2) { - return AppletControllerUtil.appletWarning("请输入手机号后两位"); - } - - // 2. 获取当前登录师傅ID(token在header) - String token = request.getHeader("token"); - Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); - if (!(Boolean) userValidation.get("valid")) { - return AppletControllerUtil.appletWarning("未登录或token无效"); - } - Users user = (Users) userValidation.get("user"); - if (user == null) { - return AppletControllerUtil.appletWarning("用户信息获取失败"); - } - Long workerId = user.getId(); - - // 3. 获取订单 - Order order = orderService.selectOrderById(id); - if (order == null) { - return AppletControllerUtil.appletWarning("订单不存在"); - } - if (!workerId.equals(order.getWorkerId())) { - return AppletControllerUtil.appletWarning("您不是该订单的师傅"); - } - // 校验用户手机号后两位 - String userPhone = order.getPhone(); - if (userPhone == null || userPhone.length() < 2) { - return AppletControllerUtil.appletWarning("用户手机号无效"); - } - String lastTwo = userPhone.substring(userPhone.length() - 2); - if (!phoneTwo.equals(lastTwo)) { - return AppletControllerUtil.appletWarning("手机号后两位不正确"); - } - - //解绑订单虚拟号 - YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone()); - - - // 4. 更新订单状态 - order.setJsonStatus(5); // 确认到达 - JSONObject typeJson = new JSONObject(); - typeJson.put("type", 4); - order.setLogJson(typeJson.toJSONString()); - // 6. 保存 - orderService.updateOrder(order); - - // 5. 写订单日志 - OrderLog orderLog = new OrderLog(); - orderLog.setOid(order.getId()); - orderLog.setOrderId(order.getOrderId()); - orderLog.setWorkerId(workerId); - orderLog.setWorkerLogId(workerId); - orderLog.setTitle("师傅到达"); - orderLog.setType(new BigDecimal("4.0")); - JSONObject content = new JSONObject(); - content.put("name", "师傅到达服务地点"); - orderLog.setContent(content.toJSONString()); - // 6. 保存 - orderLogService.insertOrderLog(orderLog); - - // 小程序推送给用户师傅已经到达 - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - WXsendMsgUtil.sendMsgForWorkerInfo(user.getOpenid(),order,serviceGoods); - return AppletControllerUtil.appletSuccess("师傅已经上门"); - } - - /** - * 获取基检项目 - * GET /api/worker/basic/project/{id} - * 返回格式参考用户图片 - */ - @GetMapping("/api/worker/basic/project/{id}") - public AjaxResult getWorkerBasicProject(@PathVariable("id") Long id) { - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(id); - if (serviceGoods == null) { - return AppletControllerUtil.appletError("商品不存在"); - } - String basic = serviceGoods.getBasic(); - List basicList = new ArrayList<>(); - if (basic != null && !basic.trim().isEmpty()) { - try { - JSONArray jsonArray = JSONArray.parseArray(basic); - for (int i = 0; i < jsonArray.size(); i++) { - String item = jsonArray.getString(i); - if (item != null && !item.trim().isEmpty()) { - basicList.add(item.trim()); - } - } - } catch (Exception e) { - String[] arr = basic.split("[\n,,]"); - for (String s : arr) { - if (!s.trim().isEmpty()) basicList.add(s.trim()); - } + String[] arr = basic.split("[\n,,]"); + for (String s : arr) { + if (!s.trim().isEmpty()) basicList.add(s.trim()); } } - Map data = new HashMap<>(); - data.put("basic", basicList); - return AjaxResult.success(data); } + Map data = new HashMap<>(); + data.put("basic", basicList); + return AjaxResult.success(data); +} - /** - * 报价获取服务项目 - * GET /api/worker/quote/craft/{goodsId} - * 返回格式参考json.txt - */ - @GetMapping("/api/worker/quote/craft/{goodsId}") - public Object getWorkerQuoteCraft(@PathVariable("goodsId") Long goodsId) { - // 1. 查询商品基本信息 - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsId); - if (serviceGoods == null) { - return AppletControllerUtil.appletError("商品不存在"); - } - // 2. 查询服务分类(IQuoteTypeService) - QuoteType typeQuery = new QuoteType(); - typeQuery.setGoodId("\"" + goodsId + "\""); - List typeList = quoteTypeService.selectQuoteTypeList(typeQuery); - List dataArr = new ArrayList<>(); - for (QuoteType type : typeList) { - Map typeMap = new HashMap<>(); - typeMap.put("id", type.getId()); - typeMap.put("title", type.getTitle()); - // 3. 查询工艺(IQuoteCraftService) - QuoteCraft craftQuery = new QuoteCraft(); - craftQuery.setTypeId("[\"" + type.getId() + "\"]"); - List craftList = quoteCraftService.selectQuoteCraftList(craftQuery); - List> craftArr = new ArrayList<>(); - for (QuoteCraft craft : craftList) { - Map craftMap = new HashMap<>(); - craftMap.put("id", craft.getId()); - craftMap.put("title", craft.getTitle()); - craftMap.put("price", craft.getPrice() != null ? craft.getPrice().toString() : "0.00"); - craftMap.put("unit", craft.getUnit()); - // type_id为数组,需解析 - List typeIdList = new ArrayList<>(); - String typeIdStr = craft.getTypeId(); - if (typeIdStr != null && typeIdStr.trim().startsWith("[") && typeIdStr.trim().endsWith("]")) { - try { - typeIdList = JSON.parseArray(typeIdStr, String.class); - } catch (Exception e) { - typeIdList.add(typeIdStr); - } - } else if (typeIdStr != null) { +/** + * 报价获取服务项目 + * GET /api/worker/quote/craft/{goodsId} + * 返回格式参考json.txt + */ +@GetMapping("/api/worker/quote/craft/{goodsId}") +public Object getWorkerQuoteCraft(@PathVariable("goodsId") Long goodsId) { + // 1. 查询商品基本信息 + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsId); + if (serviceGoods == null) { + return AppletControllerUtil.appletError("商品不存在"); + } + // 2. 查询服务分类(IQuoteTypeService) + QuoteType typeQuery = new QuoteType(); + typeQuery.setGoodId("\"" + goodsId + "\""); + List typeList = quoteTypeService.selectQuoteTypeList(typeQuery); + List dataArr = new ArrayList<>(); + for (QuoteType type : typeList) { + Map typeMap = new HashMap<>(); + typeMap.put("id", type.getId()); + typeMap.put("title", type.getTitle()); + // 3. 查询工艺(IQuoteCraftService) + QuoteCraft craftQuery = new QuoteCraft(); + craftQuery.setTypeId("[\"" + type.getId() + "\"]"); + List craftList = quoteCraftService.selectQuoteCraftList(craftQuery); + List> craftArr = new ArrayList<>(); + for (QuoteCraft craft : craftList) { + Map craftMap = new HashMap<>(); + craftMap.put("id", craft.getId()); + craftMap.put("title", craft.getTitle()); + craftMap.put("price", craft.getPrice() != null ? craft.getPrice().toString() : "0.00"); + craftMap.put("unit", craft.getUnit()); + // type_id为数组,需解析 + List typeIdList = new ArrayList<>(); + String typeIdStr = craft.getTypeId(); + if (typeIdStr != null && typeIdStr.trim().startsWith("[") && typeIdStr.trim().endsWith("]")) { + try { + typeIdList = JSON.parseArray(typeIdStr, String.class); + } catch (Exception e) { typeIdList.add(typeIdStr); } - craftMap.put("type_id", typeIdList); - craftArr.add(craftMap); + } else if (typeIdStr != null) { + typeIdList.add(typeIdStr); } - typeMap.put("craft", craftArr); - dataArr.add(typeMap); + craftMap.put("type_id", typeIdList); + craftArr.add(craftMap); } - Map result = new HashMap<>(); - result.put("data", dataArr); - result.put("code", 200); - result.put("msg", "OK"); - return result; + typeMap.put("craft", craftArr); + dataArr.add(typeMap); } + Map result = new HashMap<>(); + result.put("data", dataArr); + result.put("code", 200); + result.put("msg", "OK"); + return result; +} - /** - * 报价所需物料查询 - * GET /api/worker/quote/material/{goodsId} - * 返回格式参考json.txt - */ - @GetMapping("/api/worker/quote/material/{goodsId}") - public Object getWorkerQuoteMaterial(@PathVariable("goodsId") Long goodsId) { - // 1. 查询商品基本信息 - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsId); - if (serviceGoods == null) { - return AppletControllerUtil.appletError("商品不存在"); - } - // 2. 查询物料分类(IQuoteMaterialTypeService) - QuoteMaterialType typeQuery = new QuoteMaterialType(); - typeQuery.setGoodId("\"" + goodsId + "\""); - List typeList = quoteMaterialTypeService.selectQuoteMaterialTypeList(typeQuery); - List dataArr = new ArrayList<>(); - for (QuoteMaterialType type : typeList) { - Map typeMap = new HashMap<>(); - typeMap.put("id", type.getId()); - typeMap.put("title", type.getTitle()); - // 3. 查询物料信息(IQuoteMaterialService) - QuoteMaterial materialQuery = new QuoteMaterial(); - materialQuery.setTypeId("\"" + type.getId() + "\""); - List materialList = quoteMaterialService.selectQuoteMaterialList(materialQuery); - List> materialArr = new ArrayList<>(); - for (QuoteMaterial material : materialList) { - Map materialMap = new HashMap<>(); - materialMap.put("id", material.getId()); - materialMap.put("title", material.getTitle()); - materialMap.put("price", material.getPrice() != null ? material.getPrice().toString() : "0.00"); - materialMap.put("unit", material.getUnit()); - // type_id为数组,需解析 - List typeIdList = new ArrayList<>(); - String typeIdStr = material.getTypeId(); - if (typeIdStr != null && typeIdStr.trim().startsWith("[") && typeIdStr.trim().endsWith("]")) { - try { - typeIdList = JSON.parseArray(typeIdStr, String.class); - } catch (Exception e) { - typeIdList.add(typeIdStr); - } - } else if (typeIdStr != null) { +/** + * 报价所需物料查询 + * GET /api/worker/quote/material/{goodsId} + * 返回格式参考json.txt + */ +@GetMapping("/api/worker/quote/material/{goodsId}") +public Object getWorkerQuoteMaterial(@PathVariable("goodsId") Long goodsId) { + // 1. 查询商品基本信息 + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsId); + if (serviceGoods == null) { + return AppletControllerUtil.appletError("商品不存在"); + } + // 2. 查询物料分类(IQuoteMaterialTypeService) + QuoteMaterialType typeQuery = new QuoteMaterialType(); + typeQuery.setGoodId("\"" + goodsId + "\""); + List typeList = quoteMaterialTypeService.selectQuoteMaterialTypeList(typeQuery); + List dataArr = new ArrayList<>(); + for (QuoteMaterialType type : typeList) { + Map typeMap = new HashMap<>(); + typeMap.put("id", type.getId()); + typeMap.put("title", type.getTitle()); + // 3. 查询物料信息(IQuoteMaterialService) + QuoteMaterial materialQuery = new QuoteMaterial(); + materialQuery.setTypeId("\"" + type.getId() + "\""); + List materialList = quoteMaterialService.selectQuoteMaterialList(materialQuery); + List> materialArr = new ArrayList<>(); + for (QuoteMaterial material : materialList) { + Map materialMap = new HashMap<>(); + materialMap.put("id", material.getId()); + materialMap.put("title", material.getTitle()); + materialMap.put("price", material.getPrice() != null ? material.getPrice().toString() : "0.00"); + materialMap.put("unit", material.getUnit()); + // type_id为数组,需解析 + List typeIdList = new ArrayList<>(); + String typeIdStr = material.getTypeId(); + if (typeIdStr != null && typeIdStr.trim().startsWith("[") && typeIdStr.trim().endsWith("]")) { + try { + typeIdList = JSON.parseArray(typeIdStr, String.class); + } catch (Exception e) { typeIdList.add(typeIdStr); } - materialMap.put("type_id", typeIdList); - materialArr.add(materialMap); + } else if (typeIdStr != null) { + typeIdList.add(typeIdStr); } - typeMap.put("material", materialArr); - dataArr.add(typeMap); + materialMap.put("type_id", typeIdList); + materialArr.add(materialMap); } - Map result = new HashMap<>(); - result.put("data", dataArr); - result.put("code", 200); - result.put("msg", "OK"); - return result; + typeMap.put("material", materialArr); + dataArr.add(typeMap); } + Map result = new HashMap<>(); + result.put("data", dataArr); + result.put("code", 200); + result.put("msg", "OK"); + return result; +} - /** - * 师傅报价接口 - * POST /api/worker/estimate - * 参数格式参考json.txt - */ - @PostMapping("/api/worker/estimate") - public AjaxResult workerEstimate(@RequestBody Map params, HttpServletRequest request) throws Exception { - if (params == null) { - return AppletControllerUtil.appletError("参数错误"); - } - // 1. 计算金额 - BigDecimal totalPrice = BigDecimal.ZERO; - List> craftList = (List>) params.get("craft"); - if (craftList != null) { - for (Map craft : craftList) { - Long craftId = null; - try { - craftId = Long.valueOf(craft.get("id").toString()); - } catch (Exception ignore) { - } - if (craftId != null) { - QuoteCraft quoteCraft = quoteCraftService.selectQuoteCraftById(craftId); - if (quoteCraft != null) { - BigDecimal price = new BigDecimal(craft.get("price").toString()); - Integer count = craft.get("count") == null ? 1 : Integer.parseInt(craft.get("count").toString()); - totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(count))); - } - } - } - } - List> materialList = (List>) params.get("material"); - if (materialList != null) { - for (Map material : materialList) { - Long materialId = null; - try { - materialId = Long.valueOf(material.get("id").toString()); - } catch (Exception ignore) { - } - if (materialId != null) { - QuoteMaterial quoteMaterial = quoteMaterialService.selectQuoteMaterialById(materialId); - if (quoteMaterial != null) { - BigDecimal price = new BigDecimal(material.get("price").toString()); - Integer count = material.get("count") == null ? 1 : Integer.parseInt(material.get("count").toString()); - totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(count))); - } - } - } - } - // 2. 组装新json - Map resultJson = new LinkedHashMap<>(); - // project - Map project = new LinkedHashMap<>(); - project.put("name", "项目费用"); - project.put("price", totalPrice); - resultJson.put("project", project); - // basic - resultJson.put("basic", params.get("basic")); - // craft - List> craftListNew = new ArrayList<>(); - if (craftList != null) { - for (Map craft : craftList) { - Map item = new LinkedHashMap<>(); - item.put("name", craft.get("title") != null ? craft.get("title") : craft.get("name")); - item.put("price", craft.get("price")); - item.put("count", craft.get("count")); - craftListNew.add(item); - } - } - resultJson.put("craft", craftListNew); - // material - List> materialListNew = new ArrayList<>(); - if (materialList != null) { - for (Map material : materialList) { - Map item = new LinkedHashMap<>(); - item.put("name", material.get("title") != null ? material.get("title") : material.get("name")); - item.put("price", material.get("price")); - item.put("count", material.get("count")); - materialListNew.add(item); - } - } - resultJson.put("material", materialListNew); - // 3. 转为字符串 - String contentStr = JSONObject.toJSONString(resultJson); - // 4. 订单相关处理 - Long orderId = null; - if (params.get("id") != null) { +/** + * 师傅报价接口 + * POST /api/worker/estimate + * 参数格式参考json.txt + */ +@PostMapping("/api/worker/estimate") +public AjaxResult workerEstimate(@RequestBody Map params, HttpServletRequest request) throws Exception { + if (params == null) { + return AppletControllerUtil.appletError("参数错误"); + } + // 1. 计算金额 + BigDecimal GoodsAllPrice = BigDecimal.ZERO; + BigDecimal ServiceAllPrice = BigDecimal.ZERO; + BigDecimal totalPrice = BigDecimal.ZERO; + List> craftList = (List>) params.get("craft"); + if (craftList != null) { + for (Map craft : craftList) { + Long craftId = null; try { - orderId = Long.valueOf(params.get("id").toString()); + craftId = Long.valueOf(craft.get("id").toString()); } catch (Exception ignore) { } - } - if (orderId == null) { - return AppletControllerUtil.appletError("订单ID格式错误"); - } - Order order = orderService.selectOrderById(orderId); - if (order == null) { - return AppletControllerUtil.appletError("订单不存在"); - } - order.setJsonStatus(6); - JSONObject jsonObject =new JSONObject(); - jsonObject.put("type", 5); - order.setLogJson(jsonObject.toJSONString()); - // order.setTotalPrice(totalPrice); - // order.setUpdatedAt(new Date()); - int update = orderService.updateOrder(order); - if (update > 0) { - OrderLog log = new OrderLog(); - log.setOid(order.getId()); - log.setOrderId(order.getOrderId()); - log.setType(new BigDecimal(5)); - log.setContent(contentStr); - log.setTitle("已检查评估报价"); - if (params.get("price")!=null) { - log.setDeposit(new BigDecimal(params.get("price").toString())); - log.setDepPaid(1); - log.setDepLogId(GenerateCustomCode.generCreateOrder("RED")); + if (craftId != null) { + QuoteCraft quoteCraft = quoteCraftService.selectQuoteCraftById(craftId); + if (quoteCraft != null) { + BigDecimal price = new BigDecimal(craft.get("price").toString()); + Integer count = craft.get("count") == null ? 1 : Integer.parseInt(craft.get("count").toString()); + totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(count))); + ServiceAllPrice = ServiceAllPrice.add(price.multiply(BigDecimal.valueOf(count))); + } } - log.setPrice(totalPrice); - log.setPaid(1l); - if (params.get("reduction")!=null) { - log.setReductionPrice(new BigDecimal(params.get("reduction").toString())); - }else{ - log.setReductionPrice(BigDecimal.ZERO); - } - log.setLogId(GenerateCustomCode.generCreateOrder("EST")); - log.setWorkerLogId(order.getWorkerId()); - log.setWorkerId(order.getWorkerId()); - orderLogService.insertOrderLog(log); - Users user = usersService.selectUsersById(order.getUid()); - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - //小程序推送用户报价成功 - WXsendMsgUtil.sendWorkerADDmoney(user.getOpenid(), order, serviceGoods); - return AppletControllerUtil.appletSuccess("报价成功"); - } else { - return AppletControllerUtil.appletError("报价失败"); } } - - /** - * 师傅开始服务接口 - * POST /api/worker/do/service - * 参数:{"oid":订单id,"image":[图片url数组]} - */ - @PostMapping("/api/worker/do/service") - public AjaxResult workerDoService(@RequestBody Map params, HttpServletRequest request) { - Long oid = 0L; - if (params.get("oid") != null) { + List> materialList = (List>) params.get("material"); + if (materialList != null) { + for (Map material : materialList) { + Long materialId = null; try { - oid = Long.valueOf(params.get("oid").toString()); - } catch (Exception e) { - return AppletControllerUtil.appletError("订单ID格式错误"); + materialId = Long.valueOf(material.get("id").toString()); + } catch (Exception ignore) { + } + if (materialId != null) { + QuoteMaterial quoteMaterial = quoteMaterialService.selectQuoteMaterialById(materialId); + if (quoteMaterial != null) { + BigDecimal price = new BigDecimal(material.get("price").toString()); + Integer count = material.get("count") == null ? 1 : Integer.parseInt(material.get("count").toString()); + totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(count))); + GoodsAllPrice = GoodsAllPrice.add(price.multiply(BigDecimal.valueOf(count))); + } } } - - Order order = orderService.selectOrderById(oid); - // 获取当前师傅id - - if (order != null) { - Long workerId = order.getWorkerId(); - if (order.getJsonStatus() == 6) { - //开始服务 - // 1. 修改订单状态 - order.setStatus(3L); // 服务中 - order.setJsonStatus(7); // 服务中 - order.setLogJson("{\"type\":6}"); - order.setIsPause(1); // 服务中 - order.setUpdatedAt(new Date()); - int update = orderService.updateOrder(order); - if (update > 0) { - // 2. 组装日志内容为数组格式 - Map logItem = new LinkedHashMap<>(); - logItem.put("name", "师傅开始服务"); - logItem.put("image", params.get("image")); - logItem.put("type", 1); - List logArr = new ArrayList<>(); - logArr.add(logItem); - String contentStr = JSONObject.toJSONString(logArr); - // 3. 写入订单日志 - OrderLog log = new OrderLog(); - log.setOid(order.getId()); - log.setOrderId(order.getOrderId()); - log.setTitle("开始服务"); - log.setType(new BigDecimal(6.0)); - log.setContent(contentStr); - log.setWorkerId(workerId); - log.setWorkerLogId(workerId); - log.setIsPause(1); - log.setCreatedAt(new Date()); - orderLogService.insertOrderLog(log); - return AppletControllerUtil.appletSuccess("服务已开始"); - } else { - return AppletControllerUtil.appletError("操作失败"); - } - } - } else { - OrderLog newlog = orderLogService.selectOrderLogById(Long.valueOf(params.get("id").toString())); - Order storder = orderService.selectOrderById(newlog.getOid()); - if (storder.getJsonStatus() == 7) { - if (newlog != null) { - newlog.setIsPause(2); - JSONArray jsonArray = JSONArray.parseArray(newlog.getContent()); - // 2. 组装日志内容为数组格式 - Map logItem = new LinkedHashMap<>(); - logItem.put("name", "暂停服务"); - logItem.put("image", params.get("image")); - logItem.put("reson", params.get("reson")); - logItem.put("next_time", params.get("next_time")); - logItem.put("time", new Date()); - logItem.put("type", 2); - jsonArray.add(logItem); - newlog.setContent(jsonArray.toJSONString()); - orderLogService.updateOrderLog(newlog); - - if (storder != null) { - // 1. 修改订单状态 - storder.setStatus(3L); // 服务中 - storder.setJsonStatus(8); // 服务中 - storder.setLogJson("{\"type\":6}"); - storder.setIsPause(2); // 服务中 - storder.setUpdatedAt(new Date()); - orderService.updateOrder(storder); - } - } - return AppletControllerUtil.appletSuccess("操作成功"); - } - if (storder.getJsonStatus() == 8) { - - if (newlog != null) { - newlog.setIsPause(1); - JSONArray jsonArray = JSONArray.parseArray(newlog.getContent()); - Map logItem = new LinkedHashMap<>(); - logItem.put("name", "继续服务"); - logItem.put("image", ""); - logItem.put("time", new Date()); - logItem.put("type", 1); - jsonArray.add(logItem); - newlog.setContent(jsonArray.toJSONString()); - orderLogService.updateOrderLog(newlog); - if (storder != null) { - //继续服务 - storder.setStatus(3L); // 服务中 - storder.setJsonStatus(7); // 服务中 - storder.setLogJson("{\"type\":6}"); - storder.setIsPause(1); // 服务中 - storder.setUpdatedAt(new Date()); - orderService.updateOrder(storder); - } - - } - return AppletControllerUtil.appletSuccess("操作成功"); - } - } - return AppletControllerUtil.appletSuccess("操作成功"); } - - /** - * 师傅完成订单接口 - * POST /api/worker/finish/service - * 参数:{"id":订单id,"image":[图片url数组]} - */ - @PostMapping("/api/worker/finish/service") - public AjaxResult workerFinishService(@RequestBody Map params, HttpServletRequest request) throws Exception { - if (params == null || params.get("id") == null) { - return AppletControllerUtil.appletError("参数错误"); + // 2. 组装新json + Map resultJson = new LinkedHashMap<>(); + // project + Map project = new LinkedHashMap<>(); + project.put("name", "项目费用"); + project.put("price", totalPrice); + resultJson.put("project", project); + // basic + resultJson.put("basic", params.get("basic")); + // craft + List> craftListNew = new ArrayList<>(); + if (craftList != null) { + for (Map craft : craftList) { + Map item = new LinkedHashMap<>(); + item.put("name", craft.get("title") != null ? craft.get("title") : craft.get("name")); + item.put("price", craft.get("price")); + item.put("count", craft.get("count")); + craftListNew.add(item); } - Long id; + } + resultJson.put("craft", craftListNew); + // material + List> materialListNew = new ArrayList<>(); + if (materialList != null) { + for (Map material : materialList) { + Map item = new LinkedHashMap<>(); + item.put("name", material.get("title") != null ? material.get("title") : material.get("name")); + item.put("price", material.get("price")); + item.put("count", material.get("count")); + materialListNew.add(item); + } + } + resultJson.put("material", materialListNew); + // 3. 转为字符串 + String contentStr = JSONObject.toJSONString(resultJson); + // 4. 订单相关处理 + Long orderId = null; + if (params.get("id") != null) { try { - id = Long.valueOf(params.get("id").toString()); + orderId = Long.valueOf(params.get("id").toString()); + } catch (Exception ignore) { + } + } + if (orderId == null) { + return AppletControllerUtil.appletError("订单ID格式错误"); + } + Order order = orderService.selectOrderById(orderId); + if (order == null) { + return AppletControllerUtil.appletError("订单不存在"); + } + order.setJsonStatus(6); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("type", 5); + order.setLogJson(jsonObject.toJSONString()); + // order.setTotalPrice(totalPrice); + // order.setUpdatedAt(new Date()); + order.setGoodPrice(GoodsAllPrice); + order.setServicePrice(ServiceAllPrice); + int update = orderService.updateOrder(order); + if (update > 0) { + OrderLog log = new OrderLog(); + log.setOid(order.getId()); + log.setOrderId(order.getOrderId()); + log.setType(new BigDecimal(5)); + log.setContent(contentStr); + log.setTitle("已检查评估报价"); + if (params.get("price") != null) { + log.setDeposit(new BigDecimal(params.get("price").toString())); + log.setDepPaid(1); + log.setDepLogId(GenerateCustomCode.generCreateOrder("RED")); + } + log.setPrice(totalPrice); + log.setPaid(1l); + if (params.get("reduction") != null) { + log.setReductionPrice(new BigDecimal(params.get("reduction").toString())); + } else { + log.setReductionPrice(BigDecimal.ZERO); + } + log.setWorkerCost(ServiceAllPrice); + log.setLogId(GenerateCustomCode.generCreateOrder("EST")); + log.setWorkerLogId(order.getWorkerId()); + log.setWorkerId(order.getWorkerId()); + orderLogService.insertOrderLog(log); + Users user = usersService.selectUsersById(order.getUid()); + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + //小程序推送用户报价成功 + WXsendMsgUtil.sendWorkerADDmoney(user.getOpenid(), order, serviceGoods); + return AppletControllerUtil.appletSuccess("报价成功"); + } else { + return AppletControllerUtil.appletError("报价失败"); + } +} + +/** + * 师傅开始服务接口 + * POST /api/worker/do/service + * 参数:{"oid":订单id,"image":[图片url数组]} + */ +@PostMapping("/api/worker/do/service") +public AjaxResult workerDoService(@RequestBody Map params, HttpServletRequest request) { + Long oid = 0L; + if (params.get("oid") != null) { + try { + oid = Long.valueOf(params.get("oid").toString()); } catch (Exception e) { return AppletControllerUtil.appletError("订单ID格式错误"); } - Order order = orderService.selectOrderById(id); - if (order == null) { - return AppletControllerUtil.appletError("订单不存在"); - } - // 1. 修改订单状态 - order.setStatus(6L); // 完成 - order.setReceiveType(3L); // 完成类型 - order.setJsonStatus(9); // 完成 - order.setLogJson("{\"type\":8}"); - int update = orderService.updateOrder(order); - if (update > 0) { - // 2. 组装日志内容 - Map logContent = new LinkedHashMap<>(); - logContent.put("name", "师傅服务完成"); - logContent.put("image", params.get("image")); - String contentStr = com.alibaba.fastjson2.JSONObject.toJSONString(logContent); - // 3. 写入订单日志 - OrderLog log = new OrderLog(); - log.setOid(order.getId()); - log.setOrderId(order.getOrderId()); - log.setTitle("服务完成"); - log.setType(new java.math.BigDecimal(7)); - log.setContent(contentStr); - log.setWorkerId(order.getWorkerId()); - log.setCreatedAt(new Date()); - orderLogService.insertOrderLog(log); - Users users = usersService.selectUsersById(order.getUid()); - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - WXsendMsgUtil.sendWorkerFinishOrder(users.getOpenid(), order, serviceGoods); - return AppletControllerUtil.appletSuccess("服务已完成"); - } else { - return AppletControllerUtil.appletError("操作失败"); - } } + Order order = orderService.selectOrderById(oid); + // 获取当前师傅id - - - /** - * 云信交互式语音通知呼叫结果推送回调接口 - * 用于接收云信平台推送的交互式语音通知呼叫结果。 - * @param requestBody 云信平台推送的JSON字符串 - * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 - */ - @PostMapping("/api/voice/interactNotify/resultCallback") - public Map voiceInteractNotifyResultCallback(@RequestBody String requestBody) { - // 解析请求体(可根据业务需要保存或处理字段) - try { - JSONObject json = JSONObject.parseObject(requestBody); - // 可提取字段:accountId、callId、calleeNumber、startCallTime、endTime、duration等 - // String accountId = json.getString("accountId"); - // String callId = json.getString("callId"); - // ... 其他字段 - // 这里可以根据业务需求进行日志记录、数据库保存等操作 - } catch (Exception e) { - // 解析异常可记录日志 + if (order != null) { + Long workerId = order.getWorkerId(); + if (order.getJsonStatus() == 6) { + //开始服务 + // 1. 修改订单状态 + order.setStatus(3L); // 服务中 + order.setJsonStatus(7); // 服务中 + order.setLogJson("{\"type\":6}"); + order.setIsPause(1); // 服务中 + order.setUpdatedAt(new Date()); + int update = orderService.updateOrder(order); + if (update > 0) { + // 2. 组装日志内容为数组格式 + Map logItem = new LinkedHashMap<>(); + logItem.put("name", "师傅开始服务"); + logItem.put("image", params.get("image")); + logItem.put("type", 1); + List logArr = new ArrayList<>(); + logArr.add(logItem); + String contentStr = JSONObject.toJSONString(logArr); + // 3. 写入订单日志 + OrderLog log = new OrderLog(); + log.setOid(order.getId()); + log.setOrderId(order.getOrderId()); + log.setTitle("开始服务"); + log.setType(new BigDecimal(6.0)); + log.setContent(contentStr); + log.setWorkerId(workerId); + log.setWorkerLogId(workerId); + log.setIsPause(1); + log.setCreatedAt(new Date()); + orderLogService.insertOrderLog(log); + return AppletControllerUtil.appletSuccess("服务已开始"); + } else { + return AppletControllerUtil.appletError("操作失败"); + } } - // 必须返回{"resultCode":"200"},否则云信会认为推送失败 - Map resp = new java.util.HashMap<>(); - resp.put("resultCode", "200"); - return resp; - } + } else { + OrderLog newlog = orderLogService.selectOrderLogById(Long.valueOf(params.get("id").toString())); + Order storder = orderService.selectOrderById(newlog.getOid()); + if (storder.getJsonStatus() == 7) { + if (newlog != null) { + newlog.setIsPause(2); + JSONArray jsonArray = JSONArray.parseArray(newlog.getContent()); + // 2. 组装日志内容为数组格式 + Map logItem = new LinkedHashMap<>(); + logItem.put("name", "暂停服务"); + logItem.put("image", params.get("image")); + logItem.put("reson", params.get("reson")); + logItem.put("next_time", params.get("next_time")); + logItem.put("time", new Date()); + logItem.put("type", 2); + jsonArray.add(logItem); + newlog.setContent(jsonArray.toJSONString()); + orderLogService.updateOrderLog(newlog); - - - - - /** - * 云信交互式小号呼叫结果推送结果推送回调接口 - * 用于接收云信平台推送的交互式语音通知呼叫结果。 - * @param requestBody 云信平台推送的JSON字符串 - * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 - */ - @PostMapping("/api/voice/middleNumberAXB/resultCallback") - public Map voiceInteractmiddleNumberAXBCallback(@RequestBody String requestBody) { - // 解析请求体(可根据业务需要保存或处理字段) - try { - JSONObject json = JSONObject.parseObject(requestBody); - // 可提取字段:accountId、callId、calleeNumber、startCallTime、endTime、duration等 - // String accountId = json.getString("accountId"); - // String callId = json.getString("callId"); - // ... 其他字段 - // 这里可以根据业务需求进行日志记录、数据库保存等操作 - } catch (Exception e) { - // 解析异常可记录日志 - } - // 必须返回{"resultCode":"200"},否则云信会认为推送失败 - Map resp = new java.util.HashMap<>(); - resp.put("resultCode", "200"); - return resp; - } - - /** - * 抢单大厅 - 获取可抢订单列表 - * - * 功能说明: - * - 查询状态为1(待接单)的订单 - * - 支持分页查询 - * - 组装商品信息和系统配置 - * - 返回标准分页格式数据 - * - * @param params 请求参数,包含分页信息 - * @param request HTTP请求对象 - * @return 抢单大厅订单列表数据 - */ - @PostMapping(value = "/api/worker/grab/lst") - public AjaxResult getWorkerGrabOrderList(@RequestBody Map params, HttpServletRequest request) { - try { - // 1. 解析分页参数 - int page = 1; - int limit = 15; - - if (params.get("page") != null) { - try { - page = Integer.parseInt(params.get("page").toString()); - if (page < 1) page = 1; - } catch (NumberFormatException e) { - page = 1; + if (storder != null) { + // 1. 修改订单状态 + storder.setStatus(3L); // 服务中 + storder.setJsonStatus(8); // 服务中 + storder.setLogJson("{\"type\":6}"); + storder.setIsPause(2); // 服务中 + storder.setUpdatedAt(new Date()); + orderService.updateOrder(storder); } } + return AppletControllerUtil.appletSuccess("操作成功"); + } + if (storder.getJsonStatus() == 8) { - if (params.get("limit") != null) { - try { - limit = Integer.parseInt(params.get("limit").toString()); - if (limit < 1) limit = 15; - if (limit > 100) limit = 100; // 限制最大每页数量 - } catch (NumberFormatException e) { - limit = 15; + if (newlog != null) { + newlog.setIsPause(1); + JSONArray jsonArray = JSONArray.parseArray(newlog.getContent()); + Map logItem = new LinkedHashMap<>(); + logItem.put("name", "继续服务"); + logItem.put("image", ""); + logItem.put("time", new Date()); + logItem.put("type", 1); + jsonArray.add(logItem); + newlog.setContent(jsonArray.toJSONString()); + orderLogService.updateOrderLog(newlog); + if (storder != null) { + //继续服务 + storder.setStatus(3L); // 服务中 + storder.setJsonStatus(7); // 服务中 + storder.setLogJson("{\"type\":6}"); + storder.setIsPause(1); // 服务中 + storder.setUpdatedAt(new Date()); + orderService.updateOrder(storder); } + } + return AppletControllerUtil.appletSuccess("操作成功"); + } + } + return AppletControllerUtil.appletSuccess("操作成功"); +} - // 2. 设置分页 - PageHelper.startPage(page, limit); +/** + * 师傅完成订单接口 + * POST /api/worker/finish/service + * 参数:{"id":订单id,"image":[图片url数组]} + */ +@PostMapping("/api/worker/finish/service") +public AjaxResult workerFinishService(@RequestBody Map params, HttpServletRequest request) throws Exception { + if (params == null || params.get("id") == null) { + return AppletControllerUtil.appletError("参数错误"); + } + Long id; + try { + id = Long.valueOf(params.get("id").toString()); + } catch (Exception e) { + return AppletControllerUtil.appletError("订单ID格式错误"); + } + Order order = orderService.selectOrderById(id); + if (order == null) { + return AppletControllerUtil.appletError("订单不存在"); + } + // 1. 修改订单状态 + order.setStatus(6L); // 完成 + order.setReceiveType(3L); // 完成类型 + order.setJsonStatus(9); // 完成 + order.setLogJson("{\"type\":8}"); + int update = orderService.updateOrder(order); + if (update > 0) { + // 2. 组装日志内容 + Map logContent = new LinkedHashMap<>(); + logContent.put("name", "师傅服务完成"); + logContent.put("image", params.get("image")); + String contentStr = com.alibaba.fastjson2.JSONObject.toJSONString(logContent); + // 3. 写入订单日志 + OrderLog log = new OrderLog(); + log.setOid(order.getId()); + log.setOrderId(order.getOrderId()); + log.setTitle("服务完成"); + log.setType(new java.math.BigDecimal(7)); + log.setContent(contentStr); + log.setWorkerId(order.getWorkerId()); + log.setCreatedAt(new Date()); + orderLogService.insertOrderLog(log); + Users users = usersService.selectUsersById(order.getUid()); + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + WXsendMsgUtil.sendWorkerFinishOrder(users.getOpenid(), order, serviceGoods); + return AppletControllerUtil.appletSuccess("服务已完成"); + } else { + return AppletControllerUtil.appletError("操作失败"); + } +} - // 3. 查询状态为1(待接单)的订单 - Order orderQuery = new Order(); - orderQuery.setStatus(1L); // 待接单状态 +/** + * 结束订单 + * POST + * 参数:{"id":订单id} + */ +@PostMapping("/api/worker/order/end") +public AjaxResult workerOrderEnd(@RequestBody Map params, HttpServletRequest request) { + // 1. 参数校验 + if (params.get("id") == null) { + return AjaxResult.error("系统错误"); + } + Long id = Long.valueOf(params.get("id").toString()); + Order orderInfo = orderService.selectOrderById(id); + if (orderInfo == null) { + return AjaxResult.error("订单不存在"); + } + Users workerInfo = usersService.selectUsersById(orderInfo.getWorkerId()); + if (workerInfo == null) { + return AjaxResult.error("师傅记录不存在"); + } + // 2. 状态判断 + String msg = null; + switch (orderInfo.getStatus().intValue()) { + case 1: + msg = "还未接单,不能结束订单"; + break; + case 3: + msg = "服务还在进行中,不能提前结束订单"; + break; + case 4: + msg = "订单已完成"; + break; + case 5: + msg = "订单已取消"; + break; + case 6: + case 7: + msg = "订单已结束"; + break; + } + if (msg != null) { + return AjaxResult.error(msg); + } + try { + // 3.1 更新订单状态为7(已结束) + Order updateOrder = new Order(); + updateOrder.setId(id); + updateOrder.setStatus(7L); + orderService.updateOrder(updateOrder); - List orderList = orderService.selectOrderList(orderQuery); - PageInfo pageInfo = new PageInfo<>(orderList); + // 3.2 插入订单日志 + OrderLog log = new OrderLog(); + log.setOid(orderInfo.getId()); + log.setOrderId(orderInfo.getOrderId()); + log.setTitle("结束订单"); + log.setType(BigDecimal.valueOf(10)); + log.setContent("{\"name\":\"师傅提前结束订单\"}"); + //Long workerId = getCurrentWorkerId(request); // 需实现 + log.setWorkerId(workerInfo.getId()); + log.setCreatedAt(new Date()); + log.setUpdatedAt(new Date()); + orderLogService.insertOrderLog(log); - // 4. 组装订单数据 - List> formattedOrderList = new ArrayList<>(); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + // 3.3 查询是否有上门费(type=2, paid=2) + OrderLog doorPriceLogself = new OrderLog(); + doorPriceLogself.setOid(orderInfo.getId()); + doorPriceLogself.setType(BigDecimal.valueOf(2)); + doorPriceLogself.setPaid(2L); + doorPriceLogself.setWorkerId(workerInfo.getId()); + OrderLog doorPriceLog = orderLogService.selectOneByOidTypeWorkerIdPaid(doorPriceLogself); + if (doorPriceLog != null && doorPriceLog.getPrice() != null) { + // 师傅等级信息 + //Users workerInfo = usersService.selectUsersById(workerId); + WorkerLevel levelInfo = workerLevelService.selectWorkerLevelByLevel(Long.valueOf(workerInfo.getLevel())); + // 更新师傅佣金 + BigDecimal price = doorPriceLog.getPrice(); + Users updateUser = new Users(); + updateUser.setId(workerInfo.getId()); + updateUser.setCommission(workerInfo.getCommission().add(price)); + updateUser.setTotalComm(workerInfo.getTotalComm().add(price)); + usersService.updateUsers(updateUser); + // 插入师傅金额记录 + WorkerMoneyLog moneyLog = new WorkerMoneyLog(); + moneyLog.setWorkerId(workerInfo.getId()); + moneyLog.setOid(orderInfo.getId()); + moneyLog.setOrderId(orderInfo.getOrderId()); + moneyLog.setPrice(price); + moneyLog.setType(1); + moneyLog.setServicePrice(BigDecimal.ZERO); + moneyLog.setReductionPrice(BigDecimal.ZERO); + moneyLog.setCr(Math.toIntExact(levelInfo != null ? levelInfo.getCr() : null)); + moneyLog.setMergin(BigDecimal.ZERO); + moneyLog.setDoorPrice(price); + moneyLog.setCreatedAt(new Date()); + moneyLog.setUpdatedAt(new Date()); + workerMoneyLogService.insertWorkerMoneyLog(moneyLog); + } + // 3.4 解绑虚拟号 + if (orderInfo.getMiddlePhone() != null) { + VoiceResponseResult unbind = YunXinPhoneUtilAPI.httpsPrivacyUnbind(orderInfo.getWorkerPhone(), orderInfo.getUserPhone(), orderInfo.getMiddlePhone()); + if (unbind.getResult().equals("000000")) { + Order phoneUpdate = new Order(); + phoneUpdate.setId(orderInfo.getId()); + phoneUpdate.setMiddlePhone(null); + phoneUpdate.setUserPhone(null); + phoneUpdate.setWorkerPhone(null); + orderService.updateOrder(phoneUpdate); + } + } + return AjaxResult.success("订单结束成功"); + } catch (Exception e) { + return AjaxResult.error("订单结束失败:" + e.getMessage()); + } +} - for (Order order : orderList) { - Map orderData = new HashMap<>(); +/** + * 云信交互式语音通知呼叫结果推送回调接口 + * 用于接收云信平台推送的交互式语音通知呼叫结果。 + * + * @param requestBody 云信平台推送的JSON字符串 + * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 + */ +@PostMapping("/api/voice/interactNotify/resultCallback") +public Map voiceInteractNotifyResultCallback(@RequestBody String requestBody) { + // 解析请求体(可根据业务需要保存或处理字段) + try { + JSONObject json = JSONObject.parseObject(requestBody); + // 可提取字段:accountId、callId、calleeNumber、startCallTime、endTime、duration等 + // String accountId = json.getString("accountId"); + // String callId = json.getString("callId"); + // ... 其他字段 + // 这里可以根据业务需求进行日志记录、数据库保存等操作 + } catch (Exception e) { + // 解析异常可记录日志 + } + // 必须返回{"resultCode":"200"},否则云信会认为推送失败 + Map resp = new java.util.HashMap<>(); + resp.put("resultCode", "200"); + return resp; +} - // 基础订单信息 - orderData.put("id", order.getId()); - orderData.put("type", order.getType()); - orderData.put("main_order_id", order.getMainOrderId()); - orderData.put("order_id", order.getOrderId()); - orderData.put("transaction_id", order.getTransactionId() != null ? order.getTransactionId() : ""); - orderData.put("create_type", order.getCreateType()); - orderData.put("create_phone", order.getCreatePhone()); - orderData.put("uid", order.getUid()); - orderData.put("product_id", order.getProductId()); - orderData.put("name", order.getName()); - orderData.put("phone", order.getPhone()); - orderData.put("address", order.getAddress()); - // 预约时间处理 - String makeTime = ""; - if (order.getMakeTime() != null) { - try { - // 将时间戳转换为日期格式 - Date makeDate = new Date(order.getMakeTime() * 1000L); - SimpleDateFormat makeDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - makeTime = makeDateFormat.format(makeDate); - if (order.getMakeHour() != null) { - makeTime += " " + order.getMakeHour(); - } - } catch (Exception e) { - makeTime = ""; +/** + * 云信交互式小号呼叫结果推送结果推送回调接口 + * 用于接收云信平台推送的交互式语音通知呼叫结果。 + * + * @param requestBody 云信平台推送的JSON字符串 + * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 + */ +@PostMapping("/api/voice/middleNumberAXB/resultCallback") +public Map voiceInteractmiddleNumberAXBCallback(@RequestBody String requestBody) { + // 解析请求体(可根据业务需要保存或处理字段) + try { + JSONObject json = JSONObject.parseObject(requestBody); + // 可提取字段:accountId、callId、calleeNumber、startCallTime、endTime、duration等 + // String accountId = json.getString("accountId"); + // String callId = json.getString("callId"); + // ... 其他字段 + // 这里可以根据业务需求进行日志记录、数据库保存等操作 + } catch (Exception e) { + // 解析异常可记录日志 + } + // 必须返回{"resultCode":"200"},否则云信会认为推送失败 + Map resp = new java.util.HashMap<>(); + resp.put("resultCode", "200"); + return resp; +} + +/** + * 抢单大厅 - 获取可抢订单列表 + *

+ * 功能说明: + * - 查询状态为1(待接单)的订单 + * - 支持分页查询 + * - 组装商品信息和系统配置 + * - 返回标准分页格式数据 + * + * @param params 请求参数,包含分页信息 + * @param request HTTP请求对象 + * @return 抢单大厅订单列表数据 + */ +@PostMapping(value = "/api/worker/grab/lst") +public AjaxResult getWorkerGrabOrderList(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 解析分页参数 + int page = 1; + int limit = 15; + + if (params.get("page") != null) { + try { + page = Integer.parseInt(params.get("page").toString()); + if (page < 1) page = 1; + } catch (NumberFormatException e) { + page = 1; + } + } + + if (params.get("limit") != null) { + try { + limit = Integer.parseInt(params.get("limit").toString()); + if (limit < 1) limit = 15; + if (limit > 100) limit = 100; // 限制最大每页数量 + } catch (NumberFormatException e) { + limit = 15; + } + } + + // 2. 设置分页 + PageHelper.startPage(page, limit); + + // 3. 查询状态为1(待接单)的订单 + Order orderQuery = new Order(); + orderQuery.setStatus(1L); // 待接单状态 + + List orderList = orderService.selectOrderList(orderQuery); + PageInfo pageInfo = new PageInfo<>(orderList); + + // 4. 组装订单数据 + List> formattedOrderList = new ArrayList<>(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + for (Order order : orderList) { + Map orderData = new HashMap<>(); + + // 基础订单信息 + orderData.put("id", order.getId()); + orderData.put("type", order.getType()); + orderData.put("main_order_id", order.getMainOrderId()); + orderData.put("order_id", order.getOrderId()); + orderData.put("transaction_id", order.getTransactionId() != null ? order.getTransactionId() : ""); + orderData.put("create_type", order.getCreateType()); + orderData.put("create_phone", order.getCreatePhone()); + orderData.put("uid", order.getUid()); + orderData.put("product_id", order.getProductId()); + orderData.put("name", order.getName()); + orderData.put("phone", order.getPhone()); + orderData.put("address", order.getAddress()); + + // 预约时间处理 + String makeTime = ""; + if (order.getMakeTime() != null) { + try { + // 将时间戳转换为日期格式 + Date makeDate = new Date(order.getMakeTime() * 1000L); + SimpleDateFormat makeDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + makeTime = makeDateFormat.format(makeDate); + if (order.getMakeHour() != null) { + makeTime += " " + order.getMakeHour(); } + } catch (Exception e) { + makeTime = ""; } - orderData.put("make_time", makeTime); - orderData.put("make_hour", order.getMakeHour()); + } + orderData.put("make_time", makeTime); + orderData.put("make_hour", order.getMakeHour()); - orderData.put("num", order.getNum()); - orderData.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); - orderData.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); - orderData.put("service_price", order.getServicePrice() != null ? order.getServicePrice().toString() : null); - orderData.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); - orderData.put("coupon_id", order.getCouponId()); - orderData.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); - orderData.put("pay_time", order.getPayTime()); - orderData.put("status", order.getStatus()); - orderData.put("is_pause", order.getIsPause()); - orderData.put("mark", order.getMark()); - orderData.put("address_id", order.getAddressId()); - orderData.put("sku", order.getSku()); - orderData.put("worker_id", order.getWorkerId()); - orderData.put("first_worker_id", order.getFirstWorkerId()); - orderData.put("receive_time", order.getReceiveTime() != null ? dateFormat.format(order.getReceiveTime()) : null); - orderData.put("is_comment", order.getIsComment()); - orderData.put("receive_type", order.getReceiveType()); - orderData.put("is_accept", order.getIsAccept()); - orderData.put("middle_phone", order.getMiddlePhone()); - orderData.put("user_phone", order.getUserPhone()); - orderData.put("worker_phone", order.getWorkerPhone()); - orderData.put("address_en", order.getAddressEn()); - orderData.put("uid_admin", order.getUidAdmin()); - orderData.put("address_admin", order.getAddressAdmin()); - orderData.put("log_status", order.getLogStatus()); - orderData.put("log_json", order.getLogJson()); - orderData.put("json_status", order.getJsonStatus()); - orderData.put("log_images", order.getLogImages()); - orderData.put("created_at", order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); - orderData.put("updated_at", order.getUpdatedAt() != null ? dateFormat.format(order.getUpdatedAt()) : null); - orderData.put("deleted_at", order.getDeletedAt()); + orderData.put("num", order.getNum()); + orderData.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); + orderData.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); + orderData.put("service_price", order.getServicePrice() != null ? order.getServicePrice().toString() : null); + orderData.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); + orderData.put("coupon_id", order.getCouponId()); + orderData.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); + orderData.put("pay_time", order.getPayTime()); + orderData.put("status", order.getStatus()); + orderData.put("is_pause", order.getIsPause()); + orderData.put("mark", order.getMark()); + orderData.put("address_id", order.getAddressId()); + orderData.put("sku", order.getSku()); + orderData.put("worker_id", order.getWorkerId()); + orderData.put("first_worker_id", order.getFirstWorkerId()); + orderData.put("receive_time", order.getReceiveTime() != null ? dateFormat.format(order.getReceiveTime()) : null); + orderData.put("is_comment", order.getIsComment()); + orderData.put("receive_type", order.getReceiveType()); + orderData.put("is_accept", order.getIsAccept()); + orderData.put("middle_phone", order.getMiddlePhone()); + orderData.put("user_phone", order.getUserPhone()); + orderData.put("worker_phone", order.getWorkerPhone()); + orderData.put("address_en", order.getAddressEn()); + orderData.put("uid_admin", order.getUidAdmin()); + orderData.put("address_admin", order.getAddressAdmin()); + orderData.put("log_status", order.getLogStatus()); + orderData.put("log_json", order.getLogJson()); + orderData.put("json_status", order.getJsonStatus()); + orderData.put("log_images", order.getLogImages()); + orderData.put("created_at", order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); + orderData.put("updated_at", order.getUpdatedAt() != null ? dateFormat.format(order.getUpdatedAt()) : null); + orderData.put("deleted_at", order.getDeletedAt()); - // 5. 组装商品信息 - Map productData = new HashMap<>(); - if (order.getProductId() != null) { - try { - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); - if (serviceGoods != null) { - productData.put("id", serviceGoods.getId()); - productData.put("title", serviceGoods.getTitle()); - productData.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); - productData.put("price", serviceGoods.getPrice() != null ? serviceGoods.getPrice().toString() : "0.00"); - } else { - // 商品不存在时的默认信息 - productData.put("id", order.getProductId()); - productData.put("title", "商品已下架"); - productData.put("icon", ""); - productData.put("price", "0.00"); - } - } catch (Exception e) { - // 查询异常时的默认信息 + // 5. 组装商品信息 + Map productData = new HashMap<>(); + if (order.getProductId() != null) { + try { + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + if (serviceGoods != null) { + productData.put("id", serviceGoods.getId()); + productData.put("title", serviceGoods.getTitle()); + productData.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); + productData.put("price", serviceGoods.getPrice() != null ? serviceGoods.getPrice().toString() : "0.00"); + } else { + // 商品不存在时的默认信息 productData.put("id", order.getProductId()); - productData.put("title", "商品信息获取失败"); + productData.put("title", "商品已下架"); productData.put("icon", ""); productData.put("price", "0.00"); } - } else { - productData.put("id", null); - productData.put("title", ""); + } catch (Exception e) { + // 查询异常时的默认信息 + productData.put("id", order.getProductId()); + productData.put("title", "商品信息获取失败"); productData.put("icon", ""); productData.put("price", "0.00"); } - orderData.put("product", productData); - - formattedOrderList.add(orderData); + } else { + productData.put("id", null); + productData.put("title", ""); + productData.put("icon", ""); + productData.put("price", "0.00"); } + orderData.put("product", productData); - // 6. 构建分页数据 - String baseUrl = request.getRequestURL().toString().split("\\?")[0]; - Map paginationData = AppletControllerUtil.buildPageResult(pageInfo, formattedOrderList, baseUrl); + formattedOrderList.add(orderData); + } - // 7. 查询系统配置(config_one) - Map configData = new HashMap<>(); - try { - SiteConfig siteConfigQuery = new SiteConfig(); - siteConfigQuery.setName("config_one"); - List configList = siteConfigService.selectSiteConfigList(siteConfigQuery); + // 6. 构建分页数据 + String baseUrl = request.getRequestURL().toString().split("\\?")[0]; + Map paginationData = AppletControllerUtil.buildPageResult(pageInfo, formattedOrderList, baseUrl); - if (!configList.isEmpty()) { - com.ruoyi.system.domain.SiteConfig config = configList.get(0); - String configValue = config.getValue(); + // 7. 查询系统配置(config_one) + Map configData = new HashMap<>(); + try { + SiteConfig siteConfigQuery = new SiteConfig(); + siteConfigQuery.setName("config_one"); + List configList = siteConfigService.selectSiteConfigList(siteConfigQuery); - if (configValue != null && !configValue.trim().isEmpty()) { - try { - // 尝试解析JSON配置 - JSONObject configJson = JSONObject.parseObject(configValue); - configData.putAll(configJson); - } catch (Exception e) { - // JSON解析失败时的默认配置 - setDefaultConfig(configData); - } - } else { - // 配置值为空时的默认配置 + if (!configList.isEmpty()) { + com.ruoyi.system.domain.SiteConfig config = configList.get(0); + String configValue = config.getValue(); + + if (configValue != null && !configValue.trim().isEmpty()) { + try { + // 尝试解析JSON配置 + JSONObject configJson = JSONObject.parseObject(configValue); + configData.putAll(configJson); + } catch (Exception e) { + // JSON解析失败时的默认配置 setDefaultConfig(configData); } } else { - // 配置不存在时的默认配置 + // 配置值为空时的默认配置 setDefaultConfig(configData); } - } catch (Exception e) { - // 查询配置异常时的默认配置 + } else { + // 配置不存在时的默认配置 setDefaultConfig(configData); } - - // 8. 构建最终返回数据 - Map responseData = new HashMap<>(); - responseData.put("data", paginationData); - responseData.put("config", configData); - - return AppletControllerUtil.appletSuccess(responseData); - } catch (Exception e) { - logger.error("获取抢单大厅订单列表异常:", e); - return AppletControllerUtil.appletError("获取抢单大厅订单列表失败:" + e.getMessage()); + // 查询配置异常时的默认配置 + setDefaultConfig(configData); } + + // 8. 构建最终返回数据 + Map responseData = new HashMap<>(); + responseData.put("data", paginationData); + responseData.put("config", configData); + + return AppletControllerUtil.appletSuccess(responseData); + + } catch (Exception e) { + logger.error("获取抢单大厅订单列表异常:", e); + return AppletControllerUtil.appletError("获取抢单大厅订单列表失败:" + e.getMessage()); } +} +/** + * 商品订单游标接口 + * + * @param params 请求参数,包含product_id(商品ID)、num(数量)、sku(规格信息) + * @param request HTTP请求对象 + * @return 返回商品ID + *

+ * 接口说明: + * - 接收商品订单相关信息 + * - 调用IGoodsOrderCursorService新增一条数据 + * - 返回商品ID作为响应数据 + *

+ * 请求参数格式: + * { + * "product_id": 2, + * "num": 1, + * "sku": "{\"价格\":\"长青泉 1.5L*6瓶 29.4元\",\"pic\":\"\",\"price\":\"29.4\",\"stock\":\"1000\"}" + * } + *

+ * 返回格式: + * { + * "code": 200, + * "msg": "OK", + * "data": 79 + * } + */ +@PostMapping("/api/service/cursor") +public AjaxResult serviceCursor(@RequestBody Map params, HttpServletRequest request) { + try { + // 1. 参数验证 + if (params == null) { + return error("请求参数不能为空"); + } + // 验证必要参数 + if (params.get("product_id") == null) { + return error("商品ID不能为空"); + } + + if (params.get("num") == null) { + return error("商品数量不能为空"); + } + + // 2. 解析参数 + Long productId; + Integer num; + String sku = params.get("sku") != null ? params.get("sku").toString() : ""; - /** - * 商品订单游标接口 - * - * @param params 请求参数,包含product_id(商品ID)、num(数量)、sku(规格信息) - * @param request HTTP请求对象 - * @return 返回商品ID - *

- * 接口说明: - * - 接收商品订单相关信息 - * - 调用IGoodsOrderCursorService新增一条数据 - * - 返回商品ID作为响应数据 - *

- * 请求参数格式: - * { - * "product_id": 2, - * "num": 1, - * "sku": "{\"价格\":\"长青泉 1.5L*6瓶 29.4元\",\"pic\":\"\",\"price\":\"29.4\",\"stock\":\"1000\"}" - * } - *

- * 返回格式: - * { - * "code": 200, - * "msg": "OK", - * "data": 79 - * } - */ - @PostMapping("/api/service/cursor") - public AjaxResult serviceCursor(@RequestBody Map params, HttpServletRequest request) { try { - // 1. 参数验证 - if (params == null) { - return error("请求参数不能为空"); - } + productId = Long.valueOf(params.get("product_id").toString()); + num = Integer.valueOf(params.get("num").toString()); + } catch (NumberFormatException e) { + return error("参数格式错误"); + } - // 验证必要参数 - if (params.get("product_id") == null) { - return error("商品ID不能为空"); - } + // 3. 验证参数有效性 + if (productId <= 0) { + return error("商品ID无效"); + } - if (params.get("num") == null) { - return error("商品数量不能为空"); - } + if (num <= 0) { + return error("商品数量必须大于0"); + } - // 2. 解析参数 - Long productId; - Integer num; - String sku = params.get("sku") != null ? params.get("sku").toString() : ""; + // 4. 验证商品是否存在 + ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId); + if (serviceGoods == null) { + return error("商品不存在"); + } + // 5. 验证商品状态 + if (serviceGoods.getStatus() == null || !"1".equals(serviceGoods.getStatus())) { + return error("商品已下架或不可购买"); + } + + // 6. 验证库存(如果有库存管理) + if (serviceGoods.getStock() != null && serviceGoods.getStock() < num) { + return error("商品库存不足"); + } + + // 7. 解析并验证SKU信息(如果有的话) + if (sku != null && !sku.trim().isEmpty()) { try { - productId = Long.valueOf(params.get("product_id").toString()); - num = Integer.valueOf(params.get("num").toString()); - } catch (NumberFormatException e) { - return error("参数格式错误"); - } + JSONObject skuJson = JSONObject.parseObject(sku); - // 3. 验证参数有效性 - if (productId <= 0) { - return error("商品ID无效"); - } - - if (num <= 0) { - return error("商品数量必须大于0"); - } - - // 4. 验证商品是否存在 - ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId); - if (serviceGoods == null) { - return error("商品不存在"); - } - - // 5. 验证商品状态 - if (serviceGoods.getStatus() == null || !"1".equals(serviceGoods.getStatus())) { - return error("商品已下架或不可购买"); - } - - // 6. 验证库存(如果有库存管理) - if (serviceGoods.getStock() != null && serviceGoods.getStock() < num) { - return error("商品库存不足"); - } - - // 7. 解析并验证SKU信息(如果有的话) - if (sku != null && !sku.trim().isEmpty()) { - try { - JSONObject skuJson = JSONObject.parseObject(sku); - - // 验证SKU中的库存 - if (skuJson.containsKey("stock")) { - String stockStr = skuJson.getString("stock"); - try { - int skuStock = Integer.parseInt(stockStr); - if (skuStock < num) { - return error("SKU库存不足"); - } - } catch (NumberFormatException e) { - // SKU库存格式错误,忽略验证 + // 验证SKU中的库存 + if (skuJson.containsKey("stock")) { + String stockStr = skuJson.getString("stock"); + try { + int skuStock = Integer.parseInt(stockStr); + if (skuStock < num) { + return error("SKU库存不足"); } + } catch (NumberFormatException e) { + // SKU库存格式错误,忽略验证 } - } catch (Exception e) { - // SKU JSON格式错误,但不影响主流程 } + } catch (Exception e) { + // SKU JSON格式错误,但不影响主流程 } + } - // 8. 构建GoodsOrderCursor对象 - GoodsOrderCursor goodsOrderCursor = new GoodsOrderCursor(); - goodsOrderCursor.setProductId(productId); - goodsOrderCursor.setType(2l); - goodsOrderCursor.setNum(num.longValue()); - goodsOrderCursor.setSku(sku); + // 8. 构建GoodsOrderCursor对象 + GoodsOrderCursor goodsOrderCursor = new GoodsOrderCursor(); + goodsOrderCursor.setProductId(productId); + goodsOrderCursor.setType(2l); + goodsOrderCursor.setNum(num.longValue()); + goodsOrderCursor.setSku(sku); - // 设置其他必要字段 + // 设置其他必要字段 // goodsOrderCursor.setCreatedAt(new Date()); // goodsOrderCursor.setUpdatedAt(new Date()); - // 计算价格(从SKU或商品价格) - BigDecimal totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); - if (sku != null && !sku.trim().isEmpty()) { - try { - JSONObject skuJson = JSONObject.parseObject(sku); - if (skuJson.containsKey("price")) { - String priceStr = skuJson.getString("price"); - try { - BigDecimal skuPrice = new BigDecimal(priceStr); - totalPrice = skuPrice.multiply(BigDecimal.valueOf(num)); - } catch (NumberFormatException e) { - // SKU价格解析失败,使用商品原价 - totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); - } + // 计算价格(从SKU或商品价格) + BigDecimal totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); + if (sku != null && !sku.trim().isEmpty()) { + try { + JSONObject skuJson = JSONObject.parseObject(sku); + if (skuJson.containsKey("price")) { + String priceStr = skuJson.getString("price"); + try { + BigDecimal skuPrice = new BigDecimal(priceStr); + totalPrice = skuPrice.multiply(BigDecimal.valueOf(num)); + } catch (NumberFormatException e) { + // SKU价格解析失败,使用商品原价 + totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); } - } catch (Exception e) { - // SKU解析失败,使用商品原价 - totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); } + } catch (Exception e) { + // SKU解析失败,使用商品原价 + totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); } - - goodsOrderCursor.setTotalPrice(totalPrice); - // goodsOrderCursor.setProductName(serviceGoods.getTitle()); - - // 9. 调用服务新增数据 - int result = goodsOrderCursorService.insertGoodsOrderCursor(goodsOrderCursor); - - if (result > 0) { - // 10. 返回商品ID - return success(goodsOrderCursor.getId()); - } else { - return error("数据保存失败"); - } - - } catch (Exception e) { - System.err.println("商品订单游标接口异常:" + e.getMessage()); - return error("操作失败:" + e.getMessage()); } - } + goodsOrderCursor.setTotalPrice(totalPrice); + // goodsOrderCursor.setProductName(serviceGoods.getTitle()); - /** - * 获取商品订单临时信息 - * - * @param id 订单临时ID - * @param request HTTP请求对象 - * @return 订单临时信息及关联商品信息 - *

- * 接口说明: - * - 根据ID查询商品订单临时数据 - * - 通过product_id关联查询商品信息 - * - 返回包含订单信息和商品详情的完整数据 - */ - @GetMapping(value = "/api/service/cursor/info/{id}") - public AjaxResult getGoodsOrderCursorInfo(@PathVariable("id") long id, HttpServletRequest request) { - try { - // 参数验证 - if (id <= 0) { - return AppletControllerUtil.appletError("订单ID无效"); - } + // 9. 调用服务新增数据 + int result = goodsOrderCursorService.insertGoodsOrderCursor(goodsOrderCursor); - // 1. 查询商品订单临时数据 - GoodsOrderCursor orderCursor = goodsOrderCursorService.selectGoodsOrderCursorById(id); - if (orderCursor == null) { - return AppletControllerUtil.appletError("订单信息不存在"); - } - - // 2. 根据product_id查询商品信息 - ServiceGoods product = null; - if (orderCursor.getProductId() != null) { - product = serviceGoodsService.selectServiceGoodsById(orderCursor.getProductId()); - } - - // 3. 构建返回数据 - Map responseData = new HashMap<>(); - - // 订单基本信息 - responseData.put("id", orderCursor.getId()); - responseData.put("product_id", orderCursor.getProductId()); - responseData.put("type", orderCursor.getType()); - responseData.put("num", orderCursor.getNum()); - responseData.put("sku", orderCursor.getSku()); - responseData.put("total_price", orderCursor.getTotalPrice() != null ? orderCursor.getTotalPrice().toString() : "0.00"); - responseData.put("postage", orderCursor.getPostage() != null ? orderCursor.getPostage().toString() : null); - responseData.put("created_at", AppletControllerUtil.formatDateToString(orderCursor.getCreatedAt())); - responseData.put("updated_at", AppletControllerUtil.formatDateToString(orderCursor.getUpdatedAt())); - - // 4. 添加商品信息 - if (product != null) { - Map productInfo = new HashMap<>(); - productInfo.put("id", product.getId()); - productInfo.put("title", product.getTitle()); - productInfo.put("price", product.getPrice() != null ? product.getPrice().toString() : "0.00"); - productInfo.put("stock", product.getStock()); - productInfo.put("sku_type", product.getSkuType()); - productInfo.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); - - responseData.put("product", productInfo); - } else { - // 商品不存在时的默认信息 - Map productInfo = new HashMap<>(); - productInfo.put("id", orderCursor.getProductId()); - productInfo.put("title", "商品已下架"); - productInfo.put("price", "0.00"); - productInfo.put("stock", 0); - productInfo.put("sku_type", 1); - productInfo.put("icon", ""); - - responseData.put("product", productInfo); - } - - return AppletControllerUtil.appletSuccess(responseData); - - } catch (Exception e) { - return AppletControllerUtil.appletError("查询订单信息失败:" + e.getMessage()); + if (result > 0) { + // 10. 返回商品ID + return success(goodsOrderCursor.getId()); + } else { + return error("数据保存失败"); } + + } catch (Exception e) { + System.err.println("商品订单游标接口异常:" + e.getMessage()); + return error("操作失败:" + e.getMessage()); } +} - /** - * 微信支付回调通知接口 - * - * @param request HTTP请求对象 - * @return XML格式的响应给微信服务器 - *

- * 接口说明: - * - 接收微信支付成功后的异步通知 - * - 验证签名确保数据安全性 - * - 处理支付成功后的业务逻辑 - * - 返回XML格式响应告知微信处理结果 - *

- * 微信支付回调特点: - * - 微信会POST XML数据到此接口 - * - 必须返回XML格式的成功/失败响应 - * - 如果返回失败,微信会重复发送通知 - * - 建议做幂等性处理,避免重复处理同一笔订单 - */ - @PostMapping(value = "/api/wechat/pay/notify") - public String handleWechatPayNotify(HttpServletRequest request) { - try { - // 记录回调日志(可选) - logger.info("收到微信支付回调通知,开始处理..."); - - // 1. 使用WechatPayUtil处理支付回调 - Map notifyResult = wechatPayUtil.handlePayNotify(request); - - // 2. 检查处理结果 - boolean success = (Boolean) notifyResult.get("success"); - String message = (String) notifyResult.get("message"); - - if (success) { - // 3. 获取支付信息 - Map paymentInfo = (Map) notifyResult.get("paymentInfo"); - - // 4. 处理支付成功的业务逻辑 - handlePaymentSuccessLogic(paymentInfo); - - // 5. 记录成功日志 - logger.info("微信支付回调处理成功:订单号={}, 微信交易号={}", - paymentInfo.get("outTradeNo"), paymentInfo.get("transactionId")); - - // 6. 返回成功响应给微信 - return buildSuccessResponse(); - - } else { - // 7. 处理失败情况 - logger.error("微信支付回调处理失败:{}", message); - - // 8. 返回失败响应给微信 - return buildFailResponse(message); - } - - } catch (Exception e) { - // 9. 异常处理 - logger.error("微信支付回调处理异常:", e); - - // 10. 返回异常响应给微信 - return buildFailResponse("处理异常:" + e.getMessage()); +/** + * 获取商品订单临时信息 + * + * @param id 订单临时ID + * @param request HTTP请求对象 + * @return 订单临时信息及关联商品信息 + *

+ * 接口说明: + * - 根据ID查询商品订单临时数据 + * - 通过product_id关联查询商品信息 + * - 返回包含订单信息和商品详情的完整数据 + */ +@GetMapping(value = "/api/service/cursor/info/{id}") +public AjaxResult getGoodsOrderCursorInfo(@PathVariable("id") long id, HttpServletRequest request) { + try { + // 参数验证 + if (id <= 0) { + return AppletControllerUtil.appletError("订单ID无效"); } - } - /** - * 处理支付成功后的业务逻辑 - * - * @param paymentInfo 支付信息 - */ - private void handlePaymentSuccessLogic(Map paymentInfo) { - try { - String outTradeNo = (String) paymentInfo.get("outTradeNo"); - String transactionId = (String) paymentInfo.get("transactionId"); - String totalFee = (String) paymentInfo.get("totalFee"); - String timeEnd = (String) paymentInfo.get("timeEnd"); - String attach = (String) paymentInfo.get("attach"); - String openid = (String) paymentInfo.get("openid"); - - logger.info("开始处理支付成功业务逻辑:订单号={}, 金额={}", outTradeNo, totalFee); - - // TODO: 根据实际业务需求实现以下逻辑 - // 1. 更新订单状态为已支付 - // 2. 记录支付流水 - // 3. 发送支付成功通知给用户 - // 4. 触发后续业务流程(如发货、服务安排等) - // 5. 更新库存(如果是商品订单) - - // 示例:如果是商品订单临时表的支付 - if (attach != null && attach.startsWith("cursor_order:")) { - String cursorOrderId = attach.replace("cursor_order:", ""); - // 可以在这里处理商品订单临时表的状态更新 - logger.info("处理商品订单临时表支付:ID={}", cursorOrderId); - } - - // 调用AppletControllerUtil的通用支付成功处理方法 - AppletControllerUtil.handlePaymentSuccess(paymentInfo, false); - - logger.info("支付成功业务逻辑处理完成:订单号={}", outTradeNo); - - } catch (Exception e) { - logger.error("处理支付成功业务逻辑异常:", e); - // 注意:即使业务逻辑处理失败,也应该向微信返回成功响应 - // 避免微信重复发送通知,可以通过日志或其他方式处理业务异常 + // 1. 查询商品订单临时数据 + GoodsOrderCursor orderCursor = goodsOrderCursorService.selectGoodsOrderCursorById(id); + if (orderCursor == null) { + return AppletControllerUtil.appletError("订单信息不存在"); } - } - /** - * 构建成功响应XML - */ - private String buildSuccessResponse() { - return "" + - "" + - "" + - ""; - } + // 2. 根据product_id查询商品信息 + ServiceGoods product = null; + if (orderCursor.getProductId() != null) { + product = serviceGoodsService.selectServiceGoodsById(orderCursor.getProductId()); + } - /** - * 构建失败响应XML - */ - private String buildFailResponse(String message) { - return "" + - "" + - "" + - ""; + // 3. 构建返回数据 + Map responseData = new HashMap<>(); + + // 订单基本信息 + responseData.put("id", orderCursor.getId()); + responseData.put("product_id", orderCursor.getProductId()); + responseData.put("type", orderCursor.getType()); + responseData.put("num", orderCursor.getNum()); + responseData.put("sku", orderCursor.getSku()); + responseData.put("total_price", orderCursor.getTotalPrice() != null ? orderCursor.getTotalPrice().toString() : "0.00"); + responseData.put("postage", orderCursor.getPostage() != null ? orderCursor.getPostage().toString() : null); + responseData.put("created_at", AppletControllerUtil.formatDateToString(orderCursor.getCreatedAt())); + responseData.put("updated_at", AppletControllerUtil.formatDateToString(orderCursor.getUpdatedAt())); + + // 4. 添加商品信息 + if (product != null) { + Map productInfo = new HashMap<>(); + productInfo.put("id", product.getId()); + productInfo.put("title", product.getTitle()); + productInfo.put("price", product.getPrice() != null ? product.getPrice().toString() : "0.00"); + productInfo.put("stock", product.getStock()); + productInfo.put("sku_type", product.getSkuType()); + productInfo.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); + + responseData.put("product", productInfo); + } else { + // 商品不存在时的默认信息 + Map productInfo = new HashMap<>(); + productInfo.put("id", orderCursor.getProductId()); + productInfo.put("title", "商品已下架"); + productInfo.put("price", "0.00"); + productInfo.put("stock", 0); + productInfo.put("sku_type", 1); + productInfo.put("icon", ""); + + responseData.put("product", productInfo); + } + + return AppletControllerUtil.appletSuccess(responseData); + + } catch (Exception e) { + return AppletControllerUtil.appletError("查询订单信息失败:" + e.getMessage()); } - /** - * 设置默认配置信息 - * - * @param configData 配置数据Map - */ - private void setDefaultConfig(Map configData) { - configData.put("phone", "02988256922"); - configData.put("loot_start", "00:59"); - configData.put("loot_end", "23:30"); - configData.put("margin", "10"); - configData.put("integral", "100"); - configData.put("hot", new String[]{"水电维修", "家电清洗", "灯具维修", "墙面翻新", "门窗家具", "改造维修", "防水维修"}); - configData.put("kf", ""); +} + + +/** + * 微信支付回调通知接口 + * + * @param request HTTP请求对象 + * @return XML格式的响应给微信服务器 + *

+ * 接口说明: + * - 接收微信支付成功后的异步通知 + * - 验证签名确保数据安全性 + * - 处理支付成功后的业务逻辑 + * - 返回XML格式响应告知微信处理结果 + *

+ * 微信支付回调特点: + * - 微信会POST XML数据到此接口 + * - 必须返回XML格式的成功/失败响应 + * - 如果返回失败,微信会重复发送通知 + * - 建议做幂等性处理,避免重复处理同一笔订单 + */ +@PostMapping(value = "/api/wechat/pay/notify") +public String handleWechatPayNotify(HttpServletRequest request) { + try { + // 记录回调日志(可选) + logger.info("收到微信支付回调通知,开始处理..."); + + // 1. 使用WechatPayUtil处理支付回调 + Map notifyResult = wechatPayUtil.handlePayNotify(request); + + // 2. 检查处理结果 + boolean success = (Boolean) notifyResult.get("success"); + String message = (String) notifyResult.get("message"); + + if (success) { + // 3. 获取支付信息 + Map paymentInfo = (Map) notifyResult.get("paymentInfo"); + + // 4. 处理支付成功的业务逻辑 + handlePaymentSuccessLogic(paymentInfo); + + // 5. 记录成功日志 + logger.info("微信支付回调处理成功:订单号={}, 微信交易号={}", + paymentInfo.get("outTradeNo"), paymentInfo.get("transactionId")); + + // 6. 返回成功响应给微信 + return buildSuccessResponse(); + + } else { + // 7. 处理失败情况 + logger.error("微信支付回调处理失败:{}", message); + + // 8. 返回失败响应给微信 + return buildFailResponse(message); + } + + } catch (Exception e) { + // 9. 异常处理 + logger.error("微信支付回调处理异常:", e); + + // 10. 返回异常响应给微信 + return buildFailResponse("处理异常:" + e.getMessage()); } +} + +/** + * 处理支付成功后的业务逻辑 + * + * @param paymentInfo 支付信息 + */ +private void handlePaymentSuccessLogic(Map paymentInfo) { + try { + String outTradeNo = (String) paymentInfo.get("outTradeNo"); + String transactionId = (String) paymentInfo.get("transactionId"); + String totalFee = (String) paymentInfo.get("totalFee"); + String timeEnd = (String) paymentInfo.get("timeEnd"); + String attach = (String) paymentInfo.get("attach"); + String openid = (String) paymentInfo.get("openid"); + + logger.info("开始处理支付成功业务逻辑:订单号={}, 金额={}", outTradeNo, totalFee); + + // TODO: 根据实际业务需求实现以下逻辑 + // 1. 更新订单状态为已支付 + // 2. 记录支付流水 + // 3. 发送支付成功通知给用户 + // 4. 触发后续业务流程(如发货、服务安排等) + // 5. 更新库存(如果是商品订单) + + // 示例:如果是商品订单临时表的支付 + if (attach != null && attach.startsWith("cursor_order:")) { + String cursorOrderId = attach.replace("cursor_order:", ""); + // 可以在这里处理商品订单临时表的状态更新 + logger.info("处理商品订单临时表支付:ID={}", cursorOrderId); + } + + // 调用AppletControllerUtil的通用支付成功处理方法 + AppletControllerUtil.handlePaymentSuccess(paymentInfo, false); + + logger.info("支付成功业务逻辑处理完成:订单号={}", outTradeNo); + + } catch (Exception e) { + logger.error("处理支付成功业务逻辑异常:", e); + // 注意:即使业务逻辑处理失败,也应该向微信返回成功响应 + // 避免微信重复发送通知,可以通过日志或其他方式处理业务异常 + } +} + +/** + * 构建成功响应XML + */ +private String buildSuccessResponse() { + return "" + + "" + + "" + + ""; +} + +/** + * 构建失败响应XML + */ +private String buildFailResponse(String message) { + return "" + + "" + + "" + + ""; +} + +/** + * 设置默认配置信息 + * + * @param configData 配置数据Map + */ +private void setDefaultConfig(Map configData) { + configData.put("phone", "02988256922"); + configData.put("loot_start", "00:59"); + configData.put("loot_end", "23:30"); + configData.put("margin", "10"); + configData.put("integral", "100"); + configData.put("hot", new String[]{"水电维修", "家电清洗", "灯具维修", "墙面翻新", "门窗家具", "改造维修", "防水维修"}); + configData.put("kf", ""); +} } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/PayNotifyController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/PayNotifyController.java index 144600a..25633a8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/PayNotifyController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/PayNotifyController.java @@ -71,6 +71,8 @@ public class PayNotifyController extends BaseController { @Autowired private IWorkerMarginLogService workerMarginLogService; + @Autowired + private IWorkerMoneyLogService workerMoneyLogService; /** * 商品支付回调接口 * @@ -406,7 +408,8 @@ public class PayNotifyController extends BaseController { // 7. 处理订单支付成功后的业务逻辑 handleOrderAmountPaymentSuccess(order, paymentInfo); - calculateCommissionMoney(order.getOrderId(), order.getUid(),order.getWorkerId()); + calculateCommissionAndRecord(order.getOrderId(),order.getWorkerId()); + //calculateCommissionMoney(order.getOrderId(), order.getUid(),order.getWorkerId()); logger.info("订单金额支付回调处理成功,订单号:{}", outTradeNo); return buildSuccessResponse(); @@ -835,60 +838,75 @@ public class PayNotifyController extends BaseController { - /** - * 分佣 - * - - * @return 商品标题 - */ - public Map calculateCommissionMoney(String orderId,long oid, Long workerId - ) { - // 结果 + public Map calculateCommissionAndRecord( + String orderId, + Long workerId + ) { Map result = new HashMap<>(); - BigDecimal totalPrice = BigDecimal.ZERO; - BigDecimal margin = BigDecimal.ZERO; - BigDecimal reduction = BigDecimal.ZERO; - BigDecimal servicePrice = BigDecimal.ZERO; - BigDecimal doorPrice = BigDecimal.ZERO; + BigDecimal totalCommission = BigDecimal.ZERO; // 师傅最终佣金 + BigDecimal margin = BigDecimal.ZERO; // 质保金 + BigDecimal reduction = BigDecimal.ZERO; // 优惠金额 + BigDecimal servicePrice = BigDecimal.ZERO; // 服务费用 + BigDecimal materialPrice = BigDecimal.ZERO; // 材料费用(如有可补充) + BigDecimal doorPrice = BigDecimal.ZERO; // 上门费 + BigDecimal cr = BigDecimal.ZERO; // 师傅等级分佣比例 - // 1. 查询订单日志 + logger.info("【分佣计算】开始计算,orderId={}, workerId={}", orderId, workerId); + + // 1. 查询订单日志(type=2,5,paid=2,give_up=null) OrderLog orderLogQuery = new OrderLog(); orderLogQuery.setOrderId(orderId); List orderLogList = orderLogService.selectOrderLogList(orderLogQuery); - //List orderLogList = orderLogService.selectOrderLogListByWorker(orderId, workerId); + logger.info("【分佣计算】查询订单日志完成,日志数量={}", orderLogList.size()); // 2. 查询订单和商品 - Order order = orderService.selectOrderById(oid); + Order order = orderService.selectOrderByOrderId(orderId); + logger.info("【分佣计算】查询订单完成,order={}", order != null ? order.getId() : null); ServiceGoods product = null; if (order != null && order.getProductId() != null) { product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); + logger.info("【分佣计算】查询商品完成,productId={}", product != null ? product.getId() : null); } // 3. 查询师傅信息 Users worker = usersService.selectUsersById(workerId); + logger.info("【分佣计算】查询师傅信息完成,worker={}", worker != null ? worker.getId() : null); - // 4. 计算佣金、上门费、优惠金额 + // 4. 计算各项费用 for (OrderLog log : orderLogList) { + logger.info("【分佣计算】处理日志,logId={}, type={}, workerCost={}, reductionPrice={}", + log.getId(), log.getType(), log.getWorkerCost(), log.getReductionPrice()); if (log.getType() != null && log.getType().intValue() == 5) { // type=5 评估报价 WorkerLevel levelInfo = workerLevelService.selectWorkerLevelByLevel(Long.valueOf(worker.getLevel())); - BigDecimal cr = (levelInfo != null && levelInfo.getCr() != null) ? new BigDecimal(levelInfo.getCr()).divide(new BigDecimal(100)) : BigDecimal.ZERO; - totalPrice = totalPrice.add(log.getWorkerCost().multiply(cr).setScale(2, BigDecimal.ROUND_HALF_UP)); + logger.info("【分佣计算】查询师傅等级,level={}, cr={}", worker.getLevel(), levelInfo != null ? levelInfo.getCr() : null); + if (levelInfo != null && levelInfo.getCr() != null) { + cr = new BigDecimal(levelInfo.getCr()).divide(new BigDecimal(100)); + } + // 师傅分佣 + BigDecimal commission = log.getWorkerCost().multiply(cr).setScale(2, BigDecimal.ROUND_HALF_UP); + totalCommission = totalCommission.add(commission); + logger.info("【分佣计算】type=5,分佣金额={}, 当前总佣金={}", commission, totalCommission); + // 服务费用 servicePrice = log.getWorkerCost().add(log.getReductionPrice() != null ? log.getReductionPrice() : BigDecimal.ZERO); + logger.info("【分佣计算】type=5,服务费用={}", servicePrice); } if (log.getType() != null && log.getType().intValue() == 2) { // type=2 上门费 - totalPrice = totalPrice.add(log.getWorkerCost()); + totalCommission = totalCommission.add(log.getWorkerCost()); doorPrice = log.getWorkerCost(); + logger.info("【分佣计算】type=2,上门费={}, 当前总佣金={}", doorPrice, totalCommission); } if (log.getReductionPrice() != null) { reduction = reduction.add(log.getReductionPrice()); + logger.info("【分佣计算】累计优惠金额={}", reduction); } } // 5. 判断是否需要扣除质保金 if (product != null && product.getMargin() != null && worker != null && worker.getMargin() != null && product.getMargin().compareTo(worker.getMargin()) > 0) { + logger.info("【分佣计算】需要扣除质保金,商品margin={}, 师傅margin={}", product.getMargin(), worker.getMargin()); // 查系统配置 SiteConfig config = siteConfigService.selectSiteConfigByName("config_one"); BigDecimal marginPercent = BigDecimal.ZERO; @@ -898,12 +916,16 @@ public class PayNotifyController extends BaseController { if (json.containsKey("margin")) { marginPercent = new BigDecimal(json.getString("margin")).divide(new BigDecimal(100)); } - } catch (Exception ignore) {} + } catch (Exception e) { + logger.error("【分佣计算】解析质保金配置异常", e); + } } - margin = totalPrice.multiply(marginPercent).setScale(2, BigDecimal.ROUND_HALF_UP); + margin = totalCommission.multiply(marginPercent).setScale(2, BigDecimal.ROUND_HALF_UP); + logger.info("【分佣计算】初步计算质保金={}, 配置比例={}", margin, marginPercent); // 超过质保金,则扣少点 if (worker.getMargin().add(margin).compareTo(product.getMargin()) > 0) { margin = product.getMargin().subtract(worker.getMargin()); + logger.info("【分佣计算】质保金超限,实际扣除={}", margin); } // 插入质保金明细 WorkerMarginLog marginLog = new WorkerMarginLog(); @@ -911,23 +933,166 @@ public class PayNotifyController extends BaseController { marginLog.setUid(workerId); marginLog.setOrderId(order != null ? order.getOrderId() : null); marginLog.setPrice(margin); -// marginLog.setCreatedAt(new Date()); -// marginLog.setUpdatedAt(new Date()); workerMarginLogService.insertWorkerMarginLog(marginLog); + logger.info("【分佣计算】插入质保金明细完成"); } - // 6. 返回 - result.put("commission", totalPrice); - result.put("margin", margin); - result.put("reduction", reduction); - result.put("service_price", servicePrice); - result.put("door_price", doorPrice); + // 6. 计算最终佣金 + BigDecimal finalCommission = totalCommission.subtract(margin); + logger.info("【分佣计算】最终佣金={}", finalCommission); + + // 7. 更新师傅账户(佣金、佣金总额、质保金) + if (worker != null) { + BigDecimal newCommission = (worker.getCommission() != null ? worker.getCommission() : BigDecimal.ZERO).add(finalCommission); + BigDecimal newTotalComm = (worker.getTotalComm() != null ? worker.getTotalComm() : BigDecimal.ZERO).add(finalCommission); + BigDecimal newMargin = (worker.getMargin() != null ? worker.getMargin() : BigDecimal.ZERO).add(margin); + + worker.setCommission(newCommission); + worker.setTotalComm(newTotalComm); + worker.setMargin(newMargin); + usersService.updateUsers(worker); + logger.info("【分佣计算】更新师傅账户完成,commission={}, total_comm={}, margin={}", newCommission, newTotalComm, newMargin); + } + + // 8. 插入师傅金额记录 + WorkerMoneyLog moneyLog = new WorkerMoneyLog(); + moneyLog.setWorkerId(workerId); + moneyLog.setOid(order.getId()); + moneyLog.setOrderId(order != null ? order.getOrderId() : null); + moneyLog.setPrice(finalCommission); + moneyLog.setType(1); // 1=收入 + moneyLog.setServicePrice(servicePrice); + moneyLog.setReductionPrice(reduction); + moneyLog.setCr(cr.multiply(new BigDecimal(100)).intValue()); // 百分比 + moneyLog.setMergin(margin); + moneyLog.setDoorPrice(doorPrice); + workerMoneyLogService.insertWorkerMoneyLog(moneyLog); + logger.info("【分佣计算】插入师傅金额记录完成"); + + // 9. 组装返回 + result.put("commission", finalCommission); // 师傅最终佣金 + result.put("margin", margin); // 质保金 + result.put("service_price", servicePrice); // 服务费用 + result.put("material_price", materialPrice); // 材料费用(如有可补充) + result.put("reduction", reduction); // 优惠金额 + result.put("door_price", doorPrice); // 上门费 + result.put("cr", cr); // 师傅分佣比例 + + // 10. 公式说明 + result.put("formula", "最终佣金 = (服务项目金额 * 师傅等级分佣比例 + 上门费) - 质保金\n" + + "质保金 = 总佣金 * 配置质保金比例,且不超过商品margin-师傅margin\n" + + "服务费用 = 评估报价worker_cost + reduction_price\n" + + "上门费 = type=2的worker_cost\n" + + "优惠金额 = 所有reduction_price之和"); + + logger.info("【分佣计算】计算结束,返回结果={}", result); return result; } + +// /** +// * 分佣 +// * +// +// * @return 商品标题 +// */ +// public Map calculateCommissionMoney(String orderId,long oid, Long workerId +// ) { +// // 结果 +// Map result = new HashMap<>(); +// BigDecimal totalPrice = BigDecimal.ZERO; +// BigDecimal margin = BigDecimal.ZERO; +// BigDecimal reduction = BigDecimal.ZERO; +// BigDecimal servicePrice = BigDecimal.ZERO; +// BigDecimal doorPrice = BigDecimal.ZERO; +// +// // 1. 查询订单日志 +// OrderLog orderLogQuery = new OrderLog(); +// orderLogQuery.setOrderId(orderId); +// List orderLogList = orderLogService.selectOrderLogList(orderLogQuery); +// //List orderLogList = orderLogService.selectOrderLogListByWorker(orderId, workerId); +// +// // 2. 查询订单和商品 +// Order order = orderService.selectOrderById(oid); +// ServiceGoods product = null; +// if (order != null && order.getProductId() != null) { +// product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); +// } +// +// // 3. 查询师傅信息 +// Users worker = usersService.selectUsersById(workerId); +// +// // 4. 计算佣金、上门费、优惠金额 +// for (OrderLog log : orderLogList) { +// BigDecimal workerCost =new BigDecimal(0); +// if (log.getWorkerCost() != null) { +// workerCost = log.getWorkerCost(); +// } +// if (log.getType() != null && log.getType().intValue() == 5) { +// // type=5 评估报价 +// WorkerLevel levelInfo = workerLevelService.selectWorkerLevelByLevel(Long.valueOf(worker.getLevel())); +// BigDecimal cr = (levelInfo != null && levelInfo.getCr() != null) ? new BigDecimal(levelInfo.getCr()).divide(new BigDecimal(100)) : BigDecimal.ZERO; +// totalPrice = totalPrice.add(workerCost.multiply(cr).setScale(2, BigDecimal.ROUND_HALF_UP)); +// servicePrice = workerCost.add(log.getReductionPrice() != null ? log.getReductionPrice() : BigDecimal.ZERO); +// } +// if (log.getType() != null && log.getType().intValue() == 2) { +// // type=2 上门费 +// totalPrice = totalPrice.add(log.getWorkerCost()); +// doorPrice = log.getWorkerCost(); +// } +// if (log.getReductionPrice() != null) { +// reduction = reduction.add(log.getReductionPrice()); +// } +// } +// +// // 5. 判断是否需要扣除质保金 +// if (product != null && product.getMargin() != null && worker != null && worker.getMargin() != null +// && product.getMargin().compareTo(worker.getMargin()) > 0) { +// // 查系统配置 +// SiteConfig config = siteConfigService.selectSiteConfigByName("config_one"); +// BigDecimal marginPercent = BigDecimal.ZERO; +// if (config != null && config.getValue() != null) { +// try { +// JSONObject json = JSONObject.parseObject(config.getValue()); +// if (json.containsKey("margin")) { +// marginPercent = new BigDecimal(json.getString("margin")).divide(new BigDecimal(100)); +// } +// } catch (Exception ignore) {} +// } +// margin = totalPrice.multiply(marginPercent).setScale(2, BigDecimal.ROUND_HALF_UP); +// // 超过质保金,则扣少点 +// if (worker.getMargin().add(margin).compareTo(product.getMargin()) > 0) { +// margin = product.getMargin().subtract(worker.getMargin()); +// } +// // 插入质保金明细 +// WorkerMarginLog marginLog = new WorkerMarginLog(); +// marginLog.setOid(order.getId()); +// marginLog.setUid(workerId); +// marginLog.setOrderId(order != null ? order.getOrderId() : null); +// marginLog.setPrice(margin); +//// marginLog.setCreatedAt(new Date()); +//// marginLog.setUpdatedAt(new Date()); +// workerMarginLogService.insertWorkerMarginLog(marginLog); +// //修改师傅质保金和分佣情况 +// worker.setCommission(totalPrice); +// // hpinnworkerzhe.setTotalComm(); +// } +// +// // 6. 返回 +// result.put("commission", totalPrice); +// result.put("margin", margin); +// result.put("reduction", reduction); +// result.put("service_price", servicePrice); +// result.put("door_price", doorPrice); +// return result; +// } + + + + /** * 获取商品标题 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/WXsendMsgUtil.java b/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/WXsendMsgUtil.java index a7a1e27..3b1acbd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/WXsendMsgUtil.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/WXsendMsgUtil.java @@ -68,6 +68,7 @@ public class WXsendMsgUtil { String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken(); ResponseEntity responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class); + System.out.println("0001responseEntity.getBody():" + responseEntity.getBody()); return responseEntity.getBody(); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/CouponUser.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/CouponUser.java index 6e4daf4..7b28868 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/CouponUser.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/CouponUser.java @@ -80,6 +80,10 @@ public class CouponUser extends BaseEntity @Excel(name = "1:未使用 2:已使用 3:已失效") private Long status; + private Boolean isUse; + private String suitTitle; + private String tag; + /** $column.columnComment */ @Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()") private Date createdAt; @@ -262,6 +266,30 @@ public class CouponUser extends BaseEntity this.uname = uname; } + public Boolean getIsUse() { + return isUse; + } + + public void setIsUse(Boolean isUse) { + this.isUse = isUse; + } + + public String getSuitTitle() { + return suitTitle; + } + + public void setSuitTitle(String suitTitle) { + this.suitTitle = suitTitle; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/CouponUserMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/CouponUserMapper.java index adea582..96d4cb7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/CouponUserMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/CouponUserMapper.java @@ -31,6 +31,10 @@ public interface CouponUserMapper */ public List selectCouponUserList(CouponUser couponUser); + public List selectCouponUserNoList(CouponUser couponUser); + + + /** * 新增优惠券领取记录 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/OrderLogMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/OrderLogMapper.java index 34919c6..4062e2d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/OrderLogMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/OrderLogMapper.java @@ -27,6 +27,8 @@ public interface OrderLogMapper */ public OrderLog selectDataTheFirstNew(Long oid); public int selectCountOrderLogByOrderId(String orderId); + public OrderLog selectOneByOidTypeWorkerIdPaid(OrderLog orderLog); + public List selectOrderLogByOrderId(String orderId); /** diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ICouponUserService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ICouponUserService.java index 9d529e3..94cb941 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/ICouponUserService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ICouponUserService.java @@ -36,6 +36,8 @@ public interface ICouponUserService */ public List selectCouponUserList(CouponUser couponUser); + public List selectCouponUserNoList(CouponUser couponUser); + /** * 新增优惠券领取记录 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/IOrderLogService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/IOrderLogService.java index 03917e6..9427c47 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/IOrderLogService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/IOrderLogService.java @@ -20,7 +20,7 @@ public interface IOrderLogService public OrderLog selectOrderLogById(Long id); - + public OrderLog selectOneByOidTypeWorkerIdPaid(OrderLog orderLog); /** * 查询最新一条日志记录 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/CouponUserServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/CouponUserServiceImpl.java index 5df5c58..9764172 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/CouponUserServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/CouponUserServiceImpl.java @@ -57,7 +57,10 @@ public class CouponUserServiceImpl implements ICouponUserService { return couponUserMapper.selectCouponUserList(couponUser); } + public List selectCouponUserNoList(CouponUser couponUser) { + return couponUserMapper.selectCouponUserNoList(couponUser); + } /** * 新增优惠券领取记录 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/OrderLogServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/OrderLogServiceImpl.java index 5c58599..3b325fb 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/OrderLogServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/OrderLogServiceImpl.java @@ -32,7 +32,9 @@ public class OrderLogServiceImpl implements IOrderLogService } - + public OrderLog selectOneByOidTypeWorkerIdPaid(OrderLog orderLog){ + return orderLogMapper.selectOneByOidTypeWorkerIdPaid(orderLog); + } /** * 查询最新一条日志记录 * diff --git a/ruoyi-system/src/main/resources/mapper/system/CouponUserMapper.xml b/ruoyi-system/src/main/resources/mapper/system/CouponUserMapper.xml index f13f9c5..6436ecd 100644 --- a/ruoyi-system/src/main/resources/mapper/system/CouponUserMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/CouponUserMapper.xml @@ -30,8 +30,19 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" select count(0) from coupon_user where coupon_id=#{couponId} + + @@ -61,6 +65,9 @@ and type = #{type} and sort = #{sort} and is_permanent = #{isPermanent} + + and type in (1,2) + and price BETWEEN #{priceMin} AND #{priceMax} diff --git a/ruoyi-system/src/main/resources/mapper/system/OrderLogMapper.xml b/ruoyi-system/src/main/resources/mapper/system/OrderLogMapper.xml index 99c8aa6..72c860a 100644 --- a/ruoyi-system/src/main/resources/mapper/system/OrderLogMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/OrderLogMapper.xml @@ -76,6 +76,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" where id = #{id} + + + + +