javacodeadmin/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppletController.java

6857 lines
314 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ruoyi.system.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.ControllerUtil.*;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.AppleDoMain.OrderApple;
import com.ruoyi.system.domain.AppleDoMain.AddressApple;
import com.ruoyi.system.service.*;
import com.winnerlook.model.VoiceResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import com.ruoyi.system.config.QiniuConfig;
import com.ruoyi.system.utils.QiniuUploadUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.WechatTransfer;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.system.domain.QuoteCraft;
import com.ruoyi.system.domain.QuoteType;
import com.ruoyi.system.domain.QuoteMaterialType;
import com.ruoyi.system.domain.QuoteMaterial;
/**
* 小程序控制器
* <p>
* 提供小程序端所需的API接口
* 主要功能:
* 1. 服务分类管理
* 2. 服务商品列表和详情
* 3. 广告图片获取
* 4. 配置信息查询
* 5. 用户信息验证
*
* @author Mr. Zhang Pan
* @version 1.0
* @date 2025-05-26
*/
@RestController
public class AppletController extends BaseController {
@Autowired
private IServiceCateService serviceCateService;
@Autowired
private IUsersService usersService;
@Autowired
private ISiteConfigService siteConfigService;
@Autowired
private IAdvImgService advImgService;
@Autowired
private IServiceGoodsService serviceGoodsService;
@Autowired
private IUserAddressService userAddressService;
@Autowired
private IOrderService orderService;
@Autowired
private IOrderReworkService orderReworkService;
@Autowired
private ICooperateService cooperateService;
@Autowired
private ICouponUserService couponUserService;
@Autowired
private IIntegralLogService integralLogService;
@Autowired
private IIntegralOrderService integralOrderService;
@Autowired
private IIntegralProductService integralProductService;
@Autowired
private IIntegralOrderLogService integralOrderLogService;
@Autowired
private IIntegralCateService integralCateService;
@Autowired
private IOrderLogService orderLogService;
@Autowired
private IDiyCityService diyCityService;
@Autowired
private ISiteSkillService siteSkillService;
@Autowired
private QiniuConfig qiniuConfig;
@Autowired
private IGoodsCartService goodsCartService;
@Autowired
private IGoodsOrderService goodsOrderService;
@Autowired
private ICouponsService couponsService;
@Autowired
private IWorkerSignService workerSignService;
@Autowired
private IWorkerLevelService workerLevelService;
@Autowired
private IOrderCommentService orderCommentService;
@Autowired
private IWorkerMarginLogService workerMarginLogService;
@Autowired
private IWorkerMoneyLogService workerMoneyLogService;
@Autowired
private IWechatTransferService wechatTransferService;
@Autowired
private IQuoteCraftService quoteCraftService;
@Autowired
private IQuoteTypeService quoteTypeService;
@Autowired
private IQuoteMaterialTypeService quoteMaterialTypeService;
@Autowired
private IQuoteMaterialService quoteMaterialService;
@Autowired
private WechatPayUtil wechatPayUtil;
@Autowired
private IGoodsOrderCursorService goodsOrderCursorService;
@Autowired
private IWorkerApplyService workerApplyService;
@Autowired
private IUserMemberRechargeProgramService userMemberRechargeProgramService;
@Autowired
private IUserMemberRechargeLogService userMemberRechargeLogService;
@Autowired
private IUserMemnerConsumptionLogService userMemnerConsumptionLogService;
@Autowired
private IUsersInvoiceInfoService usersInvoiceInfoService;
@Autowired
private IUserGroupBuyingService userGroupBuyingService;
/**
* 获取服务分类列表
*
* @param request HTTP请求对象
* @return 分类列表数据
* <p>
* 接口说明:
* - 获取状态为启用的服务分类
* - 自动添加图片CDN前缀
* - 支持用户登录状态验证
*/
@GetMapping(value = "/api/service/cate")
public AjaxResult getInfo(HttpServletRequest request) {
try {
// 验证用户登录状态(可选)
Map<String, Object> userData = AppletControllerUtil.getUserData(request.getHeader("token"), usersService);
// 构建查询条件:状态启用且类型为服务
ServiceCate serviceCateQuery = new ServiceCate();
serviceCateQuery.setStatus(1L); // 启用状态
// serviceCateQuery.setType(1L); // 服务类型
// 查询分类列表
List<ServiceCate> categoryList = serviceCateService.selectServiceCateList(serviceCateQuery);
// 为每个分类添加CDN前缀
for (ServiceCate category : categoryList) {
category.setIcon(AppletControllerUtil.buildImageUrl(category.getIcon()));
}
return AppletControllerUtil.appletSuccess(categoryList);
} catch (Exception e) {
return AppletControllerUtil.appletError("获取服务分类列表失败:" + e.getMessage());
}
}
/**
* 获取系统配置信息
*
* @param name 配置项名称
* @param request HTTP请求对象
* @return 配置信息数据
* <p>
* 接口说明:
* - 根据配置名称获取对应的配置值
* - 配置值以JSON格式返回
* - 支持动态配置管理
*/
@GetMapping(value = "/api/public/config/{name}")
public AjaxResult config(@PathVariable("name") String name, HttpServletRequest request) {
try {
// 参数验证
if (name == null || name.trim().isEmpty()) {
return AppletControllerUtil.appletWarning("配置名称不能为空");
}
// 构建查询条件
SiteConfig configQuery = new SiteConfig();
configQuery.setName(name.trim());
// 查询配置列表
List<SiteConfig> configList = siteConfigService.selectSiteConfigList(configQuery);
if (!configList.isEmpty()) {
// 解析配置值为JSON对象
String configValue = configList.get(0).getValue();
if (configValue != null && !configValue.trim().isEmpty()) {
JSONObject jsonObject = JSONObject.parseObject(configValue);
return AppletControllerUtil.appletSuccess(jsonObject);
} else {
return AppletControllerUtil.appletWarning("配置值为空");
}
} else {
return AppletControllerUtil.appletWarning("未找到指定的配置项:" + name);
}
} catch (Exception e) {
return AppletControllerUtil.appletError("获取配置信息失败:" + e.getMessage());
}
}
/**
* 获取默认配置信息
*
* @param request HTTP请求对象
* @return 返回config_one配置的JSON对象
* <p>
* 功能说明:
* - 获取名为"config_one"的系统配置
* - 将配置值解析为JSON对象并返回
* - 用于小程序获取基础配置信息
*/
@GetMapping(value = "/api/public/get/config")
public AjaxResult getconfig(HttpServletRequest request) {
try {
SiteConfig configQuery = new SiteConfig();
configQuery.setName("config_one");
List<SiteConfig> list = siteConfigService.selectSiteConfigList(configQuery);
if (list != null && !list.isEmpty()) {
JSONObject jsonObject = JSONObject.parseObject(list.get(0).getValue());
return AppletControllerUtil.appletSuccess(jsonObject);
} else {
return AppletControllerUtil.appletWarning("未找到默认配置信息");
}
} catch (Exception e) {
return AppletControllerUtil.appletError("获取配置信息失败:" + e.getMessage());
}
}
/**
* 查询用户收货地址列表
*
* @param limit 每页显示数量
* @param page 页码
* @param request HTTP请求对象
* @return 分页地址列表
* <p>
* 请求参数:
* - limit: 每页显示数量默认15
* - page: 页码默认1
* <p>
*/
@GetMapping("/api/user/address/list")
public AjaxResult getaddresslist(
@RequestParam(value = "limit", defaultValue = "15") int limit,
@RequestParam(value = "page", defaultValue = "1") int page,
HttpServletRequest request) {
try {
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 设置分页参数
PageHelper.startPage(page, limit);
// 5. 查询用户地址列表
UserAddress userAddressQuery = new UserAddress();
userAddressQuery.setUid(user.getId());
List<UserAddress> addressList = userAddressService.selectUserAddressList(userAddressQuery);
// 6. 获取分页信息并构建响应
TableDataInfo tableDataInfo = getDataTable(addressList);
// 7. 构建符合要求的分页响应格式
Map<String, Object> pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit);
return AppletControllerUtil.appletSuccess(pageData);
} catch (Exception e) {
System.err.println("查询用户地址列表异常:" + e.getMessage());
return AppletControllerUtil.appletError("查询地址列表失败:" + e.getMessage());
}
}
/**
* 根据地址ID查询用户收货地址详情
*
* @param id 地址ID
* @param request HTTP请求对象
* @return 地址详细信息
* <p>
* 接口说明:
* - 根据地址ID获取单个地址的详细信息
* - 验证用户登录状态和地址归属权
* - 返回AddressApple格式的地址数据用于前端修改页面
* <p>
*/
@GetMapping("/api/user/address/info/{id}")
public AjaxResult getAddressInfo(@PathVariable("id") Long id, HttpServletRequest request) {
try {
// 1. 参数验证
if (id == null || id <= 0) {
return AppletControllerUtil.appletWarning("地址ID无效");
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 查询地址信息
UserAddress userAddress = userAddressService.selectUserAddressById(id);
if (userAddress == null) {
return AppletControllerUtil.appletWarning("地址不存在");
}
// 5. 验证地址归属权
if (!userAddress.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("无权访问该地址信息");
}
// 6. 转换为AddressApple格式并返回
AddressApple addressApple = AddressApple.fromUserAddress(userAddress);
return AppletControllerUtil.appletSuccess(addressApple);
} catch (Exception e) {
System.err.println("查询用户地址详情异常:" + e.getMessage());
return AppletControllerUtil.appletError("查询地址详情失败:" + e.getMessage());
}
}
/**
* 修改用户收货地址
*
* @param params 地址修改参数
* @param request HTTP请求对象
* @return 修改结果
* 接口说明:
* - 验证用户登录状态和地址归属权
* - 支持修改地址的所有字段
* - 自动处理默认地址逻辑(设为默认时会取消其他默认地址)
* - 返回修改后的地址信息
*/
@PostMapping("/api/user/address/edit")
public AjaxResult editAddress(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 参数验证
if (params == null || params.get("id") == null) {
return AppletControllerUtil.appletWarning("地址ID不能为空");
}
Long addressId;
try {
addressId = Long.valueOf(params.get("id").toString());
if (addressId <= 0) {
return AppletControllerUtil.appletWarning("地址ID无效");
}
} catch (NumberFormatException e) {
return AppletControllerUtil.appletWarning("地址ID格式错误");
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 查询原地址信息并验证归属权
UserAddress existingAddress = userAddressService.selectUserAddressById(addressId);
if (existingAddress == null) {
return AppletControllerUtil.appletWarning("地址不存在");
}
if (!existingAddress.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("无权修改该地址");
}
// 5. 构建更新的地址对象
UserAddress updateAddress = AppletControllerUtil.buildUpdateAddress(params, addressId, user.getId());
// 6. 验证必填字段
String validationResult = AppletControllerUtil.validateAddressParams(updateAddress);
if (validationResult != null) {
return AppletControllerUtil.appletWarning(validationResult);
}
// 7. 处理默认地址逻辑
if (updateAddress.getIsDefault() != null && updateAddress.getIsDefault() == 1L) {
// 如果设置为默认地址,先将该用户的所有地址设为非默认
userAddressService.updateUserAddressDefault(user.getId());
}
// 8. 执行地址更新
int updateResult = userAddressService.updateUserAddress(updateAddress);
if (updateResult > 0) {
return AppletControllerUtil.appletSuccess("地址修改成功");
} else {
return AppletControllerUtil.appletWarning("地址修改失败");
}
} catch (Exception e) {
System.err.println("修改用户地址异常:" + e.getMessage());
return AppletControllerUtil.appletError("修改地址失败:" + e.getMessage());
}
}
/**
* 新增用户收货地址
*
* @param params 地址新增参数
* @param request HTTP请求对象
* @return 新增结果
* 接口说明:
* - 验证用户登录状态
* - 支持新增地址的所有字段
* - 自动处理默认地址逻辑(设为默认时会取消其他默认地址)
* - 返回新增后的地址信息
*/
@PostMapping("/api/user/address/add")
public AjaxResult addAddress(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 构建新增的地址对象
UserAddress newAddress = AppletControllerUtil.buildNewAddress(params, user.getId());
// 4. 验证必填字段
String validationResult = AppletControllerUtil.validateAddressParams(newAddress);
if (validationResult != null) {
return AppletControllerUtil.appletWarning(validationResult);
}
// 5. 处理默认地址逻辑
if (newAddress.getIsDefault() != null && newAddress.getIsDefault() == 1L) {
// 如果设置为默认地址,先将该用户的所有地址设为非默认
userAddressService.updateUserAddressDefault(user.getId());
}
// 6. 执行地址新增
int insertResult = userAddressService.insertUserAddress(newAddress);
if (insertResult > 0) {
return AppletControllerUtil.appletSuccess("地址新增成功");
} else {
return AppletControllerUtil.appletWarning("地址新增失败");
}
} catch (Exception e) {
System.err.println("新增用户地址异常:" + e.getMessage());
return AppletControllerUtil.appletError("新增地址失败:" + e.getMessage());
}
}
/**
* 售后返修申请接口
*
* @param params 请求参数 包含order_id(订单ID)、phone(联系电话)、mark(返修原因备注)
* @param request HTTP请求对象
* @return 返修申请结果
* <p>
* 功能说明:
* - 验证用户登录状态和订单归属权
* - 检查订单状态是否允许申请售后
* - 处理售后返修申请逻辑
* - 更新订单状态为售后处理中
* - 记录返修申请信息和联系方式
* <p>
* 请求参数:
* - order_id: 订单ID
* - phone: 联系电话
* - mark: 返修原因备注
*/
@PostMapping("/api/service/order/rework")
public AjaxResult serviceOrderRework(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 参数验证
if (params == null) {
return AppletControllerUtil.appletWarning("请求参数不能为空");
}
String orderId = (String) params.get("order_id");
String phone = (String) params.get("phone");
String mark = (String) params.get("mark");
if (StringUtils.isEmpty(orderId)) {
return AppletControllerUtil.appletWarning("订单ID不能为空");
}
if (StringUtils.isEmpty(phone)) {
return AppletControllerUtil.appletWarning("联系电话不能为空");
}
// 验证手机号格式
if (!phone.matches("^1[3-9]\\d{9}$")) {
return AppletControllerUtil.appletWarning("联系电话格式不正确");
}
if (StringUtils.isEmpty(mark)) {
return AppletControllerUtil.appletWarning("返修原因不能为空");
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 3. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 4. 查询订单信息并验证归属权
Order order = orderService.selectOrderByOrderId(orderId);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
if (!order.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("无权操作此订单");
}
// 5. 验证订单状态是否允许申请售后
if (!AppletControllerUtil.isOrderAllowRework(order.getStatus())) {
return AppletControllerUtil.appletWarning("当前订单状态不允许申请售后");
}
// 6. 处理售后返修申请
boolean reworkResult = AppletControllerUtil.processReworkApplication(order, phone, mark, user, orderReworkService, orderService);
if (reworkResult) {
return AppletControllerUtil.appletSuccess("售后返修申请已提交,我们会尽快联系您处理");
} else {
return AppletControllerUtil.appletWarning("售后申请提交失败,请稍后重试");
}
} catch (Exception e) {
System.err.println("售后返修申请异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("售后申请失败:" + e.getMessage());
}
}
/**
* 获取用户服务订单列表
*
* @param params 请求参数 包含page(页码)、limit(每页数量)、status(订单状态)
* @param request HTTP请求对象
* @return 返回分页的服务订单列表
* <p>
* 功能说明:
* - 获取当前登录用户的服务类订单(type=1)
* - 支持按订单状态筛选
* - 返回带分页信息的订单列表
* - 自动填充商品信息(标题、图标、价格等)
*/
@PostMapping("api/service/order/lst")
public AjaxResult getserviceorderlst(@RequestBody Map<String, Object> params,
HttpServletRequest request) {
int page = (int) params.get("page");
int limit = (int) params.get("limit");
String status = (String) params.get("status");
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 3. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 4. 设置分页参数
PageHelper.startPage(page, limit);
// 5. 查询用户地址列表
OrderApple order = new OrderApple();
// order.setType(1);
order.setUid(user.getId());
if (StringUtils.isNotNull(status) && !"".equals(status)) {
order.setStatus(Long.valueOf(status));
}
List<OrderApple> orderList = orderService.selectOrderAppleList(order);
for (OrderApple orderdata : orderList) {
Map<String, Object> jsonObject = new HashMap<>();
if (orderdata.getProduct_id() != null) {
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(orderdata.getProduct_id());
if (serviceGoods != null) {
jsonObject.put("title", serviceGoods.getTitle());
jsonObject.put("icon", "https://img.huafurenjia.cn/" + serviceGoods.getIcon());
jsonObject.put("id", serviceGoods.getId());
jsonObject.put("price_zn", serviceGoods.getPriceZn());
jsonObject.put("sub_title", serviceGoods.getSubTitle());
orderdata.setProduct(jsonObject);
}
}
}
// 6. 获取分页信息并构建响应
TableDataInfo tableDataInfo = getDataTable(orderList);
// 7. 构建符合要求的分页响应格式
Map<String, Object> pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit);
return AppletControllerUtil.appletSuccess(pageData);
}
/**
* 获取用户商品订单列表
*
* @param params 请求参数 包含page(页码)、limit(每页数量)、status(订单状态)
* @param request HTTP请求对象
* @return 返回分页的商品订单列表
* <p>
* 功能说明:
* - 获取当前登录用户的商品类订单
* - 支持按订单状态筛选
* - 返回带分页信息的订单列表
* - 包含完整的商品信息和订单状态文本
*/
@PostMapping("/api/goods/order/lst")
public AjaxResult getgoodsorderlst(@RequestBody Map<String, Object> params,
HttpServletRequest request) {
try {
int page = (int) params.get("page");
int limit = (int) params.get("limit");
String status = (String) params.get("status");
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 设置分页参数
PageHelper.startPage(page, limit);
// 5. 构建查询条件
GoodsOrder queryOrder = new GoodsOrder();
queryOrder.setUid(user.getId());
if (StringUtils.isNotNull(status) && !"".equals(status)) {
queryOrder.setStatus(Long.valueOf(status));
}
// 6. 查询商品订单列表
List<GoodsOrder> orderList = goodsOrderService.selectGoodsOrderList(queryOrder);
// 7. 为每个订单填充商品信息
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (GoodsOrder order : orderList) {
Map<String, Object> orderData = new HashMap<>();
// 订单基本信息
orderData.put("id", order.getId());
orderData.put("order_id", order.getOrderId());
orderData.put("order_no", order.getOrderId()); // 小程序常用字段
orderData.put("status", order.getStatus());
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) {
orderData.put("sku", order.getSku());
} else {
orderData.put("sku", null);
}
// 时间字段格式化
if (order.getPayTime() != null) {
orderData.put("pay_time", sdf.format(order.getPayTime()));
} else {
orderData.put("pay_time", null);
}
if (order.getCreatedAt() != null) {
orderData.put("created_at", sdf.format(order.getCreatedAt()));
} else {
orderData.put("created_at", null);
}
// 查询并添加商品详细信息
if (order.getProductId() != null) {
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (serviceGoods != null) {
Map<String, Object> productInfo = new HashMap<>();
productInfo.put("id", serviceGoods.getId());
productInfo.put("title", serviceGoods.getTitle());
productInfo.put("sub_title", serviceGoods.getSubTitle());
productInfo.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon()));
productInfo.put("price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00");
productInfo.put("num", order.getNum());
orderData.put("product", productInfo);
}
}
resultList.add(orderData);
}
// 8. 构建分页信息
PageInfo<GoodsOrder> pageInfo = new PageInfo<>(orderList);
// 9. 构建返回数据格式(简化版本,更适合小程序)
Map<String, Object> responseData = new HashMap<>();
responseData.put("current_page", pageInfo.getPageNum());
responseData.put("data", resultList);
responseData.put("total", pageInfo.getTotal());
responseData.put("per_page", pageInfo.getPageSize());
responseData.put("last_page", pageInfo.getPages());
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
System.err.println("查询商品订单列表异常:" + e.getMessage());
return AppletControllerUtil.appletError("查询商品订单列表失败:" + e.getMessage());
}
}
/**
* 获取订单状态文本
*
* @param status 订单状态
* @return 状态文本
*/
private String getOrderStatusText(Long status) {
if (status == null) {
return "未知状态";
}
switch (status.intValue()) {
case 1:
return "待付款";
case 2:
return "待发货";
case 3:
return "待收货";
case 4:
return "待评价";
case 5:
return "已完成";
case 6:
return "已取消";
case 7:
return "售后中";
case 8:
return "已退款";
default:
return "未知状态";
}
}
/**
* 用户登录验证接口
*
* @param request HTTP请求对象
* @return 返回用户信息或错误信息
* <p>
* 功能说明:
* - 通过请求头中的token验证用户身份
* - 查询用户基本信息并返回
* - 设置remember_token字段用于前端使用
*/
@PostMapping(value = "/api/user/login")
public AjaxResult getuserlogin(HttpServletRequest request) {
String token = request.getHeader("token");
Users users = usersService.selectUsersByRememberToken(token);
if (users != null) {
users.setRemember_token(users.getRememberToken());
return AppletControllerUtil.appletSuccess(users);
} else {
return AppletControllerUtil.appletWarning("用户不存在");
}
}
/**
* 获取服务商品列表
* 前端参数格式:{cate_id: 18, keywords:"dfffff"}
* 返回格式:按分类分组的商品列表
*/
@PostMapping(value = "/api/service/lst")
public AjaxResult getServiceGoodsList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
Long cateId = null;
String keywords = null;
// 处理分类ID参数
if (params.get("cate_id") != null) {
Object cateIdObj = params.get("cate_id");
if (cateIdObj instanceof Integer) {
cateId = ((Integer) cateIdObj).longValue();
} else if (cateIdObj instanceof String) {
try {
cateId = Long.parseLong((String) cateIdObj);
} catch (NumberFormatException e) {
return AppletControllerUtil.appletWarning("分类ID格式错误");
}
}
}
// 处理关键词参数
if (params.get("keywords") != null) {
keywords = params.get("keywords").toString().trim();
if (keywords.isEmpty()) {
keywords = null;
}
}
// 构建返回数据结构
List<Map<String, Object>> resultList = new ArrayList<>();
if (cateId != null) {
// 查询指定分类
ServiceCate category = serviceCateService.selectServiceCateById(cateId);
if (category != null) {
Map<String, Object> categoryData = AppletControllerUtil.buildCategoryData(category, keywords, serviceGoodsService);
resultList.add(categoryData);
}
} else {
// 查询所有分类
ServiceCate serviceCateQuery = new ServiceCate();
serviceCateQuery.setStatus(1L);
serviceCateQuery.setType(1L);
List<ServiceCate> categories = serviceCateService.selectServiceCateList(serviceCateQuery);
for (ServiceCate category : categories) {
Map<String, Object> categoryData = AppletControllerUtil.buildCategoryData(category, keywords, serviceGoodsService);
// 只返回有商品的分类
List<Map<String, Object>> goods = (List<Map<String, Object>>) categoryData.get("goods");
if (!goods.isEmpty()) {
resultList.add(categoryData);
}
}
}
return AppletControllerUtil.appletSuccess(resultList);
} catch (Exception e) {
return AppletControllerUtil.appletWarning("查询服务商品列表失败:" + e.getMessage());
}
}
/**
* 获取服务商品详细信息
*
* @param id 商品ID
* @param request HTTP请求对象
* @return 商品详细信息
* <p>
* 接口说明:
* - 根据商品ID获取详细信息
* - type=1时返回ServiceGoodsResponse格式
* - type=2时返回json.txt中的商品格式
* - 包含图片、基础信息等数组数据
*/
@GetMapping(value = "/api/service/info/id/{id}")
public AjaxResult serviceGoodsQuery(@PathVariable("id") long id, HttpServletRequest request) {
try {
// 参数验证
if (id <= 0) {
return AppletControllerUtil.appletError("商品ID无效");
}
// 查询商品信息
ServiceGoods serviceGoodsData = serviceGoodsService.selectServiceGoodsById(id);
if (serviceGoodsData == null) {
return AppletControllerUtil.appletError("商品不存在或已下架");
}
// 根据商品类型返回不同格式的数据
if (serviceGoodsData.getType() != null && serviceGoodsData.getType().intValue() == 2) {
// type=2时返回json.txt格式
Map<String, Object> goodsData = AppletControllerUtil.buildType2ServiceGoodsResponse(serviceGoodsData);
return AppletControllerUtil.appletSuccess(goodsData);
} else {
// type=1时返回ServiceGoodsResponse格式
AppletControllerUtil.ServiceGoodsResponse response = new AppletControllerUtil.ServiceGoodsResponse(serviceGoodsData);
return AppletControllerUtil.appletSuccess(response);
}
} catch (Exception e) {
return AppletControllerUtil.appletError("查询商品详情失败:" + e.getMessage());
}
}
/**
* 获取广告图片列表
*
* @param type 广告类型
* @param request HTTP请求对象
* @return 广告图片列表
* <p>
* 接口说明:
* - 根据广告类型获取对应的图片列表
* - 自动添加图片CDN前缀
* - 支持多种广告位配置
*/
@GetMapping(value = "/api/public/adv/lst/{type}")
public AjaxResult getAdvImgData(@PathVariable("type") long type, HttpServletRequest request) {
try {
// 参数验证
if (type < 0) {
return AppletControllerUtil.appletWarning("广告类型无效");
}
// 构建查询条件
AdvImg advImgQuery = new AdvImg();
advImgQuery.setType(type);
// 查询广告图片列表
List<AdvImg> advImgList = advImgService.selectAdvImgList(advImgQuery);
// 为每张图片添加CDN前缀
for (AdvImg advImg : advImgList) {
advImg.setImage(AppletControllerUtil.buildImageUrl(advImg.getImage()));
}
return AppletControllerUtil.appletSuccess(advImgList);
} catch (Exception e) {
return AppletControllerUtil.appletWarning("获取广告图片失败:" + e.getMessage());
}
}
/**
* 微信用户登录接口
*
* @param params 请求参数
* @param request HTTP请求对象
* @return 登录结果
* 登录流程:
* 1. 验证请求参数
* 2. 通过usercode获取微信openid
* 3. 检查用户是否已存在通过openid
* 4. 如果用户存在,直接返回用户信息
* 5. 如果用户不存在,获取手机号并创建/更新用户
*/
@PostMapping(value = "/api/user/phone/login")
public AjaxResult wechatLogin(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 使用AppletLoginUtil执行完整的微信登录流程
return AppletLoginUtil.executeWechatLogin(params, usersService);
}
/**
* 获取用户基本信息接口
*
* @param request HTTP请求对象
* @return 用户基本信息
* <p>
* 接口说明:
* - 通过token获取当前登录用户的基本信息
* - 返回完整的用户数据
* - 需要用户登录验证
* <p>
*/
@GetMapping(value = "/api/user/info")
public AjaxResult getUserInfo(HttpServletRequest request) {
try {
Map<String, Object> order_num = new HashMap<>();
Map<String, Object> goods_order_num = new HashMap<>();
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 构建用户信息响应数据
Map<String, Object> userInfo = buildUserInfoResponse(user);
userInfo.put("remember_token", userInfo.get("rememberToken"));
order_num.put("pending_accept", orderService.selectCountOrderByUid(user.getId(), 2L));
order_num.put("pending_service", orderService.selectCountOrderByUid(user.getId(), 3L));
order_num.put("in_service", orderService.selectCountOrderByUid(user.getId(), 4L));
order_num.put("other_status", orderService.selectAllCountOrderByUid(user.getId()));
userInfo.put("order_num", order_num);
goods_order_num.put("pending_accept", goodsOrderService.selectCountGoodsOrderByUid(user.getId(), 2L));
goods_order_num.put("pending_service", goodsOrderService.selectCountGoodsOrderByUid(user.getId(), 3L));
goods_order_num.put("in_service", goodsOrderService.selectCountGoodsOrderByUid(user.getId(), 5L));
goods_order_num.put("other_status", goodsOrderService.selectAllCountGoodsOrderByUid(user.getId()));
userInfo.put("goods_order_num", goods_order_num);
// 新增tx_time字段
List<Object> txTimeArr = new ArrayList<>();
try {
SiteConfig configQuery = new SiteConfig();
configQuery.setName("config_four");
List<SiteConfig> configList = siteConfigService.selectSiteConfigList(configQuery);
if (configList != null && !configList.isEmpty()) {
String configValue = configList.get(0).getValue();
if (configValue != null && !configValue.trim().isEmpty()) {
JSONObject json = JSONObject.parse(configValue);
if (json.containsKey("time")) {
Object timeObj = json.get("time");
if (timeObj instanceof List) {
txTimeArr = (List<Object>) timeObj;
} else if (timeObj instanceof JSONArray) {
txTimeArr = ((JSONArray) timeObj).toJavaList(Object.class);
}
}
}
}
} catch (Exception ignore) {
}
userInfo.put("tx_time", txTimeArr);
return AppletControllerUtil.appletSuccess(userInfo);
} catch (Exception e) {
System.err.println("查询用户基本信息异常:" + e.getMessage());
return AppletControllerUtil.appletError("查询用户信息失败:" + e.getMessage());
}
}
/**
* 构建用户信息响应数据
*
* @param user 用户实体
* @return 格式化的用户信息
*/
private Map<String, Object> buildUserInfoResponse(Users user) {
Map<String, Object> userInfo = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 基本信息
userInfo.put("id", user.getId());
userInfo.put("name", user.getName());
userInfo.put("nickname", user.getNickname());
userInfo.put("phone", user.getPhone());
userInfo.put("password", null); // 密码不返回
// 头像处理
String avatar = user.getAvatar();
if (avatar != null && !avatar.isEmpty()) {
userInfo.put("avatar", AppletControllerUtil.buildImageUrl(avatar));
} else {
userInfo.put("avatar", "https://img.huafurenjia.cn/default/user_avatar.jpeg");
}
// 其他业务字段
//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");
}
if (user.getType().equals("1")) {
userInfo.put("balance", user.getBalance().toString() != null ? user.getBalance().toString() : "0.00");
userInfo.put("ismember", user.getIsmember());
userInfo.put("member_begin",user.getMemberBegin() != null ? sdf.format(user.getMemberBegin()) : null );
userInfo.put("member_end",user.getMemberEnd() != null ? sdf.format(user.getMemberEnd()) : null );
}
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());
userInfo.put("level", user.getLevel());
userInfo.put("login_status", user.getLoginStatus() != null ? user.getLoginStatus() : 2);
userInfo.put("margin", user.getMargin() != null ? user.getMargin() : 0);
userInfo.put("middle_auth", user.getMiddleAuth());
userInfo.put("openid", user.getOpenid());
userInfo.put("prohibit_time", user.getProhibitTime());
userInfo.put("prohibit_time_str", null);
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_integral", user.getTotalIntegral() != null ? user.getTotalIntegral() : 100);
userInfo.put("type", user.getType() != null ? user.getType().toString() : "1");
userInfo.put("worker_time", user.getWorkerTime());
// 时间字段格式化
if (user.getCreatedAt() != null) {
userInfo.put("created_at", sdf.format(user.getCreatedAt()));
} else {
userInfo.put("created_at", null);
}
if (user.getUpdatedAt() != null) {
userInfo.put("updated_at", sdf.format(user.getUpdatedAt()));
} else {
userInfo.put("updated_at", null);
}
// 处理服务城市ID数组
if (user.getServiceCityIds() != null && !user.getServiceCityIds().isEmpty()) {
userInfo.put("service_city_ids", AppletControllerUtil.parseStringToList(user.getServiceCityIds()));
} else {
userInfo.put("service_city_ids", new ArrayList<>());
}
// 处理技能ID数组
if (user.getSkillIds() != null && !user.getSkillIds().isEmpty()) {
userInfo.put("skill_ids", AppletControllerUtil.parseStringToList(user.getSkillIds()));
} else {
userInfo.put("skill_ids", new ArrayList<>());
}
return userInfo;
}
/**
* 修改用户基本信息接口
*
* @param params 请求参数,包含用户信息字段
* @param request HTTP请求对象
* @return 修改结果
* <p>
* 接口说明:
* - 通过token验证用户身份后修改用户基本信息
* - 支持修改用户的各种字段信息
* - 自动处理服务城市ID和技能ID数组
* - 需要用户登录验证
* <p>
*/
@PostMapping(value = "/api/user/edit/info")
public AjaxResult editUserInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletUnauthorized();
}
// 2. 获取当前登录用户信息
Users currentUser = (Users) userValidation.get("user");
if (currentUser == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证请求参数
if (params == null || params.isEmpty()) {
return AppletControllerUtil.appletWarning("请求参数不能为空");
}
// 4. 验证用户ID是否匹配安全性检查
Object userIdObj = params.get("id");
if (userIdObj != null) {
Long userId = Long.valueOf(userIdObj.toString());
if (!userId.equals(currentUser.getId())) {
return AppletControllerUtil.appletWarning("无权修改其他用户的信息");
}
}
// 5. 构建更新用户对象
Users updateUser = AppletControllerUtil.buildUpdateUserFromdataParams(params, currentUser.getId());
// 6. 验证必要字段
String validationResult = validateUserEditdataParams(updateUser);
if (validationResult != null) {
return AppletControllerUtil.appletWarning(validationResult);
}
// 7. 执行用户信息更新
int updateResult = usersService.updateUsers(updateUser);
if (updateResult > 0) {
// 8. 返回成功响应(按照图片中的格式返回空数组)
return AppletControllerUtil.appletSuccess(new ArrayList<>());
} else {
return AppletControllerUtil.appletWarning("用户信息修改失败");
}
} catch (Exception e) {
System.err.println("修改用户基本信息异常:" + e.getMessage());
return AppletControllerUtil.appletError("修改用户信息失败:" + e.getMessage());
}
}
/**
* 解析对象为Integer类型用于编辑接口
*/
private Integer parseToIntegerdataForEdit(Object value) {
if (value == null) return null;
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof Long) {
return ((Long) value).intValue();
} else if (value instanceof String) {
try {
return Integer.parseInt((String) value);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
/**
* 验证用户编辑参数
*
* @param user 用户对象
* @return 验证结果null表示验证通过
*/
private String validateUserEditdataParams(Users user) {
// 验证手机号格式(如果提供了的话)
if (user.getPhone() != null && !user.getPhone().isEmpty()) {
if (!user.getPhone().matches("^1[3-9]\\d{9}$")) {
return "手机号格式不正确";
}
}
// 验证用户名长度
if (user.getName() != null && user.getName().length() > 50) {
return "用户名长度不能超过50个字符";
}
// 验证昵称长度
if (user.getNickname() != null && user.getNickname().length() > 50) {
return "昵称长度不能超过50个字符";
}
return null; // 验证通过
}
/**
* 验证用户token接口
*
* @param request HTTP请求对象
* @return 验证结果
* <p>
* 接口说明:
* - 验证用户token的有效性
* - 返回用户基本信息
* - 检查用户账号状态
* - 过滤敏感信息
*/
@PostMapping(value = "/api/user/validate")
public AjaxResult validateToken(HttpServletRequest request) {
try {
// 1. 获取token
String token = AppletLoginUtil.extractToken(
request.getHeader("Authorization"),
request.getHeader("token")
);
if (token == null) {
return AppletControllerUtil.appletWarning("未提供token请先登录");
}
// 2. 验证token
Map<String, Object> validateResult = AppletLoginUtil.validateUserToken(token, usersService);
// 3. 返回验证结果
boolean valid = (Boolean) validateResult.get("valid");
if (valid) {
return AppletControllerUtil.appletSuccess(validateResult);
} else {
return AppletControllerUtil.appletWarning((String) validateResult.get("message"));
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("验证token失败" + e.getMessage());
}
}
/**
* 微信支付统一下单接口
*
* @param params 支付参数
* @param request HTTP请求对象
* @return 支付结果
*/
@PostMapping(value = "/api/pay/unifiedorder")
public AjaxResult createPayOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
WechatPayUtil wechatPayUtil = new WechatPayUtil();
// 2. 调用微信支付统一下单
Map<String, Object> payResult = wechatPayUtil.unifiedOrder((String) params.get("openid"), (String) params.get("orderNo"), (int) params.get("totalFee"), (String) params.get("body"), (String) params.get("notifyUrl"), (String) params.get("attach"));
// 3. 返回结果
boolean success = (Boolean) payResult.get("success");
if (success) {
return AppletControllerUtil.appletSuccess(payResult);
} else {
return AppletControllerUtil.appletWarning((String) payResult.get("message"));
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("创建支付订单失败:" + e.getMessage());
}
}
/**
* 查询支付订单状态接口
*
* @param orderNo 订单号
* @param request HTTP请求对象
* @return 查询结果
*/
@GetMapping(value = "/api/pay/query/{orderNo}")
public AjaxResult queryPayOrder(@PathVariable("orderNo") String orderNo, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
WechatPayUtil wechatPayUtil = new WechatPayUtil();
// 2. 查询订单状态
Map<String, Object> queryResult = wechatPayUtil.queryOrder(orderNo, null);
// 3. 返回结果
boolean success = (Boolean) queryResult.get("success");
if (success) {
return AppletControllerUtil.appletSuccess(queryResult);
} else {
return AppletControllerUtil.appletWarning((String) queryResult.get("message"));
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("查询订单状态失败:" + e.getMessage());
}
}
/**
* 创建代付订单接口
*
* @param params 代付参数
* @param request HTTP请求对象
* @return 代付结果
*/
@PostMapping(value = "/api/pay/payfor")
public AjaxResult createPayForOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
WechatPayUtil wechatPayUtil = new WechatPayUtil();
// 2. 创建代付订单
Map<String, Object> 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");
if (success) {
return AppletControllerUtil.appletSuccess(payForResult);
} else {
return AppletControllerUtil.appletWarning((String) payForResult.get("message"));
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("创建代付订单失败:" + e.getMessage());
}
}
/**
* 微信支付回调接口
*
* @param request HTTP请求对象
* @return 回调处理结果
* <p>
* 注意:此接口供微信服务器回调使用,不需要用户认证
* 返回格式必须是XML格式用于告知微信处理结果
*/
@PostMapping(value = "/api/pay/notify")
public String handlePayNotify(HttpServletRequest request) {
try {
WechatPayUtil wechatPayUtil = new WechatPayUtil();
// 1. 处理支付回调
Map<String, Object> notifyResult = wechatPayUtil.handlePayNotify(request);
// 2. 获取支付信息
boolean success = (Boolean) notifyResult.get("success");
if (success) {
Map<String, Object> paymentInfo = (Map<String, Object>) notifyResult.get("paymentInfo");
boolean isPayFor = (Boolean) notifyResult.get("isPayFor");
// 3. 根据业务需要处理支付成功逻辑
// 例如:更新订单状态、发送通知等
AppletControllerUtil.handlePaymentSuccess(paymentInfo, isPayFor);
// 4. 返回成功响应给微信
return (String) notifyResult.get("responseXml");
} else {
// 5. 返回失败响应给微信
return (String) notifyResult.get("responseXml");
}
} catch (Exception e) {
// 6. 异常时返回失败响应
return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理异常]]></return_msg></xml>";
}
}
/**
* 申请退款接口
*
* @param params 退款参数
* @param request HTTP请求对象
* @return 退款结果
* <p>
* 请求参数格式:
* {
* "orderNo": "原订单号",
* "refundNo": "退款单号",
* "totalFee": 订单总金额(分),
* "refundFee": 退款金额(分),
* "refundDesc": "退款原因"
* }
*/
@PostMapping(value = "/api/pay/refund")
public AjaxResult refundOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
WechatPayUtil wechatPayUtil = new WechatPayUtil();
// 2. 申请退款
Map<String, Object> refundResult = wechatPayUtil.refund(params);
// 3. 返回结果
boolean success = (Boolean) refundResult.get("success");
if (success) {
return AppletControllerUtil.appletSuccess(refundResult);
} else {
return AppletControllerUtil.appletWarning((String) refundResult.get("message"));
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("申请退款失败:" + e.getMessage());
}
}
/**
* 查询用户售后返修列表
*
* @param params 请求参数包含page(页码)、limit(每页数量)
* @param request HTTP请求对象
* @return 返回分页的售后返修列表
* <p>
* 功能说明:
* - 获取当前登录用户的售后返修记录
* - 支持分页查询
* - 按创建时间倒序排列
* - 返回符合前端要求的分页格式
*/
@PostMapping("/api/service/order/rework/lst")
public AjaxResult getReworkList(@RequestBody Map<String, Object> 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;
int status = (Integer) params.get("status");
// 2. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 3. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 4. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 5. 设置分页参数
PageHelper.startPage(page, limit);
// 6. 构建查询条件
OrderRework queryCondition = new OrderRework();
queryCondition.setUid(user.getId()); // 只查询当前用户的售后记录
queryCondition.setStatus(status);
// 7. 查询售后返修列表
List<OrderRework> reworkList = orderReworkService.selectOrderReworkList(queryCondition);
// 8. 构建分页数据
PageInfo<OrderRework> pageInfo = new PageInfo<>(reworkList);
// 9. 构建返回数据格式
Map<String, Object> responseData = new HashMap<>();
responseData.put("current_page", pageInfo.getPageNum());
responseData.put("data", reworkList);
responseData.put("from", pageInfo.getStartRow());
responseData.put("last_page", pageInfo.getPages());
responseData.put("per_page", String.valueOf(pageInfo.getPageSize()));
responseData.put("to", pageInfo.getEndRow());
responseData.put("total", pageInfo.getTotal());
// 构建分页链接信息
Map<String, Object> links = new HashMap<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
"https://www.huafurenjia.cn/api/service/order/rework/lst?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
responseData.put("links", new Object[]{prevLink, nextLink});
responseData.put("next_page_url", pageInfo.isHasNextPage() ?
"https://www.huafurenjia.cn/api/service/order/rework/lst?page=" + pageInfo.getNextPage() : null);
responseData.put("path", "https://www.huafurenjia.cn/api/service/order/rework/lst");
responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ?
"https://www.huafurenjia.cn/api/service/order/rework/lst?page=" + pageInfo.getPrePage() : null);
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
System.err.println("查询售后返修列表异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询售后返修列表失败:" + e.getMessage());
}
}
/**
* 合作申请提交接口
*
* @param params 请求参数包含company(公司名称)、name(姓名)、phone(电话)、address(地址)、info(合作意向)
* @param request HTTP请求对象
* @return 申请提交结果
* <p>
* 功能说明:
* - 验证用户登录状态(可选)
* - 接收合作申请表单数据
* - 验证必填字段
* - 保存合作申请记录
* - 设置默认状态为待处理
* <p>
*/
@PostMapping("/api/form/cooperate")
public AjaxResult submitCooperateApplication(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 参数验证
if (params == null) {
return AppletControllerUtil.appletWarning("请求参数不能为空");
}
String company = (String) params.get("company");
String name = (String) params.get("name");
String phone = (String) params.get("phone");
String address = (String) params.get("address");
String info = (String) params.get("info");
// 2. 验证必填字段
if (StringUtils.isEmpty(company)) {
return AppletControllerUtil.appletWarning("公司名称不能为空");
}
if (StringUtils.isEmpty(name)) {
return AppletControllerUtil.appletWarning("联系人姓名不能为空");
}
if (StringUtils.isEmpty(phone)) {
return AppletControllerUtil.appletWarning("联系电话不能为空");
}
// 验证手机号格式
if (!phone.matches("^1[3-9]\\d{9}$")) {
return AppletControllerUtil.appletWarning("联系电话格式不正确");
}
if (StringUtils.isEmpty(address)) {
return AppletControllerUtil.appletWarning("联系地址不能为空");
}
if (StringUtils.isEmpty(info)) {
return AppletControllerUtil.appletWarning("合作意向不能为空");
}
// 3. 获取用户信息(可选,不强制要求登录)
Long uid = null;
String uname = null;
String token = request.getHeader("token");
if (StringUtils.isNotEmpty(token)) {
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if ((Boolean) userValidation.get("valid")) {
Users user = (Users) userValidation.get("user");
if (user != null) {
uid = user.getId();
uname = user.getNickname();
}
}
}
// 4. 构建合作申请对象
Cooperate cooperate = AppletControllerUtil.buildCooperateApplication(params, uid, uname);
// 5. 验证合作申请参数
String validationResult = AppletControllerUtil.validateCooperateParams(cooperate);
if (validationResult != null) {
return AppletControllerUtil.appletWarning(validationResult);
}
// 6. 保存合作申请记录
int insertResult = cooperateService.insertCooperate(cooperate);
if (insertResult > 0) {
return AppletControllerUtil.appletSuccess("合作申请提交成功,我们会尽快联系您");
} else {
return AppletControllerUtil.appletWarning("合作申请提交失败,请稍后重试");
}
} catch (Exception e) {
System.err.println("合作申请提交异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("合作申请提交失败:" + e.getMessage());
}
}
/**
* 查询用户优惠券列表
*
* @param params 请求参数包含status(优惠券状态)、product_id(指定商品ID)、price(最低价格)
* @param request HTTP请求对象
* @return 返回用户优惠券列表
*/
@PostMapping("/api/coupon/my/lst")
public AjaxResult getMyCouponList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 3. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 4. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
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<CouponUser> 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<Coupons> couponsList =CouponUtil.iscoupon(userId,couponsService,couponUserService);
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());
List<CouponUser> couponUserDataList = couponUserService.selectCouponUserList(couponUserData);
if (couponUserDataList!=null){
return AppletControllerUtil.appletSuccess(AppletControllerUtil.buildCouponUserList(couponUserDataList,serviceCateService,serviceGoodsService,productId,totalPrice));
}
}
// 按is_use排序
return AjaxResult.success();
}
/**
* 积分订单收货确认接口
* @param request
* @return AjaxResult
* 订单状态 1:待支付 2已支付待发货3待收货 4待评价 5已收货 6取消 20申请退款 21同意退款 22驳回退款
*/
@GetMapping("/api/integral/user/order/confirm/{id}")
public AjaxResult confirmOrder(@PathVariable("id") String id,HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
IntegralOrder integralOrder = integralOrderService.selectIntegralOrderById(Long.valueOf(id));
if (integralOrder==null){
return AppletControllerUtil.appletWarning("订单不存在");
}
if(!user.getId().equals(integralOrder.getUid())){
return AppletControllerUtil.appletWarning("确认收货失败,收货人和操作人应为同一人,请确认后再进行操作");
}
if (!integralOrder.getStatus().equals("2")){
return AppletControllerUtil.appletWarning("订单状态错误");
}
integralOrder.setStatus("3");
integralOrderService.updateIntegralOrder(integralOrder);
IntegralOrderLog integralOrderLog = new IntegralOrderLog();
integralOrderLog.setOrderId(integralOrder.getOrderId());
integralOrderLog.setOid(integralOrder.getId());
integralOrderLog.setType(3L);
integralOrderLog.setTitle("确认收货");
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","用户确认收货");
integralOrderLog.setContent(jsonObject.toJSONString());
int flg=integralOrderLogService.insertIntegralOrderLog(integralOrderLog);
if (flg>0){
return AppletControllerUtil.appletSuccess("确认收货成功");
}else{
return AppletControllerUtil.appletWarning("确认收货失败");
}
}
/**
* 商品订单评价接口
* @param param {order_id, content, num, images}
* @param request
* @return AjaxResult
* 订单状态 1:待支付 2已支付待发货3待收货 4待评价 5已收货 6取消 20申请退款 21同意退款 22驳回退款
*/
@PostMapping("/api/goods/order/comment")
public AjaxResult commentGoodsOrder(@RequestBody Map<String, Object> param, HttpServletRequest request) {
// 参数校验
String orderId = (String) param.get("order_id");
String content = (String) param.get("content");
Integer num = param.get("num") != null ? Integer.parseInt(param.get("num").toString()) : null;
Object imagesObj = param.get("images");
if (orderId == null || orderId.isEmpty()) {
return AjaxResult.error("请选择评价的订单");
}
if (content == null || content.isEmpty()) {
return AjaxResult.error("请输入评价内容");
}
if (num == null) {
return AjaxResult.error("请打分");
}
// 获取当前登录用户假设有token或session示例用1L
Long uid = 1L;
// 判断是否已评价
GoodsOrder goodsOrder = null;
{
GoodsOrder query = new GoodsOrder();
query.setOrderId(orderId);
List<GoodsOrder> orderList = goodsOrderService.selectGoodsOrderList(query);
if (orderList == null || orderList.isEmpty()) {
return AjaxResult.error("订单不存在");
}
goodsOrder = orderList.get(0);
}
int count = orderCommentService.selectCountOrderCommentByOid(goodsOrder.getId());
if (count > 0) {
return AjaxResult.error("请勿重复提交");
}
// 评分类型
long numType = num == 1 ? 3 : ((num == 2 || num == 3) ? 2 : 1);
// 组装评价对象
OrderComment comment = new OrderComment();
comment.setOid(goodsOrder.getId());
comment.setOrderId(orderId);
comment.setProductId(goodsOrder.getProductId());
comment.setContent(content);
comment.setNum((long) num);
comment.setUid(goodsOrder.getUid()); // 或uid
comment.setImages(imagesObj != null ? JSON.toJSONString(imagesObj) : null);
comment.setNumType(numType);
comment.setCreatedAt(new java.util.Date());
comment.setUpdatedAt(new java.util.Date());
comment.setStatus(1); // 显示
int result = orderCommentService.insertOrderComment(comment);
if (result > 0) {
goodsOrder.setStatus(5L); // 订单状态改为已收货
goodsOrderService.updateGoodsOrder(goodsOrder);
return AjaxResult.success();
} else {
return AjaxResult.error("操作失败");
}
}
/**
* 查询用户积分日志列表
*
* @param params 请求参数包含limit(每页数量)、page(页码)
* @param request HTTP请求对象
* @return 返回分页的积分日志列表
*/
@PostMapping("/api/integral/user/log/lst")
public AjaxResult getUserIntegralLogList(@RequestBody Map<String, Object> 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<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 3. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 4. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 5. 设置分页参数
PageHelper.startPage(page, limit);
// 6. 构建查询条件并查询
IntegralLog integralLogQuery = new IntegralLog();
integralLogQuery.setUid(user.getId());
List<IntegralLog> integralLogList = integralLogService.selectIntegralLogList(integralLogQuery);
// 7. 构建分页信息
PageInfo<IntegralLog> pageInfo = new PageInfo<>(integralLogList);
// 8. 使用工具类处理数据格式化
List<Map<String, Object>> formattedLogList = AppletControllerUtil.buildIntegralLogList(integralLogList);
Map<String, Object> paginationData = AppletControllerUtil.buildPaginationResponse(
pageInfo, formattedLogList, "https://www.huafurenjia.cn/api/integral/user/log/lst");
Map<String, Object> userData = AppletControllerUtil.buildUserDataInfo(user);
// 9. 构建最终返回数据结构
Map<String, Object> responseData = new HashMap<>();
responseData.put("data", paginationData);
responseData.put("user", userData);
responseData.put("msg", "OK");
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
System.err.println("查询用户积分日志列表异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询积分日志列表失败:" + e.getMessage());
}
}
/**
* 查询用户积分商城订单列表
*
* @param params 请求参数包含limit(每页数量)、page(页码)、status(订单状态)
* @param request HTTP请求对象
* @return 返回分页的积分商城订单列表
*/
@PostMapping("/api/integral/user/order")
public AjaxResult getUserIntegralOrderList(@RequestBody Map<String, Object> 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<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 3. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 4. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 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<IntegralOrder> integralOrderList = integralOrderService.selectIntegralOrderList(integralOrderQuery);
// 7. 构建分页信息
PageInfo<IntegralOrder> pageInfo = new PageInfo<>(integralOrderList);
// 8. 使用工具类处理数据格式化
List<Map<String, Object>> formattedOrderList = AppletControllerUtil.buildIntegralOrderList(
integralOrderList, integralProductService);
Map<String, Object> responseData = AppletControllerUtil.buildPaginationResponse(
pageInfo, formattedOrderList, "https://www.huafurenjia.cn/api/integral/user/order");
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
System.err.println("查询用户积分商城订单列表异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询积分商城订单列表失败:" + 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 AppletControllerUtil.appletWarning("订单ID无效");
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 3. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 4. 查询积分订单信息
IntegralOrder integralOrder = integralOrderService.selectIntegralOrderById(id);
if (integralOrder == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 5. 验证订单归属权
if (!integralOrder.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("无权访问该订单信息");
}
// 6. 使用工具类构建订单详情数据
Map<String, Object> orderData = AppletControllerUtil.buildIntegralOrderDetail(
integralOrder, integralProductService, integralOrderLogService);
return AppletControllerUtil.appletSuccess(orderData);
} catch (Exception e) {
System.err.println("查询积分订单详情异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询订单详情失败:" + e.getMessage());
}
}
/**
* 查询积分商品分类列表
*
* @param request HTTP请求对象
* @return 返回积分商品分类列表
* <p>
* 功能说明:
* - 获取所有启用状态的积分商品分类
* - 返回分类的ID和名称
* - 用于积分商城分类展示
*/
@GetMapping("/api/integral/product/cate")
public AjaxResult getIntegralProductCateList(HttpServletRequest request) {
try {
// 1. 构建查询条件:查询启用状态的积分商品分类
IntegralCate integralCateQuery = new IntegralCate();
integralCateQuery.setStatus(1L); // 启用状态
// 2. 查询积分商品分类列表
List<IntegralCate> integralCateList = integralCateService.selectIntegralCateList(integralCateQuery);
// 3. 构建返回数据格式
List<Map<String, Object>> resultList = new ArrayList<>();
for (IntegralCate integralCate : integralCateList) {
Map<String, Object> cateData = new HashMap<>();
cateData.put("id", integralCate.getId());
cateData.put("title", integralCate.getTitle());
resultList.add(cateData);
}
return AppletControllerUtil.appletSuccess(resultList);
} catch (Exception e) {
System.err.println("查询积分商品分类列表异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询分类列表失败:" + e.getMessage());
}
}
/**
* 查询积分商品列表
*
* @param params 请求参数包含limit(每页数量)、page(页码)、type(分类ID)
* @param request HTTP请求对象
* @return 返回分页的积分商品列表
* <p>
* 功能说明:
* - 获取积分商品列表,支持分页
* - 支持按分类筛选
* - 返回商品详细信息和分页信息
* - 按创建时间倒序排列
*/
@PostMapping("/api/integral/product/lst")
public AjaxResult getIntegralProductList(@RequestBody Map<String, Object> 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<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletWarning((String) pageValidation.get("message"));
}
// 3. 设置分页参数
PageHelper.startPage(page, limit);
// 4. 构建查询条件
IntegralProduct integralProductQuery = new IntegralProduct();
integralProductQuery.setStatus(1L); // 只查询启用状态的商品
// 如果有分类参数,添加分类筛选
if (type != null && !type.trim().isEmpty()) {
try {
Long cateId = Long.parseLong(type.trim());
integralProductQuery.setCateId(cateId);
} catch (NumberFormatException e) {
return AppletControllerUtil.appletWarning("分类参数格式错误");
}
}
// 5. 查询积分商品列表
List<IntegralProduct> integralProductList = integralProductService.selectIntegralProductList(integralProductQuery);
// 6. 构建分页信息
PageInfo<IntegralProduct> pageInfo = new PageInfo<>(integralProductList);
// 7. 使用工具类处理数据格式化
List<Map<String, Object>> formattedProductList = AppletControllerUtil.buildIntegralProductList(integralProductList);
Map<String, Object> responseData = AppletControllerUtil.buildPaginationResponse(
pageInfo, formattedProductList, "https://www.huafurenjia.cn/api/integral/product/lst");
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
System.err.println("查询积分商品列表异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询积分商品列表失败:" + e.getMessage());
}
}
/**
* 查询积分商品详情
*
* @param id 商品ID
* @param request HTTP请求对象
* @return 返回积分商品详细信息
* <p>
* 功能说明:
* - 根据商品ID获取积分商品详细信息
* - 返回完整的商品数据包括图片、规格、库存等
* - 自动处理图片URL添加CDN前缀
* - 格式化轮播图和标签为数组格式
* <p>
*/
@GetMapping("/api/integral/product/info/{id}")
public AjaxResult getIntegralProductInfo(@PathVariable("id") Long id, HttpServletRequest request) {
try {
// 1. 参数验证
if (id == null || id <= 0) {
return AppletControllerUtil.appletWarning("商品ID无效");
}
// 2. 查询积分商品信息
IntegralProduct integralProduct = integralProductService.selectIntegralProductById(id);
if (integralProduct == null) {
return AppletControllerUtil.appletWarning("商品不存在");
}
// 3. 验证商品状态(只返回启用状态的商品)
if (integralProduct.getStatus() == null || integralProduct.getStatus() != 1) {
return AppletControllerUtil.appletWarning("商品已下架或不可用");
}
// 4. 使用工具类构建商品详情数据
Map<String, Object> productDetail = AppletControllerUtil.buildIntegralProductDetail(integralProduct);
return AppletControllerUtil.appletSuccess(productDetail);
} catch (Exception e) {
System.err.println("查询积分商品详情异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询商品详情失败:" + e.getMessage());
}
}
/**
* 获取用户默认收货地址
*
* @param request HTTP请求对象
* @return 默认地址信息
* <p>
* 接口说明:
* - 查询用户的默认收货地址is_default = 1
* - 如果没有默认地址,返回用户地址列表的第一条数据
* - 验证用户登录状态和地址归属权
* - 返回AddressApple格式的地址数据
* <p>
*/
@GetMapping("/api/user/address/default")
public AjaxResult getUserDefaultAddress(HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 首先查询用户的默认地址
UserAddress userAddressQuery = new UserAddress();
userAddressQuery.setUid(user.getId());
userAddressQuery.setIsDefault(1L); // 查询默认地址
List<UserAddress> defaultAddressList = userAddressService.selectUserAddressList(userAddressQuery);
UserAddress targetAddress = null;
if (!defaultAddressList.isEmpty()) {
// 找到默认地址
targetAddress = defaultAddressList.get(0);
} else {
// 没有默认地址,查询用户的第一条地址
UserAddress allAddressQuery = new UserAddress();
allAddressQuery.setUid(user.getId());
List<UserAddress> allAddressList = userAddressService.selectUserAddressList(allAddressQuery);
if (!allAddressList.isEmpty()) {
targetAddress = allAddressList.get(0);
} else {
return AppletControllerUtil.appletWarning("用户暂无收货地址");
}
}
// 4. 转换为AddressApple格式并返回
AddressApple addressApple = AddressApple.fromUserAddress(targetAddress);
return AppletControllerUtil.appletSuccess(addressApple);
} catch (Exception e) {
System.err.println("查询用户默认地址异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询默认地址失败:" + e.getMessage());
}
}
/**
* 获取用户小程序通知订阅状态
*
* @param request HTTP请求对象
* @return 用户通知订阅状态
* <p>
* 接口说明:
* - 查询用户对小程序消息模板的订阅状态
* - 返回三个消息模板的订阅配置信息
* - 支持不同业务场景的消息通知配置
* - 验证用户登录状态
*/
@GetMapping("/api/user/notification/status")
public AjaxResult getUserNotificationStatus(HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 直接返回固定的消息模板配置数据
Map<String, Object> notificationStatus = AppletControllerUtil.buildMiniProgramNotificationStatus(user);
return AppletControllerUtil.appletSuccess(notificationStatus);
} catch (Exception e) {
System.err.println("查询用户通知订阅状态异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("查询通知订阅状态失败:" + e.getMessage());
}
}
/**
* 用户订阅消息授权接口
*
* @param params 请求参数包含tmplIds(模板ID数组)
* @param request HTTP请求对象
* @return 授权结果
*/
@PostMapping("/api/user/notification/subscribe")
public AjaxResult subscribeNotification(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 获取模板ID列表
List<String> tmplIds = (List<String>) params.get("tmplIds");
if (tmplIds == null || tmplIds.isEmpty()) {
return AppletControllerUtil.appletWarning("模板ID列表不能为空");
}
// 4. 验证模板ID的有效性
List<String> validTemplateIds = new ArrayList<>();
validTemplateIds.add("pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M");
validTemplateIds.add("YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8");
validTemplateIds.add("5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU");
for (String tmplId : tmplIds) {
if (!validTemplateIds.contains(tmplId)) {
return AppletControllerUtil.appletWarning("无效的模板ID" + tmplId);
}
}
// 5. 处理订阅逻辑这里可以记录到数据库或调用微信API
Map<String, Object> 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 AppletControllerUtil.appletSuccess(subscribeResult);
} catch (Exception e) {
System.err.println("用户订阅消息异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("订阅消息失败:" + e.getMessage());
}
}
/**
* 小程序下单时用户订阅消息推送接口(前端不传值,后端返回固定结构)
*
* @return 订阅消息推送ID分类结果
*/
@GetMapping("/api/public/massge/notice")
public Map<String, Object> subscribeMessageNotice() {
Map<String, Object> 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<String, Object> 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 兑换结果
*/
@PostMapping("/api/integral/user/exchange")
public AjaxResult exchangeIntegralProduct(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证请求参数
String validationResult = AppletControllerUtil.validateIntegralExchangeParams(params);
if (validationResult != null) {
return AppletControllerUtil.appletWarning(validationResult);
}
// 4. 获取并验证积分商品信息
Long productId = Long.valueOf(params.get("id").toString());
IntegralProduct product = integralProductService.selectIntegralProductById(productId);
if (product == null) {
return AppletControllerUtil.appletWarning("积分商品不存在");
}
if (product.getStatus() == null || product.getStatus() != 1) {
return AppletControllerUtil.appletWarning("积分商品已下架或不可用");
}
// 5. 获取并验证收货地址信息
Long addressId = Long.valueOf(params.get("address_id").toString());
UserAddress address = userAddressService.selectUserAddressById(addressId);
if (address == null) {
return AppletControllerUtil.appletWarning("收货地址不存在");
}
if (!address.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("无权使用该收货地址");
}
// 6. 计算所需积分并验证库存
Integer num = Integer.valueOf(params.get("num").toString());
if (product.getStock() != null && product.getStock() < num) {
return AppletControllerUtil.appletWarning("商品库存不足");
}
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 AppletControllerUtil.appletWarning("订单创建失败");
}
// 9. 扣除用户积分
Users updateUser = new Users();
updateUser.setId(user.getId());
updateUser.setIntegral(user.getIntegral() - totalIntegral);
int updateResult = usersService.updateUsers(updateUser);
if (updateResult <= 0) {
return AppletControllerUtil.appletWarning("扣除积分失败");
}
// 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 服务订单详细信息
* <p>
* 接口说明:
* - 根据订单ID获取服务订单完整信息
* - 包含订单基本信息、订单日志和商品信息
* - 验证用户登录状态和订单归属权
* - 返回完整的订单详情数据
* <p>
*/
@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<String, Object> 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<String, Object> 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 城市列表数据
* <p>
* 接口说明:
* - 获取所有启用状态的城市列表
* - 返回城市的ID、名称和父级ID
* - 用于小程序城市选择功能
* - 无需用户登录验证
* <p>
*/
@GetMapping(value = "/api/public/diy/city")
public AjaxResult getDiyCityList(HttpServletRequest request) {
try {
// 查询所有城市列表
List<DiyCity> cityList = diyCityService.selectDiyCityList(null);
// 构建树状结构数据
List<Map<String, Object>> 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 技能列表数据
* <p>
* 接口说明:
* - 获取所有技能列表数据
* - 返回技能的ID、名称、排序、状态等信息
* - 用于小程序技能选择功能
* - 无需用户登录验证
* <p>
*/
@GetMapping(value = "/api/form/skill/lst")
public AjaxResult getSkillList(HttpServletRequest request) {
try {
// 查询技能列表
List<SiteSkill> skillList = siteSkillService.selectSiteSkillList(null);
// 构建返回数据格式
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (SiteSkill skill : skillList) {
Map<String, Object> 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 上传结果
* <p>
* 接口说明:
* - 支持图片和视频文件上传
* - 优先使用七牛云上传,未启用时使用本地上传
* - 自动验证文件格式和大小
* - 无需用户登录验证public 接口)
*/
@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",
// 视频格式
"mp4", "avi", "mov", "wmv", "flv", "m4v", "3gp", "rmvb", "mkv"
};
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<String, Object> 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 时间段列表数据
* <p>
* 接口说明:
* - 根据指定日期获取可预约的时间段列表
* - 返回每个时间段的可用状态和剩余数量
* - 支持动态时间段配置
* - 无需用户登录验证
* <p>
*/
@PostMapping(value = "/api/service/make/time")
public AjaxResult getServiceMakeTime(@RequestBody Map<String, Object> 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<Map<String, Object>> 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 添加结果
* <p>
* 接口说明:
* - 将指定商品添加到用户购物车
* - 验证商品是否存在和可用
* - 支持商品规格选择
* - 需要用户登录验证
* <p>
*/
@PostMapping(value = "/api/cart/add")
public AjaxResult addToCart(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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 = 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. 验证商品状态
// if (serviceGoods.getStatus() == null || !serviceGoods.getStatus().equals(1L)) {
// return AppletControllerUtil.appletWarning("商品已下架或不可用");
// }
// 7. 检查商品库存(如果有库存管理)
// if (serviceGoods.getStock() != null && serviceGoods.getStock() <= 0L) {
// return AppletControllerUtil.appletWarning("商品库存不足");
// }
// 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());
}
}
/**
* 查询购物车列表接口
*
* @param params 请求参数包含limit(每页数量)、page(页码)
* @param request HTTP请求对象
* @return 购物车列表数据
* <p>
* 接口说明:
* - 获取当前登录用户的购物车商品列表
* - 支持分页查询
* - 返回完整的商品信息
* - 需要用户登录验证
* <p>
*/
@PostMapping(value = "/api/cart/lst")
public AjaxResult getCartList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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<String, Object> 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<GoodsCart> cartList = goodsCartService.selectGoodsCartList(queryCart);
// 8. 为每个购物车项目填充商品信息
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (GoodsCart cart : cartList) {
Map<String, Object> 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<String, Object> goodInfo = AppletControllerUtil.getGoodDetailForCart(cart.getGoodId(), serviceGoodsService);
cartData.put("good", goodInfo);
resultList.add(cartData);
}
// 9. 构建分页信息
PageInfo<GoodsCart> pageInfo = new PageInfo<>(cartList);
// 10. 构建返回数据格式
Map<String, Object> 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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
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 搜索结果列表
* <p>
* 接口说明:
* - 根据关键词搜索服务商品
* - 支持按商品标题进行模糊查询
* - 支持分页查询
* - 无需用户登录验证
* <p>
*/
@PostMapping(value = "/api/service/search")
public AjaxResult searchServices(@RequestBody Map<String, Object> 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<String, Object> 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<ServiceGoods> goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods);
// 6. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
for (ServiceGoods goods : goodsList) {
Map<String, Object> goodsData = AppletControllerUtil.buildServiceGoodsData(goods);
resultList.add(goodsData);
}
// 7. 构建分页信息
PageInfo<ServiceGoods> pageInfo = new PageInfo<>(goodsList);
// 8. 构建返回数据格式
Map<String, Object> 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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
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 订单详细信息
* <p>
* 接口说明:
* - 根据订单ID获取商品订单完整信息
* - 包含订单基本信息、用户地址、商品信息等
* - 验证用户登录状态和订单归属权
* - 返回完整的订单详情数据
* <p>
*/
@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<String, Object> 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<String, Object> 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<String, Object> buildGoodsOrderDetail(GoodsOrder order) {
Map<String, Object> 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<String, Object> 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);
}
}
// 查询并添加商品信息
if (order.getProductId() != null) {
ServiceGoods product = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (product != null) {
Map<String, Object> 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()));
orderDetail.put("product", productInfo);
}
}
// 添加评论和配送信息(暂时为空数组,后续可以扩展)
orderDetail.put("comment", new ArrayList<>());
orderDetail.put("delivery", new ArrayList<>());
return orderDetail;
}
/**
* 获取用户优惠券数量统计接口
*
* @param request HTTP请求对象
* @return 优惠券数量统计信息
* <p>
* 接口说明:
* - 统计当前登录用户的优惠券数量
* - 包含未使用、已使用、已过期、待领取数量
* - 需要用户登录验证
* <p>
*/
@GetMapping("/api/coupon/my/count")
public AjaxResult getMyCouponCount(HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 6. 构建返回数据
Map<String, Object> countData = new HashMap<>();
countData.put("one", couponUserService.selectCountCouponsByUid(user.getId(), 1L)); // 未使用数量
countData.put("two",couponUserService.selectCountCouponsByUid(user.getId(), 3L)); // 已使用数量
countData.put("three",couponUserService.selectCountCouponsByUid(user.getId(), 2L)); // 已过期数量
countData.put("four", CouponUtil.iscoupon(user.getId(), couponsService, couponUserService).size()); // 待领取数量
return AppletControllerUtil.appletSuccess(countData);
} 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());
}
}
// 如果状态为3表示已失效
if (couponUser.getStatus() != null && couponUser.getStatus() == 3L) {
return true;
}
// 如果都没有设置,认为未过期
return false;
}
/**
* 创建服务订单(支持多商品批量下单)
*
* @param params 请求参数,包含多个商品信息、地址信息和预约时间
* @param request HTTP请求对象
* @return 返回创建结果
*/
@PostMapping("/api/service/create/order")
public AjaxResult createServiceOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证订单参数
if (params == null || params.isEmpty()) {
return AppletControllerUtil.appletWarning("订单参数不能为空");
}
// 4. 生成主订单号
String mainOrderId = GenerateCustomCode.generCreateOrder("WXB");
// 5. 存储所有订单信息
List<Map<String, Object>> orderList = new ArrayList<>();
BigDecimal totalAmount = BigDecimal.ZERO; // 总金额
// 6. 遍历所有订单项
for (String key : params.keySet()) {
// 跳过非数字键
if (!key.matches("\\d+")) {
continue;
}
Map<String, Object> orderParams = (Map<String, Object>) params.get(key);
// 验证必要参数
if (orderParams.get("product_id") == null || orderParams.get("address_id") == null) {
return AppletControllerUtil.appletWarning("商品ID或地址ID不能为空");
}
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 AppletControllerUtil.appletWarning("商品ID " + productId + " 不存在");
}
// 查询地址信息(只需要查询一次,假设所有订单使用相同地址)
UserAddress userAddress = userAddressService.selectUserAddressById(addressId);
if (userAddress == null) {
return AppletControllerUtil.appletWarning("地址不存在");
}
// 计算单个订单金额
BigDecimal itemPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num));
totalAmount = totalAmount.add(itemPrice);
// 判断商品类型并创建相应订单
BigDecimal DeductionPrice = new BigDecimal("0");
if (serviceGoods.getType() == 2) {
// 创建服务订单
String coupon_id = orderParams.get("coupon_id") != null ? orderParams.get("coupon_id").toString() : "";
CouponUser coupon=null;
if (coupon_id!=null){
coupon = couponUserService.selectCouponUserById(Long.valueOf(coupon_id));
if (coupon==null){
return AppletControllerUtil.appletWarning("优惠券不存在");
}
}
if (coupon != null) {
DeductionPrice= new BigDecimal(coupon.getCouponPrice()).divide(new BigDecimal(params.size()),2, RoundingMode.HALF_UP);
}
if (coupon != null) {
coupon.setStatus(2L);
}
couponUserService.updateCouponUser(coupon) ;
// 创建商品订单
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(DeductionPrice);
goodsOrder.setCouponId(Long.valueOf(coupon_id));
goodsOrder.setStatus(1L); // 待支付状态
goodsOrder.setAddressId(addressId);
goodsOrder.setSku(sku);
// 保存商品订单
int insertResult = goodsOrderService.insertGoodsOrder(goodsOrder);
if (insertResult <= 0) {
return AppletControllerUtil.appletWarning("商品订单创建失败,请稍后重试");
}
// 添加到订单列表
Map<String, Object> 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() : "";
String fileData = orderParams.get("fileData") != null ? orderParams.get("fileData").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.setFileData(fileData != null ? JSON.toJSONString(fileData) : null);
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);
}
}
}
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 AppletControllerUtil.appletWarning("服务订单创建失败,请稍后重试");
}
// 添加订单日志
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<String, Object> 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")));
if (hasGoodsOrder && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
// 使用工具类简化微信支付参数组装
Map<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), mainOrderId, new BigDecimal(0.01), orderList.size(), "https://7ce20b15.r5.cpolar.xyz/api/goods/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> 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 AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
} else {
// 没有商品订单,只有服务订单,直接返回成功
Map<String, Object> 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 AppletControllerUtil.appletWarning("创建订单失败:" + e.getMessage());
}
}
/**
* 尾款结算
*/
@PostMapping("api/service/order/pay/total/price")
public AjaxResult apiServiceOrderPayTotalPprice(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证必要参数
if (params == null || params.get("order_id") == null || params.get("worker_id") == null) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
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<OrderLog> logList = orderLogService.selectOrderLogByOrderId(order.getOrderId());
OrderLog log = null;
for (OrderLog l : logList) {
if (l.getType() != null && l.getType().intValue() == 5) {
log = l;
break;
}
}
if (log == null && !logList.isEmpty()) {
log = logList.get(0);
}
if (log == null) {
return AppletControllerUtil.appletWarning("未找到订单日志");
}
if (params.get("coupon_id")!= null) {
String coupon_id = params.get("coupon_id").toString();
if (coupon_id != null && !coupon_id.isEmpty()) {
CouponUser couponUser = couponUserService.selectCouponUserById(Long.valueOf(coupon_id));
if (couponUser == null && couponUser.getStatus() != 1) {
return AppletControllerUtil.appletWarning("优惠券已被使用,或优惠券不存在");
}
OrderLog orderLogQery = new OrderLog();
orderLogQery.setOrderId(order.getOrderId());
orderLogQery.setType(new BigDecimal(5));
orderLogQery.setWorkerId(worker_id);
OrderLog orderLognew = orderLogService.selectOneByOidTypeWorkerIdPaid(orderLogQery);
if (orderLognew != null) {
orderLognew.setCouponId(couponUser.getCouponId());
orderLognew.setDeduction(new BigDecimal(couponUser.getCouponPrice()));
orderLogService.updateOrderLog(orderLognew);
order.setCouponId(couponUser.getCouponId());
order.setDeduction(new BigDecimal(couponUser.getCouponPrice()));
orderService.updateOrder(order);
}
}
}
Map<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(
user.getOpenid(),
String.valueOf(order_id),
new BigDecimal(0.01),
1,
"https://7ce20b15.r5.cpolar.xyz/api/order/amount/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> 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 AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
}
/**
* 上门费支付接口
*/
@PostMapping("api/service/order/pay_fee")
public AjaxResult apiServiceOrderPayFee(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证必要参数
if (params == null || params.get("id") == null) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
Long orderId = Long.valueOf(params.get("id").toString());
OrderLog orderLog = orderLogService.selectOrderLogById(orderId);
if (orderLog != null) {
Map<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(
user.getOpenid(),
String.valueOf(orderLog.getId()),
new BigDecimal(0.01),
1,
"https://7ce20b15.r5.cpolar.xyz/api/door/fee/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> 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 AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
}
return AppletControllerUtil.appletWarning("支付失败");
}
/**
* 定金支付接口
*/
@PostMapping("/api/service/order/pay/deposit")
public AjaxResult apiServiceOrderPaydeposit(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证必要参数
if (params == null || params.get("id") == null) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
Long orderId = Long.valueOf(params.get("id").toString());
OrderLog orderLog = orderLogService.selectOrderLogById(orderId);
if (orderLog != null) {
Map<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(
user.getOpenid(),
String.valueOf(orderLog.getId()),
new BigDecimal(0.01),
1,
"https://7ce20b15.r5.cpolar.xyz/api/deposit/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> 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 AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
}
return AppletControllerUtil.appletWarning("支付失败");
}
/**
* 单个商品支付
*/
@PostMapping("api/goods/order/once_pay")
public AjaxResult apiGoodsOrderOncePay(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证必要参数
if (params == null || params.get("id") == null) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
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<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(), goodsOrder.getMainOrderId(), new BigDecimal(0.01), 1, "https://7ce20b15.r5.cpolar.xyz/api/goods/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> 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 AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
}
}
return AppletControllerUtil.appletWarning("支付失败");
}
/**
* 取消服务订单
*
* @param params 请求参数包含订单ID和取消原因
* @param request HTTP请求对象
* @return 返回取消结果
*/
@PostMapping("/api/service/cancel/order")
public AjaxResult cancelServiceOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证必要参数
if (params == null || params.get("id") == null || params.get("content") == null) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
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<Order> orders = orderService.selectOrderList(orderQuery);
if (orders == null || orders.isEmpty()) {
return AppletControllerUtil.appletWarning("订单不存在");
}
Order order = orders.get(0);
// 5. 验证订单状态是否可以取消
if (order.getStatus() != 1L) {
return AppletControllerUtil.appletWarning("当前订单状态不可取消");
}
// 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 AppletControllerUtil.appletSuccess("取消成功");
} else {
return AppletControllerUtil.appletWarning("取消失败,请稍后重试");
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("取消失败:" + 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<String, Object> 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<String, Object> 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<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验token并获取师傅信息
String token = request.getHeader("token");
Map<String, Object> 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<Order> orderList = orderService.selectOrderList(query);
List<Map<String, Object>> 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<String, Object> 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<String, Object> 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<Order> pageInfo = new PageInfo<>(orderList);
Map<String, Object> dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, "/api/worker/order/lst");
// 外层data结构
Map<String, Object> outerData = new HashMap<>();
outerData.put("data", dataPage);
Map<String, Object> 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<String, Object> 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<SiteConfig> 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<WorkerSign> signList = workerSignService.selectWorkerSignList(signQuery);
if (signList != null && !signList.isEmpty()) {
signed = true;
}
// 4. 构建user数据
Map<String, Object> userMap = buildUserInfoResponse(user);
// 5. 构建返回结构
Map<String, Object> 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<String, Object> 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<String, Object> 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<OrderLog> logList = orderLogService.selectOrderLogList(logQuery);
List<Map<String, Object>> logArr = new ArrayList<>();
for (OrderLog log : logList) {
Map<String, Object> 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<String, Object> 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);
if (order.getFileData() != null){
data.put("file_data", JSON.parseArray(order.getFileData()));
}else{
data.put("file_data", null);
}
data.put("log", logArr);
return AjaxResult.success(data);
} catch (Exception e) {
return AppletControllerUtil.appletError("查询师傅订单详情失败:" + e.getMessage());
}
}
/**
* 支付尾款回调到页面的数据
*/
@PostMapping("/api/service/order/pay/total/price/info")
public AjaxResult getOrderPayLastInfo(@RequestBody Map<String, Object> params) {
try {
String orderId = (String) params.get("order_id");
if (StringUtils.isEmpty(orderId)) {
return AppletControllerUtil.appletWarning("订单号不能为空");
}
// 1. 查询订单
Order order = orderService.selectOrderByOrderId(orderId);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 2. 查询订单日志取type=5评估报价或最新一条
List<OrderLog> logList = orderLogService.selectOrderLogByOrderId(orderId);
OrderLog log = null;
for (OrderLog l : logList) {
if (l.getType() != null && l.getType().intValue() == 5) {
log = l;
break;
}
}
if (log == null && !logList.isEmpty()) {
log = logList.get(0);
}
if (log == null) {
return AppletControllerUtil.appletWarning("未找到订单日志");
}
// 3. 组装content字段
JSONObject contentJson;
try {
contentJson = JSONObject.parseObject(log.getContent());
} catch (Exception e) {
contentJson = new JSONObject();
}
// 4. 组装返回数据
Map<String, Object> 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 AppletControllerUtil.appletSuccess(data);
} catch (Exception e) {
return AppletControllerUtil.appletWarning("查询失败:" + e.getMessage());
}
}
/**
* 师傅列表接
*/
@PostMapping("/api/worker/user/lst")
public AjaxResult getWorkerUserList(@RequestBody Map<String, Object> 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);
}
PageHelper.startPage(page, limit);
List<Users> userList = usersService.selectUsersList(query);
PageInfo<Users> pageInfo = new PageInfo<>(userList);
List<Map<String, Object>> resultList = new ArrayList<>();
for (Users user : userList) {
Map<String, Object> 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 {
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<String> cityNames = new ArrayList<>();
List<String> 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<String> skillNames = new ArrayList<>();
List<String> 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<String, Object> 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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
for (int i = 1; i <= pageInfo.getPages(); i++) {
Map<String, Object> 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<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
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());
}
}
/**
* 用户申请师傅接口
*/
@PostMapping("/api/form/apply/worker")
public AjaxResult applyWorker(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 构建WorkerApply对象
WorkerApply apply = new WorkerApply();
apply.setUid(user.getId());
apply.setName((String) params.getOrDefault("name", ""));
apply.setPhone((String) params.getOrDefault("phone", ""));
apply.setAddress((String) params.getOrDefault("address", ""));
apply.setCardNo((String) params.getOrDefault("card_no", ""));
// city_pid
Object cityPidObj = params.get("city_pid");
if (cityPidObj != null) {
try {
apply.setCityPid(Long.valueOf(cityPidObj.toString()));
} catch (Exception ignore) {}
}
// city_ids
Object cityIdsObj = params.get("city_ids");
if (cityIdsObj instanceof List) {
List<?> cityIdsList = (List<?>) cityIdsObj;
apply.setCityIds(cityIdsList.toString().replace(" ","")); // 存字符串如[5,7,10,11]
} else if (cityIdsObj != null) {
apply.setCityIds(cityIdsObj.toString());
}
// skill_id
Object skillIdObj = params.get("skill_id");
if (skillIdObj instanceof List) {
List<?> skillIdList = (List<?>) skillIdObj;
apply.setSkillId(skillIdList.toString().replace(" ",""));
} else if (skillIdObj != null) {
apply.setSkillId(skillIdObj.toString());
}
// 图片相关
apply.setSkill((String) params.getOrDefault("skill", ""));
apply.setCriminal((String) params.getOrDefault("criminal", ""));
apply.setDrive((String) params.getOrDefault("drive", ""));
apply.setEducation((String) params.getOrDefault("education", ""));
apply.setHealth((String) params.getOrDefault("health", ""));
apply.setImage((String) params.getOrDefault("image", ""));
// 其他字段可按需补充
int result = workerApplyService.insertWorkerApply(apply);
if (result > 0) {
return AppletControllerUtil.appletSuccess("申请已提交");
} else {
return AppletControllerUtil.appletWarning("申请提交失败,请稍后重试");
}
} catch (Exception e) {
return AppletControllerUtil.appletError("申请失败:" + e.getMessage());
}
}
/**
* 师傅转单接口
*
* @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<OrderLog> 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<String, Object> 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());
}
}
/**
* 师傅首页接口
* 返回结构见json.txt
*/
@PostMapping("/api/worker/index")
public AjaxResult getWorkerIndex(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验token并获取师傅信息
String token = request.getHeader("token");
Map<String, Object> 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<String, Object> 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<Map<String, Object>> skillArr = new ArrayList<>();
List<String> 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<String, Object> skillMap = new HashMap<>();
skillMap.put("id", skill.getId());
skillMap.put("title", skill.getTitle());
skillArr.add(skillMap);
}
}
} catch (Exception ignore) {
}
}
// 4. 查询服务城市数组
List<Map<String, Object>> cityArr = new ArrayList<>();
List<String> 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<String, Object> 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<OrderComment> 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<String, Object> commentStat = new HashMap<>();
commentStat.put("one", one);
commentStat.put("two", two);
commentStat.put("three", three);
commentStat.put("total", total);
// 6. 构建user数据
Map<String, Object> 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<OrderComment> 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<Map<String, Object>> 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<String, Object> 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<String, Object> 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<String, Object> 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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
for (int i = 1; i <= lastPage; i++) {
Map<String, Object> 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<String, Object> nextLink = new HashMap<>();
nextLink.put("url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null);
nextLink.put("label", "Next &raquo;");
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<String, Object> 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<String, Object> params, HttpServletRequest request) {
try {
// 校验token并获取用户
String token = request.getHeader("token");
Map<String, Object> 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<WorkerSign> allList = workerSignService.selectWorkerSignList(query);
List<Map<String, Object>> result = new ArrayList<>();
for (WorkerSign sign : allList) {
if (sign.getTime() != null && !sign.getTime().before(start) && !sign.getTime().after(end)) {
Map<String, Object> 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());
}
}
/**
* 师傅质保金日志接口
*
* @param params {"limit":15,"page":1}
* @param request
* @return 质保金日志分页数据和师傅信息
*/
@PostMapping("/api/worker/mergin/log")
public AjaxResult getWorkerMarginLog(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 校验token并获取用户
String token = request.getHeader("token");
Map<String, Object> 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<WorkerMarginLog> logList = workerMarginLogService.selectWorkerMarginLogList(query);
PageInfo<WorkerMarginLog> pageInfo = new PageInfo<>(logList);
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (WorkerMarginLog log : logList) {
Map<String, Object> 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<String, Object> 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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
for (int i = 1; i <= pageInfo.getPages(); i++) {
Map<String, Object> 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<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
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<String, Object> userMap = buildUserInfoResponse(user);
// 最终返回结构
Map<String, Object> 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":"1"}
* @param request
* @return 收益明细分页数据
*/
@PostMapping("/api/worker/money/log")
public AjaxResult getWorkerMoneyLog(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 校验token并获取用户
String token = request.getHeader("token");
Map<String, Object> 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<WorkerMoneyLog> logList = workerMoneyLogService.selectWorkerMoneyLogList(query);
PageInfo<WorkerMoneyLog> pageInfo = new PageInfo<>(logList);
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (WorkerMoneyLog log : logList) {
Map<String, Object> 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<String, Object> 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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
for (int i = 1; i <= pageInfo.getPages(); i++) {
Map<String, Object> 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<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
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<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验token并获取用户
String token = request.getHeader("token");
Map<String, Object> 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;
// 3. 构建查询条件
WechatTransfer query = new WechatTransfer();
query.setUid(user.getId());
//if (type != null) query.setStatus(type);
PageHelper.startPage(page, limit);
List<WechatTransfer> logList = wechatTransferService.selectWechatTransferList(query);
PageInfo<WechatTransfer> pageInfo = new PageInfo<>(logList);
// 4. 数据组装
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (WechatTransfer log : logList) {
Map<String, Object> 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<String, Object> 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<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验token并获取用户
String token = request.getHeader("token");
Map<String, Object> 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());
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);
}
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. 获取当前登录师傅IDtoken在header
String token = request.getHeader("token");
Map<String, Object> 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("您不是该订单的师傅");
}
// if (order.getStatus() == null || order.getStatus() != 2L) {
// return AppletControllerUtil.appletWarning("订单状态不正确");
// }
// if (order.getJsonStatus() == null || order.getJsonStatus() != 3) {
// return AppletControllerUtil.appletWarning("订单进度不正确");
// }
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<String, Object> 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("请输入手机号后两位");
}
// 2. 获取当前登录师傅IDtoken在header
String token = request.getHeader("token");
Map<String, Object> 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<String> 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());
}
}
}
Map<String, Object> data = new HashMap<>();
data.put("basic", basicList);
return AjaxResult.success(data);
}
/**
* 报价获取服务项目
* GET /api/worker/quote/craft/{goodsId}
*/
@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<QuoteType> typeList = quoteTypeService.selectQuoteTypeList(typeQuery);
List<Object> dataArr = new ArrayList<>();
for (QuoteType type : typeList) {
Map<String, Object> typeMap = new HashMap<>();
typeMap.put("id", type.getId());
typeMap.put("title", type.getTitle());
// 3. 查询工艺IQuoteCraftService
QuoteCraft craftQuery = new QuoteCraft();
craftQuery.setTypeId("[\"" + type.getId() + "\"]");
List<QuoteCraft> craftList = quoteCraftService.selectQuoteCraftList(craftQuery);
List<Map<String, Object>> craftArr = new ArrayList<>();
for (QuoteCraft craft : craftList) {
Map<String, Object> 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<String> 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) {
typeIdList.add(typeIdStr);
}
craftMap.put("type_id", typeIdList);
craftArr.add(craftMap);
}
typeMap.put("craft", craftArr);
dataArr.add(typeMap);
}
Map<String, Object> result = new HashMap<>();
result.put("data", dataArr);
result.put("code", 200);
result.put("msg", "OK");
return result;
}
/**
* 报价所需物料查询
* GET /api/worker/quote/material/{goodsId}
*/
@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<QuoteMaterialType> typeList = quoteMaterialTypeService.selectQuoteMaterialTypeList(typeQuery);
List<Object> dataArr = new ArrayList<>();
for (QuoteMaterialType type : typeList) {
Map<String, Object> typeMap = new HashMap<>();
typeMap.put("id", type.getId());
typeMap.put("title", type.getTitle());
// 3. 查询物料信息IQuoteMaterialService
QuoteMaterial materialQuery = new QuoteMaterial();
materialQuery.setTypeId("\"" + type.getId() + "\"");
List<QuoteMaterial> materialList = quoteMaterialService.selectQuoteMaterialList(materialQuery);
List<Map<String, Object>> materialArr = new ArrayList<>();
for (QuoteMaterial material : materialList) {
Map<String, Object> 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<String> 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) {
typeIdList.add(typeIdStr);
}
materialMap.put("type_id", typeIdList);
materialArr.add(materialMap);
}
typeMap.put("material", materialArr);
dataArr.add(typeMap);
}
Map<String, Object> result = new HashMap<>();
result.put("data", dataArr);
result.put("code", 200);
result.put("msg", "OK");
return result;
}
/**
* 师傅报价接口
* POST /api/worker/estimate
*/
@PostMapping("/api/worker/estimate")
public AjaxResult workerEstimate(@RequestBody Map<String, Object> 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<Map<String, Object>> craftList = (List<Map<String, Object>>) params.get("craft");
if (craftList != null) {
for (Map<String, Object> 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)));
ServiceAllPrice = ServiceAllPrice.add(price.multiply(BigDecimal.valueOf(count)));
}
}
}
}
List<Map<String, Object>> materialList = (List<Map<String, Object>>) params.get("material");
if (materialList != null) {
for (Map<String, Object> 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)));
GoodsAllPrice = GoodsAllPrice.add(price.multiply(BigDecimal.valueOf(count)));
}
}
}
}
BigDecimal reductionPrice = BigDecimal.ZERO;
String reduction = params.get("reduction").toString();
if (reduction != null && !reduction.trim().isEmpty()) {
reductionPrice = new BigDecimal(reduction);
totalPrice = totalPrice.subtract(reductionPrice);
}
// 2. 组装新json
Map<String, Object> resultJson = new LinkedHashMap<>();
// project
Map<String, Object> project = new LinkedHashMap<>();
project.put("name", "项目费用");
project.put("price", totalPrice);
resultJson.put("project", project);
Map<String, Object> reductionproject = new LinkedHashMap<>();
reductionproject.put("name", "优惠金额");
reductionproject.put("price", params.get("reduction"));
resultJson.put("reduction", reductionproject);
Map<String, Object> depositproject = new LinkedHashMap<>();
depositproject.put("name", "定金");
depositproject.put("price", params.get("price"));
resultJson.put("deposit", depositproject);
// basic
resultJson.put("basic", params.get("basic"));
// craft
List<Map<String, Object>> craftListNew = new ArrayList<>();
if (craftList != null) {
for (Map<String, Object> craft : craftList) {
Map<String, Object> 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<Map<String, Object>> materialListNew = new ArrayList<>();
if (materialList != null) {
for (Map<String, Object> material : materialList) {
Map<String, Object> 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 {
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"));
}else {
log.setDeposit(BigDecimal.ZERO);
}
log.setPrice(totalPrice.add(reductionPrice));
log.setPaid(1l);
if (params.get("reduction") != null) {
log.setReductionPrice(new BigDecimal(params.get("reduction").toString()));
} else {
log.setReductionPrice(BigDecimal.ZERO);
}
log.setWorkerCost(ServiceAllPrice.subtract(reductionPrice));
//log.set
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<String, Object> 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(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<String, Object> logItem = new LinkedHashMap<>();
logItem.put("name", "师傅开始服务");
logItem.put("image", params.get("image"));
logItem.put("type", 1);
List<Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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("操作失败");
}
}
/**
* 结束订单
* POST
* 参数:{"id":订单id}
*/
@PostMapping("/api/worker/order/end")
public AjaxResult workerOrderEnd(@RequestBody Map<String, Object> 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);
// 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);
// 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.setStatus(1);//锁单
moneyLog.setStatusType(0);//后台锁定
moneyLog.setBeginlook(new Date());
//7天锁单
LocalDateTime ldt = LocalDateTime.now().plusDays(7);
Date end = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
moneyLog.setEndlook(end);
moneyLog.setLookday(7);
moneyLog.setLookMoney(price);
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());
}
}
/**
* 云信交互式语音通知呼叫结果推送回调接口
* 用于接收云信平台推送的交互式语音通知呼叫结果。
*
* @param requestBody 云信平台推送的JSON字符串
* @return 必须返回{"resultCode":"200"},否则云信认为推送失败
*/
@PostMapping("/api/voice/interactNotify/resultCallback")
public Map<String, Object> 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<String, Object> resp = new java.util.HashMap<>();
resp.put("resultCode", "200");
return resp;
}
/**
* 云信交互式小号呼叫结果推送结果推送回调接口
* 用于接收云信平台推送的交互式语音通知呼叫结果。
*
* @param requestBody 云信平台推送的JSON字符串
* @return 必须返回{"resultCode":"200"},否则云信认为推送失败
*/
@PostMapping("/api/voice/middleNumberAXB/resultCallback")
public Map<String, Object> 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<String, Object> resp = new java.util.HashMap<>();
resp.put("resultCode", "200");
return resp;
}
/**
* 抢单大厅 - 获取可抢订单列表
* <p>
* 功能说明:
* - 查询状态为1待接单的订单
* - 支持分页查询
* - 组装商品信息和系统配置
* - 返回标准分页格式数据
*
* @param params 请求参数,包含分页信息
* @param request HTTP请求对象
* @return 抢单大厅订单列表数据
*/
@PostMapping(value = "/api/worker/grab/lst")
public AjaxResult getWorkerGrabOrderList(@RequestBody Map<String, Object> 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<Order> orderList = orderService.selectOrderList(orderQuery);
PageInfo<Order> pageInfo = new PageInfo<>(orderList);
// 4. 组装订单数据
List<Map<String, Object>> formattedOrderList = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Order order : orderList) {
Map<String, Object> 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("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<String, Object> 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) {
// 查询异常时的默认信息
productData.put("id", order.getProductId());
productData.put("title", "商品信息获取失败");
productData.put("icon", "");
productData.put("price", "0.00");
}
} else {
productData.put("id", null);
productData.put("title", "");
productData.put("icon", "");
productData.put("price", "0.00");
}
orderData.put("product", productData);
formattedOrderList.add(orderData);
}
// 6. 构建分页数据
String baseUrl = request.getRequestURL().toString().split("\\?")[0];
Map<String, Object> paginationData = AppletControllerUtil.buildPageResult(pageInfo, formattedOrderList, baseUrl);
// 7. 查询系统配置config_one
Map<String, Object> configData = new HashMap<>();
try {
SiteConfig siteConfigQuery = new SiteConfig();
siteConfigQuery.setName("config_one");
List<SiteConfig> configList = siteConfigService.selectSiteConfigList(siteConfigQuery);
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);
}
} else {
// 配置不存在时的默认配置
setDefaultConfig(configData);
}
} catch (Exception e) {
// 查询配置异常时的默认配置
setDefaultConfig(configData);
}
// 8. 构建最终返回数据
Map<String, Object> 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
* <p>
* 接口说明:
* - 接收商品订单相关信息
* - 调用IGoodsOrderCursorService新增一条数据
* - 返回商品ID作为响应数据
* <p>
*/
@PostMapping("/api/service/cursor")
public AjaxResult serviceCursor(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 参数验证
if (params == null) {
return AppletControllerUtil.appletWarning("请求参数不能为空");
}
// 验证必要参数
if (params.get("product_id") == null) {
return AppletControllerUtil.appletWarning("商品ID不能为空");
}
if (params.get("num") == null) {
return AppletControllerUtil.appletWarning("商品数量不能为空");
}
// 2. 解析参数
Long productId;
Integer num;
String sku = params.get("sku") != null ? params.get("sku").toString() : "";
try {
productId = Long.valueOf(params.get("product_id").toString());
num = Integer.valueOf(params.get("num").toString());
} catch (NumberFormatException e) {
return AppletControllerUtil.appletWarning("参数格式错误");
}
// 3. 验证参数有效性
if (productId <= 0) {
return AppletControllerUtil.appletWarning("商品ID无效");
}
if (num <= 0) {
return AppletControllerUtil.appletWarning("商品数量必须大于0");
}
// 4. 验证商品是否存在
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId);
if (serviceGoods == null) {
return AppletControllerUtil.appletWarning("商品不存在");
}
// 5. 验证商品状态
if (serviceGoods.getStatus() == null || !"1".equals(serviceGoods.getStatus())) {
return AppletControllerUtil.appletWarning("商品已下架或不可购买");
}
// 6. 验证库存(如果有库存管理)
if (serviceGoods.getStock() != null && serviceGoods.getStock() < num) {
return AppletControllerUtil.appletWarning("商品库存不足");
}
// 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 AppletControllerUtil.appletWarning("SKU库存不足");
}
} catch (NumberFormatException e) {
// SKU库存格式错误忽略验证
}
}
} catch (Exception e) {
// SKU JSON格式错误但不影响主流程
}
}
// 8. 构建GoodsOrderCursor对象
GoodsOrderCursor goodsOrderCursor = new GoodsOrderCursor();
goodsOrderCursor.setProductId(productId);
goodsOrderCursor.setType(2l);
goodsOrderCursor.setNum(num.longValue());
goodsOrderCursor.setSku(sku);
// 设置其他必要字段
// 计算价格从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));
}
}
goodsOrderCursor.setTotalPrice(totalPrice);
// goodsOrderCursor.setProductName(serviceGoods.getTitle());
// 9. 调用服务新增数据
int result = goodsOrderCursorService.insertGoodsOrderCursor(goodsOrderCursor);
if (result > 0) {
// 10. 返回商品ID
return AppletControllerUtil.appletSuccess(goodsOrderCursor.getId());
} else {
return AppletControllerUtil.appletWarning("数据保存失败");
}
} catch (Exception e) {
System.err.println("商品订单游标接口异常:" + e.getMessage());
return AppletControllerUtil.appletWarning("操作失败:" + e.getMessage());
}
}
/**
* 云信交互式小号呼叫结果推送结果推送回调接口
* 用于接收云信平台推送的交互式语音通知呼叫结果。
*
* @return 必须返回{"resultCode":"200"},否则云信认为推送失败
*/
@PostMapping("api/worker/withdraw")
public Map<String, Object> withdraw(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletUnauthorized();
}
String orderId =GenerateCustomCode.generCreateOrder("TX");
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
String money = params.get("money").toString();
if (money == null || money.trim().isEmpty()) {
return AppletControllerUtil.appletWarning("提现金额不能为空");
}
BigDecimal moneyBigDecimal = new BigDecimal(money);
if (moneyBigDecimal.compareTo(BigDecimal.ZERO) <= 0) {
return AppletControllerUtil.appletWarning("提现金额必须大于0");
}
if (moneyBigDecimal.compareTo(user.getCommission()) > 0) {
return AppletControllerUtil.appletWarning("提现金额不能大于账户余额");
}
if (moneyBigDecimal.compareTo(new BigDecimal("2000")) > 0) {
return AppletControllerUtil.appletWarning("提现金额不能大于2000");
}
//--------------------------预留提现的接口实现核心逻辑开始--------------------------------
//------------------------------------结束--------------------------------
WechatTransfer wechatTransfer = new WechatTransfer();
wechatTransfer.setUid(user.getId());
wechatTransfer.setMoney(moneyBigDecimal);
wechatTransfer.setUname(user.getName());
wechatTransfer.setOrderId(orderId);
wechatTransfer.setStatus(1L);
wechatTransfer.setPaid(0L);
wechatTransfer.setOpenid(user.getOpenid());
int flg= wechatTransferService.insertWechatTransfer(wechatTransfer);
if(flg>0){
//减少师傅提现的余额
user.setCommission(user.getCommission().subtract(moneyBigDecimal));
//增加师傅的累计提现金额
user.setPropose(user.getPropose().add(moneyBigDecimal));
usersService.updateUsers(user);
}
Map<String, Object> resp = new java.util.HashMap<>();
resp.put("resultCode", "200");
return resp;
}
/**
* 获取商品订单临时信息
*
* @param id 订单临时ID
* @param request HTTP请求对象
* @return 订单临时信息及关联商品信息
* <p>
* 接口说明:
* - 根据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无效");
}
// 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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 params 请求参数包含id(充值类目ID)、money(充值金额)
* @param request HTTP请求对象
* @return 支付结果
*/
@PostMapping("api/member/recharge/pay")
public AjaxResult memberRechargePay(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 新增参数判断逻辑:只允许 id 和 money 有一个有值,不允许两个都为空或 null如果两个都有值只走 id 有值的逻辑
Object idObj = params.get("id");
Object moneyObj = params.get("money");
boolean idEmpty = (idObj == null || idObj.toString().trim().isEmpty());
boolean moneyEmpty = (moneyObj == null || moneyObj.toString().trim().isEmpty());
if (idEmpty && moneyEmpty) {
return AppletControllerUtil.appletWarning("参数不能为空,类目和金额必须有一个有值");
}
// 如果 id 和 money 都有值,只走 id 逻辑money 置空
if (!idEmpty && !moneyEmpty) {
moneyObj = null;
}
String money = "";
UserMemberRechargeLog userMemberRechargeLog = new UserMemberRechargeLog();
userMemberRechargeLog.setUid(Math.toIntExact(user.getId()));
userMemberRechargeLog.setOrderid(GenerateCustomCode.generCreateOrder("DYZ"));
userMemberRechargeLog.setPaytype(0);
userMemberRechargeLog.setPaytime(new Date());
if (!idEmpty) { // id 有值,优先走 id 逻辑
UserMemberRechargeProgram userMemberRechargeProgram = userMemberRechargeProgramService.selectUserMemberRechargeProgramById(Integer.valueOf(idObj.toString()));
if (userMemberRechargeProgram != null) {
userMemberRechargeLog.setInmoney(userMemberRechargeProgram.getMoney());
userMemberRechargeLog.setComemoney(userMemberRechargeProgram.getDiscount());
userMemberRechargeLog.setReamk("购买" + userMemberRechargeProgram.getRechargename() + "应付" + userMemberRechargeProgram.getMoney() + "元,应到" + userMemberRechargeProgram.getDiscount() + "");
userMemberRechargeLog.setProid(userMemberRechargeProgram.getId());
money = userMemberRechargeProgram.getMoney().toString();
// type大于0就是会员包年充值回调需要特殊处理
if (userMemberRechargeProgram.getType() > 0) {
userMemberRechargeLog.setIsmember(1);
} else {
userMemberRechargeLog.setIsmember(2);
}
}
} else if (!moneyEmpty) { // 只有 money 有值
money = moneyObj.toString();
userMemberRechargeLog.setInmoney(new BigDecimal(money));
userMemberRechargeLog.setComemoney(new BigDecimal(money));
userMemberRechargeLog.setIsmember(2);
userMemberRechargeLog.setReamk("会员现金充值" + money + "");
}
if (userMemberRechargeLogService.insertUserMemberRechargeLog(userMemberRechargeLog) > 0) {
Map<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(
user.getOpenid(),
userMemberRechargeLog.getId().toString(),
new BigDecimal("0.01"),
1,
"https://7ce20b15.r5.cpolar.xyz/api/recharge/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> responseData = new HashMap<>();
responseData.put("mainOrderId", String.valueOf(userMemberRechargeLog.getId().toString()));
//responseData.put("orderList", orderList);
responseData.put("totalAmount", money);
responseData.put("prepayId", payResult.get("prepayId"));
// 直接合并所有支付参数
responseData.putAll(payResult);
return AppletControllerUtil.appletSuccess(responseData);
} else {
String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败";
return AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
}
return AppletControllerUtil.appletWarning("支付失败");
}
/**
* 获取充值类目(用于充值项目选择)
*
* @return 充值类目列表
*/
@GetMapping("/api/member/recharge/catalogue")
public AjaxResult getRechargeCatalogue() {
try {
UserMemberRechargeProgram query = new UserMemberRechargeProgram();
query.setStatus(0);
query.setType(0);
List<UserMemberRechargeProgram> list = userMemberRechargeProgramService.selectUserMemberRechargeProgramList(query);
return AppletControllerUtil.appletSuccess(list);
} catch (Exception e) {
return AppletControllerUtil.appletError("获取充值类目失败:" + e.getMessage());
}
}
/**
* 获取包年充值项目
*
* @param id 类型ID
* @return 包年充值项目列表
*/
@GetMapping("/api/member/recharge/catal/{id}")
public AjaxResult getRechargeCatalyear(@PathVariable("id") int id) {
try {
UserMemberRechargeProgram query = new UserMemberRechargeProgram();
query.setStatus(0);
query.setType(id);
List<UserMemberRechargeProgram> list = userMemberRechargeProgramService.selectUserMemberRechargeProgramList(query);
if (!list.isEmpty()){
return AppletControllerUtil.appletSuccess(list);
}else{
return AppletControllerUtil.appletWarning("暂无数据");
}
} catch (Exception e) {
return AppletControllerUtil.appletError("获取充值类目失败:" + e.getMessage());
}
}
/**
* 获取用户充值记录
*
* @param request HTTP请求对象
* @return 用户充值记录列表
*/
@GetMapping("/api/member/recharge/log")
public AjaxResult getRechargelog(HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
try {
UserMemberRechargeLog query = new UserMemberRechargeLog();
query.setUid(Math.toIntExact(user.getId()));
List<UserMemberRechargeLog> list = userMemberRechargeLogService.selectUserMemberRechargeLogList(query);
if (!list.isEmpty()){
return AppletControllerUtil.appletSuccess(list);
}else{
return AppletControllerUtil.appletWarning("暂无数据");
}
} catch (Exception e) {
return AppletControllerUtil.appletError("获取数据失败:" + e.getMessage());
}
}
/**
* 获取用户消费记录
*
* @param request HTTP请求对象
* @return 用户消费记录
*/
@GetMapping("/api/member/consumption/log")
public AjaxResult getconsumptionlog(HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
try {
UserMemnerConsumptionLog query = new UserMemnerConsumptionLog();
query.setUid(Math.toIntExact(user.getId()));
List<UserMemnerConsumptionLog> list = userMemnerConsumptionLogService.selectUserMemnerConsumptionLogList(query);
if (!list.isEmpty()){
return AppletControllerUtil.appletSuccess(list.getFirst());
}else{
return AppletControllerUtil.appletWarning("暂无数据");
}
} catch (Exception e) {
return AppletControllerUtil.appletError("获取充值类目失败:" + e.getMessage());
}
}
/**
* 用户发票信息保存/修改接口
*
* @param params 请求参数包含id(发票信息ID)、invoiceTitle(发票抬头)、taxNumber(纳税人识别号)、bankName(开户银行)、bankAccount(银行账号)、address(单位地址)、phone(联系电话)、email(联系邮箱)、wechat(微信号)、type(发票类型)、category(发票类别)
* @param request HTTP请求对象
* @return 保存结果
*/
// @PostMapping("/api/user/invoice/info")
// public AjaxResult saveOrUpdateUserInvoiceInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// // 1. 验证用户登录状态
// String token = request.getHeader("token");
// Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
// if (!(Boolean) userValidation.get("valid")) {
// return AppletControllerUtil.appletWarning("用户未登录或token无效");
// }
// // 2. 获取用户信息
// Users user = (Users) userValidation.get("user");
// if (user == null) {
// return AppletControllerUtil.appletWarning("用户信息获取失败");
// }
//
// // 3. 构建发票信息对象
// UsersInvoiceInfo info = new UsersInvoiceInfo();
// info.setUid(user.getId().intValue());
// info.setInvoiceTitle((String) params.get("invoiceTitle"));
// info.setTaxNumber((String) params.get("taxNumber"));
// info.setBankName((String) params.get("bankName"));
// info.setBankAccount((String) params.get("bankAccount"));
// info.setAddress((String) params.get("address"));
// info.setPhone((String) params.get("phone"));
// info.setEmail((String) params.get("email"));
// info.setWechat((String) params.get("wechat"));
// info.setType(Integer.parseInt(params.get("type").toString()));
// info.setCategory(Integer.parseInt(params.get("category").toString()));
//
// // 4. 保存或更新发票信息
// Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : null;
// if (id != null) {
// info.setId(id);
// usersInvoiceInfoService.updateUsersInvoiceInfo(info);
// } else {
// usersInvoiceInfoService.insertUsersInvoiceInfo(info);
// }
// return AppletControllerUtil.appletSuccess();
// }
// ... existing code ...
@PostMapping("/api/user/invoice/info")
public AjaxResult saveOrUpdateUserInvoiceInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 获取新参数并校验必填
Long orderId = params.get("orderid") != null ? Long.valueOf(params.get("orderid").toString()) : null;
Integer dataType = params.get("datatype") != null ? Integer.valueOf(params.get("datatype").toString()) : null;
if (orderId == null || dataType == null) {
return AppletControllerUtil.appletWarning("orderid和datatype不能为空");
}
BigDecimal invoiceMoney = BigDecimal.ZERO;
String invoiceText = "";
if (dataType == 1) {
GoodsOrder order = goodsOrderService.selectGoodsOrderById(orderId);
if (order != null) {
invoiceMoney = order.getTotalPrice();
invoiceText = "商品订单-" + order.getOrderId();
}
} else if (dataType == 2) {
Order order = orderService.selectOrderById(orderId);
if (order != null) {
invoiceMoney = order.getTotalPrice();
invoiceText = "服务订单-" + order.getOrderId();
}
} else if (dataType == 3) {
UserMemberRechargeLog recharge = userMemberRechargeLogService.selectUserMemberRechargeLogById(orderId.intValue());
if (recharge != null) {
invoiceMoney = recharge.getInmoney();
invoiceText = "充值订单-" + recharge.getInmoney();
}
}
// 4. 构建发票信息对象
UsersInvoiceInfo info = new UsersInvoiceInfo();
info.setUid(user.getId().intValue());
info.setInvoiceTitle((String) params.get("invoiceTitle"));
info.setTaxNumber((String) params.get("taxNumber"));
info.setBankName((String) params.get("bankName"));
info.setBankAccount((String) params.get("bankAccount"));
info.setAddress((String) params.get("address"));
info.setPhone((String) params.get("phone"));
info.setEmail((String) params.get("email"));
info.setWechat((String) params.get("wechat"));
info.setType(Integer.parseInt(params.get("type").toString()));
info.setCategory(Integer.parseInt(params.get("category").toString()));
info.setOrderid(orderId.toString());
info.setInvoicemoney(invoiceMoney);
info.setStatus(1);
info.setInvoicetext(invoiceText);
// 5. 保存或更新发票信息
Integer id = params.get("id") != null ? Integer.parseInt(params.get("id").toString()) : null;
if (id != null) {
info.setId(id);
usersInvoiceInfoService.updateUsersInvoiceInfo(info);
} else {
usersInvoiceInfoService.insertUsersInvoiceInfo(info);
}
return AppletControllerUtil.appletSuccess();
}
/**
* 查询用户发票信息列表接口
*
* @param request HTTP请求对象
* @return 用户发票信息列表
*/
@GetMapping("/api/user/invoice/list")
public AjaxResult getUserInvoiceInfoList(HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
UsersInvoiceInfo query = new UsersInvoiceInfo();
query.setUid(user.getId().intValue());
// 3. 查询用户发票信息列表
List<UsersInvoiceInfo> list = usersInvoiceInfoService.selectUsersInvoiceInfoList(query);
return AppletControllerUtil.appletSuccess(list);
}
/**
* 删除用户发票信息接口
*
* @param id 发票信息ID
* @param request HTTP请求对象
* @return 删除结果
*/
@DeleteMapping("/api/user/invoice/info/{id}")
public AjaxResult deleteUserInvoiceInfo(@PathVariable("id") Integer id, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 删除用户发票信息
int result = usersInvoiceInfoService.deleteUsersInvoiceInfoById(id);
if (result > 0) {
return AppletControllerUtil.appletSuccess();
} else {
return AppletControllerUtil.appletWarning("删除失败");
}
}
/**
* 验证用户图像和昵称是否为系统默认
*
* @param request HTTP请求对象
* @return 验证结果
*/
@GetMapping("/api/user/check/default")
public AjaxResult checkUserDefault(HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 验证图像和昵称是否为系统默认
String defaultAvatar = "https://img.huafurenjia.cn/default/user_avatar.jpeg";
String defaultName = "微信用户";
if (defaultAvatar.equals(user.getAvatar()) && defaultName.equals(user.getName())) {
return AppletControllerUtil.appletWarning("请修改您的图像和昵称");
}
return AppletControllerUtil.appletSuccess("校验通过");
} catch (Exception e) {
System.err.println("验证用户图像和昵称异常:" + e.getMessage());
return AppletControllerUtil.appletError("验证失败:" + e.getMessage());
}
}
/**
* 拼团支付接口
* IUserGroupBuyingService userGroupBuyingService;
*/
@PostMapping("api/group/once_pay")
public AjaxResult apigroupOncePay(@RequestBody Map<String, Object> params, HttpServletRequest request) {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletWarning("用户未登录或token无效");
}
// 2. 获取用户信息
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletWarning("用户信息获取失败");
}
// 3. 验证必要参数
if (params == null || params.get("id") == null) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
Long orderId = Long.valueOf(params.get("id").toString());
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(orderId);
if (serviceGoods == null) {
return AppletControllerUtil.appletWarning("商品信息获取失败");
}
UserGroupBuying userGroupBuying = new UserGroupBuying();
userGroupBuying.setId(orderId);
userGroupBuying.setUid(user.getId());
userGroupBuying.setStatus(Long.valueOf(4));
userGroupBuying.setUname(user.getName());
userGroupBuying.setProductId(serviceGoods.getId());
userGroupBuying.setPaytype(Long.valueOf(1));
userGroupBuying.setMoney(serviceGoods.getGroupprice());
userGroupBuying.setOrderid(GenerateCustomCode.generCreateOrder("G"));
int flg =userGroupBuyingService.insertUserGroupBuying(userGroupBuying);
if (flg > 0) {
Map<String, Object> payResult = wechatPayUtil.createBatchOrderAndPay(user.getOpenid(),
userGroupBuying.getId().toString(),
new BigDecimal(0.01),
1,
"https://7ce20b15.r5.cpolar.xyz/api/group/pay/notify");
if (payResult != null && Boolean.TRUE.equals(payResult.get("success"))) {
Map<String, Object> responseData = new HashMap<>();
responseData.put("mainOrderId", userGroupBuying.getOrderid());
//responseData.put("orderList", orderList);
responseData.put("totalAmount", serviceGoods.getGroupprice());
responseData.put("prepayId", payResult.get("prepayId"));
// 直接合并所有支付参数
responseData.putAll(payResult);
return AppletControllerUtil.appletSuccess(responseData);
} else {
String errorMsg = payResult != null ? (String) payResult.get("message") : "微信支付下单失败";
return AppletControllerUtil.appletWarning("支付下单失败:" + errorMsg);
}
}
return AppletControllerUtil.appletWarning("支付失败");
}
}