From 3d18a1972b76f12f127cdfcfe56460aae965bc57 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Fri, 16 Oct 2026 16:25:03 +0800 Subject: [PATCH 01/73] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E8=BE=93=E5=85=A5=E4=B8=8E=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E4=BA=A4=E4=BA=92=E8=AE=BE=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...026-10-16-预约客户输入与选择交互-design.md | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md diff --git a/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md new file mode 100644 index 00000000..efc815c7 --- /dev/null +++ b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md @@ -0,0 +1,52 @@ +# 预约客户输入与选择交互设计 + +## 目标 + +优化 Salon 小程序新增预约页面的客户录入体验:客户姓名直接输入,已有客户通过按钮选择;未选择已有客户时,在提交阶段按统一唯一性规则检查客户,并在需要时引导创建客户。 + +## 唯一性规则 + +- 客户姓名和手机号都填写时,以“姓名 + 手机号”作为唯一组合。 +- 手机号为空时,以客户姓名作为唯一键。 +- 后端创建客户和预约关联前必须再次校验,前端检查仅用于改善交互,不能替代后端校验。 +- 已存在同一唯一键的客户不得重复创建。 + +## 页面交互 + +### 主表单 + +客户字段改为横向布局:左侧为客户姓名输入框,右侧为“选择已有客户”按钮。手机号作为同一客户信息的可选输入项保留在客户区域内。输入姓名或手机号时清除 `customerUserId`,防止修改文本后仍绑定旧客户。 + +点击“选择已有客户”打开现有底部选择页,支持按姓名或手机号搜索;选择后回填客户 ID、姓名和手机号并关闭选择页。 + +### 提交前检查 + +未选择已有客户且填写客户姓名时,提交预约前调用客户查询接口,使用姓名和手机号作为查询条件: + +1. 找到唯一匹配客户:弹窗询问“已找到匹配客户,是否使用该客户”,按钮为“使用已有客户”和“继续新建”。选择使用则回填客户 ID 后继续提交;继续新建则进入创建确认。 +2. 未找到匹配客户:弹窗询问“系统中没有该客户,是否新建客户”,按钮为“确认”和“不新建”。确认后调用客户创建接口,成功后使用返回 ID 提交预约;不新建则取消本次提交。 +3. 后端返回唯一性冲突:提示客户已存在并要求重新选择或修改信息,不重复创建。 + +手机号为空时不要求手机号格式校验;填写手机号时仍校验中国大陆手机号格式。客户姓名仍为预约必填字段。 + +## 后端接口与模型 + +- 扩展 `GET /manager/customers` 的姓名、手机号筛选能力,保证查询条件能够表达姓名加手机号的组合。 +- 调整 `POST /manager/customers`:手机号改为可选;无手机号时不生成手机号账号,使用系统生成的不可登录账号或现有客户创建约定;有手机号时保留现有账号兼容逻辑。 +- 创建前在事务内按唯一性规则查询并拒绝重复,返回明确业务错误。 +- 不修改预约提交协议,预约仍使用 `customerUserId`、`customerName` 和 `phone` 字段。 +- 保留已有客户列表、详情和其他端客户管理能力;后端规则对所有入口生效。 + +## 状态与错误处理 + +- 查询或创建失败时保持用户输入,不关闭页面,提示可重试。 +- 创建成功但预约提交失败时保留返回的客户 ID 和表单内容,避免重复创建;再次提交优先使用已创建客户。 +- 选择已有客户、手动输入、弹窗关闭均不清除未提交的姓名和手机号,除非用户明确选择其他客户。 + +## 兼容与测试 + +- 复用 `entity-selector-sheet`,不新增客户选择组件。 +- 覆盖已有客户选择、姓名输入清除绑定、姓名+手机号命中、仅姓名命中、未命中后确认创建、取消创建、手机号为空和重复创建冲突场景。 +- 后端测试覆盖有手机号组合唯一、无手机号姓名唯一、并发重复创建和旧客户数据兼容。 +- 不修改 ArtList、Nacos 或数据库初始化基线;如现有表约束无法表达规则,仅新增中文版本 SQL 变更脚本。 + -- 2.54.0 From 4a7bd9008876f52c5d71bf456a25bd02b063f993 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Fri, 16 Oct 2026 17:33:58 +0800 Subject: [PATCH 02/73] =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E8=BE=93=E5=85=A5=E4=B8=8E=E5=94=AF=E4=B8=80?= =?UTF-8?q?=E6=80=A7=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/AdminManagerController.java | 23 ++- .../manager/dto/ManagerCustomerCreateDTO.java | 3 - .../service/impl/PlanningServiceImpl.java | 39 ++--- .../modules/user/service/UserService.java | 5 + .../user/service/impl/UserServiceImpl.java | 90 +++++++++++- JC-Salon-WeChat/api/customers.js | 7 + .../appointment-form/entity-selector.test.js | 29 +++- .../pages/appointment-form/index.js | 138 ++++++++++++------ .../pages/appointment-form/index.wxml | 43 +----- .../pages/appointment-form/index.wxss | 96 ++++++------ ...026-10-16-预约客户输入与选择交互-design.md | 2 +- docs/项目变更记录.md | 7 + 12 files changed, 318 insertions(+), 164 deletions(-) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java index 2474ec4e..308f420a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java @@ -141,6 +141,16 @@ public class AdminManagerController { return Result.success(result); } + @GetMapping("/customers/matches") + @RequirePermission("user:view") + public Result> customerMatches(HttpServletRequest request, + @RequestParam String nickname, + @RequestParam(required = false) String phone) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(userService.findCustomerMatches(nickname, phone, shopId)); + } + @GetMapping("/customers/{id}") @RequirePermission("user:view") public Result customer(HttpServletRequest request, @PathVariable Long id) { @@ -157,18 +167,7 @@ public class AdminManagerController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再新增客户"); Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); - String phone = dto.getPhone().trim(); - UserDTO userDTO = new UserDTO(); - userDTO.setNickname(dto.getNickname().trim()); - userDTO.setPhone(phone); - userDTO.setContactPhone(phone); - userDTO.setAccount(phone); - userDTO.setType(0); - userDTO.setShopId(shopId); - userDTO.setShopIds(List.of(shopId)); - userDTO.setLevel("普通"); - userDTO.setVipId(0L); - return Result.success(userService.createUser(userDTO)); + return Result.success(userService.createManagerCustomer(dto.getNickname(), dto.getPhone(), shopId)); } @GetMapping("/employees") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java index 396e8700..43fd0742 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java @@ -3,7 +3,6 @@ package com.xiaowang.jayucloud.salon.core.modules.manager.dto; import lombok.Data; import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; @Data public class ManagerCustomerCreateDTO { @@ -11,7 +10,5 @@ public class ManagerCustomerCreateDTO { @NotBlank(message = "客户姓名不能为空") private String nickname; - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") private String phone; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index 21a076f2..d7a04df9 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -23,6 +23,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; import com.xiaowang.jayucloud.salon.core.modules.planning.service.PlanningService; @@ -71,7 +72,6 @@ public class PlanningServiceImpl implements PlanningService { private static final String RESERVATION_UNASSIGNED = "UNASSIGNED"; private static final String ASSIGNMENT_ASSIGNED = "ASSIGNED"; private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT"; - private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; private static final List ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED); private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final List ARTIST_COLORS = List.of( @@ -80,6 +80,7 @@ public class PlanningServiceImpl implements PlanningService { private final AdminScopeHelper adminScopeHelper; private final UserMapper userMapper; + private final UserService userService; private final NailArtistInfoMapper nailArtistInfoMapper; private final ArtistScheduleMapper artistScheduleMapper; private final ArtistScheduleExceptionMapper artistScheduleExceptionMapper; @@ -780,34 +781,26 @@ public class PlanningServiceImpl implements PlanningService { private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) { if (dto.getCustomerUserId() != null) { UserDO customer = userMapper.selectById(dto.getCustomerUserId()); - if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) { + if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete()) || !Integer.valueOf(0).equals(customer.getType())) { throw new RuntimeException("客户不存在"); } return customer; } - if (!hasText(dto.getPhone())) { - throw new RuntimeException("客户手机号不能为空"); + String customerName = firstNonBlank(dto.getCustomerName(), dto.getPhone()); + if (!hasText(customerName)) { + throw new RuntimeException("客户姓名不能为空"); } - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("is_delete", 0) - .and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone())) - .last("LIMIT 1"); - UserDO existing = userMapper.selectOne(wrapper); - if (existing != null) { - return existing; + String phone = trimToNull(dto.getPhone()); + List matches = + userService.findCustomerMatches(customerName, phone, shopId); + if (matches.size() > 1) { + throw new RuntimeException("存在多个匹配客户,请先选择已有客户"); } - UserDO customer = new UserDO(); - customer.setShopId(shopId); - customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone())); - customer.setPhone(dto.getPhone()); - customer.setContactPhone(dto.getPhone()); - customer.setAccount(dto.getPhone()); - customer.setPassword(ENCODED_UNSET_PASSWORD); - customer.setType(0); - customer.setStatus(1); - customer.setIsDelete(0); - userMapper.insert(customer); - return customer; + if (!matches.isEmpty()) { + return userMapper.selectById(matches.get(0).getId()); + } + Long customerId = userService.createManagerCustomer(customerName, phone, shopId); + return userMapper.selectById(customerId); } private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java index e517db55..62eab615 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java @@ -34,6 +34,11 @@ public interface UserService extends IService { */ Long createUser(UserDTO userDTO); + Long createManagerCustomer(String nickname, String phone, Long shopId); + + List findCustomerMatches(String nickname, String phone, Long shopId); + + /** * Update an existing record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index 7b65f92f..f703d3ee 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -69,6 +69,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import com.xiaowang.jayucloud.salon.core.modules.auth.dto.BindEmailRequestDTO; @@ -356,6 +357,10 @@ public class UserServiceImpl extends ServiceImpl implements @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserDTO userDTO) { + return createUserInternal(userDTO, false); + } + + private Long createUserInternal(UserDTO userDTO, boolean allowMissingCustomerPhone) { String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); // 检查账号是否已存在 UserDO existingUser = userMapper.selectOne( @@ -374,8 +379,12 @@ public class UserServiceImpl extends ServiceImpl implements List validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); Long validatedShopId = pickPrimaryShopId(validatedShopIds); - String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); Integer userType = userDTO.getType(); + String validatedPhone = validateUserPhone(userDTO.getPhone(), null, + !(allowMissingCustomerPhone && Integer.valueOf(0).equals(userType))); + if (Integer.valueOf(0).equals(userType)) { + ensureCustomerUnique(userDTO.getNickname(), validatedPhone); + } String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); @@ -461,6 +470,68 @@ public class UserServiceImpl extends ServiceImpl implements return userDO.getId(); } + @Override + @Transactional(rollbackFor = Exception.class) + public Long createManagerCustomer(String nickname, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) { + throw new RuntimeException("客户姓名不能为空"); + } + if (shopId == null || shopId <= 0) { + throw new RuntimeException("请先选择店铺后再新增客户"); + } + String normalizedPhone = phone == null || phone.trim().isEmpty() ? null : phone.trim(); + ensureCustomerUnique(nickname, normalizedPhone); + normalizedPhone = validateUserPhone(normalizedPhone, null, false); + UserDTO customer = new UserDTO(); + customer.setNickname(nickname.trim()); + customer.setPhone(normalizedPhone); + customer.setContactPhone(normalizedPhone); + customer.setAccount(normalizedPhone == null + ? "customer" + UUID.randomUUID().toString().replace("-", "") + : normalizedPhone); + customer.setType(0); + customer.setShopId(shopId); + customer.setShopIds(List.of(shopId)); + customer.setLevel(VIP_LEVEL_NORMAL); + customer.setVipId(0L); + return createUserInternal(customer, true); + } + + @Override + public List findCustomerMatches(String nickname, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) { + return List.of(); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + if (StringUtils.hasText(phone)) { + String normalizedPhone = phone.trim(); + wrapper.and(query -> query.eq(UserDO::getPhone, normalizedPhone) + .or().eq(UserDO::getContactPhone, normalizedPhone)); + } + if (shopId != null && shopId > 0) { + List shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (shopUserIds.isEmpty()) { + wrapper.eq(UserDO::getShopId, shopId); + } else { + wrapper.and(query -> query.eq(UserDO::getShopId, shopId) + .or().in(UserDO::getId, shopUserIds)); + } + } + return userMapper.selectList(wrapper).stream().map(user -> { + UserVO customer = new UserVO(); + customer.setId(user.getId()); + customer.setNickname(user.getNickname()); + customer.setAccount(user.getAccount()); + customer.setPhone(user.getPhone()); + customer.setContactPhone(user.getContactPhone()); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + return customer; + }).collect(Collectors.toList()); + } + /** * 分配默认权限 * @param userId 用户ID @@ -3047,6 +3118,23 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("手机号已被使用"); } } + + private void ensureCustomerUnique(String nickname, String phone) { + if (!StringUtils.hasText(nickname)) { + throw new RuntimeException("客户姓名不能为空"); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + if (StringUtils.hasText(phone)) { + wrapper.and(query -> query.eq(UserDO::getPhone, phone) + .or().eq(UserDO::getContactPhone, phone)); + } + if (userMapper.selectCount(wrapper) > 0) { + throw new RuntimeException("客户已存在,请选择已有客户"); + } + } /** * Run business method `buildRelationVO`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-WeChat/api/customers.js b/JC-Salon-WeChat/api/customers.js index d6a2b36b..8d4c25cd 100644 --- a/JC-Salon-WeChat/api/customers.js +++ b/JC-Salon-WeChat/api/customers.js @@ -14,6 +14,13 @@ module.exports = { }) }, + matchIdentity(nickname, phone) { + return request({ + url: '/manager/customers/matches', + params: { nickname, phone } + }) + }, + create(data) { return request({ url: '/manager/customers', diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index 128b531b..0eba88f5 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -7,13 +7,17 @@ global.wx = { setStorageSync: () => {}, removeStorageSync: () => {}, showToast: () => {}, + showModal: options => options.success({ confirm: modalConfirm }), navigateTo: () => {} } global.getApp = () => ({ globalData: { userInfo: { type: 2, id: 1, shopId: 2 } } }) +let modalConfirm = true + let definition global.Page = value => { definition = value } require('./index') +const customersApi = require('../../api/customers') function createPage() { return { @@ -39,11 +43,30 @@ async function run() { assert.strictEqual(page.data.customerSheetVisible, false) page.data.form.customerUserId = 18 - page.data.manualCustomerForm = { name: '新客户', phone: '13900139000' } - page.useManualCustomer() + page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '13900139000') + assert.strictEqual(page.data.form.phone, '') + + customersApi.matchIdentity = async () => [] + customersApi.create = async payload => { + assert.strictEqual(payload.nickname, '新客户') + assert.strictEqual(payload.phone, undefined) + return '42' + } + assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) + assert.strictEqual(page.data.form.customerUserId, '42') + + page.data.form.customerUserId = '' + page.data.form.customerName = '小周' + page.data.form.phone = '13800138000' + customersApi.matchIdentity = async (name, phone) => { + assert.strictEqual(name, '小周') + assert.strictEqual(phone, '13800138000') + return [{ id: '18', nickname: '小周', phone: '13800138000' }] + } + assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) + assert.strictEqual(page.data.form.customerUserId, '18') page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }] page.onArtistSearch({ detail: { value: '李' } }) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 2a47ba0f..68b7923d 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -295,8 +295,6 @@ Page({ customerKeyword: '', customerLoading: false, customerError: '', - manualCustomerVisible: false, - manualCustomerForm: { name: '', phone: '' }, products: [], filteredProducts: [], artists: [], @@ -434,6 +432,20 @@ Page({ } }, + onCustomerInput(event) { + const field = event.currentTarget.dataset.field + const patch = { + [`form.${field}`]: event.detail.value, + 'form.customerUserId': '' + } + if (field === 'customerName' && this.data.form.customerUserId) { + patch['form.phone'] = '' + } + this.setData({ + ...patch + }) + }, + openCustomerSheet() { this.setData({ customerSheetVisible: true }) this.searchCustomers(this.data.customerKeyword) @@ -491,45 +503,6 @@ Page({ }) }, - openManualCustomer() { - this.setData({ - customerSheetVisible: false, - manualCustomerVisible: true, - manualCustomerForm: { - name: this.data.form.customerName || '', - phone: this.data.form.phone || '' - } - }) - }, - - closeManualCustomer() { - this.setData({ manualCustomerVisible: false }) - }, - - onManualCustomerInput(event) { - this.setData({ [`manualCustomerForm.${event.currentTarget.dataset.field}`]: event.detail.value }) - }, - - useManualCustomer() { - const name = String(this.data.manualCustomerForm.name || '').trim() - const phone = String(this.data.manualCustomerForm.phone || '').trim() - if (!name) { - wx.showToast({ title: '请输入客户姓名', icon: 'none' }) - return - } - if (!/^1[3-9]\d{9}$/.test(phone)) { - wx.showToast({ title: '请输入正确手机号', icon: 'none' }) - return - } - this.setData({ - 'form.customerUserId': '', - 'form.customerName': name, - 'form.phone': phone, - manualCustomerVisible: false, - customerKeyword: '' - }) - }, - onUnload() { if (this._customerTimer) { clearTimeout(this._customerTimer) @@ -949,7 +922,83 @@ Page({ } }, + async ensureCustomerBeforeSubmit() { + const name = String(this.data.form.customerName || '').trim() + const phone = String(this.data.form.phone || '').trim() + if (!name) { + wx.showToast({ title: '请输入客户姓名', icon: 'none' }) + return false + } + if (phone && !/^1[3-9]\d{9}$/.test(phone)) { + wx.showToast({ title: '请输入正确手机号', icon: 'none' }) + return false + } + if (this.data.form.customerUserId) { + return true + } + + this.setData({ loading: true }) + try { + const matches = await customersApi.matchIdentity(name, phone || undefined) + if (matches.length > 1) { + this.setData({ + customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem), + customerKeyword: name, + customerSheetVisible: true + }) + return false + } + if (matches.length > 0) { + const customer = normalizeCustomer(matches[0]) + const choice = await new Promise(resolve => { + wx.showModal({ + title: '客户已存在', + content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`, + cancelText: '取消', + confirmText: '使用已有', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!choice.confirm) { + return false + } + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone + }) + return true + } + + const createChoice = await new Promise(resolve => { + wx.showModal({ + title: '新建客户', + content: '系统中没有匹配客户,是否新建到客户档案?', + cancelText: '不新建', + confirmText: '确认', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!createChoice.confirm) { + return false + } + const customerId = await customersApi.create({ nickname: name, phone: phone || undefined }) + this.setData({ 'form.customerUserId': customerId }) + return true + } catch (error) { + wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) + return false + } finally { + this.setData({ loading: false }) + } + }, + async submit() { + if (this.data.loading) { + return + } if (!this.data.canCreateAppointment) { wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return @@ -957,11 +1006,11 @@ Page({ const form = this.data.form const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || !form.phone || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { + if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } - if (!/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { + if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return } @@ -987,6 +1036,9 @@ Page({ }) if (!result.confirm) return } + if (!(await this.ensureCustomerBeforeSubmit())) { + return + } this.setData({ loading: true }) try { const payload = { diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index b72a8f68..3ecd6fec 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,15 +1,13 @@ - - 客户 - - - {{form.customerName || '请选择客户'}} - {{form.phone || '搜索已有客户或手动录入'}} - - 已有 - › + + 客户姓名 + + + + + 已关联系统客户 预约日期 @@ -76,12 +74,10 @@ selected-id="{{form.customerUserId}}" loading="{{customerLoading}}" error-text="{{customerError}}" - empty-text="暂无匹配客户,可手动录入" - action-text="手动录入客户" + empty-text="暂无匹配客户" bind:search="onCustomerSearch" bind:select="selectCustomer" bind:retry="retryCustomerSearch" - bind:action="openManualCustomer" bind:close="closeCustomerSheet" /> @@ -103,29 +99,6 @@ bind:close="closeArtistSheet" /> - - - - - 手动录入客户 - 录入后将直接带回本次预约 - - × - - - - 客户姓名 - - - - 手机号 - - - - - - - diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxss b/JC-Salon-WeChat/pages/appointment-form/index.wxss index 8cb157d3..ed1ef6a0 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxss @@ -4,6 +4,7 @@ } .customer-field { + display: block; align-items: stretch; padding: 18rpx 0; } @@ -13,6 +14,58 @@ align-items: center; } +.customer-entry { + display: flex; + align-items: center; + gap: 14rpx; + width: 100%; +} + +.customer-name-input { + min-width: 0; + flex: 1; + height: 78rpx; + padding: 0 18rpx; + border: 1rpx solid #e7e0d7; + border-radius: 18rpx; + background: #f8f4ee; + color: #29241f; + font-size: 27rpx; +} + +.customer-select-btn { + flex: 0 0 auto; + min-width: 176rpx; + height: 78rpx; + margin: 0; + padding: 0 18rpx; + border: 1rpx solid #d7b38e; + border-radius: 18rpx; + background: #fff7ed; + color: #9f5f2d; + font-size: 23rpx; + line-height: 78rpx; +} + +.customer-phone-input { + width: 100%; + height: 66rpx; + margin-top: 14rpx; + padding: 0 18rpx; + border: 1rpx solid #e7e0d7; + border-radius: 16rpx; + background: #fff; + color: #29241f; + font-size: 25rpx; +} + +.customer-selected-tip { + display: block; + margin-top: 10rpx; + color: #55786d; + font-size: 21rpx; +} + .reference-card, .reference-value { display: flex; @@ -215,49 +268,6 @@ background: rgba(18, 15, 12, 0.48); } -.manual-customer-sheet { - display: flex; - width: 100%; - height: 88vh; - max-height: 88vh; - flex-direction: column; - padding: 28rpx 28rpx calc(28rpx + env(safe-area-inset-bottom)); - border-radius: 34rpx 34rpx 0 0; - background: #fffaf4; - box-shadow: 0 -18rpx 40rpx rgba(41, 31, 23, 0.16); -} - -.manual-customer-form { - flex: 1; - padding-top: 12rpx; -} - -.manual-customer-field { - margin-bottom: 20rpx; - padding: 20rpx 22rpx; - border: 1rpx solid #e7e0d7; - border-radius: 20rpx; - background: #fff; -} - -.manual-customer-field text { - display: block; - margin-bottom: 10rpx; - color: #625c55; - font-size: 24rpx; - font-weight: 800; -} - -.manual-customer-field input { - height: 64rpx; - color: #29241f; - font-size: 28rpx; -} - -.manual-customer-submit { - flex: 0 0 auto; -} - .time-modal { width: 100%; max-height: 82vh; diff --git a/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md index efc815c7..97aaa790 100644 --- a/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md +++ b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md @@ -31,7 +31,7 @@ ## 后端接口与模型 -- 扩展 `GET /manager/customers` 的姓名、手机号筛选能力,保证查询条件能够表达姓名加手机号的组合。 +- 新增 `GET /manager/customers/matches`,按姓名及可选手机号返回当前店铺的精确匹配客户;原 `GET /manager/customers` 列表接口保持不变。 - 调整 `POST /manager/customers`:手机号改为可选;无手机号时不生成手机号账号,使用系统生成的不可登录账号或现有客户创建约定;有手机号时保留现有账号兼容逻辑。 - 创建前在事务内按唯一性规则查询并拒绝重复,返回明确业务错误。 - 不修改预约提交协议,预约仍使用 `customerUserId`、`customerName` 和 `phone` 字段。 diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index a4a1c9d5..3ad56ad1 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -1,5 +1,12 @@ # 项目变更记录 +## 2026-10-16 Salon 预约客户输入与选择优化 + +- 新增预约客户字段改为“客户姓名输入框 + 选择已有客户”按钮,手机号改为可选输入,输入文本时自动解除旧客户绑定。 +- 提交前按“姓名 + 手机号”或“仅姓名”规则查询客户;已存在时引导使用已有客户,未存在时提供确认新建和不新建选择。 +- 后端新增客户匹配接口,客户创建支持无手机号并在事务内执行唯一性校验,预约接口同步支持无手机号客户解析。 +- 更新预约页选择测试和 Core 预约测试夹具;GitNexus 当前无可调用接口,使用静态引用、JavaScript 检查和 Maven 测试替代影响分析。 + ## 2026-10-16 Gitea 工作流 YAML 兼容性修复 - 问题:Gitea Actions 页面只显示工作流文件名并标记无效,推送后没有执行。 -- 2.54.0 From c952a913e8788c3d398f87cf9b97d120d25fb8f4 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Tue, 20 Oct 2026 13:29:55 +0800 Subject: [PATCH 03/73] =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E8=A1=A8=E5=8D=95=E5=B9=B6=E6=94=AF=E6=8C=81=E6=95=A3=E5=AE=A2?= =?UTF-8?q?=E9=A2=84=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/PlanningAppointmentCreateDTO.java | 2 + .../service/impl/PlanningServiceImpl.java | 52 +- .../service/impl/PlanningServiceImplTest.java | 348 ++++++++++++ .../components/entity-selector-sheet/index.js | 11 + .../entity-selector-sheet/index.wxml | 13 +- .../entity-selector-sheet/index.wxss | 60 ++ .../product-selector-sheet/index.js | 1 + .../product-selector-sheet/index.wxml | 2 +- .../appointment-form/entity-selector.test.js | 11 +- .../pages/appointment-form/index.js | 529 +++++++++++++----- .../pages/appointment-form/index.wxml | 165 ++---- .../pages/appointment-form/index.wxss | 368 +++++++++++- .../appointment-form/modal-scroll.test.js | 4 +- .../appointment-form/product-selector.test.js | 15 +- .../pages/appointment-form/unassigned.test.js | 26 + .../2026-10-20-salon预约表单与客户身份设计.md | 35 ++ docs/项目变更记录.md | 9 + 17 files changed, 1376 insertions(+), 275 deletions(-) create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java create mode 100644 docs/superpowers/specs/2026-10-20-salon预约表单与客户身份设计.md diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java index b11e4eea..ba3d50f1 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java @@ -16,6 +16,8 @@ public class PlanningAppointmentCreateDTO { private String appointmentTime; private String appointmentStartTime; private Integer durationMinutes; + private BigDecimal amount; + private Boolean createCustomerRecord; private String manualProductTitle; private BigDecimal manualProductPrice; private String manualProductDescription; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index d7a04df9..65bf2bd0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -44,6 +44,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; @@ -183,11 +184,18 @@ public class PlanningServiceImpl implements PlanningService { ensureWithinBusinessHours(shopId, startTime, endTime); BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity)); + BigDecimal amount = dto.getAmount() == null + ? unitPrice.multiply(BigDecimal.valueOf(quantity)) + : dto.getAmount(); + if (amount.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } OrderDO order = new OrderDO(); order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); - order.setUserId(customer.getId()); + order.setUserId(customer == null ? null : customer.getId()); + order.setCustomerNameSnapshot(customer == null ? trimToNull(dto.getCustomerName()) : null); + order.setCustomerPhoneSnapshot(customer == null ? trimToNull(dto.getPhone()) : null); order.setShopId(shopId); order.setTotalAmount(amount); order.setActualAmount(amount); @@ -208,7 +216,7 @@ public class PlanningServiceImpl implements PlanningService { item.setOrderId(order.getId()); item.setProductId(product.getId()); item.setQuantity(quantity); - item.setPrice(unitPrice); + item.setPrice(amount.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP)); item.setArtistId(artist == null ? null : artist.getId()); item.setAppointmentTime(startTime); item.setIsDelete(0); @@ -295,7 +303,8 @@ public class PlanningServiceImpl implements PlanningService { Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); Map customerMap = order.getUserId() == null ? Map.of() : loadUsers(Set.of(order.getUserId())); - return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); + return toAppointmentVO(reservation, item, order, product, customer, artistMap); } @Override @@ -516,7 +525,7 @@ public class PlanningServiceImpl implements PlanningService { continue; } ProductDO product = item == null ? null : productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap)); if (reservation.getOrderItemId() != null) { reservationItemIds.add(reservation.getOrderItemId()); @@ -531,7 +540,7 @@ public class PlanningServiceImpl implements PlanningService { continue; } ProductDO product = productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); result.add(toAppointmentVO(null, item, order, product, customer, artistMap)); } result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo)) @@ -731,12 +740,19 @@ public class PlanningServiceImpl implements PlanningService { private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { String title = trimToNull(dto.getManualProductTitle()); + String imageFileIds = trimToNull(dto.getManualProductImageFileIds()); if (!hasText(title)) { - throw new RuntimeException("请选择预约作品或填写手动作品名称"); + title = firstNonBlank(dto.getCustomerName(), hasText(imageFileIds) ? "散客款式" : null); } - BigDecimal price = dto.getManualProductPrice(); - if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { - throw new RuntimeException("手动作品价格不能小于0"); + if (!hasText(title) && !hasText(imageFileIds)) { + throw new RuntimeException("请填写美甲款式名称或上传款式图片"); + } + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null) { + throw new RuntimeException("成交金额不能为空"); + } + if (price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); } int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); ProductDO product = new ProductDO(); @@ -746,7 +762,7 @@ public class PlanningServiceImpl implements PlanningService { product.setTags(trimToNull(dto.getManualProductTags())); product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); product.setPrecautions(trimToNull(dto.getManualProductPrecautions())); - product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + product.setImageFileIds(imageFileIds); product.setPrice(price); product.setLikeCount(0); product.setCollectCount(0); @@ -786,11 +802,17 @@ public class PlanningServiceImpl implements PlanningService { } return customer; } - String customerName = firstNonBlank(dto.getCustomerName(), dto.getPhone()); - if (!hasText(customerName)) { - throw new RuntimeException("客户姓名不能为空"); - } + String customerName = trimToNull(dto.getCustomerName()); String phone = trimToNull(dto.getPhone()); + if (!hasText(customerName) && hasText(phone)) { + throw new RuntimeException("填写手机号时请同时填写客户姓名"); + } + if (Boolean.FALSE.equals(dto.getCreateCustomerRecord())) { + return null; + } + if (!hasText(customerName)) { + return null; + } List matches = userService.findCustomerMatches(customerName, phone, shopId); if (matches.size() > 1) { diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java new file mode 100644 index 00000000..599b10c4 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -0,0 +1,348 @@ +package com.xiaowang.jayucloud.salon.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PlanningServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserMapper userMapper; + @Mock private UserService userService; + @Mock private NailArtistInfoMapper nailArtistInfoMapper; + @Mock private ArtistScheduleMapper artistScheduleMapper; + @Mock private ArtistScheduleExceptionMapper artistScheduleExceptionMapper; + @Mock private AppointmentReservationMapper appointmentReservationMapper; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private ShopMapper shopMapper; + @Mock private AppointmentCapacityService appointmentCapacityService; + @Mock private OrderService orderService; + @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + private PlanningServiceImpl service; + + @BeforeEach + void setUp() { + service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, + artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, + productMapper, shopMapper, appointmentCapacityService, orderService, snowflakeIdGenerator); + } + + @Test + void rejectsCompletingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(11L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(11L)).thenReturn(order); + when(orderItemMapper.selectCount(any(Wrapper.class))).thenReturn(1L); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.updateStatus(operator, 11L, dto)); + + assertEquals("请先分配员工", error.getMessage()); + verify(orderService, never()).processOrder(11L, OrderStatus.COMPLETED.getCode()); + } + + @Test + void allowsCancellingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(12L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(12L)).thenReturn(order); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.CANCELLED.getCode()); + + service.updateStatus(operator, 12L, dto); + + verify(orderService).processOrder(12L, OrderStatus.CANCELLED.getCode()); + } + + @Test + void createsUnassignedAppointmentWithoutReservation() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(31L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(31L)).thenReturn(customer); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10001"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(51L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(61L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 61L); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(31L); + dto.setProductId(41L); + dto.setAppointmentDate("2026-10-13"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertNull(itemCaptor.getValue().getArtistId()); + verify(appointmentCapacityService, never()).reserveConfirmedOrThrow( + any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithPhotoOnlyStyleAndSnapshotAmount() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10002"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(42L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(52L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(62L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 62L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小鹿"); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-42"); + dto.setAmount(java.math.BigDecimal.valueOf(168)); + dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("小鹿", productCaptor.getValue().getTitle()); + assertEquals("file-42", productCaptor.getValue().getImageFileIds()); + assertEquals(java.math.BigDecimal.valueOf(168), productCaptor.getValue().getPrice()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertEquals("小鹿", orderCaptor.getValue().getCustomerNameSnapshot()); + assertEquals(java.math.BigDecimal.valueOf(168), orderCaptor.getValue().getActualAmount()); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertEquals(0, itemCaptor.getValue().getPrice().compareTo(java.math.BigDecimal.valueOf(168))); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithoutCustomerUsingWalkInStyleTitle() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10003"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(43L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(53L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(63L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 63L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-43"); + dto.setAmount(java.math.BigDecimal.valueOf(88)); + dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(45); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("散客款式", productCaptor.getValue().getTitle()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + assertNull(orderCaptor.getValue().getCustomerPhoneSnapshot()); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void readsWalkInAppointmentCustomerSnapshotWithoutLookingUpNullUserId() { + UserDO operator = new UserDO(); + operator.setType(2); + OrderDO order = order(54L, OrderStatus.PENDING_SERVICE.getCode()); + order.setCustomerNameSnapshot("散客预约"); + order.setCustomerPhoneSnapshot("13800138000"); + OrderItemDO item = new OrderItemDO(); + item.setId(64L); + item.setOrderId(54L); + item.setQuantity(1); + item.setAppointmentTime(java.time.LocalDateTime.of(2026, 10, 22, 14, 0)); + + when(orderItemMapper.selectById(64L)).thenReturn(item); + when(orderMapper.selectById(54L)).thenReturn(order); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result = + service.getAppointment(operator, 64L); + + assertNull(result.getCustomerId()); + assertEquals("散客预约", result.getCustomerName()); + assertEquals("13800138000", result.getCustomerPhone()); + verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull()); + } + + @Test + void createsCustomerInAppointmentFlowWhenConfirmed() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(71L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(71L)).thenReturn(customer); + when(userService.findCustomerMatches("小周", "13800138000", 21L)).thenReturn(java.util.List.of()); + when(userService.createManagerCustomer("小周", "13800138000", 21L)).thenReturn(71L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(55L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(65L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 65L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小周"); + dto.setPhone("13800138000"); + dto.setCreateCustomerRecord(true); + dto.setProductId(41L); + dto.setAmount(java.math.BigDecimal.valueOf(128)); + dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + verify(userService).createManagerCustomer("小周", "13800138000", 21L); + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertEquals(71L, orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + } + + private OrderDO order(Long id, int status) { + OrderDO order = new OrderDO(); + order.setId(id); + order.setShopId(21L); + order.setStatus(status); + order.setIsDelete(0); + return order; + } +} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.js b/JC-Salon-WeChat/components/entity-selector-sheet/index.js index 45eecd27..943ae555 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.js @@ -10,6 +10,9 @@ Component({ errorText: { type: String, value: '' }, emptyText: { type: String, value: '暂无可选内容' }, actionText: { type: String, value: '' }, + showViewSwitch: { type: Boolean, value: false }, + viewMode: { type: String, value: 'list' }, + sortLabel: { type: String, value: '' }, showSearch: { type: Boolean, value: true } }, @@ -36,6 +39,14 @@ Component({ action() { this.triggerEvent('action') + }, + + changeView(event) { + this.triggerEvent('changeview', { mode: event.currentTarget.dataset.mode }) + }, + + sort() { + this.triggerEvent('sort') } } }) diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml index 051750ac..cdba0c65 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml @@ -10,6 +10,14 @@ + + + + + + + + @@ -20,12 +28,13 @@ {{emptyText}} - - + + {{item.title}} + {{item.rightText}} {{item.badge}} {{item.subtitle}} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss index d20b4840..9917c0fa 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss @@ -125,6 +125,35 @@ transform: rotate(45deg); } +.selector-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12rpx; + padding: 0 28rpx 16rpx; +} + +.selector-view-switch { + display: flex; + flex: 1; + gap: 8rpx; +} + +.selector-view-switch button, +.selector-sort { + height: 58rpx; + padding: 0 18rpx; + border-radius: 16rpx; + background: #f1f5f3; + color: #687a72; + font-size: 22rpx; + line-height: 58rpx; +} + +.selector-view-switch button { flex: 1; } +.selector-view-switch button.active { background: #dff1e9; color: #247b63; font-weight: 800; } +.selector-sort { flex: 0 0 auto; color: #476259; } + .selector-search { height: 78rpx; flex: 1; @@ -157,6 +186,28 @@ .selector-item:active { transform: scale(0.99); } .selector-item.selected { border-color: #8eafa3; background: #f0f6f3; } +.selector-list.card-view { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12rpx; +} + +.selector-item.card-view { + position: relative; + display: block; + min-height: 190rpx; + margin: 0; + padding: 18rpx; +} + +.selector-item.card-view .selector-avatar { width: 66rpx; height: 66rpx; margin-bottom: 12rpx; } +.selector-item.card-view .selector-copy { margin-left: 0; } +.selector-item.card-view .selector-title-row { align-items: flex-start; } +.selector-item.card-view .selector-item-title { white-space: normal; } +.selector-item.card-view .selector-subtitle, +.selector-item.card-view .selector-meta { display: block; margin-top: 8rpx; } +.selector-item.card-view .selector-check { position: absolute; right: 18rpx; bottom: 16rpx; } + .selector-avatar { width: 76rpx; height: 76rpx; @@ -180,6 +231,8 @@ } .selector-item-title { + min-width: 0; + flex: 1; overflow: hidden; color: #2b2621; font-size: 28rpx; @@ -188,6 +241,13 @@ white-space: nowrap; } +.selector-right-text { + flex: 0 0 auto; + color: #756e66; + font-size: 23rpx; + font-weight: 600; +} + .selector-badge { flex: 0 0 auto; padding: 5rpx 12rpx; diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.js b/JC-Salon-WeChat/components/product-selector-sheet/index.js index 9983ecd1..c9e9d6e3 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.js @@ -13,6 +13,7 @@ Component({ manualForm: { type: Object, value: {} }, manualMoreExpanded: { type: Boolean, value: false }, showManualExtra: { type: Boolean, value: true }, + showManualAction: { type: Boolean, value: true }, manualImageUrl: { type: String, value: '' }, manualImageUploading: { type: Boolean, value: false } }, diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml index d877e401..5c2a40a1 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml @@ -17,7 +17,7 @@ - + diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index 0eba88f5..f503979e 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -46,16 +46,13 @@ async function run() { page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '') + assert.strictEqual(page.data.form.phone, '13800138000') customersApi.matchIdentity = async () => [] - customersApi.create = async payload => { - assert.strictEqual(payload.nickname, '新客户') - assert.strictEqual(payload.phone, undefined) - return '42' - } + customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) - assert.strictEqual(page.data.form.customerUserId, '42') + assert.strictEqual(page.data.form.customerUserId, '') + assert.strictEqual(page.data.form.createCustomerRecord, true) page.data.form.customerUserId = '' page.data.form.customerName = '小周' diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 68b7923d..a53209fc 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -192,6 +192,113 @@ function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } +function buildTimeValues(durationMinutes) { + const values = [] + const open = dateUtil.minutesOfDay('10:00') + const close = dateUtil.minutesOfDay('22:00') + for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) { + values.push(dateUtil.timeFromMinutes(minute)) + } + return values +} + +function buildTimePickerSlots(calendar, form, durationMinutes) { + const schedules = calendar.schedules || [] + const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] + return buildTimeValues(durationMinutes).map(value => { + const startMinute = dateUtil.minutesOfDay(value) + const endMinute = startMinute + durationMinutes + const occupied = hasBusyConflict(startMinute, endMinute, busyRanges) + const scheduled = !form.artistId || schedules.some(schedule => + isScheduleCoveringTime(schedule, form, startMinute, endMinute) + ) + const status = occupied ? 'occupied' : scheduled ? 'available' : 'off-shift' + return { + value, + hour: Number(value.slice(0, 2)), + minute: Number(value.slice(3, 5)), + rangeText: buildTimeRangeLabel(startMinute, durationMinutes), + status, + statusText: status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : '' + } + }) +} + +function buildTimePickerGroups(slots) { + const groupMap = { + morning: { key: 'morning', title: '上午', times: [] }, + afternoon: { key: 'afternoon', title: '下午', times: [] }, + evening: { key: 'evening', title: '晚上', times: [] } + } + ;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot)) + return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) +} + +function buildTimeWheelState(slots, preferredTime) { + if (!slots || slots.length === 0) { + return { + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift' + } + } + const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00') + const firstAvailableSlot = slots.find(slot => slot.status === 'available') + const selectedSlot = preferredSlot && preferredSlot.status === 'available' + ? preferredSlot + : firstAvailableSlot || preferredSlot || slots[0] + const hours = Array.from(new Set(slots.map(slot => slot.hour))) + const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour)) + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute)) + return { + timePickerHours: hours.map(hour => ({ + value: hour, + label: String(hour).padStart(2, '0'), + disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available') + })), + timePickerMinutes: minutes, + timePickerValue: [selectedHourIndex, selectedMinuteIndex], + selectedTimeCandidate: selectedSlot.value, + timePickerCandidateStatus: selectedSlot.status + } +} + +function timeWheelStateForHour(slots, hour, selectedMinute) { + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute)) + return { timePickerMinutes: minutes, selectedMinuteIndex } +} + +function customerCreatedAt(customer) { + return customer.createTime || customer.createdAt || customer.addedAt || '' +} + +function formatCustomerCreatedAt(value) { + if (!value) return '添加时间未知' + return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}` +} + function parseProductTags(product) { if (Array.isArray(product.tagList) && product.tagList.length > 0) { return product.tagList @@ -245,7 +352,8 @@ function normalizeCustomer(customer) { name, phone, displayName: name || phone || '客户', - displayPhone: phone || '未填写手机号' + displayPhone: phone || '未填写手机号', + createdAt: customerCreatedAt(customer) } } @@ -253,8 +361,8 @@ function buildCustomerSelectorItem(customer) { return { ...customer, title: customer.displayName, - subtitle: customer.displayPhone, - badge: '已有客户' + subtitle: formatCustomerCreatedAt(customer.createdAt), + rightText: customer.displayPhone } } @@ -276,6 +384,7 @@ Page({ phone: '', appointmentDate: dateUtil.formatDate(new Date()), appointmentTime: '', + amount: '', productId: '', manualProductTitle: '', manualProductPrice: '', @@ -285,14 +394,18 @@ Page({ manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', - durationMinutes: '', + durationMinutes: '60', artistId: '', + createCustomerRecord: false, remark: '' }, - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, customerOptions: [], + customerDirectory: [], customerSheetVisible: false, customerKeyword: '', + customerViewMode: 'list', + customerNewestFirst: true, + customerSuggestions: [], customerLoading: false, customerError: '', products: [], @@ -306,8 +419,6 @@ Page({ selectedProductPriceText: '', selectedArtist: {}, productModalVisible: false, - productSelectorMode: 'list', - manualProductMoreExpanded: false, productKeyword: '', productError: '', loadingProducts: false, @@ -317,6 +428,14 @@ Page({ draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, + timePickerMode: 'wheel', + timePickerValue: [0, 0], + timePickerHours: [], + timePickerMinutes: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerCandidateStatus: 'off-shift', + selectedTimeCandidate: '', timeLoading: false, timeError: '', timeSelectTip: '请先选择美甲师并填写时长', @@ -330,16 +449,6 @@ Page({ const baseForm = draftForm || {} this.setData({ canCreateAppointment: creatable, - manualProductDraft: { - title: baseForm.manualProductTitle || '', - price: baseForm.manualProductPrice || '', - description: baseForm.manualProductDescription || '', - tags: baseForm.manualProductTags || '', - targetAudience: baseForm.manualProductTargetAudience || '', - precautions: baseForm.manualProductPrecautions || '', - imageFileIds: baseForm.manualProductImageFileIds || '', - imageUrl: baseForm.manualProductImageUrl || '' - }, form: { ...this.data.form, ...baseForm, @@ -375,10 +484,14 @@ Page({ await this.loadArtists() this.refreshProductCards() const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {} - this.setData({ + const selectedProductPatch = { selectedProduct, selectedProductPriceText: selectedProduct.priceText || '' - }) + } + if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) { + selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price) + } + this.setData(selectedProductPatch) await this.refreshAvailableTimes() this.checkAvailability() }, @@ -420,6 +533,47 @@ Page({ } }, + async loadCustomerDirectory() { + this.setData({ customerLoading: true }) + try { + const size = 100 + const rows = [] + let page = 1 + let total = Number.POSITIVE_INFINITY + while (rows.length < total) { + const result = await customersApi.list({ page, size }) + const currentRows = Array.isArray(result) ? result : (result.list || []) + rows.push(...currentRows) + if (!Array.isArray(result) && Number.isFinite(Number(result.total))) { + total = Number(result.total) + } else if (currentRows.length < size) { + total = rows.length + } + if (currentRows.length === 0) break + page += 1 + } + const directory = rows.map(normalizeCustomer) + this.setData({ + customerDirectory: directory, + customerOptions: this.sortCustomerOptions(directory), + customerError: '' + }) + this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone) + } catch (error) { + this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' }) + } finally { + this.setData({ customerLoading: false }) + } + }, + + sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) { + return (customers || []).slice().sort((left, right) => { + const leftDate = String(left.createdAt || '') + const rightDate = String(right.createdAt || '') + return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate) + }).map(buildCustomerSelectorItem) + }, + onInput(event) { const field = event.currentTarget.dataset.field const patch = { @@ -432,18 +586,81 @@ Page({ } }, + onStyleTitleInput(event) { + const patch = { 'form.manualProductTitle': event.detail.value } + if (this.data.form.productId) { + patch['form.productId'] = '' + patch.selectedProduct = {} + patch.selectedProductPriceText = '' + patch['form.manualProductImageFileIds'] = '' + patch['form.manualProductImageUrl'] = '' + } + this.setData(patch) + }, + onCustomerInput(event) { const field = event.currentTarget.dataset.field const patch = { [`form.${field}`]: event.detail.value, - 'form.customerUserId': '' - } - if (field === 'customerName' && this.data.form.customerUserId) { - patch['form.phone'] = '' + 'form.customerUserId': '', + 'form.createCustomerRecord': false } this.setData({ ...patch }) + const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName + const phone = field === 'phone' ? event.detail.value : this.data.form.phone + this.refreshCustomerSuggestions(customerName, phone) + }, + + refreshCustomerSuggestions(nameValue, phoneValue) { + const name = String(nameValue || '').trim().toLowerCase() + const phone = String(phoneValue || '').trim().toLowerCase() + if (!name && !phone) { + this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1 + clearTimeout(this._suggestionTimer) + this.setData({ customerSuggestions: [] }) + return + } + const suggestions = this.data.customerDirectory + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: suggestions }) + const requestSeq = (this._customerSuggestionSeq || 0) + 1 + this._customerSuggestionSeq = requestSeq + clearTimeout(this._suggestionTimer) + this._suggestionTimer = setTimeout(async () => { + try { + const result = await customersApi.list({ page: 1, size: 50, keyword: name || phone }) + if (requestSeq !== this._customerSuggestionSeq) return + const rows = Array.isArray(result) ? result : (result.list || []) + const remoteSuggestions = rows.map(normalizeCustomer) + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: remoteSuggestions }) + } catch (error) { + if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) { + this.setData({ customerSuggestions: [] }) + } + } + }, 240) + }, + + selectCustomerSuggestion(event) { + const index = Number(event.currentTarget.dataset.index) + const customer = this.data.customerSuggestions[index] + if (!customer) return + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false, + customerSuggestions: [], + customerSheetVisible: false, + customerKeyword: '' + }) }, openCustomerSheet() { @@ -467,22 +684,24 @@ Page({ return } const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() - this.setData({ customerLoading: true }) - try { - const data = await customersApi.list({ keyword, page: 1, size: 20 }) - const list = data.list || data || [] - this.setData({ - customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem), - customerError: '' - }) - } catch (error) { - this.setData({ - customerOptions: [], - customerError: error.message || '客户列表加载失败' - }) - } finally { - this.setData({ customerLoading: false }) - } + if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase()) + ) + this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' }) + }, + + changeCustomerView(event) { + this.setData({ customerViewMode: event.detail.mode || 'list' }) + }, + + toggleCustomerSort() { + const customerNewestFirst = !this.data.customerNewestFirst + const keyword = String(this.data.customerKeyword || '').trim().toLowerCase() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword) + ) + this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) }) }, retryCustomerSearch() { @@ -498,8 +717,10 @@ Page({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, 'form.phone': customer.phone, + 'form.createCustomerRecord': false, customerSheetVisible: false, - customerKeyword: '' + customerKeyword: '', + customerSuggestions: [] }) }, @@ -507,6 +728,9 @@ Page({ if (this._customerTimer) { clearTimeout(this._customerTimer) } + if (this._suggestionTimer) { + clearTimeout(this._suggestionTimer) + } }, async onDateChange(event) { @@ -555,29 +779,20 @@ Page({ openProductModal() { this.refreshProductCards() - this.setData({ productModalVisible: true, productSelectorMode: 'list' }) + this.setData({ productModalVisible: true }) }, closeProductModal() { - this.setData({ productModalVisible: false, productSelectorMode: 'list' }) + this.setData({ productModalVisible: false }) }, openManualProduct() { - this.setData({ productSelectorMode: 'manual', manualProductMoreExpanded: false }) - }, - - backToProductList() { - this.setData({ productSelectorMode: 'list' }) - this.refreshProductCards() - }, - - onManualProductInput(event) { - const field = event.detail.field - this.setData({ [`manualProductDraft.${field}`]: event.detail.value }) - }, - - toggleManualProductMore() { - this.setData({ manualProductMoreExpanded: !this.data.manualProductMoreExpanded }) + this.setData({ + productModalVisible: false, + selectedProduct: {}, + selectedProductPriceText: '', + 'form.productId': '' + }) }, stopTap() { @@ -597,16 +812,8 @@ Page({ this.setData({ selectedProduct, selectedProductPriceText: selectedProduct.priceText || '', - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, 'form.productId': selectedProduct.id, - 'form.manualProductTitle': '', - 'form.manualProductPrice': '', - 'form.manualProductDescription': '', - 'form.manualProductTags': '', - 'form.manualProductTargetAudience': '', - 'form.manualProductPrecautions': '', - 'form.manualProductImageFileIds': '', - 'form.manualProductImageUrl': '', + 'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price), 'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '') }) this.closeProductModal() @@ -614,33 +821,6 @@ Page({ this.checkAvailability() }, - useManualProduct() { - const draft = this.data.manualProductDraft - const title = String(draft.title || '').trim() - const priceText = String(draft.price === undefined ? '' : draft.price).trim() - const price = Number(priceText) - if (!title || !priceText || !Number.isFinite(price) || price < 0) { - wx.showToast({ title: '请填写手动预约作品名称和价格', icon: 'none' }) - return - } - this.setData({ - selectedProduct: {}, - selectedProductPriceText: `¥${price}`, - 'form.productId': '', - 'form.manualProductTitle': title, - 'form.manualProductPrice': String(price), - 'form.manualProductDescription': String(draft.description || '').trim(), - 'form.manualProductTags': String(draft.tags || '').trim(), - 'form.manualProductTargetAudience': String(draft.targetAudience || '').trim(), - 'form.manualProductPrecautions': String(draft.precautions || '').trim(), - 'form.manualProductImageFileIds': String(draft.imageFileIds || ''), - 'form.manualProductImageUrl': String(draft.imageUrl || '') - }) - this.closeProductModal() - this.refreshAvailableTimes() - this.checkAvailability() - }, - async chooseManualProductImage() { if (this.data.manualImageUploading) { return @@ -658,8 +838,11 @@ Page({ throw new Error('作品图片上传成功但未返回文件ID') } this.setData({ - 'manualProductDraft.imageFileIds': String(fileId), - 'manualProductDraft.imageUrl': fileUrl + 'form.productId': '', + selectedProduct: {}, + selectedProductPriceText: '', + 'form.manualProductImageFileIds': String(fileId), + 'form.manualProductImageUrl': fileUrl }) } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) @@ -670,8 +853,8 @@ Page({ removeManualProductImage() { this.setData({ - 'manualProductDraft.imageFileIds': '', - 'manualProductDraft.imageUrl': '' + 'form.manualProductImageFileIds': '', + 'form.manualProductImageUrl': '' }) }, @@ -781,6 +964,13 @@ Page({ if (!form.appointmentDate || !durationMinutes) { const patch = { availableTimeGroups: [], + timePickerGroups: [], + timePickerSlots: [], + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift', timeError: '', timeSelectTip: '请先填写预约日期和时长' } @@ -792,8 +982,12 @@ Page({ } if (!form.artistId) { const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes) + const timePickerSlots = buildTimePickerSlots({ schedules: [], appointments: [] }, form, durationMinutes) this.setData({ availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), timeError: '', timeLoading: false, timeSelectTip: '请选择预约时间,员工可稍后分配' @@ -816,8 +1010,12 @@ Page({ } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) const patch = { availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { @@ -845,7 +1043,7 @@ Page({ wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' }) return } - this.setData({ timeSheetVisible: true }) + this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' }) await this.refreshAvailableTimes() }, @@ -855,16 +1053,61 @@ Page({ selectAvailableTime(event) { const value = event.currentTarget.dataset.value - this.setData({ - 'form.appointmentTime': value, - timeSheetVisible: false - }) - this.checkAvailability() + const slot = this.data.timePickerSlots.find(item => item.value === value) + if (!slot || slot.status !== 'available') { + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status }) }, - async checkAvailability() { + onTimePickerModeChange(event) { + this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' }) + }, + + onTimePickerChange(event) { + const values = event.detail.value || [0, 0] + const hourItem = this.data.timePickerHours[values[0]] + if (!hourItem) return + const hour = Number(hourItem.value) + const minuteIndex = Number(values[1] || 0) + const minuteItem = this.data.timePickerMinutes[minuteIndex] + const minute = minuteItem ? Number(minuteItem.value) : 0 + const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute) + this.setData({ + timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex], + timePickerMinutes: nextMinutes.timePickerMinutes, + selectedTimeCandidate: candidate, + timePickerCandidateStatus: slot ? slot.status : 'off-shift' + }) + }, + + confirmTimeSelection() { + const candidate = this.data.selectedTimeCandidate + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + if (!slot || slot.status !== 'available') { + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.checkAvailability(candidate).then(availability => { + if (!availability.ok) { + wx.showToast({ + title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约', + icon: 'none' + }) + return + } + this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false }) + this.checkAvailability() + }) + }, + + async checkAvailability(candidateTime) { const form = this.data.form - if (!form.appointmentDate || !form.appointmentTime) { + const appointmentTime = candidateTime || form.appointmentTime + if (!form.appointmentDate || !appointmentTime) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } @@ -873,7 +1116,7 @@ Page({ this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } - const startMinute = dateUtil.minutesOfDay(form.appointmentTime) + const startMinute = dateUtil.minutesOfDay(appointmentTime) const endMinute = startMinute + durationMinutes if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) { const tip = '该时间超出营业时间 10:00-22:00' @@ -912,7 +1155,7 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { @@ -925,8 +1168,12 @@ Page({ async ensureCustomerBeforeSubmit() { const name = String(this.data.form.customerName || '').trim() const phone = String(this.data.form.phone || '').trim() + if (!name && !phone) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } if (!name) { - wx.showToast({ title: '请输入客户姓名', icon: 'none' }) + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) return false } if (phone && !/^1[3-9]\d{9}$/.test(phone)) { @@ -934,6 +1181,7 @@ Page({ return false } if (this.data.form.customerUserId) { + this.setData({ 'form.createCustomerRecord': false }) return true } @@ -941,6 +1189,20 @@ Page({ try { const matches = await customersApi.matchIdentity(name, phone || undefined) if (matches.length > 1) { + const choice = await new Promise(resolve => { + wx.showModal({ + title: '找到多个同名客户', + content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。', + cancelText: '不关联提交', + confirmText: '选择客户', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!choice.confirm) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } this.setData({ customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem), customerKeyword: name, @@ -954,20 +1216,22 @@ Page({ wx.showModal({ title: '客户已存在', content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`, - cancelText: '取消', + cancelText: '不关联提交', confirmText: '使用已有', success: resolve, fail: () => resolve({ confirm: false }) }) }) - if (!choice.confirm) { - return false + if (choice.confirm) { + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false + }) + } else { + this.setData({ 'form.createCustomerRecord': false }) } - this.setData({ - 'form.customerUserId': customer.id, - 'form.customerName': customer.name, - 'form.phone': customer.phone - }) return true } @@ -981,11 +1245,7 @@ Page({ fail: () => resolve({ confirm: false }) }) }) - if (!createChoice.confirm) { - return false - } - const customerId = await customersApi.create({ nickname: name, phone: phone || undefined }) - this.setData({ 'form.customerUserId': customerId }) + this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) }) return true } catch (error) { wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) @@ -1003,13 +1263,25 @@ Page({ wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } - const form = this.data.form - const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() + let form = this.data.form + const manualProductTitle = String(form.manualProductTitle || '').trim() + const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() + const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim()) + const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim() + const amount = Number(amountText) const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { + if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } + if (!Number.isFinite(amount) || amount < 0) { + wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' }) + return + } + if (form.phone && !String(form.customerName || '').trim()) { + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) + return + } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return @@ -1039,12 +1311,17 @@ Page({ if (!(await this.ensureCustomerBeforeSubmit())) { return } + form = this.data.form this.setData({ loading: true }) try { const payload = { ...form, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: form.artistId ? String(form.artistId) : undefined, + customerName: String(form.customerName || '').trim() || undefined, + phone: String(form.phone || '').trim() || undefined, + amount, + createCustomerRecord: Boolean(form.createCustomerRecord), durationMinutes, clientRequestId: buildClientRequestId('manager-appointment') } @@ -1054,8 +1331,8 @@ Page({ payload.manualProductPrice = undefined } else { payload.productId = undefined - payload.manualProductTitle = String(form.manualProductTitle || '').trim() - payload.manualProductPrice = Number(form.manualProductPrice) + payload.manualProductTitle = manualProductTitle || undefined + payload.manualProductPrice = amount payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index 3ecd6fec..4420cff7 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,136 +1,67 @@ - - - - 客户姓名 - - - - - - 已关联系统客户 + + + + 美甲款式手动输入为主,也可快速选择已有款式 + - - 预约日期 - - {{form.appointmentDate}} - + + + {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · {{selectedProduct.durationText || '时长待定'}} + - - 预约作品 - + + + - - 预计时长 - - 分钟 + + + - - 员工(可稍后分配) - - {{selectedArtist.name || '暂不分配'}} - › - - - - 预约时间 - - - {{form.appointmentTime || timeSelectTip}} - {{form.appointmentDate}} · {{selectedArtist.name || '待分配'}} · {{form.durationMinutes}}分钟 - - › - - - - 备注 - 图 + 图 diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 5fcff649..b778560e 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -2065,6 +2065,10 @@ Page({ this.persistDraft(true) }, + onSelectedProductImageError() { + this.setData({ 'selectedProduct.coverImage': '' }) + }, + back() { wx.navigateBack() } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index f11e7683..afedb8a1 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -27,7 +27,7 @@ › - + ✦ {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · 本次 {{form.amount || '待填'}} 元 · {{form.durationMinutes || '60'}} 分钟 diff --git a/JC-Salon-WeChat/pages/backfill-order/index.js b/JC-Salon-WeChat/pages/backfill-order/index.js index 5fb06490..665c051d 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.js +++ b/JC-Salon-WeChat/pages/backfill-order/index.js @@ -121,6 +121,7 @@ Page({ async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ manualImageUploading: false }) } }, removeManualProductImage(event) { const index = Number(event.currentTarget.dataset.index); this.setData(imagePatch((this.data.form.manualProductImages || []).filter((item, itemIndex) => itemIndex !== index))) }, onManualProductImageError(event) { const index = Number(event.currentTarget.dataset.index); const images = this.data.form.manualProductImages || []; if (!images[index] || !images[index].fileUrl) return; const fallback = images.slice(); fallback[index] = { ...fallback[index], previewUrl: fallback[index].fileUrl }; this.setData(imagePatch(fallback)) }, + onSelectedProductImageError() { this.setData({ 'selectedProduct.coverImage': '' }) }, onInput(event) { const field = event.currentTarget.dataset.field; const value = event.detail.value; this.setData({ [`form.${field}`]: value, ...(field === 'amount' ? { 'manualProductDraft.price': value } : {}) }) }, onDateChange(event) { this.setData({ 'form.serviceDate': event.detail.value }) }, onTimeChange(event) { this.setData({ 'form.serviceTime': event.detail.value }) }, diff --git a/JC-Salon-WeChat/pages/backfill-order/index.wxml b/JC-Salon-WeChat/pages/backfill-order/index.wxml index 05080ead..4cf35371 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.wxml +++ b/JC-Salon-WeChat/pages/backfill-order/index.wxml @@ -25,7 +25,7 @@ › - + ✦ {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · 本次 {{form.amount || '待填'}} 元 · {{form.durationMinutes || '60'}} 分钟 diff --git a/JC-Salon-WeChat/pages/employee-create/index.js b/JC-Salon-WeChat/pages/employee-create/index.js index dba2f3a7..0a95d798 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.js +++ b/JC-Salon-WeChat/pages/employee-create/index.js @@ -56,10 +56,11 @@ Page({ if (!filePath) return this.setData({ avatarUploading: true }) const uploadResult = await uploadObjectFile(filePath) - const avatarUrl = uploadResult.fileUrl || uploadResult.primaryUrl || filePath + // 私有对象存储地址可能无法被小程序直接访问,上传完成后先用本地临时文件即时预览。 + const storedAvatar = uploadResult.fileUrl || uploadResult.primaryUrl || '' this.setData({ - 'form.avatar': avatarUrl, - 'form.avatarUrl': avatarUrl + 'form.avatar': storedAvatar, + 'form.avatarUrl': filePath }) } catch (error) { wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) @@ -72,6 +73,10 @@ Page({ this.setData({ 'form.avatar': '', 'form.avatarUrl': '' }) }, + onAvatarError() { + this.setData({ 'form.avatarUrl': '' }) + }, + stopTouchMove() { }, diff --git a/JC-Salon-WeChat/pages/employee-create/index.wxml b/JC-Salon-WeChat/pages/employee-create/index.wxml index ba8f37fb..5d1c7de6 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.wxml +++ b/JC-Salon-WeChat/pages/employee-create/index.wxml @@ -5,7 +5,7 @@ - + 美甲师头像 diff --git a/JC-Salon-WeChat/pages/employee-detail/index.js b/JC-Salon-WeChat/pages/employee-detail/index.js index 62831a66..aafcebdd 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.js +++ b/JC-Salon-WeChat/pages/employee-detail/index.js @@ -44,6 +44,10 @@ Page({ wx.navigateTo({ url: `${event.currentTarget.dataset.url}?id=${this.data.id}` }) }, + onAvatarError() { + this.setData({ 'employee.avatar': '' }) + }, + back() { wx.navigateBack() } diff --git a/JC-Salon-WeChat/pages/employee-detail/index.wxml b/JC-Salon-WeChat/pages/employee-detail/index.wxml index be9a8833..b4e82f9f 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.wxml +++ b/JC-Salon-WeChat/pages/employee-detail/index.wxml @@ -5,7 +5,8 @@ - {{employee.shortName}} + + {{employee.shortName}} {{employee.name}} 美甲师色 diff --git a/JC-Salon-WeChat/pages/employee-detail/index.wxss b/JC-Salon-WeChat/pages/employee-detail/index.wxss index 2212bace..6ed875b3 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.wxss +++ b/JC-Salon-WeChat/pages/employee-detail/index.wxss @@ -26,6 +26,12 @@ color: #fff; font-size: 34rpx; font-weight: 900; + overflow: hidden; +} + +.image-avatar image { + width: 100%; + height: 100%; } .employee-name { diff --git a/JC-Salon-WeChat/pages/employees/index.js b/JC-Salon-WeChat/pages/employees/index.js index ac3ec785..2136f665 100644 --- a/JC-Salon-WeChat/pages/employees/index.js +++ b/JC-Salon-WeChat/pages/employees/index.js @@ -291,6 +291,18 @@ Page({ } }, + onEmployeeAvatarError(event) { + const index = Number(event.currentTarget.dataset.index) + if (!Number.isInteger(index) || !this.data.employees[index]) return + this.setData({ [`employees[${index}].avatar`]: '' }) + }, + + onReviewAvatarError(event) { + const index = Number(event.currentTarget.dataset.index) + if (!Number.isInteger(index) || !this.data.reviewApplications[index]) return + this.setData({ [`reviewApplications[${index}].applicantAvatar`]: '' }) + }, + openDetail(event) { wx.navigateTo({ url: `/pages/employee-detail/index?id=${event.currentTarget.dataset.id}` }) }, diff --git a/JC-Salon-WeChat/pages/employees/index.wxml b/JC-Salon-WeChat/pages/employees/index.wxml index a62372c8..30caa0f9 100644 --- a/JC-Salon-WeChat/pages/employees/index.wxml +++ b/JC-Salon-WeChat/pages/employees/index.wxml @@ -20,7 +20,7 @@ 暂无待审核美甲师申请 - + {{item.applicantDisplayName}} 已预关联美甲师 @@ -45,7 +45,7 @@ - + {{item.shortName}} diff --git a/JC-Salon-WeChat/pages/planning/index.js b/JC-Salon-WeChat/pages/planning/index.js index 2161f3ad..8a23f9c4 100644 --- a/JC-Salon-WeChat/pages/planning/index.js +++ b/JC-Salon-WeChat/pages/planning/index.js @@ -331,6 +331,10 @@ Page({ this.loadCalendar() }, + onProfileAvatarError() { + this.setData({ 'profileForm.avatar': '' }) + }, + selectWeekDate(event) { const appointmentDate = dateUtil.formatDate(event.currentTarget.dataset.date) const target = toLocalDate(appointmentDate) diff --git a/JC-Salon-WeChat/pages/planning/index.wxml b/JC-Salon-WeChat/pages/planning/index.wxml index 3c9c03fb..0dde0bb6 100644 --- a/JC-Salon-WeChat/pages/planning/index.wxml +++ b/JC-Salon-WeChat/pages/planning/index.wxml @@ -44,7 +44,7 @@ 完善你的工作名片头像和昵称会用于门店协作展示,可暂时跳过。 diff --git a/JC-Salon-WeChat/pages/profile-edit/index.js b/JC-Salon-WeChat/pages/profile-edit/index.js index 976999dd..5e6f0138 100644 --- a/JC-Salon-WeChat/pages/profile-edit/index.js +++ b/JC-Salon-WeChat/pages/profile-edit/index.js @@ -139,6 +139,10 @@ Page({ } }, + onAvatarImageError() { + this.setData({ 'form.avatar': '' }) + }, + async chooseWechatAvatar(event) { if (this.data.loading || this.data.avatarUploading || this.data.saving) return try { diff --git a/JC-Salon-WeChat/pages/profile-edit/index.wxml b/JC-Salon-WeChat/pages/profile-edit/index.wxml index 9313a9aa..487202de 100644 --- a/JC-Salon-WeChat/pages/profile-edit/index.wxml +++ b/JC-Salon-WeChat/pages/profile-edit/index.wxml @@ -3,7 +3,7 @@ - + {{avatarText}} {{avatarUploading ? '上传中' : '点击更换'}} diff --git a/JC-Salon-WeChat/pages/profile/index.js b/JC-Salon-WeChat/pages/profile/index.js index 89de49de..25f793b7 100644 --- a/JC-Salon-WeChat/pages/profile/index.js +++ b/JC-Salon-WeChat/pages/profile/index.js @@ -90,6 +90,10 @@ Page({ wx.navigateTo({ url: event.currentTarget.dataset.url }) }, + onProfileAvatarError() { + this.setData({ 'profileCard.avatar': '' }) + }, + async loadProfile() { try { const profile = await profileCache.getProfile() diff --git a/JC-Salon-WeChat/pages/profile/index.wxml b/JC-Salon-WeChat/pages/profile/index.wxml index 589376b8..e1ef8abf 100644 --- a/JC-Salon-WeChat/pages/profile/index.wxml +++ b/JC-Salon-WeChat/pages/profile/index.wxml @@ -2,7 +2,7 @@ diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index d6a5e8b6..8582cd82 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -1,5 +1,14 @@ # 项目变更记录 +## 2026-11-01 Salon 对象存储头像与文件展示修复 + +- 修复 DEV/SIT 使用 MinIO 时,数据库中的内网或公共 MinIO 地址无法解析对象名,导致头像、作品和其他文件不能生成可访问签名地址的问题;统一支持 MinIO 内网端点、MinIO 公共端点、七牛域名和 OSS 引用。 +- 已识别的私有对象存储地址在签名失败时不再原样返回,避免小程序拿到不可访问或不应公开的内网地址;外部默认头像仍保持兼容。 +- 日程员工列表、注册审核候选美甲师统一使用可访问头像地址;审核采用申请头像时保存规范化存储地址,避免把临时/内网 URL 写入员工资料。 +- 小程序新增美甲师上传后优先使用本地临时文件预览;员工列表、员工详情、审核关联选择器、作品选择器、预约/补录款式图片和个人资料头像增加加载失败回退。 +- 新增 `JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java`,覆盖 MinIO 内外网 URL、七牛、OSS 解析及签名失败不泄露私有地址;该测试目录受仓库 `test/` 忽略规则影响,提交时需显式纳入。 +- Core 对象存储、日程、注册关联相关测试 29 项通过;小程序相关测试及 JavaScript 语法检查通过。 + ## 2026-10-30 Salon 安全接入配置服务启动循环修复 - 安全接入配置服务不再依赖 `AdminScopeHelper` / `UserServiceImpl`,改为在服务边界校验调用方必须为平台管理员 `type = 4`,保留配置读取和写入的管理员门禁。 -- 2.54.0 From 203dac2370a1980739c555ae4f29dbfbe9ddf255 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Sun, 1 Nov 2026 14:43:04 +0800 Subject: [PATCH 65/73] =?UTF-8?q?=E6=8F=90=E4=BA=A4Salon=E6=97=A7=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=B8=85=E7=90=86=E4=B8=8E=E5=AE=89=E5=85=A8=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=9F=BA=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../salon/core/config/JwtProperties.java | 11 +- .../admin/AdminCampaignController.java | 52 - .../admin/AdminCouponController.java | 182 - .../controller/front/CouponController.java | 190 - .../controller/front/GrowthController.java | 25 - .../front/ProductLikeController.java | 65 - .../front/VipBenefitController.java | 99 - .../controller/front/VipInfoController.java | 99 - .../front/VipRechargePlanController.java | 113 - .../controller/front/WishlistController.java | 100 - .../controller/front/CartController.java | 116 - .../admin/AdminPaymentController.java | 62 - .../front/BalanceChangeDetailController.java | 99 - .../controller/front/BalanceController.java | 99 - .../controller/admin/AdminUserController.java | 104 - .../user/controller/front/UserController.java | 31 - .../src/main/resources/bootstrap.yaml | 8 +- JC-Salon-Frontend/src/App.vue | 43 +- JC-Salon-Frontend/src/api/cart.ts | 79 - JC-Salon-Frontend/src/api/coupon.ts | 221 -- JC-Salon-Frontend/src/api/index.ts | 3 - JC-Salon-Frontend/src/api/productLike.ts | 51 - JC-Salon-Frontend/src/api/wishlist.ts | 123 - .../src/components/BottomNav.vue | 45 +- JC-Salon-Frontend/src/utils/cart-state.ts | 41 - JC-Salon-Frontend/src/utils/recovery.test.ts | 5 +- JC-Salon-Frontend/src/utils/recovery.ts | 3 +- .../src/utils/system-message-action.ts | 14 - JC-Salon-Frontend/src/views/CartView.vue | 3267 ----------------- JC-Salon-Frontend/src/views/CouponView.vue | 446 --- JC-Salon-Frontend/src/views/HomeView.vue | 1601 -------- JC-Salon-Frontend/src/views/OrderView.vue | 2631 ------------- .../src/views/ProductDetailView.vue | 1935 ---------- .../src/views/ProductListView.vue | 1053 ------ JC-Salon-Frontend/src/views/ProfileView.vue | 1436 -------- .../src/views/ShopDetailView.vue | 1916 ---------- JC-Salon-Frontend/src/views/VipCenterView.vue | 755 ---- JC-Salon-Frontend/src/views/WishlistView.vue | 520 --- .../src/views/admin/CampaignsView.vue | 312 -- .../src/views/admin/CouponsView.vue | 987 ----- .../src/views/admin/UsersView.vue | 180 - .../src/views/admin/VipRechargePlansView.vue | 189 - .../salon/gateway/config/CorsConfig.java | 14 +- .../salon/gateway/config/CorsProperties.java | 15 + .../salon/gateway/config/JwtProperties.java | 11 +- .../src/main/resources/bootstrap.yaml | 8 +- .../DEFAULT_GROUP/gateway.yaml | 36 +- .../DEFAULT_GROUP/gateway.yaml | 33 +- .../DEFAULT_GROUP/gateway.yaml | 33 +- 49 files changed, 73 insertions(+), 19388 deletions(-) delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java delete mode 100644 JC-Salon-Frontend/src/api/cart.ts delete mode 100644 JC-Salon-Frontend/src/api/coupon.ts delete mode 100644 JC-Salon-Frontend/src/api/productLike.ts delete mode 100644 JC-Salon-Frontend/src/api/wishlist.ts delete mode 100644 JC-Salon-Frontend/src/utils/cart-state.ts delete mode 100644 JC-Salon-Frontend/src/views/CartView.vue delete mode 100644 JC-Salon-Frontend/src/views/CouponView.vue delete mode 100644 JC-Salon-Frontend/src/views/HomeView.vue delete mode 100644 JC-Salon-Frontend/src/views/OrderView.vue delete mode 100644 JC-Salon-Frontend/src/views/ProductDetailView.vue delete mode 100644 JC-Salon-Frontend/src/views/ProductListView.vue delete mode 100644 JC-Salon-Frontend/src/views/ProfileView.vue delete mode 100644 JC-Salon-Frontend/src/views/ShopDetailView.vue delete mode 100644 JC-Salon-Frontend/src/views/VipCenterView.vue delete mode 100644 JC-Salon-Frontend/src/views/WishlistView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/CampaignsView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/CouponsView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/VipRechargePlansView.vue create mode 100644 JC-Salon-Gateway/src/main/java/com/xiaowang/jayucloud/salon/gateway/config/CorsProperties.java diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java index 27018ef0..20d49713 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java @@ -4,6 +4,8 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; +import javax.annotation.PostConstruct; + /** * JWT 配置。 */ @@ -15,7 +17,7 @@ public class JwtProperties { /** * HS512 密钥,生产环境请通过 Nacos 覆盖。 */ - private String secret = "jayucloud-salon-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + private String secret; /** * Token 发行者。 @@ -41,4 +43,11 @@ public class JwtProperties { * 时钟偏移容忍,单位秒。 */ private long clockSkewSeconds = 30; + + @PostConstruct + public void validate() { + if (secret == null || secret.trim().length() < 64) { + throw new IllegalStateException("jayucloud-salon.security.jwt.secret 未配置或长度不足 64 位"); + } + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java deleted file mode 100644 index 4373969b..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CampaignDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CampaignService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CampaignVO; -import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/admin/campaign") -@RequiredArgsConstructor -public class AdminCampaignController { - - private final CampaignService campaignService; - private final AdminScopeHelper adminScopeHelper; - private final SecurityAuditSupport securityAuditSupport; - - @GetMapping("/list") - @RequirePermission("campaign:view") - public Result> list(HttpServletRequest request, - @RequestParam(required = false) Integer status, - @RequestParam(defaultValue = "1") Integer page, - @RequestParam(defaultValue = "10") Integer size) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); - return Result.success(campaignService.listCampaigns(shopId, status, page, size)); - } - - @PostMapping("/save") - @RequirePermission("campaign:manage") - public Result save(HttpServletRequest request, @RequestBody CampaignDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); - try { - CampaignVO result = campaignService.saveCampaign(dto); - securityAuditSupport.success(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "campaignId=" + result.getId()); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java deleted file mode 100644 index 882fa9c3..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - -/** - * 后台优惠券管理控制器 - */ -@RestController -@RequestMapping("/admin/coupon") -@RequiredArgsConstructor -public class AdminCouponController { - /** - * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponService couponService; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建优惠券 - */ - @PostMapping("/create") - @RequirePermission("coupon:create") - @OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - @OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - @OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 获取所有优惠券 - */ - @GetMapping("/list/all") - @RequirePermission("coupon:view") - public Result> listAllCoupons(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - List coupons = couponService.listAllCoupons(); - Long resolvedShopId = shopId; - if (resolvedShopId != null) { - coupons = coupons.stream() - .filter(coupon -> resolvedShopId.equals(coupon.getShopId())) - .collect(Collectors.toList()); - } - return Result.success(coupons); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - @OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - @OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java deleted file mode 100644 index e437ed39..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.UserCouponVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * 优惠券控制器 - */ -@RestController -@RequestMapping("/coupon") -@RequiredArgsConstructor -public class CouponController { - /** - * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponService couponService; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建优惠券 - */ - @PostMapping("/create") - @RequirePermission("coupon:create") - public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 获取用户优惠券列表 - */ - @GetMapping("/user/list") - public Result> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) { - List userCoupons = couponService.listUserCoupons(userId, status); - return Result.success(userCoupons); - } - - /** - * 使用优惠券 - */ - @PostMapping("/use") - public Result useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) { - boolean success = couponService.useCoupon(userCouponId, userId); - return Result.success(success); - } - - /** - * 获取商品可用的优惠券 - */ - @GetMapping("/available") - public Result> getAvailableCoupons( - @RequestParam(required = false, defaultValue = "") String productTags, - @RequestParam Double productPrice, - @RequestParam(required = false) Long shopId, - @RequestAttribute("userId") Long userId - ) { - List availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId); - return Result.success(availableCoupons); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java deleted file mode 100644 index 125fde8a..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.GrowthService; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.GrowthSummaryVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/growth") -@RequiredArgsConstructor -public class GrowthController { - - private final GrowthService growthService; - - @GetMapping("/summary") - public Result summary(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(growthService.getSummary(userId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java deleted file mode 100644 index dd000704..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.ProductLikeService; -import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -/** - * 商品点赞控制器 - * - * @author xiaowang - * @date 2026-03-05 - */ -@RestController -@RequestMapping("/product-like") -@RequiredArgsConstructor -public class ProductLikeController { - /** - * Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductLikeService productLikeService; - - /** - * 点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/like/{productId}") - @OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.addLike(userId, productId); - return Result.success(true); - } - - /** - * 取消点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/unlike/{productId}") - @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.removeLike(userId, productId); - return Result.success(true); - } - - /** - * 检查用户是否已点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否已点赞 - */ - @GetMapping("/check/{productId}") - public Result checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - boolean isLiked = productLikeService.isProductLiked(userId, productId); - return Result.success(isLiked); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java deleted file mode 100644 index 0fc71ff0..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipBenefitDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipBenefitVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipBenefitService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * VIP权益信息表 Controller - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/vip-benefit", "/api/vip-benefit"}) -@RequiredArgsConstructor -public class VipBenefitController { - /** - * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipBenefitService vipBenefitService; - - /** - * 创建VIP权益 - * - * @param vipBenefitDTO VIP权益DTO - * @return VIP权益ID - */ - @PostMapping("/create") - public Result createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { - Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); - return Result.success(id); - } - - /** - * 更新VIP权益 - * - * @param id VIP权益ID - * @param vipBenefitDTO VIP权益DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { - boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); - return Result.success(success); - } - - /** - * 删除VIP权益 - * - * @param id VIP权益ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipBenefit(@PathVariable Long id) { - boolean success = vipBenefitService.deleteVipBenefit(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP权益 - * - * @param id VIP权益ID - * @return VIP权益VO - */ - @GetMapping("/get/{id}") - public Result getVipBenefitById(@PathVariable Long id) { - VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); - return Result.success(vipBenefitVO); - } - - /** - * 查询所有VIP权益 - * - * @return VIP权益VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipBenefits() { - List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); - return Result.success(vipBenefitVOs); - } - - /** - * 根据所需VIP等级查询VIP权益 - * - * @param requiredVipLevel 所需VIP等级 - * @return VIP权益VO列表 - */ - @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") - public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { - List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); - return Result.success(vipBenefitVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java deleted file mode 100644 index c98795da..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipInfoDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipInfoVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipInfoService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户VIP信息表 Controller - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/vip-info", "/api/vip-info"}) -@RequiredArgsConstructor -public class VipInfoController { - /** - * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipInfoService vipInfoService; - - /** - * 创建VIP信息 - * - * @param vipInfoDTO VIP信息DTO - * @return VIP信息ID - */ - @PostMapping("/create") - public Result createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { - Long id = vipInfoService.createVipInfo(vipInfoDTO); - return Result.success(id); - } - - /** - * 更新VIP信息 - * - * @param id VIP信息ID - * @param vipInfoDTO VIP信息DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { - boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); - return Result.success(success); - } - - /** - * 删除VIP信息 - * - * @param id VIP信息ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipInfo(@PathVariable Long id) { - boolean success = vipInfoService.deleteVipInfo(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP信息 - * - * @param id VIP信息ID - * @return VIP信息VO - */ - @GetMapping("/get/{id}") - public Result getVipInfoById(@PathVariable Long id) { - VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); - return Result.success(vipInfoVO); - } - - /** - * 查询所有VIP信息 - * - * @return VIP信息VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipInfos() { - List vipInfoVOs = vipInfoService.listAllVipInfos(); - return Result.success(vipInfoVOs); - } - - /** - * 根据VIP等级查询VIP信息 - * - * @param vipLevel VIP等级 - * @return VIP信息VO列表 - */ - @GetMapping("/list/vipLevel/{vipLevel}") - public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { - List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); - return Result.success(vipInfoVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java deleted file mode 100644 index a8a5a343..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipRechargePlanDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipRechargePlanService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipRechargePlanVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"}) -/** - * VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class VipRechargePlanController { - /** - * Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipRechargePlanService vipRechargePlanService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @GetMapping("/admin/list") - @RequirePermission("user:vip:manage") - /** - * Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); - } - - @PostMapping("/admin/create") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); - } - - @PutMapping("/admin/{id}") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); - } - - @PutMapping("/admin/{id}/status") - @RequirePermission("user:vip:manage") - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); - } - - @GetMapping("/my/list") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listMy(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(vipRechargePlanService.listMyPlans(userId)); - } - - @GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"}) - /** - * Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java deleted file mode 100644 index f1b850fb..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistAddWithGroupDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistGroupDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistMoveDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.WishlistService; -import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistGroupVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistInspirationVO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestAttribute; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/wishlist") -public class WishlistController { - - @Autowired - private WishlistService wishlistService; - - @PostMapping("/add") - @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @PostMapping("/add-with-group") - @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request); - return Result.success("ok"); - } - - @PostMapping("/remove") - @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.removeFromWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @GetMapping("/check") - public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.isInWishlist(userId, productId)); - } - - @GetMapping("/list") - public Result> getWishlist(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getWishlistByUserId(userId)); - } - - @GetMapping("/groups") - public Result> listGroups(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.listGroups(userId)); - } - - @PostMapping("/groups") - public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.createGroup(userId, request)); - } - - @PutMapping("/groups/{id}") - public Result updateGroup( - @PathVariable Long id, - @RequestBody WishlistGroupDTO request, - @RequestAttribute("userId") Long userId - ) { - return Result.success(wishlistService.updateGroup(userId, id, request)); - } - - @DeleteMapping("/groups/{id}") - public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.deleteGroup(userId, id)); - } - - @PostMapping("/move") - @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.moveWishlist(userId, request)); - } - - @GetMapping("/inspiration") - public Result getInspiration(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getInspiration(userId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java deleted file mode 100644 index 029b3630..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.order.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.order.dto.CartDTO; -import com.xiaowang.jayucloud.salon.core.modules.order.service.CartService; -import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jayucloud.salon.core.modules.order.vo.CartVO; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@RestController -@RequestMapping("/cart") -/** - * CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class CartController { - - @Resource - /** - * Purpose: cartService supports CartController.java by holding or executing the cart service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CartService cartService; - - @PostMapping("/add") - @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.addToCart(userId, cartDTO); - return Result.success(); - } - - @DeleteMapping("/remove/{productId}") - @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.removeFromCart(userId, productId); - return Result.success(); - } - - @PostMapping("/batch-remove") - @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `batchRemoveFromCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartItemIds parameter `cartItemIds` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.batchRemoveFromCart(userId, cartItemIds); - return Result.success(); - } - - @PutMapping("/update") - @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.updateCartQuantity(userId, cartDTO); - return Result.success(); - } - - @GetMapping("/list") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getCartList(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - List cartList = cartService.getCartList(userId); - return Result.success(cartList); - } - - @DeleteMapping("/clear") - @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `clearCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result clearCart(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.clearCart(userId); - return Result.success(); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java deleted file mode 100644 index 45e4fc77..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.admin; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.RefundOrderVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/admin/payment") -@RequiredArgsConstructor -public class AdminPaymentController { - - private final PaymentService paymentService; - private final AdminScopeHelper adminScopeHelper; - private final SecurityAuditSupport securityAuditSupport; - - @PostMapping("/order/{orderId}/manual-confirm") - @RequirePermission("payment:manage") - public Result manualConfirm(HttpServletRequest request, - @PathVariable Long orderId, - @RequestParam(required = false) String remark) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - try { - PaymentOrderVO result = paymentService.manualConfirmOrderPaid(currentUser.getId(), orderId, remark); - securityAuditSupport.success(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/order/{orderId}/manual-refund") - @RequirePermission("refund:manage") - public Result manualRefund(HttpServletRequest request, - @PathVariable Long orderId, - @RequestParam(required = false) Long afterSaleId, - @RequestParam(required = false) String remark) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - try { - RefundOrderVO result = paymentService.manualRefundOrder(currentUser.getId(), orderId, afterSaleId, remark); - securityAuditSupport.success(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java deleted file mode 100644 index 87f1c49b..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceChangeDetailDTO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceChangeDetailService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户余额变动明细表 Controller - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"}) -@RequiredArgsConstructor -public class BalanceChangeDetailController { - /** - * Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceChangeDetailService balanceChangeDetailService; - - /** - * 创建余额变动明细 - * - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 余额变动明细ID - */ - @PostMapping("/create") - public Result createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO); - return Result.success(id); - } - - /** - * 更新余额变动明细 - * - * @param id 余额变动明细ID - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO); - return Result.success(success); - } - - /** - * 删除余额变动明细 - * - * @param id 余额变动明细ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalanceChangeDetail(@PathVariable Long id) { - boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id); - return Result.success(success); - } - - /** - * 根据ID查询余额变动明细 - * - * @param id 余额变动明细ID - * @return 余额变动明细VO - */ - @GetMapping("/get/{id}") - public Result getBalanceChangeDetailById(@PathVariable Long id) { - BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id); - return Result.success(balanceChangeDetailVO); - } - - /** - * 查询所有余额变动明细 - * - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalanceChangeDetails() { - List balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails(); - return Result.success(balanceChangeDetailVOs); - } - - /** - * 根据用户ID查询余额变动明细 - * - * @param userId 用户ID - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/user/{userId}") - public Result> listBalanceChangeDetailsByUserId(@PathVariable Long userId) { - List balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId); - return Result.success(balanceChangeDetailVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java deleted file mode 100644 index c625c430..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceDTO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户余额信息表 Controller - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/balance", "/api/balance"}) -@RequiredArgsConstructor -public class BalanceController { - /** - * Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceService balanceService; - - /** - * 创建余额 - * - * @param balanceDTO 余额DTO - * @return 余额ID - */ - @PostMapping("/create") - public Result createBalance(@RequestBody BalanceDTO balanceDTO) { - Long id = balanceService.createBalance(balanceDTO); - return Result.success(id); - } - - /** - * 更新余额 - * - * @param id 余额ID - * @param balanceDTO 余额DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) { - boolean success = balanceService.updateBalance(id, balanceDTO); - return Result.success(success); - } - - /** - * 删除余额 - * - * @param id 余额ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalance(@PathVariable Long id) { - boolean success = balanceService.deleteBalance(id); - return Result.success(success); - } - - /** - * 根据ID查询余额 - * - * @param id 余额ID - * @return 余额VO - */ - @GetMapping("/get/{id}") - public Result getBalanceById(@PathVariable Long id) { - BalanceVO balanceVO = balanceService.getBalanceById(id); - return Result.success(balanceVO); - } - - /** - * 查询所有余额 - * - * @return 余额VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalances() { - List balanceVOs = balanceService.listAllBalances(); - return Result.success(balanceVOs); - } - - /** - * 根据用户ID查询余额 - * - * @param userId 用户ID - * @return 余额VO - */ - @GetMapping("/get/user/{userId}") - public Result getBalanceByUserId(@PathVariable Long userId) { - BalanceVO balanceVO = balanceService.getBalanceByUserId(userId); - return Result.success(balanceVO); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java index 938c6780..b2ff295e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java @@ -3,22 +3,17 @@ package com.xiaowang.jayucloud.salon.core.modules.user.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserBalanceChangeDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserVipOverrideDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserRelationUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import lombok.Data; @@ -42,10 +37,6 @@ public class AdminUserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; /** * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -334,101 +325,6 @@ public class AdminUserController { } } - @GetMapping("/{id}/asset") - @RequirePermission("user:balance:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getUserAsset(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户资产"); - UserAssetVO assetVO = userAssetService.getUserAsset(targetUser.getId()); - return Result.success(assetVO); - } - - @GetMapping("/{id}/balance/history") - @RequirePermission("user:balance:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getUserBalanceHistory(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户余额流水"); - List history = userAssetService.listBalanceHistory(targetUser.getId()); - return Result.success(history); - } - - @PostMapping("/{id}/balance/change") - @RequirePermission("user:balance:manage") - @OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result changeUserBalance( - HttpServletRequest request, - @PathVariable Long id, - @RequestBody AdminUserBalanceChangeDTO balanceChangeDTO - ) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额"); - try { - UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO); - securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/{id}/vip/override") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result overrideUserVip( - HttpServletRequest request, - @PathVariable Long id, - @RequestBody AdminUserVipOverrideDTO vipOverrideDTO - ) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP"); - try { - UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO); - securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/{id}/vip/recalculate") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - /** - * Run business method `recalculateUserVip`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); - try { - UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId()); - securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - @GetMapping("/info") /** * Load data by the supplied parameter. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java index b7d6eb3d..975cb151 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java @@ -10,14 +10,11 @@ import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelp import com.xiaowang.jayucloud.salon.core.modules.file.vo.ChunkUploadSessionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.InviteCodeVO; import com.xiaowang.jayucloud.salon.core.modules.integration.vo.WechatMiniLoginResultVO; import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; @@ -77,10 +74,6 @@ public class UserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; /** * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -229,30 +222,6 @@ public class UserController { return Result.success(success); } - @GetMapping("/asset/me") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getMyAsset(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.getUserAsset(userId)); - } - - @GetMapping("/balance/history/me") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getMyBalanceHistory(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.listBalanceHistory(userId)); - } - /** * 根据ID查询用户 * diff --git a/JC-Salon-Core/src/main/resources/bootstrap.yaml b/JC-Salon-Core/src/main/resources/bootstrap.yaml index e9039e7d..4666dccc 100644 --- a/JC-Salon-Core/src/main/resources/bootstrap.yaml +++ b/JC-Salon-Core/src/main/resources/bootstrap.yaml @@ -18,8 +18,8 @@ spring: # 是否将当前服务注册到 Nacos。 register-enabled: true # Nacos 认证信息可由运行环境覆盖。 - username: ${NACOS_USERNAME:jayucloud} - password: ${NACOS_PASSWORD:122503wcy....} + username: ${NACOS_USERNAME:} + password: ${NACOS_PASSWORD:} config: # Nacos 配置中心与服务发现使用同一运行环境参数。 server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} @@ -34,8 +34,8 @@ spring: # 是否启用配置中心。 enabled: true # Nacos 认证信息可由运行环境覆盖。 - username: ${NACOS_USERNAME:jayucloud} - password: ${NACOS_PASSWORD:122503wcy....} + username: ${NACOS_USERNAME:} + password: ${NACOS_PASSWORD:} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml diff --git a/JC-Salon-Frontend/src/App.vue b/JC-Salon-Frontend/src/App.vue index f444f52c..6f75b9db 100644 --- a/JC-Salon-Frontend/src/App.vue +++ b/JC-Salon-Frontend/src/App.vue @@ -34,7 +34,7 @@ * App page script. * Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events. */ -import { computed, h, onMounted, onUnmounted, provide, ref, watch } from 'vue' +import { computed, h, onMounted, onUnmounted, ref, watch } from 'vue' import { useRoute, useRouter } from 'vue-router' import { ConfigProvider, Modal } from 'ant-design-vue' import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes' @@ -42,7 +42,6 @@ import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context' import { CheckOutlined } from '@ant-design/icons-vue' import BottomNav from './components/BottomNav.vue' import SystemMessageCard from './components/SystemMessageCard.vue' -import { cartApi } from './api/cart' /** * Purpose: SystemMessageVO supports App.vue by holding or executing the system message vo page or API role. * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. @@ -78,7 +77,7 @@ const adminThemeRefreshOptions = { mode: 'admin' as const } const customerThemeRefreshOptions = { mode: 'customer' as const } const isAdminShell = computed(() => route.path.startsWith('/admin') || route.matched.some(r => r.meta.isAdmin)) -const bottomNavRouteNames = new Set(['home', 'products', 'cart', 'profile']) +const bottomNavRouteNames = new Set(['home', 'products', 'profile']) /** isHiddenNav is a reactive state variable used by the template and event handlers. */ const isHiddenNav = computed(() => { @@ -119,39 +118,9 @@ const antdTheme = computed(() => ({ } })) -// 全局购物车数量状态 -/** cartCount is a reactive state variable used by the template and event handlers. */ -const cartCount = ref(0) /** checkingPopupMessages is a reactive state variable used by the template and event handlers. */ const checkingPopupMessages = ref(false) -// 加载购物车数量 -/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const loadCartCount = async () => { - try { - // 检查用户是否已登录 - const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') - if (!token) { - cartCount.value = 0 - return - } - - const response = await cartApi.getCartList() as any - const data = response || [] - const cartList = Array.isArray(data) ? data : [] - const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0) - cartCount.value = totalQuantity - } catch (error) { - cartCount.value = 0 - } -} - -// 提供更新购物车数量的方法 -/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const updateCartCount = async () => { - await loadCartCount() -} - /** * Purpose: resolveSystemMessageActionPath supports App.vue by holding or executing the resolve system message action path page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -235,23 +204,15 @@ const checkPopupMessages = async () => { } } -provide('updateCartCount', updateCartCount) -provide('cartCount', cartCount) - -// 监听路由变化,更新购物车数量 watch(() => route.path, async () => { // 检查当前是否是后台页面,如果是则不加载购物车数据 const isAdminPage = route.matched.some(r => r.meta.isAdmin) await refreshShopTheme(isAdminPage ? adminThemeRefreshOptions : customerThemeRefreshOptions) if (!isAdminPage) { - await loadCartCount() await checkPopupMessages() } }) -// 页面加载时获取购物车数量 -loadCartCount() - onMounted(async () => { stopThemeSync = setupShopThemeSync() await router.isReady() diff --git a/JC-Salon-Frontend/src/api/cart.ts b/JC-Salon-Frontend/src/api/cart.ts deleted file mode 100644 index 5586962e..00000000 --- a/JC-Salon-Frontend/src/api/cart.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -interface CartItem { - productId: IdType - quantity: number -} - -/** - * cartApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const cartApi = { - // 添加作品到购物车 - /** - * `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param item: CartItem caller-supplied value for `item: CartItem` - */ - addToCart: (item: CartItem) => { - return api.post('/cart/add', item) - }, - - // 从购物车移除作品 - /** - * `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - removeFromCart: (productId: IdType) => { - return api.delete(`/cart/remove/${productId}`) - }, - - // 批量从购物车移除作品 - /** - * `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]` - */ - batchRemoveFromCart: (cartItemIds: IdType[]) => { - return api.post('/cart/batch-remove', cartItemIds) - }, - - // 更新购物车作品数量 - /** - * `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param item: CartItem caller-supplied value for `item: CartItem` - */ - updateCartQuantity: (item: CartItem) => { - return api.put('/cart/update', item) - }, - - // 获取购物车列表 - /** - * `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - getCartList: () => { - return api.get('/cart/list') - }, - - // 清空购物车 - /** - * `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - clearCart: () => { - return api.delete('/cart/clear') - } -} diff --git a/JC-Salon-Frontend/src/api/coupon.ts b/JC-Salon-Frontend/src/api/coupon.ts deleted file mode 100644 index edc87861..00000000 --- a/JC-Salon-Frontend/src/api/coupon.ts +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import request from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Coupon { - id: IdType - couponCode: string - couponName: string - couponType: number - couponTypeName: string - discountValue?: number - minAmount?: number - reduceAmount?: number - totalCount: number - usedCount: number - remainingCount: number - startTime: string - endTime: string - status: number - statusName: string - shopId?: IdType - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTags: Tag[] - unavailableTags: Tag[] -} - -/** - * Purpose: Tag supports coupon.ts by holding or executing the tag page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Tag { - id: IdType - tagName?: string -} - -/** - * Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserCoupon { - id: IdType - couponId: IdType - couponName: string - couponType: number - couponTypeName: string - discountValue: string - minAmount: string - reduceAmount: string - startTime: string - endTime: string - status: number - statusName: string - obtainTime: string - useTime: string - sourceType?: string - requiredVipLevel?: string - autoMatched?: boolean -} - -/** - * Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface CreateCouponRequest { - couponCode: string - couponName: string - couponType: number - discountValue?: number - minAmount?: number - reduceAmount?: number - totalCount: number - startTime: string - endTime: string - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTagIds: IdType[] - unavailableTagIds: IdType[] -} - -/** - * Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface CouponListResponse { - list: Coupon[] - total: number - page: number - size: number -} - -/** - * couponApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const couponApi = { - // 创建优惠券 - /** - * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` - */ - createCoupon: (data: CreateCouponRequest) => { - return request({ - url: '/coupon/create', - method: 'post', - data - }) - }, - - // 更新优惠券 - /** - * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` - */ - updateCoupon: (id: IdType, data: CreateCouponRequest) => { - return request({ - url: `/coupon/update/${id}`, - method: 'put', - data - }) - }, - - // 删除优惠券 - /** - * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - deleteCoupon: (id: IdType) => { - return request({ - url: `/coupon/delete/${id}`, - method: 'delete' - }) - }, - - // 获取优惠券详情 - /** - * `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getCouponById: (id: IdType) => { - return request({ - url: `/coupon/detail/${id}`, - method: 'get' - }) - }, - - // 获取优惠券列表 - /** - * `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }` - */ - listCoupons: (params: { page: number; size: number; shopId?: IdType }) => { - return request({ - url: '/coupon/list', - method: 'get', - params - }) - }, - - // 为用户分配优惠券 - /** - * `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param userId: IdType caller-supplied value for `userId: IdType` - * @param couponId: IdType caller-supplied value for `couponId: IdType` - */ - assignCouponToUser: (userId: IdType, couponId: IdType) => { - return request({ - url: '/coupon/assign', - method: 'post', - params: { userId, couponId } - }) - }, - - // 获取用户优惠券列表 - listUserCoupons: async (status?: number): Promise => { - return await request({ - url: '/coupon/user/list', - method: 'get', - params: { status } - }) as UserCoupon[] - }, - - // 使用优惠券 - /** - * `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param userCouponId: IdType caller-supplied value for `userCouponId: IdType` - */ - useCoupon: (userCouponId: IdType) => { - return request({ - url: '/coupon/use', - method: 'post', - params: { userCouponId } - }) - }, - - // 获取作品可用的优惠券 - getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise => { - return await request({ - url: '/coupon/available', - method: 'get', - params: { productTags, productPrice, shopId } - }) as UserCoupon[] - } -} diff --git a/JC-Salon-Frontend/src/api/index.ts b/JC-Salon-Frontend/src/api/index.ts index f45d9081..f4f0731a 100644 --- a/JC-Salon-Frontend/src/api/index.ts +++ b/JC-Salon-Frontend/src/api/index.ts @@ -5,7 +5,6 @@ import axios, { AxiosError } from 'axios' import { authApi } from './auth' import { adminAuthApi } from './admin' -import { wishlistApi } from './wishlist' import { message, Modal } from 'ant-design-vue' import { API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' @@ -393,6 +392,4 @@ export const fileApi = { } } -export { wishlistApi } - export default api diff --git a/JC-Salon-Frontend/src/api/productLike.ts b/JC-Salon-Frontend/src/api/productLike.ts deleted file mode 100644 index 5ce0831d..00000000 --- a/JC-Salon-Frontend/src/api/productLike.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * productLikeApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const productLikeApi = { - /** - * 点赞作品 - * @param productId 作品ID - */ - /** - * `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - likeProduct: (productId: IdType) => { - return api.post(`/product-like/like/${productId}`) - }, - - /** - * 取消点赞作品 - * @param productId 作品ID - */ - /** - * `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - unlikeProduct: (productId: IdType) => { - return api.post(`/product-like/unlike/${productId}`) - }, - - /** - * 检查用户是否已点赞作品 - * @param productId 作品ID - */ - /** - * `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - checkLikeStatus: (productId: IdType) => { - return api.get(`/product-like/check/${productId}`) - } -} diff --git a/JC-Salon-Frontend/src/api/wishlist.ts b/JC-Salon-Frontend/src/api/wishlist.ts deleted file mode 100644 index aacabd9f..00000000 --- a/JC-Salon-Frontend/src/api/wishlist.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface WishlistItem { - id: IdType - userId: IdType - productId: IdType - groupId?: IdType | null - groupName?: string | null - note?: string | null - sortOrder?: number | null - product: { - id: IdType - shopId: IdType | null - shopName?: string - title: string - description: string - imageFileIds?: string - imageUrls?: string[] - price: number - tags?: string - tagList?: string[] - tagInfos?: any[] - likeCount?: number - collectCount?: number - approximateDuration?: string - bookableArtists?: string - availableCoupons?: string - createTime: string - updateTime: string - } -} - -export interface WishlistGroup { - id: IdType - name: string - sortOrder: number - itemCount: number - items?: WishlistItem[] -} - -export interface WishlistInspiration { - total: number - groups: WishlistGroup[] -} - -export interface WishlistGroupPayload { - name: string - sortOrder?: number -} - -export interface WishlistAddWithGroupPayload { - productId: IdType - groupId?: IdType | null - note?: string - sortOrder?: number -} - -export interface WishlistMovePayload { - wishlistId?: IdType - productId?: IdType - groupId?: IdType | null - note?: string - sortOrder?: number -} - -/** - * wishlistApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const wishlistApi = { - addToWishlist: async (productId: IdType): Promise => { - return await api.post('/wishlist/add', { productId }) as unknown as boolean - }, - - removeFromWishlist: async (productId: IdType): Promise => { - return await api.post('/wishlist/remove', { productId }) as unknown as boolean - }, - - checkWishlist: async (productId: IdType): Promise => { - return await api.get(`/wishlist/check?productId=${productId}`) as unknown as boolean - }, - - getWishlist: async (): Promise => { - return await api.get('/wishlist/list') as unknown as WishlistItem[] - }, - - getGroups: async (): Promise => { - return await api.get('/wishlist/groups') as unknown as WishlistGroup[] - }, - - createGroup: async (payload: WishlistGroupPayload): Promise => { - return await api.post('/wishlist/groups', payload) as unknown as IdType - }, - - updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise => { - return await api.put(`/wishlist/groups/${id}`, payload) as unknown as boolean - }, - - deleteGroup: async (id: IdType): Promise => { - return await api.delete(`/wishlist/groups/${id}`) as unknown as boolean - }, - - addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise => { - return await api.post('/wishlist/add-with-group', payload) as unknown as boolean - }, - - moveWishlist: async (payload: WishlistMovePayload): Promise => { - return await api.post('/wishlist/move', payload) as unknown as boolean - }, - - getInspiration: async (): Promise => { - return await api.get('/wishlist/inspiration') as unknown as WishlistInspiration - } -} diff --git a/JC-Salon-Frontend/src/components/BottomNav.vue b/JC-Salon-Frontend/src/components/BottomNav.vue index af791df6..247cd91e 100644 --- a/JC-Salon-Frontend/src/components/BottomNav.vue +++ b/JC-Salon-Frontend/src/components/BottomNav.vue @@ -19,15 +19,6 @@ 作品集 - - -