refactor: 默认 skills 装到 .agents,并清空 example 旧演示实现
对齐安装目录与 opencode 扫描路径;按 confirmed plan 清掉与 iteration1 不对齐的示例业务代码与 as-built 文档,只留空壳与需求输入。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,67 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.assembler.AppointmentAssembler;
|
||||
import com.consultation.application.assembler.BranchAssembler;
|
||||
import com.consultation.application.assembler.ConsultantAssembler;
|
||||
import com.consultation.application.assembler.UserAssembler;
|
||||
import com.consultation.application.service.AdminService;
|
||||
import com.consultation.application.service.AppointmentService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin")
|
||||
@RequiredArgsConstructor
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public class AdminController {
|
||||
|
||||
private final AdminService adminService;
|
||||
private final AppointmentService appointmentService;
|
||||
private final ConsultantAssembler consultantAssembler;
|
||||
private final UserAssembler userAssembler;
|
||||
private final BranchAssembler branchAssembler;
|
||||
private final AppointmentAssembler appointmentAssembler;
|
||||
|
||||
|
||||
@GetMapping("/dashboard")
|
||||
public Map<String, Object> dashboard() { return adminService.dashboard(); }
|
||||
|
||||
@GetMapping("/users")
|
||||
public List<UserAssembler.UserResponse> users() { return adminService.allUsers(); }
|
||||
|
||||
@PutMapping("/users/{id}/toggle-status")
|
||||
public ResponseEntity<Void> toggleUserStatus(@PathVariable String id) { adminService.toggleUserStatus(id); return ResponseEntity.ok().build(); }
|
||||
|
||||
@GetMapping("/consultants")
|
||||
public ResponseEntity<List<ConsultantAssembler.ConsultantResponse>> consultants() {
|
||||
return ResponseEntity.ok(adminService.allConsultants().stream().map(consultantAssembler::toResponse).toList());
|
||||
}
|
||||
|
||||
@GetMapping("/appointments")
|
||||
public List<AppointmentAssembler.AppointmentResponse> appointments() {
|
||||
return appointmentService.getAllAppointments();
|
||||
}
|
||||
|
||||
@GetMapping("/branches")
|
||||
public List<BranchAssembler.BranchResponse> branches() {
|
||||
return adminService.allBranches();
|
||||
}
|
||||
|
||||
@PostMapping("/branches")
|
||||
public BranchAssembler.BranchResponse createBranch(@RequestBody Map<String, String> body) {
|
||||
return adminService.createBranch(body.get("name"), body.get("address"), body.get("phone"));
|
||||
}
|
||||
|
||||
@PutMapping("/branches/{id}")
|
||||
public ResponseEntity<Void> updateBranch(@PathVariable String id, @RequestBody Map<String, String> body) {
|
||||
adminService.updateBranch(id, body.get("name"), body.get("address"), body.get("phone")); return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@DeleteMapping("/branches/{id}")
|
||||
public ResponseEntity<Void> deleteBranch(@PathVariable String id) { adminService.deleteBranch(id); return ResponseEntity.ok().build(); }
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.service.AppointmentService;
|
||||
import com.consultation.infrastructure.security.SecurityUtils;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/appointments")
|
||||
@RequiredArgsConstructor
|
||||
public class AppointmentController {
|
||||
|
||||
private final AppointmentService appointmentService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<?> list() {
|
||||
return ResponseEntity.ok(appointmentService.getMyAppointments(SecurityUtils.currentUserId()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<?> get(@PathVariable String id) { return ResponseEntity.ok(appointmentService.getById(id)); }
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> create(@Valid @RequestBody CreateRequest r) {
|
||||
return ResponseEntity.ok(appointmentService.create(SecurityUtils.currentUserId(),
|
||||
r.consultantId, r.branchId, r.date, r.startTime, r.endTime, r.note));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/cancel")
|
||||
public ResponseEntity<Void> cancel(@PathVariable String id, @RequestBody Map<String, String> body) {
|
||||
appointmentService.cancel(id, SecurityUtils.currentUserId(), body.getOrDefault("reason", "用户取消"));
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class CreateRequest {
|
||||
@NotBlank String consultantId;
|
||||
String branchId;
|
||||
@NotBlank String date;
|
||||
@NotBlank String startTime;
|
||||
@NotBlank String endTime;
|
||||
String note;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.service.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<?> register(@Valid @RequestBody RegisterRequest r) {
|
||||
return ResponseEntity.ok(authService.register(r.email, r.password, r.name, r.phone));
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<?> login(@Valid @RequestBody LoginRequest r) {
|
||||
return ResponseEntity.ok(authService.login(r.email, r.password));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class RegisterRequest {
|
||||
@NotBlank @Email String email;
|
||||
@NotBlank @Size(min = 8) String password;
|
||||
@NotBlank String name;
|
||||
String phone;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class LoginRequest {
|
||||
@NotBlank @Email String email;
|
||||
@NotBlank String password;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.service.BusinessRuleAppService;
|
||||
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 java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/business-rules")
|
||||
@RequiredArgsConstructor
|
||||
public class BusinessRuleController {
|
||||
|
||||
private final BusinessRuleAppService service;
|
||||
|
||||
@GetMapping
|
||||
public List<Map<String, Object>> list() {
|
||||
return service.getAllRules();
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.service.ConsultantService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/consultants")
|
||||
@RequiredArgsConstructor
|
||||
public class ConsultantController {
|
||||
|
||||
private final ConsultantService consultantService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<?> list() { return ResponseEntity.ok(consultantService.findAllActive()); }
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<?> get(@PathVariable String id) { return ResponseEntity.ok(consultantService.getById(id)); }
|
||||
|
||||
@GetMapping("/{id}/slots")
|
||||
public ResponseEntity<List<Map<String, String>>> slots(@PathVariable String id, @RequestParam String date) {
|
||||
return ResponseEntity.ok(consultantService.getAvailableSlots(id, date));
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.service.DataDictionaryAppService;
|
||||
import com.consultation.domain.datadictionary.DataDictionary;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/data-dictionaries")
|
||||
@RequiredArgsConstructor
|
||||
public class DataDictionaryController {
|
||||
|
||||
private final DataDictionaryAppService service;
|
||||
|
||||
@GetMapping
|
||||
public List<DataDictionary> list() {
|
||||
return service.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{type}")
|
||||
public DataDictionary getByType(@PathVariable String type) {
|
||||
return service.getByType(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/health")
|
||||
public class HealthController {
|
||||
|
||||
@GetMapping
|
||||
public Map<String, String> health() {
|
||||
return Map.of("status", "UP");
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/home")
|
||||
public class HomeController {
|
||||
|
||||
@GetMapping("/info")
|
||||
public ResponseEntity<Map<String, Object>> info() {
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"title", "专业咨询服务",
|
||||
"description", "我们提供专业的在线咨询服务,预约方便快捷。",
|
||||
"consultants", java.util.List.of()
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.application.service.UserService;
|
||||
import com.consultation.infrastructure.security.SecurityUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
@RequiredArgsConstructor
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<?> profile() { return ResponseEntity.ok(userService.getProfile(SecurityUtils.currentUserId())); }
|
||||
|
||||
@PutMapping("/me")
|
||||
public ResponseEntity<?> update(@RequestBody Map<String, String> body) {
|
||||
return ResponseEntity.ok(userService.updateProfile(SecurityUtils.currentUserId(), body.get("name"), body.get("phone")));
|
||||
}
|
||||
|
||||
@PutMapping("/me/password")
|
||||
public ResponseEntity<Void> changePw(@RequestBody Map<String, String> body) {
|
||||
userService.changePassword(SecurityUtils.currentUserId(), body.get("oldPassword"), body.get("newPassword"));
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.consultation.application.assembler;
|
||||
|
||||
import com.consultation.domain.aggregate.Appointment;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AppointmentAssembler {
|
||||
public AppointmentResponse toResponse(Appointment a) {
|
||||
if (a == null) return null;
|
||||
return AppointmentResponse.builder().id(a.getId()).userId(a.getUserId()).consultantId(a.getConsultantId())
|
||||
.branchId(a.getBranchId()).appointmentDate(a.getAppointmentDate().toString())
|
||||
.startTime(a.getStartTime()).endTime(a.getEndTime()).durationMinutes(a.getDurationMinutes())
|
||||
.status(a.getStatus().name()).note(a.getNote()).cancelReason(a.getCancelReason()).build();
|
||||
}
|
||||
|
||||
@Data @Builder
|
||||
public static class AppointmentResponse {
|
||||
String id; String userId; String consultantId; String branchId;
|
||||
String appointmentDate; String startTime; String endTime;
|
||||
int durationMinutes; String status; String note; String cancelReason;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.consultation.application.assembler;
|
||||
|
||||
import com.consultation.domain.aggregate.Branch;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class BranchAssembler {
|
||||
public BranchResponse toResponse(Branch b) {
|
||||
if (b == null) return null;
|
||||
return BranchResponse.builder().id(b.getId()).name(b.getName()).address(b.getAddress())
|
||||
.phone(b.getPhone()).status(b.getStatus().name()).build();
|
||||
}
|
||||
|
||||
@Data @Builder
|
||||
public static class BranchResponse { String id; String name; String address; String phone; String status; }
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.consultation.application.assembler;
|
||||
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ConsultantAssembler {
|
||||
public ConsultantResponse toResponse(Consultant c) {
|
||||
if (c == null) return null;
|
||||
return ConsultantResponse.builder().id(c.getId()).name(c.getName()).title(c.getTitle()).bio(c.getBio())
|
||||
.specialties(c.getSpecialties()).avatar(c.getAvatar()).branchId(c.getBranchId())
|
||||
.status(c.getStatus().name()).sortOrder(c.getSortOrder()).build();
|
||||
}
|
||||
|
||||
@Data @Builder
|
||||
public static class ConsultantResponse {
|
||||
String id; String name; String title; String bio; String specialties;
|
||||
String avatar; String branchId; String status; int sortOrder;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.consultation.application.assembler;
|
||||
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class UserAssembler {
|
||||
public UserResponse toResponse(User u) {
|
||||
if (u == null) return null;
|
||||
return UserResponse.builder().id(u.getId()).email(u.getEmail()).name(u.getName())
|
||||
.phone(u.getPhone()).role(u.getRole().name()).status(u.getStatus().name()).build();
|
||||
}
|
||||
public AuthResponse toAuth(User u, String token) {
|
||||
return AuthResponse.builder().token(token).user(toResponse(u)).build();
|
||||
}
|
||||
|
||||
@Data @Builder
|
||||
public static class UserResponse { String id; String email; String name; String phone; String role; String status; }
|
||||
@Data @Builder
|
||||
public static class AuthResponse { String token; UserResponse user; }
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.application.assembler.BranchAssembler;
|
||||
import com.consultation.application.assembler.UserAssembler;
|
||||
import com.consultation.domain.aggregate.Branch;
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import com.consultation.domain.repository.AppointmentRepository;
|
||||
import com.consultation.domain.repository.BranchRepository;
|
||||
import com.consultation.domain.repository.ConsultantRepository;
|
||||
import com.consultation.domain.repository.UserRepository;
|
||||
import com.consultation.domain.vo.UserStatus;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminService {
|
||||
|
||||
private final UserRepository userRepo;
|
||||
private final BranchRepository branchRepo;
|
||||
private final ConsultantRepository consultantRepo;
|
||||
private final AppointmentRepository appointmentRepo;
|
||||
private final BranchAssembler branchAssembler;
|
||||
private final UserAssembler userAssembler;
|
||||
|
||||
public Map<String, Object> dashboard() {
|
||||
return Map.of("totalUsers", userRepo.findAll().size(), "totalConsultants", consultantRepo.count(),
|
||||
"totalAppointments", appointmentRepo.count(), "pendingAppointments", appointmentRepo.countByStatus("PENDING"),
|
||||
"totalBranches", branchRepo.count());
|
||||
}
|
||||
|
||||
public List<UserAssembler.UserResponse> allUsers() { return userRepo.findAll().stream().map(userAssembler::toResponse).toList(); }
|
||||
public List<Consultant> allConsultants() { return consultantRepo.findAll(); }
|
||||
public List<BranchAssembler.BranchResponse> allBranches() { return branchRepo.findAll().stream().map(branchAssembler::toResponse).toList(); }
|
||||
|
||||
@Transactional
|
||||
public void toggleUserStatus(String id) {
|
||||
User u = userRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("用户不存在"));
|
||||
User upd = User.builder().id(u.getId()).email(u.getEmail()).password(u.getPassword())
|
||||
.name(u.getName()).phone(u.getPhone()).role(u.getRole())
|
||||
.status(u.getStatus() == UserStatus.ACTIVE ? UserStatus.DISABLED : UserStatus.ACTIVE).build();
|
||||
userRepo.update(upd);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BranchAssembler.BranchResponse createBranch(String name, String address, String phone) {
|
||||
return branchAssembler.toResponse(branchRepo.save(Branch.builder().id(UUID.randomUUID().toString())
|
||||
.name(name).address(address).phone(phone).status(Branch.BranchStatus.ACTIVE).build()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateBranch(String id, String name, String address, String phone) {
|
||||
Branch b = branchRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("网点不存在"));
|
||||
branchRepo.update(Branch.builder().id(id).name(name != null ? name : b.getName())
|
||||
.address(address != null ? address : b.getAddress()).phone(phone != null ? phone : b.getPhone())
|
||||
.status(b.getStatus()).build());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteBranch(String id) { branchRepo.deleteById(id); }
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.application.assembler.AppointmentAssembler;
|
||||
import com.consultation.domain.aggregate.Appointment;
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import com.consultation.domain.repository.AppointmentRepository;
|
||||
import com.consultation.domain.repository.ConsultantRepository;
|
||||
import com.consultation.domain.service.AppointmentConflictService;
|
||||
import com.consultation.domain.vo.AppointmentStatus;
|
||||
import com.consultation.domain.vo.TimeSlot;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AppointmentService {
|
||||
|
||||
private final AppointmentRepository appointmentRepo;
|
||||
private final ConsultantRepository consultantRepo;
|
||||
private final AppointmentConflictService conflictService = new AppointmentConflictService();
|
||||
private final AppointmentAssembler assembler;
|
||||
|
||||
public AppointmentAssembler.AppointmentResponse getById(String id) {
|
||||
return assembler.toResponse(appointmentRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("预约不存在")));
|
||||
}
|
||||
|
||||
public List<AppointmentAssembler.AppointmentResponse> getMyAppointments(String userId) {
|
||||
return appointmentRepo.findByUserId(userId, 1, 100).stream().map(assembler::toResponse).toList();
|
||||
}
|
||||
|
||||
public List<AppointmentAssembler.AppointmentResponse> getAllAppointments() {
|
||||
return appointmentRepo.findAll(1, 1000).stream().map(assembler::toResponse).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AppointmentAssembler.AppointmentResponse create(String userId, String consultantId, String branchId,
|
||||
String date, String startTime, String endTime, String note) {
|
||||
Consultant consultant = consultantRepo.findById(consultantId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("咨询师不存在"));
|
||||
if (!consultant.isAvailable()) throw new IllegalStateException("该咨询师当前不可预约");
|
||||
|
||||
LocalDate ld = LocalDate.parse(date);
|
||||
LocalTime st = LocalTime.parse(startTime);
|
||||
LocalTime et = LocalTime.parse(endTime);
|
||||
var existing = appointmentRepo.findByConsultantIdAndDate(consultantId, ld);
|
||||
conflictService.validateNoConflict(existing, new TimeSlot(ld, st, et));
|
||||
|
||||
Appointment a = appointmentRepo.save(Appointment.builder().id(UUID.randomUUID().toString())
|
||||
.userId(userId).consultantId(consultantId).branchId(branchId)
|
||||
.appointmentDate(ld).startTime(startTime).endTime(endTime)
|
||||
.durationMinutes((int) java.time.Duration.between(st, et).toMinutes())
|
||||
.status(AppointmentStatus.PENDING).note(note).build());
|
||||
return assembler.toResponse(a);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void cancel(String id, String userId, String reason) {
|
||||
Appointment a = appointmentRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("预约不存在"));
|
||||
if (!a.canCancel()) throw new IllegalStateException("当前状态不允许取消");
|
||||
Appointment upd = Appointment.builder().id(a.getId()).userId(a.getUserId()).consultantId(a.getConsultantId())
|
||||
.branchId(a.getBranchId()).appointmentDate(a.getAppointmentDate()).startTime(a.getStartTime())
|
||||
.endTime(a.getEndTime()).durationMinutes(a.getDurationMinutes()).status(AppointmentStatus.CANCELLED)
|
||||
.note(a.getNote()).cancelReason(reason != null ? reason : "用户取消").build();
|
||||
appointmentRepo.update(upd);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.application.assembler.UserAssembler;
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import com.consultation.domain.repository.UserRepository;
|
||||
import com.consultation.domain.service.PasswordService;
|
||||
import com.consultation.domain.vo.UserRole;
|
||||
import com.consultation.domain.vo.UserStatus;
|
||||
import com.consultation.infrastructure.security.JwtTokenProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
|
||||
private final UserRepository userRepo;
|
||||
private final PasswordService passwordService;
|
||||
private final JwtTokenProvider tokenProvider;
|
||||
private final UserAssembler assembler;
|
||||
|
||||
@Transactional
|
||||
public UserAssembler.AuthResponse register(String email, String password, String name, String phone) {
|
||||
if (userRepo.existsByEmail(email)) throw new IllegalArgumentException("邮箱已被注册");
|
||||
User user = userRepo.save(User.builder().id(UUID.randomUUID().toString()).email(email)
|
||||
.password(passwordService.encode(password)).name(name).phone(phone)
|
||||
.role(UserRole.ROLE_USER).status(UserStatus.ACTIVE).build());
|
||||
return assembler.toAuth(user, tokenProvider.generate(user.getId(), user.getEmail(), user.getRole().name()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserAssembler.AuthResponse login(String email, String password) {
|
||||
User user = userRepo.findByEmail(email).orElseThrow(() -> new IllegalArgumentException("邮箱或密码错误"));
|
||||
if (!user.isActive()) throw new IllegalStateException("账户已被停用");
|
||||
if (!passwordService.matches(password, user.getPassword())) throw new IllegalArgumentException("邮箱或密码错误");
|
||||
return assembler.toAuth(user, tokenProvider.generate(user.getId(), user.getEmail(), user.getRole().name()));
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.infrastructure.config.BusinessRuleProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BusinessRuleAppService {
|
||||
|
||||
private final BusinessRuleProvider provider;
|
||||
|
||||
public List<Map<String, Object>> getAllRules() {
|
||||
return provider.getAllRules();
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.application.assembler.ConsultantAssembler;
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import com.consultation.domain.repository.AppointmentRepository;
|
||||
import com.consultation.domain.repository.ConsultantRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ConsultantService {
|
||||
|
||||
private final ConsultantRepository consultantRepo;
|
||||
private final AppointmentRepository appointmentRepo;
|
||||
private final ConsultantAssembler assembler;
|
||||
|
||||
public List<ConsultantAssembler.ConsultantResponse> findAllActive() {
|
||||
return consultantRepo.findAllActive().stream().map(assembler::toResponse).toList();
|
||||
}
|
||||
|
||||
public ConsultantAssembler.ConsultantResponse getById(String id) {
|
||||
return assembler.toResponse(consultantRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("咨询师不存在")));
|
||||
}
|
||||
|
||||
public List<Map<String, String>> getAvailableSlots(String consultantId, String date) {
|
||||
if (!consultantRepo.existsById(consultantId)) return List.of();
|
||||
LocalDate localDate = LocalDate.parse(date);
|
||||
var booked = new HashSet<String>();
|
||||
appointmentRepo.findByConsultantIdAndDate(consultantId, localDate).stream()
|
||||
.filter(a -> a.getStatus() != com.consultation.domain.vo.AppointmentStatus.CANCELLED)
|
||||
.forEach(a -> booked.add(a.getStartTime()));
|
||||
|
||||
List<Map<String, String>> slots = new ArrayList<>();
|
||||
for (int h = 9; h < 18; h++) {
|
||||
String s = String.format("%02d:00", h);
|
||||
String e = String.format("%02d:00", h + 1);
|
||||
if (!booked.contains(s)) slots.add(Map.of("startTime", s, "endTime", e));
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ConsultantAssembler.ConsultantResponse create(String name, String title, String bio, String specialties, String avatar, String branchId, int sortOrder) {
|
||||
Consultant c = consultantRepo.save(Consultant.builder().id(UUID.randomUUID().toString()).name(name)
|
||||
.title(title).bio(bio).specialties(specialties).avatar(avatar).branchId(branchId)
|
||||
.status(Consultant.ConsultantStatus.ACTIVE).sortOrder(sortOrder).build());
|
||||
return assembler.toResponse(c);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ConsultantAssembler.ConsultantResponse update(String id, String name, String title, String bio, String specialties) {
|
||||
Consultant existing = consultantRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("咨询师不存在"));
|
||||
Consultant upd = Consultant.builder().id(id).name(name != null ? name : existing.getName())
|
||||
.title(title != null ? title : existing.getTitle()).bio(bio != null ? bio : existing.getBio())
|
||||
.specialties(specialties != null ? specialties : existing.getSpecialties())
|
||||
.avatar(existing.getAvatar()).branchId(existing.getBranchId()).status(existing.getStatus())
|
||||
.sortOrder(existing.getSortOrder()).build();
|
||||
consultantRepo.update(upd);
|
||||
return assembler.toResponse(upd);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(String id) { consultantRepo.deleteById(id); }
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.domain.datadictionary.DataDictionary;
|
||||
import com.consultation.domain.datadictionary.DataDictionaryUtil;
|
||||
import com.consultation.domain.datadictionary.DemoDataDictionaryType;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class DataDictionaryAppService {
|
||||
|
||||
public List<DataDictionary> getAll() {
|
||||
return DataDictionaryUtil.allDictionaries(DemoDataDictionaryType.values());
|
||||
}
|
||||
|
||||
public DataDictionary getByType(String typeName) {
|
||||
return Arrays.stream(DemoDataDictionaryType.values())
|
||||
.filter(t -> t.name().equalsIgnoreCase(typeName))
|
||||
.findFirst()
|
||||
.map(DataDictionaryUtil::toDataDictionary)
|
||||
.orElseThrow(() -> new IllegalArgumentException("字典类型不存在: " + typeName));
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.consultation.application.service;
|
||||
|
||||
import com.consultation.application.assembler.UserAssembler;
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import com.consultation.domain.repository.UserRepository;
|
||||
import com.consultation.domain.service.PasswordService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepo;
|
||||
private final PasswordService passwordService;
|
||||
private final UserAssembler assembler;
|
||||
|
||||
public UserAssembler.UserResponse getProfile(String userId) {
|
||||
return assembler.toResponse(userRepo.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在")));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserAssembler.UserResponse updateProfile(String userId, String name, String phone) {
|
||||
User u = userRepo.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在"));
|
||||
User upd = User.builder().id(u.getId()).email(u.getEmail()).password(u.getPassword())
|
||||
.name(name != null ? name : u.getName()).phone(phone != null ? phone : u.getPhone())
|
||||
.role(u.getRole()).status(u.getStatus()).build();
|
||||
userRepo.update(upd);
|
||||
return assembler.toResponse(upd);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void changePassword(String userId, String oldPw, String newPw) {
|
||||
User u = userRepo.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在"));
|
||||
if (!passwordService.matches(oldPw, u.getPassword())) throw new IllegalArgumentException("原密码错误");
|
||||
User upd = User.builder().id(u.getId()).email(u.getEmail()).password(passwordService.encode(newPw))
|
||||
.name(u.getName()).phone(u.getPhone()).role(u.getRole()).status(u.getStatus()).build();
|
||||
userRepo.update(upd);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.consultation.domain.aggregate;
|
||||
|
||||
import com.consultation.domain.vo.AppointmentStatus;
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Value @Builder
|
||||
public class Appointment {
|
||||
String id; String userId; String consultantId; String branchId;
|
||||
LocalDate appointmentDate; String startTime; String endTime;
|
||||
int durationMinutes; AppointmentStatus status; String note; String cancelReason;
|
||||
|
||||
public boolean isOwnedBy(String uid) { return userId.equals(uid); }
|
||||
public boolean canCancel() { return status == AppointmentStatus.PENDING || status == AppointmentStatus.CONFIRMED; }
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.consultation.domain.aggregate;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
|
||||
@Value @Builder
|
||||
public class Branch {
|
||||
String id; String name; String address; String phone; BranchStatus status;
|
||||
public enum BranchStatus implements com.consultation.domain.datadictionary.Description {
|
||||
ACTIVE("营业中"), DISABLED("已关闭");
|
||||
private final String description;
|
||||
BranchStatus(String description) { this.description = description; }
|
||||
@Override public String getCode() { return name(); }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.consultation.domain.aggregate;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
|
||||
@Value @Builder
|
||||
public class Consultant {
|
||||
String id; String name; String title; String bio; String specialties;
|
||||
String avatar; String branchId; ConsultantStatus status; int sortOrder;
|
||||
|
||||
public enum ConsultantStatus implements com.consultation.domain.datadictionary.Description {
|
||||
ACTIVE("可预约"), DISABLED("不可预约");
|
||||
private final String description;
|
||||
ConsultantStatus(String description) { this.description = description; }
|
||||
@Override public String getCode() { return name(); }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
public boolean isAvailable() { return status == ConsultantStatus.ACTIVE; }
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.consultation.domain.aggregate;
|
||||
|
||||
import com.consultation.domain.vo.UserRole;
|
||||
import com.consultation.domain.vo.UserStatus;
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
|
||||
@Value @Builder
|
||||
public class User {
|
||||
String id;
|
||||
String email;
|
||||
String password;
|
||||
String name;
|
||||
String phone;
|
||||
UserRole role;
|
||||
UserStatus status;
|
||||
|
||||
public boolean isAdmin() { return role == UserRole.ROLE_ADMIN; }
|
||||
public boolean isActive() { return status == UserStatus.ACTIVE; }
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.consultation.domain.businessrule;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public enum AppointmentRule implements IBusinessRule {
|
||||
CONFLICT_DETECTION("appointment_conflict_detection", "同一咨询师同一时段不可重复预约"),
|
||||
SLOT_INTERVAL("appointment_slot_interval", "预约时段间隔为 60 分钟"),
|
||||
AVAILABLE_HOURS("appointment_available_hours", "可预约时段为 09:00-18:00"),
|
||||
CANCEL_WINDOW("appointment_cancel_window", "PENDING / CONFIRMED 状态可取消");
|
||||
|
||||
private final String ruleName;
|
||||
private final String description;
|
||||
|
||||
@Override public String getRuleName() { return ruleName; }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.consultation.domain.businessrule;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public enum AuthRule implements IBusinessRule {
|
||||
PASSWORD_MIN_LENGTH("auth_password_min_length", "密码最少 8 位"),
|
||||
TOKEN_EXPIRATION("auth_token_expiration", "JWT 有效期 24 小时"),
|
||||
PASSWORD_ALGORITHM("auth_password_algorithm", "密码使用 BCrypt 加密");
|
||||
|
||||
private final String ruleName;
|
||||
private final String description;
|
||||
|
||||
@Override public String getRuleName() { return ruleName; }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
@@ -9,47 +9,17 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 业务规则配置空壳。后续按 feature 扩展字段,并由 YAML 绑定。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties
|
||||
@ConfigurationProperties(prefix = "business-rules")
|
||||
public class BusinessRuleConfig {
|
||||
|
||||
private Map<String, Object> appointment = new HashMap<>();
|
||||
private Map<String, Object> rules = new HashMap<>();
|
||||
|
||||
private AuthConfig auth = new AuthConfig();
|
||||
|
||||
@Data
|
||||
public static class AuthConfig {
|
||||
|
||||
private PasswordConfig password = new PasswordConfig();
|
||||
|
||||
private TokenConfig token = new TokenConfig();
|
||||
|
||||
/**
|
||||
* 免鉴权端点列表。YAML 里写成序列,若这里声明为 Map<String, Object>,
|
||||
* 会被 Spring Boot 的 binder 绑成以 0/1/2… 为键的 Map,序列化出错误结构。
|
||||
*/
|
||||
private List<String> publicEndpoints = new ArrayList<>(List.of(
|
||||
"/api/v1/auth/**",
|
||||
"/api/v1/home/**",
|
||||
"/api/v1/consultants/**",
|
||||
"/api/v1/data-dictionaries/**",
|
||||
"/api/v1/business-rules/**"));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class PasswordConfig {
|
||||
|
||||
private int minLength = 8;
|
||||
|
||||
private String algorithm = "BCrypt";
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class TokenConfig {
|
||||
|
||||
private long expirationMs = 86400000L;
|
||||
|
||||
private String algorithm = "HMAC-SHA256";
|
||||
}
|
||||
private List<String> publicEndpoints = new ArrayList<>(List.of(
|
||||
"/api/v1/health"
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.consultation.domain.datadictionary;
|
||||
|
||||
import com.consultation.domain.aggregate.Branch;
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import com.consultation.domain.vo.AppointmentStatus;
|
||||
import com.consultation.domain.vo.UserRole;
|
||||
import com.consultation.domain.vo.UserStatus;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public enum DemoDataDictionaryType implements DataDictionaryType {
|
||||
USER_ROLE(UserRole.class, "用户角色"),
|
||||
USER_STATUS(UserStatus.class, "用户状态"),
|
||||
APPOINTMENT_STATUS(AppointmentStatus.class, "预约状态"),
|
||||
CONSULTANT_STATUS(Consultant.ConsultantStatus.class, "咨询师状态"),
|
||||
BRANCH_STATUS(Branch.BranchStatus.class, "网点状态");
|
||||
|
||||
private final Class<? extends Description> clazz;
|
||||
private final String description;
|
||||
|
||||
@Override public Class<? extends Description> getClazz() { return clazz; }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.consultation.domain.repository;
|
||||
|
||||
import com.consultation.domain.aggregate.Appointment;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface AppointmentRepository {
|
||||
Optional<Appointment> findById(String id);
|
||||
List<Appointment> findByUserId(String userId, int page, int pageSize);
|
||||
List<Appointment> findByConsultantIdAndDate(String consultantId, LocalDate date);
|
||||
List<Appointment> findAll(int page, int pageSize);
|
||||
Appointment save(Appointment a);
|
||||
void update(Appointment a);
|
||||
long count();
|
||||
long countByStatus(String status);
|
||||
long countByUserId(String userId);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.consultation.domain.repository;
|
||||
|
||||
import com.consultation.domain.aggregate.Branch;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface BranchRepository {
|
||||
Optional<Branch> findById(String id);
|
||||
List<Branch> findAll();
|
||||
Branch save(Branch b);
|
||||
void update(Branch b);
|
||||
void deleteById(String id);
|
||||
long count();
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.consultation.domain.repository;
|
||||
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface ConsultantRepository {
|
||||
Optional<Consultant> findById(String id);
|
||||
List<Consultant> findAllActive();
|
||||
List<Consultant> findAll();
|
||||
Consultant save(Consultant c);
|
||||
void update(Consultant c);
|
||||
void deleteById(String id);
|
||||
long count();
|
||||
boolean existsById(String id);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.consultation.domain.repository;
|
||||
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository {
|
||||
Optional<User> findById(String id);
|
||||
Optional<User> findByEmail(String email);
|
||||
List<User> findAll();
|
||||
User save(User user);
|
||||
void update(User user);
|
||||
boolean existsByEmail(String email);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.consultation.domain.service;
|
||||
|
||||
import com.consultation.domain.aggregate.Appointment;
|
||||
import com.consultation.domain.vo.AppointmentStatus;
|
||||
import com.consultation.domain.vo.TimeSlot;
|
||||
import java.util.List;
|
||||
|
||||
public class AppointmentConflictService {
|
||||
|
||||
public void validateNoConflict(List<Appointment> existing, TimeSlot requested) {
|
||||
boolean conflict = existing.stream().anyMatch(a ->
|
||||
a.getAppointmentDate().equals(requested.date()) &&
|
||||
a.getStartTime().equals(requested.startTime().toString()) &&
|
||||
a.getStatus() != AppointmentStatus.CANCELLED);
|
||||
if (conflict) throw new IllegalStateException("该时间段已被预约");
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.consultation.domain.vo;
|
||||
|
||||
import com.consultation.domain.datadictionary.Description;
|
||||
|
||||
public enum AppointmentStatus implements Description {
|
||||
PENDING("待确认"),
|
||||
CONFIRMED("已确认"),
|
||||
COMPLETED("已完成"),
|
||||
CANCELLED("已取消");
|
||||
|
||||
private final String description;
|
||||
AppointmentStatus(String description) { this.description = description; }
|
||||
@Override public String getCode() { return name(); }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.consultation.domain.vo;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
|
||||
public record TimeSlot(LocalDate date, LocalTime startTime, LocalTime endTime) {
|
||||
public int durationMinutes() { return (int) Duration.between(startTime, endTime).toMinutes(); }
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.consultation.domain.vo;
|
||||
|
||||
import com.consultation.domain.datadictionary.Description;
|
||||
|
||||
public enum UserRole implements Description {
|
||||
ROLE_USER("普通用户"),
|
||||
ROLE_ADMIN("管理员");
|
||||
|
||||
private final String description;
|
||||
UserRole(String description) { this.description = description; }
|
||||
@Override public String getCode() { return name(); }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.consultation.domain.vo;
|
||||
|
||||
import com.consultation.domain.datadictionary.Description;
|
||||
|
||||
public enum UserStatus implements Description {
|
||||
ACTIVE("正常"),
|
||||
DISABLED("已停用");
|
||||
|
||||
private final String description;
|
||||
UserStatus(String description) { this.description = description; }
|
||||
@Override public String getCode() { return name(); }
|
||||
@Override public String getDescription() { return description; }
|
||||
}
|
||||
@@ -8,7 +8,10 @@ import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -26,30 +29,19 @@ public class BusinessRuleProvider {
|
||||
Map<String, Object> detail = new LinkedHashMap<>();
|
||||
detail.put("ruleName", rule.getRuleName());
|
||||
detail.put("description", rule.getDescription());
|
||||
|
||||
Map<String, Object> ruleConfig = new LinkedHashMap<>();
|
||||
addIfPresent(ruleConfig, "appointment", projected.get("appointment"));
|
||||
addIfPresent(ruleConfig, "auth", projected.get("auth"));
|
||||
if (!ruleConfig.isEmpty()) detail.put("config", ruleConfig);
|
||||
|
||||
if (!projected.isEmpty()) {
|
||||
detail.put("config", projected);
|
||||
}
|
||||
ruleCache.put(rule.getRuleName(), detail);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getAllRules() {
|
||||
return new ArrayList<Map<String, Object>>(ruleCache.values());
|
||||
return new ArrayList<>(ruleCache.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 把强类型的配置对象投影成 Map,保持对外返回结构为 {@code List<Map<String, Object>>}。
|
||||
* JSON 形状属于基础设施关注点,故投影放在 infrastructure 层,domain 不依赖 ObjectMapper。
|
||||
*/
|
||||
private Map<String, Object> projectConfig() {
|
||||
return objectMapper.convertValue(config, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
}
|
||||
|
||||
private void addIfPresent(Map<String, Object> target, String key, Object source) {
|
||||
if (source instanceof Map<?, ?> map && !map.isEmpty()) target.put(key, map);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,11 @@
|
||||
package com.consultation.infrastructure.config;
|
||||
|
||||
import com.consultation.domain.businessrule.AppointmentRule;
|
||||
import com.consultation.domain.businessrule.AuthRule;
|
||||
import com.consultation.domain.businessrule.IBusinessRule;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 业务规则 Bean 注册入口(当前为空壳)。
|
||||
* iteration1 实现时在此注册 {@link com.consultation.domain.businessrule.IBusinessRule} 实现。
|
||||
*/
|
||||
@Configuration
|
||||
public class BusinessRuleRegistration {
|
||||
|
||||
@Bean
|
||||
public IBusinessRule appointmentConflictDetection() {
|
||||
return AppointmentRule.CONFLICT_DETECTION;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBusinessRule appointmentSlotInterval() {
|
||||
return AppointmentRule.SLOT_INTERVAL;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBusinessRule appointmentAvailableHours() {
|
||||
return AppointmentRule.AVAILABLE_HOURS;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBusinessRule appointmentCancelWindow() {
|
||||
return AppointmentRule.CANCEL_WINDOW;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBusinessRule authPasswordMinLength() {
|
||||
return AuthRule.PASSWORD_MIN_LENGTH;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBusinessRule authTokenExpiration() {
|
||||
return AuthRule.TOKEN_EXPIRATION;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IBusinessRule authPasswordAlgorithm() {
|
||||
return AuthRule.PASSWORD_ALGORITHM;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.consultation.infrastructure.security.JwtAuthenticationFilter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
@@ -25,13 +24,7 @@ public class SecurityConfig {
|
||||
http.csrf(c -> c.disable())
|
||||
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(a -> a
|
||||
.requestMatchers("/api/v1/auth/**").permitAll()
|
||||
.requestMatchers("/api/v1/home/**").permitAll()
|
||||
.requestMatchers("/api/v1/data-dictionaries/**").permitAll()
|
||||
.requestMatchers("/api/v1/business-rules/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/consultants", "/api/v1/consultants/*/slots").permitAll()
|
||||
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
|
||||
.requestMatchers("/admin/**").hasRole("ADMIN")
|
||||
.requestMatchers("/api/v1/health").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.converter;
|
||||
|
||||
import com.consultation.domain.aggregate.Appointment;
|
||||
import com.consultation.domain.vo.AppointmentStatus;
|
||||
import com.consultation.infrastructure.persistence.po.AppointmentPO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AppointmentConverter {
|
||||
public Appointment toDomain(AppointmentPO po) {
|
||||
if (po == null) return null;
|
||||
return Appointment.builder().id(po.getId()).userId(po.getUserId()).consultantId(po.getConsultantId())
|
||||
.branchId(po.getBranchId()).appointmentDate(po.getAppointmentDate())
|
||||
.startTime(po.getStartTime()).endTime(po.getEndTime()).durationMinutes(po.getDurationMinutes())
|
||||
.status(AppointmentStatus.valueOf(po.getStatus())).note(po.getNote()).cancelReason(po.getCancelReason()).build();
|
||||
}
|
||||
public AppointmentPO toPO(Appointment a) {
|
||||
if (a == null) return null;
|
||||
AppointmentPO po = new AppointmentPO();
|
||||
po.setId(a.getId()); po.setUserId(a.getUserId()); po.setConsultantId(a.getConsultantId());
|
||||
po.setBranchId(a.getBranchId()); po.setAppointmentDate(a.getAppointmentDate());
|
||||
po.setStartTime(a.getStartTime()); po.setEndTime(a.getEndTime()); po.setDurationMinutes(a.getDurationMinutes());
|
||||
po.setStatus(a.getStatus().name()); po.setNote(a.getNote()); po.setCancelReason(a.getCancelReason());
|
||||
return po;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.converter;
|
||||
|
||||
import com.consultation.domain.aggregate.Branch;
|
||||
import com.consultation.infrastructure.persistence.po.BranchPO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class BranchConverter {
|
||||
public Branch toDomain(BranchPO po) {
|
||||
if (po == null) return null;
|
||||
return Branch.builder().id(po.getId()).name(po.getName()).address(po.getAddress())
|
||||
.phone(po.getPhone()).status(Branch.BranchStatus.valueOf(po.getStatus())).build();
|
||||
}
|
||||
public BranchPO toPO(Branch b) {
|
||||
if (b == null) return null;
|
||||
BranchPO po = new BranchPO();
|
||||
po.setId(b.getId()); po.setName(b.getName()); po.setAddress(b.getAddress());
|
||||
po.setPhone(b.getPhone()); po.setStatus(b.getStatus().name());
|
||||
return po;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.converter;
|
||||
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import com.consultation.infrastructure.persistence.po.ConsultantPO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ConsultantConverter {
|
||||
public Consultant toDomain(ConsultantPO po) {
|
||||
if (po == null) return null;
|
||||
return Consultant.builder().id(po.getId()).name(po.getName()).title(po.getTitle()).bio(po.getBio())
|
||||
.specialties(po.getSpecialties()).avatar(po.getAvatar()).branchId(po.getBranchId())
|
||||
.status(Consultant.ConsultantStatus.valueOf(po.getStatus())).sortOrder(po.getSortOrder()).build();
|
||||
}
|
||||
public ConsultantPO toPO(Consultant c) {
|
||||
if (c == null) return null;
|
||||
ConsultantPO po = new ConsultantPO();
|
||||
po.setId(c.getId()); po.setName(c.getName()); po.setTitle(c.getTitle()); po.setBio(c.getBio());
|
||||
po.setSpecialties(c.getSpecialties()); po.setAvatar(c.getAvatar()); po.setBranchId(c.getBranchId());
|
||||
po.setStatus(c.getStatus().name()); po.setSortOrder(c.getSortOrder());
|
||||
return po;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.converter;
|
||||
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import com.consultation.domain.vo.UserRole;
|
||||
import com.consultation.domain.vo.UserStatus;
|
||||
import com.consultation.infrastructure.persistence.po.UserPO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class UserConverter {
|
||||
public User toDomain(UserPO po) {
|
||||
if (po == null) return null;
|
||||
return User.builder().id(po.getId()).email(po.getEmail()).password(po.getPassword())
|
||||
.name(po.getName()).phone(po.getPhone())
|
||||
.role(UserRole.valueOf(po.getRole())).status(UserStatus.valueOf(po.getStatus())).build();
|
||||
}
|
||||
public UserPO toPO(User u) {
|
||||
if (u == null) return null;
|
||||
UserPO po = new UserPO();
|
||||
po.setId(u.getId()); po.setEmail(u.getEmail()); po.setPassword(u.getPassword());
|
||||
po.setName(u.getName()); po.setPhone(u.getPhone());
|
||||
po.setRole(u.getRole().name()); po.setStatus(u.getStatus().name());
|
||||
return po;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.consultation.infrastructure.persistence.po.AppointmentPO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface AppointmentMapper extends BaseMapper<AppointmentPO> {}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.consultation.infrastructure.persistence.po.BranchPO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface BranchMapper extends BaseMapper<BranchPO> {}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.consultation.infrastructure.persistence.po.ConsultantPO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface ConsultantMapper extends BaseMapper<ConsultantPO> {}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.consultation.infrastructure.persistence.po.UserPO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface UserMapper extends BaseMapper<UserPO> {}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("appointment")
|
||||
public class AppointmentPO {
|
||||
private String id; private String userId; private String consultantId; private String branchId;
|
||||
private LocalDate appointmentDate; private String startTime; private String endTime;
|
||||
private Integer durationMinutes; private String status; private String note; private String cancelReason;
|
||||
private String createdBy; private LocalDateTime createdTime;
|
||||
private String updatedBy; private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("branch")
|
||||
public class BranchPO {
|
||||
private String id; private String name; private String address; private String phone;
|
||||
private String status;
|
||||
private String createdBy; private LocalDateTime createdTime;
|
||||
private String updatedBy; private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("consultant")
|
||||
public class ConsultantPO {
|
||||
private String id; private String name; private String title; private String bio;
|
||||
private String specialties; private String avatar; private String branchId;
|
||||
private String status; private Integer sortOrder;
|
||||
private String createdBy; private LocalDateTime createdTime;
|
||||
private String updatedBy; private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.consultation.infrastructure.persistence.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("user")
|
||||
public class UserPO {
|
||||
private String id; private String email; private String password; private String name;
|
||||
private String phone; private String role; private String status; private Integer deleted;
|
||||
private String createdBy; private LocalDateTime createdTime;
|
||||
private String updatedBy; private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.consultation.infrastructure.repositoryimpl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.consultation.domain.aggregate.Appointment;
|
||||
import com.consultation.domain.repository.AppointmentRepository;
|
||||
import com.consultation.infrastructure.persistence.converter.AppointmentConverter;
|
||||
import com.consultation.infrastructure.persistence.mapper.AppointmentMapper;
|
||||
import com.consultation.infrastructure.persistence.po.AppointmentPO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class AppointmentRepositoryImpl implements AppointmentRepository {
|
||||
|
||||
private final AppointmentMapper mapper;
|
||||
private final AppointmentConverter converter;
|
||||
|
||||
@Override public Optional<Appointment> findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); }
|
||||
|
||||
@Override
|
||||
public List<Appointment> findByUserId(String userId, int page, int pageSize) {
|
||||
return mapper.selectPage(new Page<>(page, pageSize),
|
||||
new LambdaQueryWrapper<AppointmentPO>().eq(AppointmentPO::getUserId, userId).orderByDesc(AppointmentPO::getCreatedTime))
|
||||
.getRecords().stream().map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Appointment> findByConsultantIdAndDate(String consultantId, LocalDate date) {
|
||||
return mapper.selectList(new LambdaQueryWrapper<AppointmentPO>()
|
||||
.eq(AppointmentPO::getConsultantId, consultantId).eq(AppointmentPO::getAppointmentDate, date))
|
||||
.stream().map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Appointment> findAll(int page, int pageSize) {
|
||||
return mapper.selectPage(new Page<>(page, pageSize), null).getRecords().stream().map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Appointment save(Appointment a) {
|
||||
AppointmentPO po = converter.toPO(a);
|
||||
po.setCreatedBy(a.getUserId()); po.setCreatedTime(LocalDateTime.now());
|
||||
po.setUpdatedBy(a.getUserId()); po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.insert(po); return a;
|
||||
}
|
||||
|
||||
@Override public void update(Appointment a) { AppointmentPO po = converter.toPO(a); po.setUpdatedTime(LocalDateTime.now()); mapper.updateById(po); }
|
||||
|
||||
@Override public long count() { return mapper.selectCount(null); }
|
||||
@Override public long countByStatus(String s) { return mapper.selectCount(new LambdaQueryWrapper<AppointmentPO>().eq(AppointmentPO::getStatus, s)); }
|
||||
@Override public long countByUserId(String u) { return mapper.selectCount(new LambdaQueryWrapper<AppointmentPO>().eq(AppointmentPO::getUserId, u)); }
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.consultation.infrastructure.repositoryimpl;
|
||||
|
||||
import com.consultation.domain.aggregate.Branch;
|
||||
import com.consultation.domain.repository.BranchRepository;
|
||||
import com.consultation.infrastructure.persistence.converter.BranchConverter;
|
||||
import com.consultation.infrastructure.persistence.mapper.BranchMapper;
|
||||
import com.consultation.infrastructure.persistence.po.BranchPO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class BranchRepositoryImpl implements BranchRepository {
|
||||
|
||||
private final BranchMapper mapper;
|
||||
private final BranchConverter converter;
|
||||
|
||||
@Override public Optional<Branch> findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); }
|
||||
@Override public List<Branch> findAll() { return mapper.selectList(null).stream().map(converter::toDomain).toList(); }
|
||||
|
||||
@Override
|
||||
public Branch save(Branch b) {
|
||||
BranchPO po = converter.toPO(b);
|
||||
po.setCreatedBy(b.getId()); po.setCreatedTime(LocalDateTime.now()); po.setUpdatedBy(b.getId()); po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.insert(po); return b;
|
||||
}
|
||||
|
||||
@Override public void update(Branch b) { BranchPO po = converter.toPO(b); po.setUpdatedTime(LocalDateTime.now()); mapper.updateById(po); }
|
||||
@Override public void deleteById(String id) { mapper.deleteById(id); }
|
||||
@Override public long count() { return mapper.selectCount(null); }
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.consultation.infrastructure.repositoryimpl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.consultation.domain.aggregate.Consultant;
|
||||
import com.consultation.domain.repository.ConsultantRepository;
|
||||
import com.consultation.infrastructure.persistence.converter.ConsultantConverter;
|
||||
import com.consultation.infrastructure.persistence.mapper.ConsultantMapper;
|
||||
import com.consultation.infrastructure.persistence.po.ConsultantPO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class ConsultantRepositoryImpl implements ConsultantRepository {
|
||||
|
||||
private final ConsultantMapper mapper;
|
||||
private final ConsultantConverter converter;
|
||||
|
||||
@Override public Optional<Consultant> findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); }
|
||||
@Override public List<Consultant> findAll() { return mapper.selectList(null).stream().map(converter::toDomain).toList(); }
|
||||
|
||||
@Override
|
||||
public List<Consultant> findAllActive() {
|
||||
return mapper.selectList(new LambdaQueryWrapper<ConsultantPO>()
|
||||
.eq(ConsultantPO::getStatus, Consultant.ConsultantStatus.ACTIVE.name())
|
||||
.orderByAsc(ConsultantPO::getSortOrder)).stream().map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Consultant save(Consultant c) {
|
||||
ConsultantPO po = converter.toPO(c);
|
||||
po.setCreatedBy(c.getId()); po.setCreatedTime(LocalDateTime.now()); po.setUpdatedBy(c.getId()); po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.insert(po); return c;
|
||||
}
|
||||
|
||||
@Override public void update(Consultant c) { ConsultantPO po = converter.toPO(c); po.setUpdatedTime(LocalDateTime.now()); mapper.updateById(po); }
|
||||
@Override public void deleteById(String id) { mapper.deleteById(id); }
|
||||
@Override public long count() { return mapper.selectCount(null); }
|
||||
@Override public boolean existsById(String id) { return mapper.selectCount(new LambdaQueryWrapper<ConsultantPO>().eq(ConsultantPO::getId, id)) > 0; }
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.consultation.infrastructure.repositoryimpl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.consultation.domain.aggregate.User;
|
||||
import com.consultation.domain.repository.UserRepository;
|
||||
import com.consultation.infrastructure.persistence.converter.UserConverter;
|
||||
import com.consultation.infrastructure.persistence.mapper.UserMapper;
|
||||
import com.consultation.infrastructure.persistence.po.UserPO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class UserRepositoryImpl implements UserRepository {
|
||||
|
||||
private final UserMapper mapper;
|
||||
private final UserConverter converter;
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); }
|
||||
|
||||
@Override
|
||||
public Optional<User> findByEmail(String email) {
|
||||
return Optional.ofNullable(converter.toDomain(mapper.selectOne(new LambdaQueryWrapper<UserPO>().eq(UserPO::getEmail, email))));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findAll() { return mapper.selectList(null).stream().map(converter::toDomain).toList(); }
|
||||
|
||||
@Override
|
||||
public User save(User u) {
|
||||
UserPO po = converter.toPO(u);
|
||||
po.setCreatedBy(u.getId()); po.setCreatedTime(LocalDateTime.now());
|
||||
po.setUpdatedBy(u.getId()); po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.insert(po);
|
||||
return u;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(User u) {
|
||||
UserPO po = converter.toPO(u);
|
||||
po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.updateById(po);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByEmail(String email) { return mapper.selectCount(new LambdaQueryWrapper<UserPO>().eq(UserPO::getEmail, email)) > 0; }
|
||||
}
|
||||
@@ -3,8 +3,6 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: consultation-backend
|
||||
config:
|
||||
import: "classpath:/business-rules/appointment.yml,classpath:/business-rules/auth.yml"
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/consultation?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
|
||||
username: root
|
||||
@@ -26,3 +24,6 @@ mybatis-plus:
|
||||
jwt:
|
||||
secret: <your-jwt-secret>
|
||||
expiration: 86400000
|
||||
business-rules:
|
||||
public-endpoints:
|
||||
- /api/v1/health
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
appointment:
|
||||
conflict:
|
||||
detection: "同一咨询师同一时段不可重复预约"
|
||||
enforcement: "uk_appointment_slot 唯一索引 + AppointmentConflictService 双重校验"
|
||||
slot:
|
||||
minMinutes: 30
|
||||
maxMinutes: 120
|
||||
intervalMinutes: 60
|
||||
available:
|
||||
start: "09:00"
|
||||
end: "18:00"
|
||||
cancel:
|
||||
allowedStatuses: "PENDING, CONFIRMED"
|
||||
reasonRequired: true
|
||||
@@ -1,13 +0,0 @@
|
||||
auth:
|
||||
password:
|
||||
minLength: 8
|
||||
algorithm: "BCrypt"
|
||||
token:
|
||||
expirationMs: 86400000
|
||||
algorithm: "HMAC-SHA256"
|
||||
publicEndpoints:
|
||||
- "/api/v1/auth/**"
|
||||
- "/api/v1/home/**"
|
||||
- "/api/v1/consultants/**"
|
||||
- "/api/v1/data-dictionaries/**"
|
||||
- "/api/v1/business-rules/**"
|
||||
@@ -1,22 +0,0 @@
|
||||
create table user
|
||||
(
|
||||
id varchar(64) not null primary key comment '用户ID',
|
||||
email varchar(128) not null comment '邮箱',
|
||||
password varchar(256) not null comment '密码(BCrypt)',
|
||||
name varchar(64) not null comment '姓名',
|
||||
phone varchar(20) null comment '手机号',
|
||||
role varchar(20) not null default 'ROLE_USER' comment '角色',
|
||||
status varchar(12) not null default 'ACTIVE' comment '状态',
|
||||
deleted tinyint(1) default 0 not null,
|
||||
created_by varchar(64) not null,
|
||||
created_time datetime default CURRENT_TIMESTAMP not null,
|
||||
updated_by varchar(64) not null,
|
||||
updated_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
|
||||
) comment '用户表' charset = utf8mb4;
|
||||
|
||||
create unique index uk_user_email on user(email);
|
||||
|
||||
insert into user (id, email, password, name, phone, role, status, created_by, updated_by)
|
||||
values ('admin-001', 'admin@test.com',
|
||||
'$2a$10$4rDXdT56xLoF0LajF1fKRuZFxxdAd6rM9CuCcZdRrb/k7eRHMTKQq',
|
||||
'管理员', '13800000000', 'ROLE_ADMIN', 'ACTIVE', 'admin-001', 'admin-001');
|
||||
@@ -1,47 +0,0 @@
|
||||
create table consultant
|
||||
(
|
||||
id varchar(64) not null primary key comment '咨询师ID',
|
||||
name varchar(64) not null comment '姓名',
|
||||
title varchar(128) null comment '头衔',
|
||||
bio text null comment '简介',
|
||||
specialties varchar(256) null comment '专长',
|
||||
avatar varchar(256) null comment '头像',
|
||||
branch_id varchar(64) null comment '网点ID',
|
||||
status varchar(12) not null default 'ACTIVE' comment '状态',
|
||||
sort_order int default 0 not null comment '排序',
|
||||
created_by varchar(64) not null,
|
||||
created_time datetime default CURRENT_TIMESTAMP not null,
|
||||
updated_by varchar(64) not null,
|
||||
updated_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
|
||||
) comment '咨询师表' charset = utf8mb4;
|
||||
|
||||
create index idx_consultant_status on consultant(status);
|
||||
|
||||
insert into consultant (id, name, title, bio, specialties, sort_order, created_by, updated_by)
|
||||
values ('c-001', '张医生', '资深心理咨询师', '拥有15年心理咨询经验。', '焦虑症,抑郁症,人际关系', 1, 'admin-001', 'admin-001'),
|
||||
('c-002', '李律师', '企业法律顾问', '10年企业法律顾问经验。', '合同法,劳动法,公司治理', 2, 'admin-001', 'admin-001'),
|
||||
('c-003', '王教练', '职业规划导师', '帮助超过500人实现职业转型。', '职业规划,简历优化', 3, 'admin-001', 'admin-001');
|
||||
|
||||
create table appointment
|
||||
(
|
||||
id varchar(64) not null primary key comment '预约ID',
|
||||
user_id varchar(64) not null comment '用户ID',
|
||||
consultant_id varchar(64) not null comment '咨询师ID',
|
||||
branch_id varchar(64) null comment '网点ID',
|
||||
appointment_date date not null comment '预约日期',
|
||||
start_time varchar(10) not null comment '开始时间',
|
||||
end_time varchar(10) not null comment '结束时间',
|
||||
duration_minutes int not null comment '时长(分钟)',
|
||||
status varchar(20) not null default 'PENDING' comment '状态',
|
||||
note text null comment '备注',
|
||||
cancel_reason varchar(256) null comment '取消原因',
|
||||
created_by varchar(64) not null,
|
||||
created_time datetime default CURRENT_TIMESTAMP not null,
|
||||
updated_by varchar(64) not null,
|
||||
updated_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
|
||||
) comment '预约表' charset = utf8mb4;
|
||||
|
||||
create index idx_appointment_user on appointment(user_id);
|
||||
create index idx_appointment_consultant on appointment(consultant_id);
|
||||
create index idx_appointment_date on appointment(appointment_date);
|
||||
create unique index uk_appointment_slot on appointment(consultant_id, appointment_date, start_time);
|
||||
@@ -1,17 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS branch (
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
address VARCHAR(255),
|
||||
phone VARCHAR(20),
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
created_by VARCHAR(64),
|
||||
created_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_by VARCHAR(64),
|
||||
updated_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO branch (id, name, address, phone, status) VALUES
|
||||
('b-001', '朝阳咨询中心', '北京市朝阳区建国路88号', '010-88880001', 'ACTIVE'),
|
||||
('b-002', '海淀咨询中心', '北京市海淀区中关村大街66号', '010-88880002', 'ACTIVE'),
|
||||
('b-003', '浦东咨询中心', '上海市浦东新区陆家嘴路100号', '021-68880003', 'ACTIVE')
|
||||
ON DUPLICATE KEY UPDATE name=VALUES(name);
|
||||
@@ -2,12 +2,10 @@ package com.consultation;
|
||||
|
||||
import com.consultation.config.ResetDbService;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public abstract class TestBase {
|
||||
@@ -24,37 +22,4 @@ public abstract class TestBase {
|
||||
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
|
||||
resetDbService.resetAll();
|
||||
}
|
||||
|
||||
protected String loginAsUser() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"test@test.com\",\"password\":\"password123\",\"name\":\"测试用户\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/register")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
var r = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"test@test.com\",\"password\":\"password123\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/login")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
return r.extract().jsonPath().getString("token");
|
||||
}
|
||||
|
||||
protected String loginAsAdmin() {
|
||||
var r = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"admin@test.com\",\"password\":\"password\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/login")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
return r.extract().jsonPath().getString("token");
|
||||
}
|
||||
|
||||
protected String authHeader(String token) {
|
||||
return "Bearer " + token;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class AdminControllerTest extends TestBase {
|
||||
|
||||
String adminToken;
|
||||
|
||||
@BeforeEach
|
||||
void initToken() {
|
||||
adminToken = loginAsAdmin();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_get_dashboard() {
|
||||
given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.when()
|
||||
.get("/api/v1/admin/dashboard")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("totalUsers", notNullValue())
|
||||
.body("totalConsultants", notNullValue())
|
||||
.body("totalAppointments", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_list_users() {
|
||||
given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.when()
|
||||
.get("/api/v1/admin/users")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_toggle_user_status() {
|
||||
var firstUserId = given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.when()
|
||||
.get("/api/v1/admin/users")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("[0].id");
|
||||
|
||||
given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.when()
|
||||
.put("/api/v1/admin/users/{id}/toggle-status", firstUserId)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_branch_crud() {
|
||||
var branchId = given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"测试网点\",\"address\":\"测试地址\",\"phone\":\"010-88888888\"}")
|
||||
.when()
|
||||
.post("/api/v1/admin/branches")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("id");
|
||||
|
||||
given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"更新网点\"}")
|
||||
.when()
|
||||
.put("/api/v1/admin/branches/{id}", branchId)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.header("Authorization", authHeader(adminToken))
|
||||
.when()
|
||||
.delete("/api/v1/admin/branches/{id}", branchId)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_crud_data_dictionary() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries/USER_ROLE")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("typeName", equalTo("USER_ROLE"))
|
||||
.body("items", not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_list_business_rules() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()));
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class AppointmentControllerTest extends TestBase {
|
||||
|
||||
String userToken;
|
||||
|
||||
@BeforeEach
|
||||
void initToken() {
|
||||
userToken = loginAsUser();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_create_and_list() {
|
||||
given()
|
||||
.header("Authorization", authHeader(userToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"10:00\",\"endTime\":\"11:00\",\"note\":\"测试预约\"}")
|
||||
.when()
|
||||
.post("/api/v1/appointments")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("id", notNullValue())
|
||||
.body("status", equalTo("PENDING"));
|
||||
|
||||
given()
|
||||
.header("Authorization", authHeader(userToken))
|
||||
.when()
|
||||
.get("/api/v1/appointments")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_reject_conflict() {
|
||||
given()
|
||||
.header("Authorization", authHeader(userToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"11:00\",\"endTime\":\"12:00\"}")
|
||||
.when()
|
||||
.post("/api/v1/appointments")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.header("Authorization", authHeader(userToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"11:00\",\"endTime\":\"12:00\"}")
|
||||
.when()
|
||||
.post("/api/v1/appointments")
|
||||
.then()
|
||||
.statusCode(409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_cancel_appointment() {
|
||||
var id = given()
|
||||
.header("Authorization", authHeader(userToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"14:00\",\"endTime\":\"15:00\"}")
|
||||
.when()
|
||||
.post("/api/v1/appointments")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("id");
|
||||
|
||||
given()
|
||||
.header("Authorization", authHeader(userToken))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"reason\":\"测试取消\"}")
|
||||
.when()
|
||||
.put("/api/v1/appointments/{id}/cancel", id)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class AuthControllerTest extends TestBase {
|
||||
|
||||
@Test
|
||||
void should_register_and_login() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"new@test.com\",\"password\":\"password123\",\"name\":\"新用户\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/register")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("token", notNullValue())
|
||||
.body("user.email", equalTo("new@test.com"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"new@test.com\",\"password\":\"password123\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/login")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("token", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_fail_duplicate_email() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"dup@test.com\",\"password\":\"password123\",\"name\":\"用户1\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/register")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"dup@test.com\",\"password\":\"password123\",\"name\":\"用户2\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/register")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("errorCode", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_fail_wrong_password() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"fail@test.com\",\"password\":\"password123\",\"name\":\"用户\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/register")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"email\":\"fail@test.com\",\"password\":\"wrongpass\"}")
|
||||
.when()
|
||||
.post("/api/v1/auth/login")
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class BusinessRuleControllerTest extends TestBase {
|
||||
|
||||
@Test
|
||||
void should_list_all_business_rules() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()))
|
||||
.body("$", hasSize(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_contain_appointment_conflict_detection_rule() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ruleName", hasItem("appointment_conflict_detection"));
|
||||
|
||||
assertThat(descriptionOf("appointment_conflict_detection"), not(isEmptyOrNullString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_contain_auth_token_expiration_rule() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ruleName", hasItem("auth_token_expiration"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_expose_yaml_config_for_each_rule() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("config", everyItem(notNullValue()))
|
||||
.body("config.appointment.slot.minMinutes", everyItem(equalTo(30)))
|
||||
.body("config.auth.token.expirationMs", everyItem(equalTo(86400000)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_access_without_token() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_expose_public_endpoints_as_json_array() {
|
||||
Object publicEndpoints = authConfig().get("publicEndpoints");
|
||||
|
||||
assertThat(publicEndpoints, notNullValue());
|
||||
assertThat(publicEndpoints, instanceOf(List.class));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Object> endpoints = (List<Object>) publicEndpoints;
|
||||
assertThat(endpoints, hasSize(5));
|
||||
assertThat(endpoints, hasItems("/api/v1/auth/**", "/api/v1/business-rules/**"));
|
||||
for (Object endpoint : endpoints) {
|
||||
assertThat((String) endpoint, startsWith("/api/v1/"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_expose_auth_scalar_config_without_type_drift() {
|
||||
Map<String, Object> auth = authConfig();
|
||||
|
||||
Map<String, Object> password = child(auth, "password");
|
||||
Map<String, Object> token = child(auth, "token");
|
||||
|
||||
assertThat(((Number) password.get("minLength")).intValue(), is(8));
|
||||
assertThat(password.get("algorithm"), is("BCrypt"));
|
||||
assertThat(((Number) token.get("expirationMs")).longValue(), is(86400000L));
|
||||
assertThat(token.get("algorithm"), is("HMAC-SHA256"));
|
||||
}
|
||||
|
||||
private String descriptionOf(String ruleName) {
|
||||
List<Map<String, Object>> rules = given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getList("$");
|
||||
return rules.stream()
|
||||
.filter(rule -> ruleName.equals(rule.get("ruleName")))
|
||||
.map(rule -> (String) rule.get("description"))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> authConfig() {
|
||||
List<Map<String, Object>> rules = given()
|
||||
.when()
|
||||
.get("/api/v1/business-rules")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getList("$");
|
||||
for (Map<String, Object> rule : rules) {
|
||||
Object config = rule.get("config");
|
||||
if (!(config instanceof Map<?, ?> configMap)) continue;
|
||||
Object auth = configMap.get("auth");
|
||||
if (auth instanceof Map<?, ?> authMap) {
|
||||
return (Map<String, Object>) authMap;
|
||||
}
|
||||
}
|
||||
throw new AssertionError("no rule exposes config.auth");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> child(Map<String, Object> parent, String key) {
|
||||
Object value = parent.get(key);
|
||||
assertThat(value, instanceOf(Map.class));
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class ConsultantControllerTest extends TestBase {
|
||||
|
||||
@Test
|
||||
void should_list_consultants() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/consultants")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_slots() {
|
||||
given()
|
||||
.queryParam("date", "2026-12-01")
|
||||
.when()
|
||||
.get("/api/v1/consultants/c-001/slots")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()))
|
||||
.body("[0].startTime", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_empty_for_invalid_consultant() {
|
||||
given()
|
||||
.queryParam("date", "2026-12-01")
|
||||
.when()
|
||||
.get("/api/v1/consultants/invalid-id/slots")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", empty());
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class DataDictionaryControllerTest extends TestBase {
|
||||
|
||||
@Test
|
||||
void should_list_all_data_dictionary_types() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$", not(empty()))
|
||||
.body("$", hasSize(5))
|
||||
.body("typeName", everyItem(not(isEmptyOrNullString())))
|
||||
.body("description", everyItem(not(isEmptyOrNullString())))
|
||||
.body("items", everyItem(hasSize(greaterThan(0))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_get_data_dictionary_by_type() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries/USER_ROLE")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("typeName", equalTo("USER_ROLE"))
|
||||
.body("description", not(isEmptyOrNullString()))
|
||||
.body("items.code", hasItems("ROLE_USER", "ROLE_ADMIN"))
|
||||
.body("items.description", everyItem(not(isEmptyOrNullString())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_get_data_dictionary_by_type_ignoring_case() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries/user_role")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("typeName", equalTo("USER_ROLE"))
|
||||
.body("items.code", hasItems("ROLE_USER", "ROLE_ADMIN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_list_all_appointment_status_codes() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries/APPOINTMENT_STATUS")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("typeName", equalTo("APPOINTMENT_STATUS"))
|
||||
.body("items.code", hasItems("PENDING", "CONFIRMED", "COMPLETED", "CANCELLED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_fail_for_unknown_dictionary_type() {
|
||||
given()
|
||||
.when()
|
||||
.get("/api/v1/data-dictionaries/NOT_EXIST")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("errorCode", equalTo("PARAM_ERROR"))
|
||||
.body("errorMessage", containsString("字典类型不存在"))
|
||||
.body("data", nullValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class HealthControllerTest {
|
||||
|
||||
@Test
|
||||
void should_return_up_when_get_health() {
|
||||
var body = new HealthController().health();
|
||||
assertEquals("UP", body.get("status"));
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.consultation.adapter.rest;
|
||||
|
||||
import com.consultation.TestBase;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
class UserControllerTest extends TestBase {
|
||||
|
||||
String token;
|
||||
|
||||
@BeforeEach
|
||||
void initToken() {
|
||||
token = loginAsUser();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_get_profile() {
|
||||
given()
|
||||
.header("Authorization", authHeader(token))
|
||||
.when()
|
||||
.get("/api/v1/users/me")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("email", equalTo("test@test.com"))
|
||||
.body("name", equalTo("测试用户"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_update_profile() {
|
||||
given()
|
||||
.header("Authorization", authHeader(token))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"更新姓名\",\"phone\":\"13900000000\"}")
|
||||
.when()
|
||||
.put("/api/v1/users/me")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo("更新姓名"))
|
||||
.body("phone", equalTo("13900000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_change_password() {
|
||||
given()
|
||||
.header("Authorization", authHeader(token))
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"oldPassword\":\"password123\",\"newPassword\":\"newpassword123\"}")
|
||||
.when()
|
||||
.put("/api/v1/users/me/password")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
spring:
|
||||
config:
|
||||
import: "classpath:/business-rules/appointment.yml,classpath:/business-rules/auth.yml"
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/consultation_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
|
||||
username: root
|
||||
@@ -16,3 +14,6 @@ spring:
|
||||
jwt:
|
||||
secret: test-secret-key-for-mysql-tests-only
|
||||
expiration: 86400000
|
||||
business-rules:
|
||||
public-endpoints:
|
||||
- /api/v1/health
|
||||
|
||||
@@ -1,17 +1 @@
|
||||
-- Seed admin user (password: password)
|
||||
insert into user (id, email, password, name, phone, role, status, created_by, updated_by)
|
||||
values ('admin-001', 'admin@test.com',
|
||||
'$2a$10$4rDXdT56xLoF0LajF1fKRuZFxxdAd6rM9CuCcZdRrb/k7eRHMTKQq',
|
||||
'管理员', '13800000000', 'ROLE_ADMIN', 'ACTIVE', 'admin-001', 'admin-001');
|
||||
|
||||
-- Seed consultants
|
||||
insert into consultant (id, name, title, bio, specialties, sort_order, created_by, updated_by)
|
||||
values ('c-001', '张医生', '资深心理咨询师', '拥有15年心理咨询经验。', '焦虑症,抑郁症,人际关系', 1, 'admin-001', 'admin-001'),
|
||||
('c-002', '李律师', '企业法律顾问', '10年企业法律顾问经验。', '合同法,劳动法,公司治理', 2, 'admin-001', 'admin-001'),
|
||||
('c-003', '王教练', '职业规划导师', '帮助超过500人实现职业转型。', '职业规划,简历优化', 3, 'admin-001', 'admin-001');
|
||||
|
||||
-- Seed branches
|
||||
insert into branch (id, name, address, phone, status, created_by, updated_by)
|
||||
values ('b-001', '朝阳咨询中心', '北京市朝阳区建国路88号', '010-88880001', 'ACTIVE', 'admin-001', 'admin-001'),
|
||||
('b-002', '海淀咨询中心', '北京市海淀区中关村大街66号', '010-88880002', 'ACTIVE', 'admin-001', 'admin-001'),
|
||||
('b-003', '浦东咨询中心', '上海市浦东新区陆家嘴路100号', '021-68880003', 'ACTIVE', 'admin-001', 'admin-001');
|
||||
-- Skeleton: no seed data.
|
||||
|
||||
@@ -1,72 +1 @@
|
||||
drop table if exists branch;
|
||||
drop table if exists appointment;
|
||||
drop table if exists consultant;
|
||||
drop table if exists user;
|
||||
|
||||
create table user (
|
||||
id varchar(64) not null primary key,
|
||||
email varchar(128) not null,
|
||||
password varchar(256) not null,
|
||||
name varchar(64) not null,
|
||||
phone varchar(20),
|
||||
role varchar(20) not null default 'ROLE_USER',
|
||||
status varchar(12) not null default 'ACTIVE',
|
||||
deleted tinyint default 0 not null,
|
||||
created_by varchar(64) not null,
|
||||
created_time datetime default CURRENT_TIMESTAMP not null,
|
||||
updated_by varchar(64) not null,
|
||||
updated_time datetime default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
|
||||
create unique index uk_user_email on user(email);
|
||||
|
||||
create table consultant (
|
||||
id varchar(64) not null primary key,
|
||||
name varchar(64) not null,
|
||||
title varchar(128),
|
||||
bio text,
|
||||
specialties varchar(256),
|
||||
avatar varchar(256),
|
||||
branch_id varchar(64),
|
||||
status varchar(12) not null default 'ACTIVE',
|
||||
sort_order int default 0 not null,
|
||||
created_by varchar(64) not null,
|
||||
created_time datetime default CURRENT_TIMESTAMP not null,
|
||||
updated_by varchar(64) not null,
|
||||
updated_time datetime default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
|
||||
create table appointment (
|
||||
id varchar(64) not null primary key,
|
||||
user_id varchar(64) not null,
|
||||
consultant_id varchar(64) not null,
|
||||
branch_id varchar(64),
|
||||
appointment_date date not null,
|
||||
start_time varchar(10) not null,
|
||||
end_time varchar(10) not null,
|
||||
duration_minutes int not null,
|
||||
status varchar(20) not null default 'PENDING',
|
||||
note text,
|
||||
cancel_reason varchar(256),
|
||||
created_by varchar(64) not null,
|
||||
created_time datetime default CURRENT_TIMESTAMP not null,
|
||||
updated_by varchar(64) not null,
|
||||
updated_time datetime default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
|
||||
create index idx_appointment_user on appointment(user_id);
|
||||
create index idx_appointment_consultant on appointment(consultant_id);
|
||||
create index idx_appointment_date on appointment(appointment_date);
|
||||
create unique index uk_appointment_slot on appointment(consultant_id, appointment_date, start_time);
|
||||
|
||||
create table branch (
|
||||
id varchar(64) primary key,
|
||||
name varchar(100) not null,
|
||||
address varchar(255),
|
||||
phone varchar(20),
|
||||
status varchar(20) not null default 'ACTIVE',
|
||||
created_by varchar(64),
|
||||
created_time datetime not null default CURRENT_TIMESTAMP,
|
||||
updated_by varchar(64),
|
||||
updated_time datetime not null default CURRENT_TIMESTAMP
|
||||
);
|
||||
-- Skeleton: no business tables. Recreate via Flyway when implementing iteration1 features.
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
<template>
|
||||
<div class="admin-layout">
|
||||
<aside class="sidebar">
|
||||
<h2>管理后台</h2>
|
||||
<nav><router-link v-for="l in links" :key="l.path" :to="l.path" class="nav-link">{{ l.label }}</router-link></nav>
|
||||
<button class="btn btn-sm" style="margin-top:auto" @click="auth.logout()">退出</button>
|
||||
</aside>
|
||||
<main class="main"><router-view /></main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
if (!auth.isLoggedIn) router.push('/login')
|
||||
const links = [
|
||||
{ path: '/admin/dashboard', label: '仪表盘' },
|
||||
{ path: '/admin/users', label: '用户管理' },
|
||||
{ path: '/admin/consultants', label: '咨询师管理' },
|
||||
{ path: '/admin/appointments', label: '预约管理' },
|
||||
{ path: '/admin/branches', label: '网点管理' },
|
||||
]
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.admin-layout { display: flex; min-height: 100vh; }
|
||||
.sidebar { width: 220px; background: #1e293b; color: #fff; padding: 1.5rem; display: flex; flex-direction: column; }
|
||||
.sidebar h2 { font-size: 1.125rem; margin-bottom: 1.5rem; }
|
||||
.nav-link { display: block; padding: 0.5rem 0.75rem; color: #cbd5e1; text-decoration: none; border-radius: 0.25rem; margin-bottom: 0.25rem; }
|
||||
.nav-link:hover, .nav-link.router-link-active { background: #334155; color: #fff; }
|
||||
.main { flex: 1; padding: 2rem; background: #f8fafc; }
|
||||
</style>
|
||||
@@ -1,37 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<header class="header">
|
||||
<div class="container header-inner">
|
||||
<router-link to="/" class="logo">咨询预约平台</router-link>
|
||||
<nav class="nav">
|
||||
<router-link to="/">首页</router-link>
|
||||
<template v-if="auth.isLoggedIn">
|
||||
<router-link to="/user/dashboard">用户中心</router-link>
|
||||
<router-link v-if="auth.isAdmin" to="/admin/dashboard">管理后台</router-link>
|
||||
<span class="user-name">{{ auth.user?.name }}</span>
|
||||
<button class="btn btn-secondary" @click="auth.logout(); router.push('/')">退出</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<router-link to="/login">登录</router-link>
|
||||
<router-link to="/register" class="btn btn-primary">注册</router-link>
|
||||
</template>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.header { background: white; border-bottom: 1px solid var(--gray-200); position: sticky; top: 0; z-index: 100; }
|
||||
.header-inner { display: flex; align-items: center; justify-content: space-between; height: 3.5rem; }
|
||||
.logo { font-size: 1.25rem; font-weight: 700; color: var(--primary); }
|
||||
.nav { display: flex; align-items: center; gap: 1rem; }
|
||||
.user-name { color: var(--gray-600); font-size: 0.875rem; }
|
||||
</style>
|
||||
@@ -1,10 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<AppHeader />
|
||||
<div class="container" style="padding-top:2rem;padding-bottom:2rem"><router-view /></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import AppHeader from './AppHeader.vue'
|
||||
</script>
|
||||
@@ -4,31 +4,6 @@ const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'home', component: () => import('@/views/home/HomePage.vue') },
|
||||
{ path: '/login', name: 'login', component: () => import('@/views/auth/Login.vue') },
|
||||
{ path: '/register', name: 'register', component: () => import('@/views/auth/Register.vue') },
|
||||
{
|
||||
path: '/user',
|
||||
component: () => import('@/components/layout/UserLayout.vue'),
|
||||
children: [
|
||||
{ path: '', redirect: '/user/dashboard' },
|
||||
{ path: 'dashboard', component: () => import('@/views/user/Dashboard.vue') },
|
||||
{ path: 'appointments', component: () => import('@/views/user/MyAppointments.vue') },
|
||||
{ path: 'book', component: () => import('@/views/user/BookAppointment.vue') },
|
||||
{ path: 'profile', component: () => import('@/views/user/Profile.vue') },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/admin',
|
||||
component: () => import('@/components/layout/AdminLayout.vue'),
|
||||
children: [
|
||||
{ path: '', redirect: '/admin/dashboard' },
|
||||
{ path: 'dashboard', component: () => import('@/views/admin/Dashboard.vue') },
|
||||
{ path: 'appointments', component: () => import('@/views/admin/Appointments.vue') },
|
||||
{ path: 'consultants', component: () => import('@/views/admin/Consultants.vue') },
|
||||
{ path: 'users', component: () => import('@/views/admin/Users.vue') },
|
||||
{ path: 'branches', component: () => import('@/views/admin/Branches.vue') },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
|
||||
@@ -1,35 +1,16 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { AuthResponse, User } from '@/types'
|
||||
import http from '@/utils/request'
|
||||
|
||||
/** Auth store shell — wire login/register when ACC is implemented. */
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const token = ref(localStorage.getItem('token') || '')
|
||||
const user = ref<User | null>(JSON.parse(localStorage.getItem('user') || 'null'))
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
const isAdmin = computed(() => user.value?.role === 'ROLE_ADMIN')
|
||||
|
||||
function setAuth(t: string, u: User) {
|
||||
token.value = t; user.value = u
|
||||
localStorage.setItem('token', t); localStorage.setItem('user', JSON.stringify(u))
|
||||
}
|
||||
|
||||
async function login(email: string, password: string) {
|
||||
const r = await http.post<AuthResponse>('/auth/login', { email, password })
|
||||
setAuth(r.data.token, r.data.user)
|
||||
return r.data
|
||||
}
|
||||
|
||||
async function register(email: string, password: string, name: string, phone?: string) {
|
||||
const r = await http.post<AuthResponse>('/auth/register', { email, password, name, phone })
|
||||
setAuth(r.data.token, r.data.user)
|
||||
return r.data
|
||||
}
|
||||
|
||||
function logout() {
|
||||
token.value = ''; user.value = null
|
||||
localStorage.removeItem('token'); localStorage.removeItem('user')
|
||||
token.value = ''
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
}
|
||||
|
||||
return { token, user, isLoggedIn, isAdmin, login, register, logout }
|
||||
return { token, isLoggedIn, logout }
|
||||
})
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
export interface User {
|
||||
id: string; email: string; name: string; phone: string; role: string; status: string
|
||||
/** Shared frontend types — extend when implementing iteration1 features. */
|
||||
|
||||
export interface HealthResponse {
|
||||
status: string
|
||||
}
|
||||
export interface AuthResponse { token: string; user: User }
|
||||
export interface Appointment {
|
||||
id: string; userId: string; consultantId: string; branchId: string;
|
||||
appointmentDate: string; startTime: string; endTime: string;
|
||||
durationMinutes: number; status: string; note: string; cancelReason: string
|
||||
}
|
||||
export interface Consultant {
|
||||
id: string; name: string; title: string; bio: string; specialties: string;
|
||||
avatar: string; branchId: string; status: string; sortOrder: number
|
||||
}
|
||||
export interface Branch {
|
||||
id: string; name: string; address: string; phone: string; status: string
|
||||
}
|
||||
export interface TimeSlot { startTime: string; endTime: string }
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
export function getWeekDates(): string[] {
|
||||
const dates: string[] = []
|
||||
const today = new Date()
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const d = new Date(today); d.setDate(d.getDate() + i)
|
||||
dates.push(d.toISOString().split('T')[0])
|
||||
}
|
||||
return dates
|
||||
}
|
||||
@@ -14,10 +14,7 @@ http.interceptors.request.use(cfg => {
|
||||
|
||||
http.interceptors.response.use(
|
||||
r => r,
|
||||
e => {
|
||||
if (e.response?.status === 401) { localStorage.removeItem('token'); localStorage.removeItem('user'); window.location.href = '/login' }
|
||||
return Promise.reject(e)
|
||||
}
|
||||
e => Promise.reject(e)
|
||||
)
|
||||
|
||||
export default http
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>预约管理</h1>
|
||||
<div v-if="loading">加载中...</div>
|
||||
<table v-else class="table"><thead><tr><th>ID</th><th>咨询师ID</th><th>日期</th><th>时间</th><th>状态</th><th>备注</th></tr></thead>
|
||||
<tbody><tr v-for="a in apps" :key="a.id"><td>{{ a.id.substring(0,8) }}...</td><td>{{ a.consultantId.substring(0,8) }}...</td>
|
||||
<td>{{ a.appointmentDate }}</td><td>{{ a.startTime }}-{{ a.endTime }}</td><td><span class="status" :class="a.status.toLowerCase()">{{ a.status }}</span></td><td>{{ a.note }}</td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import http from '@/utils/request'
|
||||
import type { Appointment } from '@/types'
|
||||
|
||||
const apps = ref<Appointment[]>([]); const loading = ref(true)
|
||||
onMounted(async () => { try { const r = await http.get('/admin/appointments'); apps.value = r.data } finally { loading.value = false } })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1rem; }
|
||||
.table { width: 100%; border-collapse: collapse; }
|
||||
.table th, .table td { text-align: left; padding: 0.75rem; border-bottom: 1px solid var(--gray-200); }
|
||||
.status { display: inline-block; padding: 0.125rem 0.5rem; border-radius: 1rem; font-size: 0.75rem; font-weight: 500; }
|
||||
.pending { background: #FEF3C7; color: #92400E; }
|
||||
.confirmed { background: #DBEAFE; color: #1E40AF; }
|
||||
.completed { background: #D1FAE5; color: #065F46; }
|
||||
.cancelled { background: #FEE2E2; color: #991B1B; }
|
||||
</style>
|
||||
@@ -1,65 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem">
|
||||
<h1>网点管理</h1>
|
||||
<button class="btn btn-primary" @click="showForm = true; editing = null; form = {name:'',address:'',phone:''}">新增网点</button>
|
||||
</div>
|
||||
<div v-if="loading">加载中...</div>
|
||||
<table v-else class="table"><thead><tr><th>名称</th><th>地址</th><th>电话</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody><tr v-for="b in branches" :key="b.id"><td>{{ b.name }}</td><td>{{ b.address }}</td><td>{{ b.phone }}</td>
|
||||
<td :class="b.status === 'ACTIVE' ? 'active' : 'disabled'">{{ b.status }}</td>
|
||||
<td><button class="btn btn-sm btn-secondary" @click="edit(b)">编辑</button><button class="btn btn-sm btn-danger" style="margin-left:0.25rem" @click="doDelete(b.id)">删除</button></td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
<div v-if="showForm" class="modal"><div class="modal-content card">
|
||||
<h3>{{ editing ? '编辑网点' : '新增网点' }}</h3>
|
||||
<div class="form-group"><label>名称</label><input v-model="form.name" class="input" /></div>
|
||||
<div class="form-group"><label>地址</label><input v-model="form.address" class="input" /></div>
|
||||
<div class="form-group"><label>电话</label><input v-model="form.phone" class="input" /></div>
|
||||
<div style="display:flex;gap:0.5rem;margin-top:1rem">
|
||||
<button class="btn btn-primary" @click="save" :disabled="saving">{{ saving ? '保存中...' : '保存' }}</button>
|
||||
<button class="btn btn-secondary" @click="showForm = false">取消</button>
|
||||
</div>
|
||||
</div></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import http from '@/utils/request'
|
||||
import type { Branch } from '@/types'
|
||||
|
||||
const branches = ref<Branch[]>([]); const loading = ref(true)
|
||||
const showForm = ref(false); const editing = ref<string | null>(null); const saving = ref(false)
|
||||
const form = ref({ name: '', address: '', phone: '' })
|
||||
|
||||
function edit(b: Branch) { editing.value = b.id; form.value = { name: b.name, address: b.address, phone: b.phone }; showForm.value = true }
|
||||
|
||||
async function save() {
|
||||
saving.value = true
|
||||
try {
|
||||
if (editing.value) { await http.put(`/admin/branches/${editing.value}`, form.value) }
|
||||
else { await http.post('/admin/branches', form.value) }
|
||||
showForm.value = false; await fetch()
|
||||
} catch (e: any) { alert(e.response?.data?.errorMessage || '操作失败') }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function doDelete(id: string) {
|
||||
if (!confirm('确定删除?')) return; await http.delete(`/admin/branches/${id}`); await fetch()
|
||||
}
|
||||
|
||||
async function fetch() { loading.value = true; try { const r = await http.get('/admin/branches'); branches.value = r.data } finally { loading.value = false } }
|
||||
onMounted(fetch)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin: 0; }
|
||||
.table { width: 100%; border-collapse: collapse; }
|
||||
.table th, .table td { text-align: left; padding: 0.75rem; border-bottom: 1px solid var(--gray-200); }
|
||||
.active { color: #16a34a; font-weight: 500; }
|
||||
.disabled { color: #dc2626; font-weight: 500; }
|
||||
.modal { position: fixed; inset: 0; background: rgba(0,0,0,0.4); display: flex; align-items: center; justify-content: center; z-index: 100; }
|
||||
.modal-content { width: 100%; max-width: 480px; }
|
||||
.btn-sm { padding: 0.25rem 0.75rem; font-size: 0.8125rem; }
|
||||
</style>
|
||||
@@ -1,29 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>咨询师管理</h1>
|
||||
<div v-if="loading">加载中...</div>
|
||||
<table v-else class="table"><thead><tr><th>姓名</th><th>职称</th><th>专长</th><th>网点ID</th><th>状态</th><th>排序</th></tr></thead>
|
||||
<tbody><tr v-for="c in consultants" :key="c.id"><td>{{ c.name }}</td><td>{{ c.title }}</td>
|
||||
<td>{{ c.specialties }}</td><td>{{ c.branchId ? c.branchId.substring(0,8)+'...' : '-' }}</td>
|
||||
<td :class="c.status === 'ACTIVE' ? 'active' : 'disabled'">{{ c.status }}</td><td>{{ c.sortOrder }}</td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import http from '@/utils/request'
|
||||
import type { Consultant } from '@/types'
|
||||
|
||||
const consultants = ref<Consultant[]>([]); const loading = ref(true)
|
||||
onMounted(async () => { try { const r = await http.get('/admin/consultants'); consultants.value = r.data } finally { loading.value = false } })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1rem; }
|
||||
.table { width: 100%; border-collapse: collapse; }
|
||||
.table th, .table td { text-align: left; padding: 0.75rem; border-bottom: 1px solid var(--gray-200); }
|
||||
.active { color: #16a34a; font-weight: 500; }
|
||||
.disabled { color: #dc2626; font-weight: 500; }
|
||||
</style>
|
||||
@@ -1,28 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>管理仪表盘</h1>
|
||||
<div class="stats-grid">
|
||||
<div class="card stat-card"><h3>{{ stats.totalUsers }}</h3><p>用户数</p></div>
|
||||
<div class="card stat-card"><h3>{{ stats.totalConsultants }}</h3><p>咨询师</p></div>
|
||||
<div class="card stat-card"><h3>{{ stats.totalAppointments }}</h3><p>总预约</p></div>
|
||||
<div class="card stat-card"><h3>{{ stats.pendingAppointments }}</h3><p>待确认</p></div>
|
||||
<div class="card stat-card"><h3>{{ stats.totalBranches }}</h3><p>网点</p></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import http from '@/utils/request'
|
||||
|
||||
const stats = ref<any>({})
|
||||
onMounted(async () => { const r = await http.get('/admin/dashboard'); stats.value = r.data })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1.5rem; }
|
||||
.stats-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 1rem; }
|
||||
.stat-card { text-align: center; }
|
||||
.stat-card h3 { font-size: 2rem; color: var(--primary); }
|
||||
.stat-card p { color: var(--gray-500); }
|
||||
</style>
|
||||
@@ -1,32 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>用户管理</h1>
|
||||
<div v-if="loading">加载中...</div>
|
||||
<table v-else class="table"><thead><tr><th>邮箱</th><th>姓名</th><th>手机</th><th>角色</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody><tr v-for="u in users" :key="u.id"><td>{{ u.email }}</td><td>{{ u.name }}</td><td>{{ u.phone }}</td>
|
||||
<td>{{ u.role }}</td><td :class="u.status === 'ACTIVE' ? 'active' : 'disabled'">{{ u.status }}</td>
|
||||
<td><button class="btn btn-sm" :class="u.status === 'ACTIVE' ? 'btn-danger' : 'btn-primary'" @click="toggle(u.id)">{{ u.status === 'ACTIVE' ? '禁用' : '启用' }}</button></td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import http from '@/utils/request'
|
||||
import type { User } from '@/types'
|
||||
|
||||
const users = ref<User[]>([]); const loading = ref(true)
|
||||
async function toggle(id: string) { await http.put(`/admin/users/${id}/toggle-status`); await fetch() }
|
||||
async function fetch() { loading.value = true; try { const r = await http.get('/admin/users'); users.value = r.data } finally { loading.value = false } }
|
||||
onMounted(fetch)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1rem; }
|
||||
.table { width: 100%; border-collapse: collapse; }
|
||||
.table th, .table td { text-align: left; padding: 0.75rem; border-bottom: 1px solid var(--gray-200); }
|
||||
.active { color: #16a34a; font-weight: 500; }
|
||||
.disabled { color: #dc2626; font-weight: 500; }
|
||||
.btn-sm { padding: 0.25rem 0.75rem; font-size: 0.8125rem; }
|
||||
</style>
|
||||
@@ -1,46 +0,0 @@
|
||||
<template>
|
||||
<div class="auth-page">
|
||||
<div class="card auth-card">
|
||||
<h2>登录</h2>
|
||||
<form @submit.prevent="handleLogin">
|
||||
<div class="form-group"><label>邮箱</label><input v-model="email" type="email" class="input" required placeholder="请输入邮箱" /></div>
|
||||
<div class="form-group"><label>密码</label><input v-model="password" type="password" class="input" required placeholder="请输入密码" /></div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<button type="submit" class="btn btn-primary" style="width:100%" :disabled="loading">{{ loading ? '登录中...' : '登录' }}</button>
|
||||
</form>
|
||||
<p class="switch">还没有账号?<router-link to="/register">立即注册</router-link></p>
|
||||
<router-link to="/" class="back-link">← 返回首页</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const error = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
async function handleLogin() {
|
||||
error.value = ''; loading.value = true
|
||||
try {
|
||||
await auth.login(email.value, password.value)
|
||||
router.push(auth.isAdmin ? '/admin/dashboard' : '/user/dashboard')
|
||||
} catch (e: any) { error.value = e.response?.data?.errorMessage || '登录失败' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.auth-page { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: var(--gray-50); }
|
||||
.auth-card { width: 100%; max-width: 400px; }
|
||||
.auth-card h2 { text-align: center; margin-bottom: 1.5rem; }
|
||||
.error { color: var(--danger); font-size: 0.875rem; margin-bottom: 0.5rem; }
|
||||
.switch { text-align: center; margin-top: 1rem; font-size: 0.875rem; color: var(--gray-500); }
|
||||
.back-link { display: block; text-align: center; margin-top: 0.5rem; font-size: 0.875rem; }
|
||||
</style>
|
||||
@@ -1,44 +0,0 @@
|
||||
<template>
|
||||
<div class="auth-page">
|
||||
<div class="card auth-card">
|
||||
<h2>注册</h2>
|
||||
<form @submit.prevent="handleRegister">
|
||||
<div class="form-group"><label>姓名</label><input v-model="name" class="input" required placeholder="请输入姓名" /></div>
|
||||
<div class="form-group"><label>邮箱</label><input v-model="email" type="email" class="input" required placeholder="请输入邮箱" /></div>
|
||||
<div class="form-group"><label>手机号</label><input v-model="phone" class="input" placeholder="选填" /></div>
|
||||
<div class="form-group"><label>密码(至少8位)</label><input v-model="password" type="password" class="input" required minlength="8" placeholder="请输入密码" /></div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<button type="submit" class="btn btn-primary" style="width:100%" :disabled="loading">{{ loading ? '注册中...' : '注册' }}</button>
|
||||
</form>
|
||||
<p class="switch">已有账号?<router-link to="/login">立即登录</router-link></p>
|
||||
<router-link to="/" class="back-link">← 返回首页</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
const name = ref(''); const email = ref(''); const phone = ref(''); const password = ref('')
|
||||
const error = ref(''); const loading = ref(false)
|
||||
|
||||
async function handleRegister() {
|
||||
error.value = ''; loading.value = true
|
||||
try { await auth.register(email.value, password.value, name.value, phone.value); router.push('/user/dashboard') }
|
||||
catch (e: any) { error.value = e.response?.data?.errorMessage || '注册失败' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.auth-page { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: var(--gray-50); }
|
||||
.auth-card { width: 100%; max-width: 400px; }
|
||||
.auth-card h2 { text-align: center; margin-bottom: 1.5rem; }
|
||||
.error { color: var(--danger); font-size: 0.875rem; }
|
||||
.switch { text-align: center; margin-top: 1rem; font-size: 0.875rem; color: var(--gray-500); }
|
||||
.back-link { display: block; text-align: center; margin-top: 0.5rem; font-size: 0.875rem; }
|
||||
</style>
|
||||
@@ -1,39 +1,25 @@
|
||||
<template>
|
||||
<div>
|
||||
<AppHeader />
|
||||
<section class="hero">
|
||||
<div class="container hero-content">
|
||||
<h1>{{ info.title }}</h1>
|
||||
<p>{{ info.description }}</p>
|
||||
<div class="hero-actions">
|
||||
<router-link v-if="!auth.isLoggedIn" to="/register" class="btn btn-primary btn-lg">免费注册</router-link>
|
||||
<router-link to="/user/book" class="btn btn-secondary btn-lg">立即预约</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<footer class="footer"><div class="container"><p>© 2026 咨询预约平台</p></div></footer>
|
||||
</div>
|
||||
<main class="shell">
|
||||
<h1>咨询预约平台</h1>
|
||||
<p class="lead">工程骨架已就绪。业务实现待按 iteration1 规格落地。</p>
|
||||
<ul>
|
||||
<li>需求规格:<code>docs/features/iteration1/</code></li>
|
||||
<li>交互原型:<code>docs/features/iteration1/prototypes/</code>(端口 5174)</li>
|
||||
<li>健康检查:<code>GET /api/v1/health</code></li>
|
||||
</ul>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import AppHeader from '@/components/layout/AppHeader.vue'
|
||||
import http from '@/utils/request'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const info = ref({ title: '', description: '' })
|
||||
onMounted(async () => {
|
||||
try { const r = await http.get('/home/info'); info.value = r.data } catch {}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hero { background: linear-gradient(135deg, var(--primary), var(--primary-light)); color: white; padding: 4rem 0; }
|
||||
.hero-content { text-align: center; }
|
||||
.hero h1 { font-size: 2.5rem; margin-bottom: 1rem; }
|
||||
.hero p { font-size: 1.125rem; opacity: 0.9; max-width: 600px; margin: 0 auto 2rem; }
|
||||
.hero-actions { display: flex; gap: 1rem; justify-content: center; }
|
||||
.btn-lg { padding: 0.75rem 2rem; font-size: 1rem; }
|
||||
.footer { background: var(--gray-800); color: var(--gray-400); padding: 2rem 0; text-align: center; }
|
||||
.shell {
|
||||
max-width: 40rem;
|
||||
margin: 4rem auto;
|
||||
padding: 0 1.5rem;
|
||||
font-family: system-ui, sans-serif;
|
||||
line-height: 1.6;
|
||||
}
|
||||
h1 { font-size: 1.75rem; margin-bottom: 0.5rem; }
|
||||
.lead { color: #555; margin-bottom: 1.5rem; }
|
||||
ul { padding-left: 1.25rem; }
|
||||
code { font-size: 0.9em; background: #f3f4f6; padding: 0.1em 0.35em; border-radius: 4px; }
|
||||
</style>
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>预约咨询</h1>
|
||||
<div class="booking-steps">
|
||||
<div class="card step">
|
||||
<h3>1. 选择咨询师</h3>
|
||||
<div class="consultant-list">
|
||||
<div v-for="c in consultants" :key="c.id" class="consultant-option"
|
||||
:class="{ selected: selectedConsultant === c.id }" @click="pickConsultant(c.id)">
|
||||
<strong>{{ c.name }}</strong> <p>{{ c.title }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="selectedConsultant" class="card step">
|
||||
<h3>2. 选择日期</h3>
|
||||
<div class="date-list">
|
||||
<button v-for="d in dates" :key="d" class="btn"
|
||||
:class="selectedDate === d ? 'btn-primary' : 'btn-secondary'" @click="pickDate(d)">{{ d }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="selectedDate && slots.length" class="card step">
|
||||
<h3>3. 选择时间</h3>
|
||||
<div class="slot-list">
|
||||
<button v-for="s in slots" :key="s.startTime" class="btn"
|
||||
:class="selectedSlot === s.startTime ? 'btn-primary' : 'btn-secondary'"
|
||||
@click="selectedSlot = s.startTime">{{ s.startTime }}-{{ s.endTime }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="selectedSlot" class="card step">
|
||||
<h3>4. 备注</h3>
|
||||
<textarea v-model="note" class="input" rows="3" placeholder="描述您的问题..."></textarea>
|
||||
<button class="btn btn-primary" style="margin-top:1rem" @click="submit" :disabled="submitting">
|
||||
{{ submitting ? '提交中...' : '确认预约' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import http from '@/utils/request'
|
||||
import { getWeekDates } from '@/utils/date'
|
||||
import type { Consultant, TimeSlot } from '@/types'
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
if (!auth.isLoggedIn) router.push('/login')
|
||||
|
||||
const consultants = ref<Consultant[]>([])
|
||||
const selectedConsultant = ref('')
|
||||
const selectedDate = ref('')
|
||||
const selectedSlot = ref('')
|
||||
const note = ref('')
|
||||
const slots = ref<TimeSlot[]>([])
|
||||
const dates = getWeekDates()
|
||||
const submitting = ref(false)
|
||||
|
||||
onMounted(async () => { const r = await http.get('/consultants'); consultants.value = r.data })
|
||||
|
||||
watch(selectedConsultant, () => { selectedDate.value = ''; selectedSlot.value = ''; slots.value = [] })
|
||||
watch(selectedDate, async (d) => {
|
||||
if (!d) return; selectedSlot.value = ''
|
||||
const r = await http.get(`/consultants/${selectedConsultant.value}/slots`, { params: { date: d } }); slots.value = r.data
|
||||
})
|
||||
|
||||
function pickConsultant(id: string) { selectedConsultant.value = id }
|
||||
function pickDate(d: string) { selectedDate.value = d }
|
||||
|
||||
async function submit() {
|
||||
submitting.value = true
|
||||
try {
|
||||
await http.post('/appointments', {
|
||||
consultantId: selectedConsultant.value, date: selectedDate.value,
|
||||
startTime: selectedSlot.value,
|
||||
endTime: `${String(Number(selectedSlot.value.split(':')[0]) + 1).padStart(2, '0')}:00`,
|
||||
note: note.value,
|
||||
})
|
||||
router.push('/user/appointments')
|
||||
} catch (e: any) { alert(e.response?.data?.errorMessage || '预约失败') }
|
||||
finally { submitting.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1.5rem; }
|
||||
.booking-steps { display: flex; flex-direction: column; gap: 1rem; max-width: 600px; }
|
||||
.step h3 { margin-bottom: 0.75rem; }
|
||||
.consultant-list { display: flex; flex-direction: column; gap: 0.5rem; }
|
||||
.consultant-option { padding: 0.75rem; border: 1px solid var(--gray-200); border-radius: 0.375rem; cursor: pointer; }
|
||||
.consultant-option:hover { border-color: var(--primary); }
|
||||
.consultant-option.selected { border-color: var(--primary); background: rgba(79,70,229,0.05); }
|
||||
.date-list, .slot-list { display: flex; flex-wrap: wrap; gap: 0.5rem; }
|
||||
</style>
|
||||
@@ -1,41 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>用户中心</h1>
|
||||
<div class="stats-grid">
|
||||
<div class="card stat-card"><h3>{{ total }}</h3><p>总预约</p></div>
|
||||
<div class="card stat-card"><h3>{{ pending }}</h3><p>待确认</p></div>
|
||||
<div class="card stat-card"><h3>{{ completed }}</h3><p>已完成</p></div>
|
||||
</div>
|
||||
<div class="actions" style="margin-top:1rem">
|
||||
<router-link to="/user/book" class="btn btn-primary">预约咨询</router-link>
|
||||
<router-link to="/user/appointments" class="btn btn-secondary" style="margin-left:0.5rem">我的预约</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
import http from '@/utils/request'
|
||||
import type { Appointment } from '@/types'
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
if (!auth.isLoggedIn) router.push('/login')
|
||||
|
||||
const appointments = ref<Appointment[]>([])
|
||||
const total = computed(() => appointments.value.length)
|
||||
const pending = computed(() => appointments.value.filter(a => a.status === 'PENDING').length)
|
||||
const completed = computed(() => appointments.value.filter(a => a.status === 'COMPLETED').length)
|
||||
|
||||
onMounted(async () => { const r = await http.get('/appointments'); appointments.value = r.data })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1.5rem; }
|
||||
.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; }
|
||||
.stat-card { text-align: center; }
|
||||
.stat-card h3 { font-size: 2rem; color: var(--primary); }
|
||||
.stat-card p { color: var(--gray-500); font-size: 0.875rem; }
|
||||
</style>
|
||||
@@ -1,69 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>我的预约</h1>
|
||||
<div v-if="loading">加载中...</div>
|
||||
<div v-else-if="appointments.length === 0" class="empty"><p>暂无预约记录</p><router-link to="/user/book" class="btn btn-primary">预约咨询</router-link></div>
|
||||
<div v-else class="appointment-list">
|
||||
<div v-for="a in appointments" :key="a.id" class="card appointment-card">
|
||||
<div>
|
||||
<span class="status" :class="a.status.toLowerCase()">{{ label(a.status) }}</span>
|
||||
<p class="date">{{ a.appointmentDate }} {{ a.startTime }}-{{ a.endTime }}</p>
|
||||
<p class="meta">咨询师ID: {{ a.consultantId.substring(0,8) }}... | 时长: {{ a.durationMinutes }}分钟</p>
|
||||
<p v-if="a.note" class="note">备注: {{ a.note }}</p>
|
||||
<p v-if="a.cancelReason" class="cancel">取消原因: {{ a.cancelReason }}</p>
|
||||
</div>
|
||||
<button v-if="a.status === 'PENDING' || a.status === 'CONFIRMED'" class="btn btn-danger btn-sm" @click="doCancel(a.id)">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
import http from '@/utils/request'
|
||||
import type { Appointment } from '@/types'
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
if (!auth.isLoggedIn) router.push('/login')
|
||||
|
||||
const appointments = ref<Appointment[]>([])
|
||||
const loading = ref(true)
|
||||
|
||||
function label(s: string) {
|
||||
const m: Record<string, string> = { PENDING: '待确认', CONFIRMED: '已确认', COMPLETED: '已完成', CANCELLED: '已取消' }
|
||||
return m[s] || s
|
||||
}
|
||||
|
||||
async function doCancel(id: string) {
|
||||
if (!confirm('确定取消?')) return
|
||||
await http.put(`/appointments/${id}/cancel`, { reason: '用户取消' })
|
||||
await fetch()
|
||||
}
|
||||
|
||||
async function fetch() {
|
||||
loading.value = true
|
||||
try { const r = await http.get('/appointments'); appointments.value = r.data } finally { loading.value = false }
|
||||
}
|
||||
|
||||
onMounted(fetch)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1.5rem; }
|
||||
.empty { text-align: center; padding: 3rem; color: var(--gray-500); }
|
||||
.appointment-list { display: flex; flex-direction: column; gap: 1rem; }
|
||||
.appointment-card { display: flex; justify-content: space-between; align-items: flex-start; }
|
||||
.status { display: inline-block; padding: 0.125rem 0.5rem; border-radius: 1rem; font-size: 0.75rem; font-weight: 500; margin-bottom: 0.5rem; }
|
||||
.pending { background: #FEF3C7; color: #92400E; }
|
||||
.confirmed { background: #DBEAFE; color: #1E40AF; }
|
||||
.completed { background: #D1FAE5; color: #065F46; }
|
||||
.cancelled { background: #FEE2E2; color: #991B1B; }
|
||||
.date { font-weight: 600; }
|
||||
.meta { font-size: 0.875rem; color: var(--gray-500); }
|
||||
.note { font-size: 0.875rem; color: var(--gray-600); }
|
||||
.cancel { font-size: 0.875rem; color: var(--danger); }
|
||||
.btn-sm { padding: 0.375rem 0.75rem; font-size: 0.8125rem; }
|
||||
</style>
|
||||
@@ -1,56 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1>个人信息</h1>
|
||||
<div class="card" style="max-width:500px">
|
||||
<div class="form-group"><label>邮箱</label><input :value="auth.user?.email" class="input" disabled /></div>
|
||||
<div class="form-group"><label>姓名</label><input v-model="name" class="input" /></div>
|
||||
<div class="form-group"><label>手机号</label><input v-model="phone" class="input" /></div>
|
||||
<p v-if="err" class="error">{{ err }}</p>
|
||||
<button class="btn btn-primary" @click="save" :disabled="saving">{{ saving ? '保存中...' : '保存' }}</button>
|
||||
</div>
|
||||
<h2 style="margin-top:2rem">修改密码</h2>
|
||||
<div class="card" style="max-width:500px">
|
||||
<div class="form-group"><label>原密码</label><input v-model="oldPw" type="password" class="input" /></div>
|
||||
<div class="form-group"><label>新密码</label><input v-model="newPw" type="password" class="input" minlength="8" /></div>
|
||||
<p v-if="pwErr" class="error">{{ pwErr }}</p>
|
||||
<button class="btn btn-primary" @click="changePw" :disabled="changing">{{ changing ? '修改中...' : '修改密码' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
import http from '@/utils/request'
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
if (!auth.isLoggedIn) router.push('/login')
|
||||
|
||||
const name = ref(auth.user?.name || '')
|
||||
const phone = ref(auth.user?.phone || '')
|
||||
const err = ref(''); const saving = ref(false)
|
||||
const oldPw = ref(''); const newPw = ref(''); const pwErr = ref(''); const changing = ref(false)
|
||||
|
||||
async function save() {
|
||||
saving.value = true; err.value = ''
|
||||
try { const r = await http.put('/users/me', { name: name.value, phone: phone.value }); auth.user = r.data; localStorage.setItem('user', JSON.stringify(r.data)); alert('保存成功') }
|
||||
catch (e: any) { err.value = e.response?.data?.errorMessage || '保存失败' }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function changePw() {
|
||||
if (newPw.value.length < 8) { pwErr.value = '密码至少8位'; return }
|
||||
changing.value = true; pwErr.value = ''
|
||||
try { await http.put('/users/me/password', { oldPassword: oldPw.value, newPassword: newPw.value }); alert('密码修改成功'); oldPw.value = ''; newPw.value = '' }
|
||||
catch (e: any) { pwErr.value = e.response?.data?.errorMessage || '修改失败' }
|
||||
finally { changing.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin-bottom: 1.5rem; } h2 { margin-bottom: 1rem; }
|
||||
.card { margin-bottom: 1rem; }
|
||||
.error { color: var(--danger); font-size: 0.875rem; margin-bottom: 0.5rem; }
|
||||
</style>
|
||||
Reference in New Issue
Block a user