功能:更新消息中心和 YumiNail 模块

This commit is contained in:
xiaowang
2026-05-13 12:43:01 +08:00
parent 6b9eba5aca
commit 2074addc40
284 changed files with 21031 additions and 4533 deletions
+137
View File
@@ -0,0 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.xiaowang</groupId>
<artifactId>YumiNail-Calendar-Core</artifactId>
<version>1.0.0</version>
<name>YumiNail-Calendar-Core</name>
<description>Independent appointment calendar backend for nail artists.</description>
<properties>
<java.version>17</java.version>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
<druid.version>1.2.23</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>YumiNail-Calendar-Core</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,12 @@
package com.xiaowang.yuminailcalendarcore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YumiNailCalendarCoreApplication {
public static void main(String[] args) {
SpringApplication.run(YumiNailCalendarCoreApplication.class, args);
}
}
@@ -0,0 +1,8 @@
package com.xiaowang.yuminailcalendarcore.common;
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
}
@@ -0,0 +1,64 @@
package com.xiaowang.yuminailcalendarcore.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ConflictException.class)
public Result<Void> handleConflictException(ConflictException e) {
return Result.error(409, e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(BindException.class)
public Result<Void> handleBindException(BindException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(ConstraintViolationException.class)
public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream()
.map(violation -> violation.getMessage())
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(IllegalArgumentException.class)
public Result<Void> handleIllegalArgumentException(IllegalArgumentException e) {
return Result.error(e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public Result<Void> handleRuntimeException(RuntimeException e) {
log.error("业务异常", e);
return Result.error(e.getMessage());
}
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
log.error("系统异常", e);
return Result.error("系统繁忙,请稍后重试");
}
}
@@ -0,0 +1,33 @@
package com.xiaowang.yuminailcalendarcore.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
private Integer code;
private String message;
private T data;
public static <T> Result<T> success() {
return new Result<>(200, "操作成功", null);
}
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
public static <T> Result<T> error(String message) {
return new Result<>(500, message, null);
}
public static <T> Result<T> error(Integer code, String message) {
return new Result<>(code, message, null);
}
}
@@ -0,0 +1,18 @@
package com.xiaowang.yuminailcalendarcore.config;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
return builder -> {
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
};
}
}
@@ -0,0 +1,22 @@
package com.xiaowang.yuminailcalendarcore.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.xiaowang.yuminailcalendarcore.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}
@@ -0,0 +1,22 @@
package com.xiaowang.yuminailcalendarcore.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
@@ -0,0 +1,123 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/appointment")
public class AppointmentController {
private final AppointmentService appointmentService;
@GetMapping("/day")
public Result<List<AppointmentVO>> getAppointmentsByDay(@RequestParam("date")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate date,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "sortBy", required = false) String sortBy) {
return Result.success(appointmentService.getAppointmentsByDay(date, keyword, sortBy));
}
@GetMapping("/list")
public Result<List<AppointmentVO>> searchAppointments(@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate,
@RequestParam(value = "customerId", required = false) Long customerId,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "serviceName", required = false) String serviceName,
@RequestParam(value = "status", required = false) String status,
@RequestParam(value = "sortBy", required = false) String sortBy) {
return Result.success(appointmentService.searchAppointments(startDate, endDate, customerId, keyword, serviceName, status, sortBy));
}
@GetMapping("/month-overview")
public Result<List<CalendarDaySummaryVO>> getMonthOverview(@RequestParam("month") String month) {
return Result.success(appointmentService.getMonthSummary(YearMonth.parse(month)));
}
@GetMapping("/dashboard")
public Result<AppointmentDashboardVO> getDashboard(@RequestParam(value = "date", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate date) {
return Result.success(appointmentService.getDashboard(date));
}
@GetMapping("/{id}")
public Result<AppointmentVO> getAppointment(@PathVariable("id") Long id) {
return Result.success(appointmentService.getAppointment(id));
}
@PostMapping
public Result<List<AppointmentVO>> createAppointment(@Valid @RequestBody AppointmentSaveRequest request) {
return Result.success(appointmentService.createAppointment(request));
}
@PutMapping("/{id}")
public Result<List<AppointmentVO>> updateAppointment(@PathVariable("id") Long id,
@Valid @RequestBody AppointmentSaveRequest request) {
return Result.success(appointmentService.updateAppointment(id, request));
}
@DeleteMapping("/{id}")
public Result<Void> deleteAppointment(@PathVariable("id") Long id,
@RequestParam(value = "deleteSeries", defaultValue = "false") boolean deleteSeries) {
appointmentService.deleteAppointment(id, deleteSeries);
return Result.success();
}
@PostMapping("/batch-delete")
public Result<Void> batchDelete(@Valid @RequestBody AppointmentBatchDeleteRequest request) {
appointmentService.batchDelete(request);
return Result.success();
}
@PatchMapping("/{id}/status")
public Result<AppointmentVO> updateStatus(@PathVariable("id") Long id,
@Valid @RequestBody AppointmentStatusUpdateRequest request) {
return Result.success(appointmentService.updateStatus(id, request));
}
@GetMapping("/export")
public Result<AppointmentExportVO> exportAppointments(@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate) {
return Result.success(appointmentService.exportAppointments(startDate, endDate));
}
@PostMapping("/import")
public Result<List<AppointmentVO>> importAppointments(@Valid @RequestBody AppointmentImportRequest request) {
return Result.success(appointmentService.importAppointments(request));
}
}
@@ -0,0 +1,59 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.BackupImportRequest;
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
import com.xiaowang.yuminailcalendarcore.service.CustomerService;
import com.xiaowang.yuminailcalendarcore.service.ServiceOrderService;
import com.xiaowang.yuminailcalendarcore.vo.BackupExportVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Collections;
@RestController
@RequiredArgsConstructor
@RequestMapping("/backup")
public class BackupController {
private final AppointmentService appointmentService;
private final CustomerService customerService;
private final ServiceOrderService serviceOrderService;
@GetMapping("/export")
public Result<BackupExportVO> exportAll() {
BackupExportVO exportVO = new BackupExportVO();
exportVO.setExportedAt(LocalDateTime.now());
exportVO.setCustomers(customerService.searchCustomers(null, null));
exportVO.setAppointments(appointmentService.searchAppointments(null, null, null, null, null, null, "time"));
exportVO.setOrders(serviceOrderService.searchOrders(null, null, null, null, null, null));
exportVO.setCustomerCount(exportVO.getCustomers().size());
exportVO.setAppointmentCount(exportVO.getAppointments().size());
exportVO.setOrderCount(exportVO.getOrders().size());
exportVO.setSettings(Collections.emptyMap());
return Result.success(exportVO);
}
@PostMapping("/import")
public Result<Void> importAll(@Valid @RequestBody BackupImportRequest request) {
if (request.getCustomers() != null && !request.getCustomers().isEmpty()) {
customerService.importCustomers(request.getCustomers());
}
if (request.getAppointments() != null && !request.getAppointments().isEmpty()) {
AppointmentImportRequest appointmentImportRequest = new AppointmentImportRequest();
appointmentImportRequest.setAppointments(request.getAppointments());
appointmentService.importAppointments(appointmentImportRequest);
}
if (request.getOrders() != null && !request.getOrders().isEmpty()) {
serviceOrderService.importOrders(request.getOrders());
}
return Result.success();
}
}
@@ -0,0 +1,55 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.CustomerSaveRequest;
import com.xiaowang.yuminailcalendarcore.service.CustomerService;
import com.xiaowang.yuminailcalendarcore.vo.CustomerVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
@GetMapping("/list")
public Result<List<CustomerVO>> searchCustomers(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "tag", required = false) String tag) {
return Result.success(customerService.searchCustomers(keyword, tag));
}
@GetMapping("/{id}")
public Result<CustomerVO> getCustomer(@PathVariable("id") Long id) {
return Result.success(customerService.getCustomer(id));
}
@PostMapping
public Result<CustomerVO> createCustomer(@Valid @RequestBody CustomerSaveRequest request) {
return Result.success(customerService.createCustomer(request));
}
@PutMapping("/{id}")
public Result<CustomerVO> updateCustomer(@PathVariable("id") Long id,
@Valid @RequestBody CustomerSaveRequest request) {
return Result.success(customerService.updateCustomer(id, request));
}
@DeleteMapping("/{id}")
public Result<Void> deleteCustomer(@PathVariable("id") Long id) {
customerService.deleteCustomer(id);
return Result.success();
}
}
@@ -0,0 +1,16 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/health")
public class HealthController {
@GetMapping("/check")
public Result<String> check() {
return Result.success("YumiNail-Calendar-Core is running");
}
}
@@ -0,0 +1,65 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.OrderSaveRequest;
import com.xiaowang.yuminailcalendarcore.service.ServiceOrderService;
import com.xiaowang.yuminailcalendarcore.vo.ServiceOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/order")
public class OrderController {
private final ServiceOrderService serviceOrderService;
@GetMapping("/list")
public Result<List<ServiceOrderVO>> searchOrders(@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate,
@RequestParam(value = "customerId", required = false) Long customerId,
@RequestParam(value = "appointmentId", required = false) Long appointmentId,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "paymentStatus", required = false) String paymentStatus) {
return Result.success(serviceOrderService.searchOrders(startDate, endDate, customerId, appointmentId, keyword, paymentStatus));
}
@GetMapping("/{id}")
public Result<ServiceOrderVO> getOrder(@PathVariable("id") Long id) {
return Result.success(serviceOrderService.getOrder(id));
}
@PostMapping
public Result<ServiceOrderVO> createOrder(@Valid @RequestBody OrderSaveRequest request) {
return Result.success(serviceOrderService.createOrder(request));
}
@PutMapping("/{id}")
public Result<ServiceOrderVO> updateOrder(@PathVariable("id") Long id,
@Valid @RequestBody OrderSaveRequest request) {
return Result.success(serviceOrderService.updateOrder(id, request));
}
@DeleteMapping("/{id}")
public Result<Void> deleteOrder(@PathVariable("id") Long id) {
serviceOrderService.deleteOrder(id);
return Result.success();
}
}
@@ -0,0 +1,15 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Data
public class AppointmentBatchDeleteRequest {
@NotEmpty(message = "请选择要删除的预约")
private List<Long> ids;
private Boolean deleteSeries;
}
@@ -0,0 +1,15 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Data
public class AppointmentImportRequest {
@Valid
@NotEmpty(message = "导入内容不能为空")
private List<AppointmentSaveRequest> appointments;
}
@@ -0,0 +1,69 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
public class AppointmentSaveRequest {
private Long id;
private Long seriesId;
private Long customerId;
private Long orderId;
@NotBlank(message = "客户姓名不能为空")
@Size(max = 50, message = "客户姓名长度不能超过50个字符")
private String customerName;
@Pattern(regexp = "^$|^[0-9+\\-() ]{6,20}$", message = "联系电话格式不正确")
private String customerPhone;
@NotNull(message = "预约开始时间不能为空")
private LocalDateTime appointmentStartTime;
@NotNull(message = "预约结束时间不能为空")
private LocalDateTime appointmentEndTime;
@NotBlank(message = "服务项目不能为空")
@Size(max = 100, message = "服务项目长度不能超过100个字符")
private String serviceName;
@NotBlank(message = "预约类型不能为空")
@Size(max = 32, message = "预约类型长度不能超过32个字符")
private String appointmentType;
@Size(max = 64, message = "订单号长度不能超过64个字符")
private String orderReference;
@Size(max = 500, message = "备注长度不能超过500个字符")
private String notes;
@Min(value = 0, message = "提醒时间不能小于0分钟")
@Max(value = 10080, message = "提醒时间不能超过7天")
private Integer reminderMinutes;
@Size(max = 32, message = "重复类型长度不能超过32个字符")
private String repeatType;
private LocalDate repeatUntil;
@Size(max = 32, message = "预约状态长度不能超过32个字符")
private String status;
private Boolean notificationEnabled;
private Boolean applyToSeries;
private LocalDateTime expectedUpdateTime;
}
@@ -0,0 +1,17 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
@Data
public class AppointmentStatusUpdateRequest {
@NotBlank(message = "预约状态不能为空")
@Size(max = 32, message = "预约状态长度不能超过32个字符")
private String status;
private LocalDateTime expectedUpdateTime;
}
@@ -0,0 +1,22 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
@Data
public class BackupImportRequest {
@Valid
private List<CustomerSaveRequest> customers;
@Valid
private List<OrderSaveRequest> orders;
@Valid
private List<AppointmentSaveRequest> appointments;
private Map<String, Object> settings;
}
@@ -0,0 +1,33 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
@Data
public class CustomerSaveRequest {
private Long id;
@Size(max = 50, message = "客户姓名长度不能超过50个字符")
private String name;
@Pattern(regexp = "^$|^[0-9+\\-() ]{6,20}$", message = "联系电话格式不正确")
private String phone;
@Size(max = 500, message = "备注长度不能超过500个字符")
private String notes;
@Size(max = 500, message = "偏好长度不能超过500个字符")
private String preferences;
@Size(max = 500, message = "禁忌说明长度不能超过500个字符")
private String cautions;
@Size(max = 255, message = "标签长度不能超过255个字符")
private String tags;
private LocalDateTime expectedUpdateTime;
}
@@ -0,0 +1,42 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
public class OrderSaveRequest {
private Long id;
private Long customerId;
private Long appointmentId;
@Size(max = 100, message = "服务项目长度不能超过100个字符")
private String serviceName;
private LocalDateTime appointmentTime;
@DecimalMin(value = "0.00", inclusive = true, message = "成交金额不能小于0")
private BigDecimal amount;
@DecimalMin(value = "0.00", inclusive = true, message = "定金不能小于0")
private BigDecimal depositAmount;
@DecimalMin(value = "0.00", inclusive = true, message = "实收金额不能小于0")
private BigDecimal receivedAmount;
@Size(max = 32, message = "支付状态长度不能超过32个字符")
private String paymentStatus;
private LocalDateTime completedAt;
@Size(max = 500, message = "备注长度不能超过500个字符")
private String notes;
private LocalDateTime expectedUpdateTime;
}
@@ -0,0 +1,50 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_calendar_appointment")
public class AppointmentDO extends BaseEntity {
private Long seriesId;
private Long customerId;
private Long orderId;
private String customerName;
private String customerPhone;
private LocalDate appointmentDate;
private LocalDateTime appointmentStartTime;
private LocalDateTime appointmentEndTime;
private String serviceName;
private String appointmentType;
private String orderReference;
private String notes;
private Integer reminderMinutes;
private String repeatType;
private LocalDate repeatUntil;
private String status;
private Boolean notificationEnabled;
private String syncStatus;
}
@@ -0,0 +1,22 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public abstract class BaseEntity {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,23 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_calendar_customer")
public class CustomerDO extends BaseEntity {
private String name;
private String phone;
private String notes;
private String preferences;
private String cautions;
private String tags;
}
@@ -0,0 +1,38 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_calendar_order")
public class ServiceOrderDO extends BaseEntity {
private Long customerId;
private Long appointmentId;
private String customerName;
private String customerPhone;
private String serviceName;
private LocalDateTime appointmentTime;
private BigDecimal amount;
private BigDecimal depositAmount;
private BigDecimal receivedAmount;
private String paymentStatus;
private LocalDateTime completedAt;
private String notes;
}
@@ -0,0 +1,7 @@
package com.xiaowang.yuminailcalendarcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
public interface AppointmentMapper extends BaseMapper<AppointmentDO> {
}
@@ -0,0 +1,7 @@
package com.xiaowang.yuminailcalendarcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
public interface CustomerMapper extends BaseMapper<CustomerDO> {
}
@@ -0,0 +1,7 @@
package com.xiaowang.yuminailcalendarcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
public interface ServiceOrderMapper extends BaseMapper<ServiceOrderDO> {
}
@@ -0,0 +1,42 @@
package com.xiaowang.yuminailcalendarcore.service;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
public interface AppointmentService {
List<AppointmentVO> getAppointmentsByDay(LocalDate date, String keyword, String sortBy);
List<AppointmentVO> searchAppointments(LocalDate startDate, LocalDate endDate, Long customerId, String keyword,
String serviceName, String status, String sortBy);
List<CalendarDaySummaryVO> getMonthSummary(YearMonth month);
AppointmentDashboardVO getDashboard(LocalDate date);
AppointmentVO getAppointment(Long id);
List<AppointmentVO> createAppointment(AppointmentSaveRequest request);
List<AppointmentVO> updateAppointment(Long id, AppointmentSaveRequest request);
void deleteAppointment(Long id, boolean deleteSeries);
void batchDelete(AppointmentBatchDeleteRequest request);
AppointmentVO updateStatus(Long id, AppointmentStatusUpdateRequest request);
AppointmentExportVO exportAppointments(LocalDate startDate, LocalDate endDate);
List<AppointmentVO> importAppointments(AppointmentImportRequest request);
}
@@ -0,0 +1,21 @@
package com.xiaowang.yuminailcalendarcore.service;
import com.xiaowang.yuminailcalendarcore.dto.CustomerSaveRequest;
import com.xiaowang.yuminailcalendarcore.vo.CustomerVO;
import java.util.List;
public interface CustomerService {
List<CustomerVO> searchCustomers(String keyword, String tag);
CustomerVO getCustomer(Long id);
CustomerVO createCustomer(CustomerSaveRequest request);
CustomerVO updateCustomer(Long id, CustomerSaveRequest request);
void deleteCustomer(Long id);
List<CustomerVO> importCustomers(List<CustomerSaveRequest> requests);
}
@@ -0,0 +1,23 @@
package com.xiaowang.yuminailcalendarcore.service;
import com.xiaowang.yuminailcalendarcore.dto.OrderSaveRequest;
import com.xiaowang.yuminailcalendarcore.vo.ServiceOrderVO;
import java.time.LocalDate;
import java.util.List;
public interface ServiceOrderService {
List<ServiceOrderVO> searchOrders(LocalDate startDate, LocalDate endDate, Long customerId, Long appointmentId,
String keyword, String paymentStatus);
ServiceOrderVO getOrder(Long id);
ServiceOrderVO createOrder(OrderSaveRequest request);
ServiceOrderVO updateOrder(Long id, OrderSaveRequest request);
void deleteOrder(Long id);
List<ServiceOrderVO> importOrders(List<OrderSaveRequest> requests);
}
@@ -0,0 +1,574 @@
package com.xiaowang.yuminailcalendarcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcalendarcore.common.ConflictException;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
import com.xiaowang.yuminailcalendarcore.mapper.AppointmentMapper;
import com.xiaowang.yuminailcalendarcore.mapper.CustomerMapper;
import com.xiaowang.yuminailcalendarcore.mapper.ServiceOrderMapper;
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
import com.xiaowang.yuminailcalendarcore.vo.IncomeTrendPointVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, AppointmentDO> implements AppointmentService {
private static final String STATUS_SCHEDULED = "SCHEDULED";
private static final String STATUS_IN_SERVICE = "IN_SERVICE";
private static final String STATUS_COMPLETED = "COMPLETED";
private static final String STATUS_CANCELLED = "CANCELLED";
private static final String STATUS_NO_SHOW = "NO_SHOW";
private static final String STATUS_MISSED = "MISSED";
private static final String REPEAT_NONE = "NONE";
private static final String REPEAT_WEEKLY = "WEEKLY";
private static final String REPEAT_MONTHLY = "MONTHLY";
private static final String SYNC_STATUS_SYNCED = "SYNCED";
private final CustomerMapper customerMapper;
private final ServiceOrderMapper serviceOrderMapper;
@Override
public List<AppointmentVO> getAppointmentsByDay(LocalDate date, String keyword, String sortBy) {
if (date == null) {
throw new IllegalArgumentException("请选择查询日期");
}
LambdaQueryWrapper<AppointmentDO> queryWrapper = new LambdaQueryWrapper<AppointmentDO>()
.eq(AppointmentDO::getAppointmentDate, date);
applyKeywordFilter(queryWrapper, keyword);
applySort(queryWrapper, sortBy);
return list(queryWrapper).stream().map(this::toVO).collect(Collectors.toList());
}
@Override
public List<AppointmentVO> searchAppointments(LocalDate startDate, LocalDate endDate, Long customerId, String keyword,
String serviceName, String status, String sortBy) {
LambdaQueryWrapper<AppointmentDO> queryWrapper = new LambdaQueryWrapper<>();
if (startDate != null) {
queryWrapper.ge(AppointmentDO::getAppointmentDate, startDate);
}
if (endDate != null) {
queryWrapper.le(AppointmentDO::getAppointmentDate, endDate);
}
if (customerId != null) {
queryWrapper.eq(AppointmentDO::getCustomerId, customerId);
}
if (StringUtils.hasText(serviceName)) {
queryWrapper.like(AppointmentDO::getServiceName, serviceName.trim());
}
if (StringUtils.hasText(status)) {
queryWrapper.eq(AppointmentDO::getStatus, normalizeStatus(status));
}
applyKeywordFilter(queryWrapper, keyword);
applySort(queryWrapper, sortBy);
return list(queryWrapper).stream().map(this::toVO).collect(Collectors.toList());
}
@Override
public List<CalendarDaySummaryVO> getMonthSummary(YearMonth month) {
if (month == null) {
throw new IllegalArgumentException("请选择查询月份");
}
LocalDate startDate = month.atDay(1);
LocalDate endDate = month.atEndOfMonth();
List<AppointmentDO> appointments = list(new LambdaQueryWrapper<AppointmentDO>()
.between(AppointmentDO::getAppointmentDate, startDate, endDate)
.orderByAsc(AppointmentDO::getAppointmentDate)
.orderByAsc(AppointmentDO::getAppointmentStartTime));
Map<LocalDate, CalendarDaySummaryVO> daySummaryMap = new LinkedHashMap<>();
for (AppointmentDO appointment : appointments) {
CalendarDaySummaryVO summary = daySummaryMap.computeIfAbsent(appointment.getAppointmentDate(), key -> {
CalendarDaySummaryVO item = new CalendarDaySummaryVO();
item.setDate(key);
item.setTotalCount(0);
item.setScheduledCount(0);
item.setCompletedCount(0);
item.setCancelledCount(0);
return item;
});
summary.setTotalCount(summary.getTotalCount() + 1);
String normalizedStatus = normalizeStatus(appointment.getStatus());
if (STATUS_COMPLETED.equals(normalizedStatus)) {
summary.setCompletedCount(summary.getCompletedCount() + 1);
} else if (STATUS_CANCELLED.equals(normalizedStatus) || STATUS_NO_SHOW.equals(normalizedStatus)) {
summary.setCancelledCount(summary.getCancelledCount() + 1);
} else {
summary.setScheduledCount(summary.getScheduledCount() + 1);
}
}
return new ArrayList<>(daySummaryMap.values());
}
@Override
public AppointmentDashboardVO getDashboard(LocalDate date) {
LocalDate targetDate = date == null ? LocalDate.now() : date;
List<AppointmentDO> appointments = list();
List<ServiceOrderDO> orders = serviceOrderMapper.selectList(null);
LocalDateTime now = LocalDateTime.now();
LocalDateTime reminderWindowEnd = now.plusHours(24);
int total = appointments.size();
int today = 0;
int scheduled = 0;
int completed = 0;
int cancelled = 0;
int upcomingReminderCount = 0;
for (AppointmentDO appointment : appointments) {
String normalizedStatus = normalizeStatus(appointment.getStatus());
if (targetDate.equals(appointment.getAppointmentDate())) {
today++;
if (STATUS_SCHEDULED.equals(normalizedStatus) || STATUS_IN_SERVICE.equals(normalizedStatus)) {
scheduled++;
}
if (STATUS_COMPLETED.equals(normalizedStatus)) {
completed++;
}
if (STATUS_CANCELLED.equals(normalizedStatus) || STATUS_NO_SHOW.equals(normalizedStatus)) {
cancelled++;
}
}
if ((STATUS_SCHEDULED.equals(normalizedStatus) || STATUS_IN_SERVICE.equals(normalizedStatus))
&& Boolean.TRUE.equals(appointment.getNotificationEnabled())
&& !appointment.getAppointmentStartTime().isBefore(now)
&& !appointment.getAppointmentStartTime().isAfter(reminderWindowEnd)) {
upcomingReminderCount++;
}
}
BigDecimal todayIncome = BigDecimal.ZERO;
BigDecimal pendingReceivables = BigDecimal.ZERO;
Map<LocalDate, BigDecimal> trendMap = new LinkedHashMap<>();
for (int index = 6; index >= 0; index--) {
trendMap.put(targetDate.minusDays(index), BigDecimal.ZERO);
}
for (ServiceOrderDO order : orders) {
BigDecimal outstanding = normalizeAmount(order.getAmount()).subtract(normalizeAmount(order.getReceivedAmount()));
if (outstanding.compareTo(BigDecimal.ZERO) > 0 && !"REFUNDED".equals(normalizePaymentStatus(order.getPaymentStatus()))) {
pendingReceivables = pendingReceivables.add(outstanding);
}
if (order.getCompletedAt() != null) {
LocalDate completedDate = order.getCompletedAt().toLocalDate();
if (targetDate.equals(completedDate)) {
todayIncome = todayIncome.add(normalizeAmount(order.getReceivedAmount()));
}
if (trendMap.containsKey(completedDate)) {
trendMap.put(completedDate, trendMap.get(completedDate).add(normalizeAmount(order.getReceivedAmount())));
}
}
}
AppointmentDashboardVO dashboardVO = new AppointmentDashboardVO();
dashboardVO.setTotalAppointments(total);
dashboardVO.setTodayAppointments(today);
dashboardVO.setScheduledAppointments(scheduled);
dashboardVO.setCompletedAppointments(completed);
dashboardVO.setCancelledAppointments(cancelled);
dashboardVO.setUpcomingReminderCount(upcomingReminderCount);
dashboardVO.setPendingReminders(upcomingReminderCount);
dashboardVO.setTodayIncome(todayIncome);
dashboardVO.setPendingReceivables(pendingReceivables);
dashboardVO.setIncomeTrend(trendMap.entrySet().stream().map(entry -> {
IncomeTrendPointVO pointVO = new IncomeTrendPointVO();
pointVO.setDate(entry.getKey());
pointVO.setAmount(entry.getValue());
return pointVO;
}).collect(Collectors.toList()));
return dashboardVO;
}
@Override
public AppointmentVO getAppointment(Long id) {
return toVO(getByIdOrThrow(id));
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<AppointmentVO> createAppointment(AppointmentSaveRequest request) {
String repeatType = normalizeRepeatType(request.getRepeatType());
Long seriesId = REPEAT_NONE.equals(repeatType)
? request.getSeriesId()
: (request.getSeriesId() == null ? IdWorker.getId() : request.getSeriesId());
List<AppointmentDO> appointments = buildSeriesAppointments(request, seriesId);
saveBatch(appointments);
return appointments.stream()
.sorted(Comparator.comparing(AppointmentDO::getAppointmentStartTime))
.map(this::toVO)
.collect(Collectors.toList());
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<AppointmentVO> updateAppointment(Long id, AppointmentSaveRequest request) {
AppointmentDO existing = getByIdOrThrow(id);
assertExpectedUpdateTime(existing, request.getExpectedUpdateTime());
boolean applyToSeries = Boolean.TRUE.equals(request.getApplyToSeries());
String repeatType = normalizeRepeatType(request.getRepeatType());
if (applyToSeries) {
Long seriesId = existing.getSeriesId() == null ? IdWorker.getId() : existing.getSeriesId();
if (existing.getSeriesId() == null) {
removeById(existing.getId());
} else {
remove(new LambdaQueryWrapper<AppointmentDO>()
.eq(AppointmentDO::getSeriesId, seriesId)
.ge(AppointmentDO::getAppointmentStartTime, existing.getAppointmentStartTime()));
}
request.setSeriesId(REPEAT_NONE.equals(repeatType) ? seriesId : (request.getSeriesId() == null ? seriesId : request.getSeriesId()));
List<AppointmentDO> appointments = buildSeriesAppointments(request, request.getSeriesId());
saveBatch(appointments);
return appointments.stream()
.sorted(Comparator.comparing(AppointmentDO::getAppointmentStartTime))
.map(this::toVO)
.collect(Collectors.toList());
}
validateRequest(request);
copyEditableFields(existing, request, existing.getSeriesId());
existing.setAppointmentStartTime(request.getAppointmentStartTime());
existing.setAppointmentEndTime(request.getAppointmentEndTime());
existing.setAppointmentDate(request.getAppointmentStartTime().toLocalDate());
existing.setRepeatType(repeatType);
existing.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
if (StringUtils.hasText(request.getStatus())) {
existing.setStatus(normalizeStatus(request.getStatus()));
}
updateById(existing);
return List.of(toVO(existing));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAppointment(Long id, boolean deleteSeries) {
AppointmentDO existing = getByIdOrThrow(id);
if (deleteSeries && existing.getSeriesId() != null) {
remove(new LambdaQueryWrapper<AppointmentDO>().eq(AppointmentDO::getSeriesId, existing.getSeriesId()));
return;
}
removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void batchDelete(AppointmentBatchDeleteRequest request) {
if (CollectionUtils.isEmpty(request.getIds())) {
throw new IllegalArgumentException("请选择要删除的预约");
}
if (!Boolean.TRUE.equals(request.getDeleteSeries())) {
removeByIds(request.getIds());
return;
}
List<AppointmentDO> appointments = listByIds(request.getIds());
Set<Long> seriesIds = appointments.stream()
.map(AppointmentDO::getSeriesId)
.filter(seriesId -> seriesId != null)
.collect(Collectors.toCollection(LinkedHashSet::new));
Set<Long> singleIds = appointments.stream()
.filter(appointment -> appointment.getSeriesId() == null)
.map(AppointmentDO::getId)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (!seriesIds.isEmpty()) {
remove(new LambdaQueryWrapper<AppointmentDO>().in(AppointmentDO::getSeriesId, seriesIds));
}
if (!singleIds.isEmpty()) {
removeByIds(singleIds);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public AppointmentVO updateStatus(Long id, AppointmentStatusUpdateRequest request) {
AppointmentDO existing = getByIdOrThrow(id);
assertExpectedUpdateTime(existing, request.getExpectedUpdateTime());
existing.setStatus(normalizeStatus(request.getStatus()));
updateById(existing);
return toVO(existing);
}
@Override
public AppointmentExportVO exportAppointments(LocalDate startDate, LocalDate endDate) {
List<AppointmentVO> appointments = searchAppointments(startDate, endDate, null, null, null, null, "time");
AppointmentExportVO exportVO = new AppointmentExportVO();
exportVO.setExportedAt(LocalDateTime.now());
exportVO.setStartDate(startDate);
exportVO.setEndDate(endDate);
exportVO.setTotal(appointments.size());
exportVO.setAppointments(appointments);
return exportVO;
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<AppointmentVO> importAppointments(AppointmentImportRequest request) {
List<AppointmentVO> imported = new ArrayList<>();
for (AppointmentSaveRequest item : request.getAppointments()) {
imported.add(toVO(saveImportedAppointment(item)));
}
return imported;
}
private List<AppointmentDO> buildSeriesAppointments(AppointmentSaveRequest request, Long seriesId) {
validateRequest(request);
List<AppointmentDO> appointments = new ArrayList<>();
String repeatType = normalizeRepeatType(request.getRepeatType());
LocalDateTime cursorStart = request.getAppointmentStartTime();
LocalDateTime cursorEnd = request.getAppointmentEndTime();
if (REPEAT_NONE.equals(repeatType)) {
appointments.add(buildAppointment(request, seriesId, cursorStart, cursorEnd, repeatType));
return appointments;
}
while (!cursorStart.toLocalDate().isAfter(request.getRepeatUntil())) {
appointments.add(buildAppointment(request, seriesId, cursorStart, cursorEnd, repeatType));
if (REPEAT_WEEKLY.equals(repeatType)) {
cursorStart = cursorStart.plusWeeks(1);
cursorEnd = cursorEnd.plusWeeks(1);
} else {
cursorStart = cursorStart.plusMonths(1);
cursorEnd = cursorEnd.plusMonths(1);
}
}
return appointments;
}
private AppointmentDO buildAppointment(AppointmentSaveRequest request, Long seriesId, LocalDateTime startTime,
LocalDateTime endTime, String repeatType) {
AppointmentDO appointment = new AppointmentDO();
copyEditableFields(appointment, request, seriesId);
appointment.setAppointmentStartTime(startTime);
appointment.setAppointmentEndTime(endTime);
appointment.setAppointmentDate(startTime.toLocalDate());
appointment.setRepeatType(repeatType);
appointment.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
if (!StringUtils.hasText(appointment.getStatus())) {
appointment.setStatus(STATUS_SCHEDULED);
}
return appointment;
}
private AppointmentDO saveImportedAppointment(AppointmentSaveRequest request) {
validateRequest(request);
String repeatType = normalizeRepeatType(request.getRepeatType());
AppointmentDO appointment = request.getId() == null ? new AppointmentDO() : getById(request.getId());
if (appointment == null) {
appointment = new AppointmentDO();
}
if (request.getId() != null) {
appointment.setId(request.getId());
}
copyEditableFields(appointment, request, request.getSeriesId());
appointment.setAppointmentStartTime(request.getAppointmentStartTime());
appointment.setAppointmentEndTime(request.getAppointmentEndTime());
appointment.setAppointmentDate(request.getAppointmentStartTime().toLocalDate());
appointment.setRepeatType(repeatType);
appointment.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
appointment.setStatus(normalizeStatus(request.getStatus()));
appointment.setSyncStatus(SYNC_STATUS_SYNCED);
if (appointment.getCreateTime() == null) {
save(appointment);
} else {
updateById(appointment);
}
return appointment;
}
private void copyEditableFields(AppointmentDO appointment, AppointmentSaveRequest request, Long seriesId) {
String repeatType = normalizeRepeatType(request.getRepeatType());
CustomerDO customer = request.getCustomerId() == null ? null : customerMapper.selectById(request.getCustomerId());
if (request.getCustomerId() != null && customer == null) {
throw new IllegalArgumentException("关联客户不存在");
}
appointment.setSeriesId(seriesId);
appointment.setCustomerId(customer == null ? request.getCustomerId() : customer.getId());
appointment.setOrderId(request.getOrderId());
appointment.setCustomerName(resolveCustomerName(customer, request));
appointment.setCustomerPhone(resolveCustomerPhone(customer, request));
appointment.setServiceName(requireText(request.getServiceName(), "服务项目不能为空"));
appointment.setAppointmentType(normalizeAppointmentType(request.getAppointmentType()));
appointment.setOrderReference(resolveOrderReference(request.getOrderId(), request.getOrderReference()));
appointment.setNotes(trimToNull(request.getNotes()));
appointment.setReminderMinutes(request.getReminderMinutes() == null ? 60 : request.getReminderMinutes());
appointment.setNotificationEnabled(request.getNotificationEnabled() == null || request.getNotificationEnabled());
appointment.setSyncStatus(SYNC_STATUS_SYNCED);
if (!StringUtils.hasText(appointment.getStatus())) {
appointment.setStatus(StringUtils.hasText(request.getStatus()) ? normalizeStatus(request.getStatus()) : STATUS_SCHEDULED);
}
appointment.setRepeatType(repeatType);
appointment.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
}
private void validateRequest(AppointmentSaveRequest request) {
if (!request.getAppointmentEndTime().isAfter(request.getAppointmentStartTime())) {
throw new IllegalArgumentException("预约结束时间必须晚于开始时间");
}
requireText(request.getCustomerName(), "客户姓名不能为空");
requireText(request.getServiceName(), "服务项目不能为空");
String repeatType = normalizeRepeatType(request.getRepeatType());
if (!REPEAT_NONE.equals(repeatType)) {
if (request.getRepeatUntil() == null) {
throw new IllegalArgumentException("重复预约请填写截止日期");
}
if (request.getRepeatUntil().isBefore(request.getAppointmentStartTime().toLocalDate())) {
throw new IllegalArgumentException("重复预约截止日期不能早于开始日期");
}
}
}
private void applyKeywordFilter(LambdaQueryWrapper<AppointmentDO> queryWrapper, String keyword) {
if (!StringUtils.hasText(keyword)) {
return;
}
String trimmed = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like(AppointmentDO::getCustomerName, trimmed)
.or()
.like(AppointmentDO::getCustomerPhone, trimmed)
.or()
.like(AppointmentDO::getServiceName, trimmed)
.or()
.like(AppointmentDO::getOrderReference, trimmed));
}
private void applySort(LambdaQueryWrapper<AppointmentDO> queryWrapper, String sortBy) {
if ("customerName".equalsIgnoreCase(sortBy)) {
queryWrapper.orderByAsc(AppointmentDO::getCustomerName)
.orderByAsc(AppointmentDO::getAppointmentStartTime);
return;
}
if ("date".equalsIgnoreCase(sortBy)) {
queryWrapper.orderByAsc(AppointmentDO::getAppointmentDate)
.orderByAsc(AppointmentDO::getAppointmentStartTime);
return;
}
queryWrapper.orderByAsc(AppointmentDO::getAppointmentStartTime)
.orderByAsc(AppointmentDO::getCustomerName);
}
private AppointmentDO getByIdOrThrow(Long id) {
AppointmentDO appointment = getById(id);
if (appointment == null) {
throw new IllegalArgumentException("预约不存在或已删除");
}
return appointment;
}
private AppointmentVO toVO(AppointmentDO appointment) {
AppointmentVO vo = new AppointmentVO();
BeanUtils.copyProperties(appointment, vo);
return vo;
}
private String normalizeRepeatType(String repeatType) {
if (!StringUtils.hasText(repeatType)) {
return REPEAT_NONE;
}
String normalized = repeatType.trim().toUpperCase(Locale.ROOT);
if (REPEAT_WEEKLY.equals(normalized) || REPEAT_MONTHLY.equals(normalized)) {
return normalized;
}
return REPEAT_NONE;
}
private String normalizeStatus(String status) {
if (!StringUtils.hasText(status)) {
return STATUS_SCHEDULED;
}
String normalized = status.trim().toUpperCase(Locale.ROOT);
if (STATUS_COMPLETED.equals(normalized) || STATUS_CANCELLED.equals(normalized)
|| STATUS_IN_SERVICE.equals(normalized) || STATUS_NO_SHOW.equals(normalized)) {
return normalized;
}
if (STATUS_MISSED.equals(normalized)) {
return STATUS_NO_SHOW;
}
return STATUS_SCHEDULED;
}
private String normalizeAppointmentType(String appointmentType) {
if (!StringUtils.hasText(appointmentType)) {
return "NORMAL";
}
return appointmentType.trim().toUpperCase(Locale.ROOT);
}
private String normalizePaymentStatus(String paymentStatus) {
return StringUtils.hasText(paymentStatus) ? paymentStatus.trim().toUpperCase(Locale.ROOT) : "UNPAID";
}
private BigDecimal normalizeAmount(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
private void assertExpectedUpdateTime(AppointmentDO existing, LocalDateTime expectedUpdateTime) {
if (expectedUpdateTime != null && existing.getUpdateTime() != null && !existing.getUpdateTime().equals(expectedUpdateTime)) {
throw new ConflictException("预约记录已在其他设备变更,请刷新后再决定保留哪一份");
}
}
private String resolveCustomerName(CustomerDO customer, AppointmentSaveRequest request) {
String value = customer != null && StringUtils.hasText(customer.getName()) ? customer.getName() : request.getCustomerName();
return requireText(value, "客户姓名不能为空");
}
private String resolveCustomerPhone(CustomerDO customer, AppointmentSaveRequest request) {
String value = customer != null && StringUtils.hasText(customer.getPhone()) ? customer.getPhone() : request.getCustomerPhone();
return trimToNull(value);
}
private String resolveOrderReference(Long orderId, String orderReference) {
if (orderId != null) {
return "ORD-" + orderId;
}
return trimToNull(orderReference);
}
private String requireText(String value, String message) {
if (!StringUtils.hasText(value)) {
throw new IllegalArgumentException(message);
}
return value.trim();
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
}
@@ -0,0 +1,193 @@
package com.xiaowang.yuminailcalendarcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcalendarcore.common.ConflictException;
import com.xiaowang.yuminailcalendarcore.dto.CustomerSaveRequest;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
import com.xiaowang.yuminailcalendarcore.mapper.AppointmentMapper;
import com.xiaowang.yuminailcalendarcore.mapper.CustomerMapper;
import com.xiaowang.yuminailcalendarcore.mapper.ServiceOrderMapper;
import com.xiaowang.yuminailcalendarcore.service.CustomerService;
import com.xiaowang.yuminailcalendarcore.vo.CustomerVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerDO> implements CustomerService {
private static final String STATUS_COMPLETED = "COMPLETED";
private static final String PAYMENT_REFUNDED = "REFUNDED";
private final AppointmentMapper appointmentMapper;
private final ServiceOrderMapper serviceOrderMapper;
@Override
public List<CustomerVO> searchCustomers(String keyword, String tag) {
LambdaQueryWrapper<CustomerDO> queryWrapper = new LambdaQueryWrapper<>();
if (StringUtils.hasText(keyword)) {
String trimmed = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like(CustomerDO::getName, trimmed)
.or()
.like(CustomerDO::getPhone, trimmed));
}
if (StringUtils.hasText(tag)) {
queryWrapper.like(CustomerDO::getTags, tag.trim());
}
queryWrapper.orderByDesc(CustomerDO::getUpdateTime);
List<CustomerDO> customers = list(queryWrapper);
return enrich(customers);
}
@Override
public CustomerVO getCustomer(Long id) {
CustomerDO customer = getById(id);
if (customer == null) {
throw new IllegalArgumentException("客户不存在或已删除");
}
return enrich(List.of(customer)).get(0);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CustomerVO createCustomer(CustomerSaveRequest request) {
CustomerDO customer = new CustomerDO();
if (request.getId() != null) {
customer.setId(request.getId());
}
copyEditableFields(customer, request);
save(customer);
return getCustomer(customer.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public CustomerVO updateCustomer(Long id, CustomerSaveRequest request) {
CustomerDO customer = getById(id);
if (customer == null) {
throw new IllegalArgumentException("客户不存在或已删除");
}
assertExpectedUpdateTime(customer, request.getExpectedUpdateTime());
copyEditableFields(customer, request);
updateById(customer);
return getCustomer(customer.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCustomer(Long id) {
long appointmentCount = appointmentMapper.selectCount(new LambdaQueryWrapper<AppointmentDO>()
.eq(AppointmentDO::getCustomerId, id));
long orderCount = serviceOrderMapper.selectCount(new LambdaQueryWrapper<ServiceOrderDO>()
.eq(ServiceOrderDO::getCustomerId, id));
if (appointmentCount > 0 || orderCount > 0) {
throw new IllegalArgumentException("该客户已有预约或订单历史,暂不支持直接删除");
}
removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<CustomerVO> importCustomers(List<CustomerSaveRequest> requests) {
for (CustomerSaveRequest request : requests) {
if (request.getId() != null && getById(request.getId()) != null) {
CustomerDO existing = getById(request.getId());
copyEditableFields(existing, request);
updateById(existing);
continue;
}
CustomerDO customer = new CustomerDO();
if (request.getId() != null) {
customer.setId(request.getId());
}
copyEditableFields(customer, request);
save(customer);
}
return searchCustomers(null, null);
}
private List<CustomerVO> enrich(List<CustomerDO> customers) {
if (customers.isEmpty()) {
return Collections.emptyList();
}
Set<Long> customerIds = customers.stream().map(CustomerDO::getId).collect(Collectors.toSet());
List<AppointmentDO> appointments = appointmentMapper.selectList(new LambdaQueryWrapper<AppointmentDO>()
.in(AppointmentDO::getCustomerId, customerIds));
List<ServiceOrderDO> orders = serviceOrderMapper.selectList(new LambdaQueryWrapper<ServiceOrderDO>()
.in(ServiceOrderDO::getCustomerId, customerIds));
Map<Long, List<AppointmentDO>> appointmentMap = appointments.stream()
.collect(Collectors.groupingBy(AppointmentDO::getCustomerId));
Map<Long, List<ServiceOrderDO>> orderMap = orders.stream()
.collect(Collectors.groupingBy(ServiceOrderDO::getCustomerId));
return customers.stream()
.map(customer -> toVO(customer, appointmentMap.get(customer.getId()), orderMap.get(customer.getId())))
.sorted(Comparator.comparing(CustomerVO::getUpdateTime, Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());
}
private CustomerVO toVO(CustomerDO customer, List<AppointmentDO> appointments, List<ServiceOrderDO> orders) {
List<AppointmentDO> safeAppointments = appointments == null ? Collections.emptyList() : appointments;
List<ServiceOrderDO> safeOrders = orders == null ? Collections.emptyList() : orders;
CustomerVO vo = new CustomerVO();
BeanUtils.copyProperties(customer, vo);
vo.setTotalVisitCount((int) safeAppointments.stream()
.filter(item -> STATUS_COMPLETED.equalsIgnoreCase(item.getStatus()))
.count());
vo.setLastVisitTime(safeAppointments.stream()
.map(AppointmentDO::getAppointmentStartTime)
.max(LocalDateTime::compareTo)
.orElse(null));
vo.setTotalSpentAmount(safeOrders.stream()
.filter(item -> !PAYMENT_REFUNDED.equalsIgnoreCase(item.getPaymentStatus()))
.map(ServiceOrderDO::getReceivedAmount)
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add));
return vo;
}
private void copyEditableFields(CustomerDO customer, CustomerSaveRequest request) {
customer.setName(requireText(request.getName(), "客户姓名不能为空"));
customer.setPhone(trimToNull(request.getPhone()));
customer.setNotes(trimToNull(request.getNotes()));
customer.setPreferences(trimToNull(request.getPreferences()));
customer.setCautions(trimToNull(request.getCautions()));
customer.setTags(trimToNull(request.getTags()));
}
private void assertExpectedUpdateTime(CustomerDO existing, LocalDateTime expectedUpdateTime) {
if (expectedUpdateTime != null && existing.getUpdateTime() != null && !existing.getUpdateTime().equals(expectedUpdateTime)) {
throw new ConflictException("客户资料已在其他设备变更,请先处理冲突");
}
}
private String requireText(String value, String message) {
if (!StringUtils.hasText(value)) {
throw new IllegalArgumentException(message);
}
return value.trim();
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
}
@@ -0,0 +1,283 @@
package com.xiaowang.yuminailcalendarcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcalendarcore.common.ConflictException;
import com.xiaowang.yuminailcalendarcore.dto.OrderSaveRequest;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
import com.xiaowang.yuminailcalendarcore.mapper.AppointmentMapper;
import com.xiaowang.yuminailcalendarcore.mapper.CustomerMapper;
import com.xiaowang.yuminailcalendarcore.mapper.ServiceOrderMapper;
import com.xiaowang.yuminailcalendarcore.service.ServiceOrderService;
import com.xiaowang.yuminailcalendarcore.vo.ServiceOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ServiceOrderServiceImpl extends ServiceImpl<ServiceOrderMapper, ServiceOrderDO> implements ServiceOrderService {
private static final String PAYMENT_UNPAID = "UNPAID";
private static final String PAYMENT_PARTIALLY_PAID = "PARTIALLY_PAID";
private static final String PAYMENT_PAID = "PAID";
private static final String PAYMENT_REFUNDED = "REFUNDED";
private final CustomerMapper customerMapper;
private final AppointmentMapper appointmentMapper;
@Override
public List<ServiceOrderVO> searchOrders(LocalDate startDate, LocalDate endDate, Long customerId, Long appointmentId,
String keyword, String paymentStatus) {
LambdaQueryWrapper<ServiceOrderDO> queryWrapper = new LambdaQueryWrapper<>();
if (startDate != null) {
queryWrapper.ge(ServiceOrderDO::getAppointmentTime, startDate.atStartOfDay());
}
if (endDate != null) {
queryWrapper.le(ServiceOrderDO::getAppointmentTime, LocalDateTime.of(endDate, LocalTime.MAX));
}
if (customerId != null) {
queryWrapper.eq(ServiceOrderDO::getCustomerId, customerId);
}
if (appointmentId != null) {
queryWrapper.eq(ServiceOrderDO::getAppointmentId, appointmentId);
}
if (StringUtils.hasText(paymentStatus)) {
queryWrapper.eq(ServiceOrderDO::getPaymentStatus, normalizePaymentStatus(paymentStatus, BigDecimal.ZERO, BigDecimal.ZERO));
}
if (StringUtils.hasText(keyword)) {
String trimmed = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like(ServiceOrderDO::getCustomerName, trimmed)
.or()
.like(ServiceOrderDO::getServiceName, trimmed)
.or()
.like(ServiceOrderDO::getNotes, trimmed));
}
queryWrapper.orderByDesc(ServiceOrderDO::getAppointmentTime).orderByDesc(ServiceOrderDO::getUpdateTime);
return list(queryWrapper).stream().map(this::toVO).collect(Collectors.toList());
}
@Override
public ServiceOrderVO getOrder(Long id) {
ServiceOrderDO order = getById(id);
if (order == null) {
throw new IllegalArgumentException("订单不存在或已删除");
}
return toVO(order);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ServiceOrderVO createOrder(OrderSaveRequest request) {
ServiceOrderDO order = new ServiceOrderDO();
if (request.getId() != null) {
order.setId(request.getId());
}
copyEditableFields(order, request);
save(order);
linkAppointment(order);
return getOrder(order.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public ServiceOrderVO updateOrder(Long id, OrderSaveRequest request) {
ServiceOrderDO order = getById(id);
if (order == null) {
throw new IllegalArgumentException("订单不存在或已删除");
}
assertExpectedUpdateTime(order, request.getExpectedUpdateTime());
copyEditableFields(order, request);
updateById(order);
linkAppointment(order);
return getOrder(order.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteOrder(Long id) {
ServiceOrderDO order = getById(id);
if (order == null) {
return;
}
if (order.getAppointmentId() != null) {
AppointmentDO appointment = appointmentMapper.selectById(order.getAppointmentId());
if (appointment != null && id.equals(appointment.getOrderId())) {
appointment.setOrderId(null);
appointment.setOrderReference(null);
appointmentMapper.updateById(appointment);
}
}
removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<ServiceOrderVO> importOrders(List<OrderSaveRequest> requests) {
for (OrderSaveRequest request : requests) {
if (request.getId() != null && getById(request.getId()) != null) {
ServiceOrderDO existing = getById(request.getId());
copyEditableFields(existing, request);
updateById(existing);
linkAppointment(existing);
continue;
}
ServiceOrderDO order = new ServiceOrderDO();
if (request.getId() != null) {
order.setId(request.getId());
}
copyEditableFields(order, request);
save(order);
linkAppointment(order);
}
return searchOrders(null, null, null, null, null, null);
}
private void copyEditableFields(ServiceOrderDO order, OrderSaveRequest request) {
AppointmentDO appointment = request.getAppointmentId() == null ? null : appointmentMapper.selectById(request.getAppointmentId());
if (request.getAppointmentId() != null && appointment == null) {
throw new IllegalArgumentException("关联预约不存在");
}
Long customerId = request.getCustomerId() != null ? request.getCustomerId()
: (appointment == null ? null : appointment.getCustomerId());
CustomerDO customer = customerId == null ? null : customerMapper.selectById(customerId);
if (customerId != null && customer == null) {
throw new IllegalArgumentException("关联客户不存在");
}
BigDecimal amount = normalizeAmount(request.getAmount());
BigDecimal receivedAmount = normalizeAmount(request.getReceivedAmount());
BigDecimal depositAmount = normalizeAmount(request.getDepositAmount());
if (request.getAmount() == null && appointment == null) {
throw new IllegalArgumentException("成交金额不能为空");
}
order.setCustomerId(customer == null ? customerId : customer.getId());
order.setAppointmentId(appointment == null ? request.getAppointmentId() : appointment.getId());
order.setCustomerName(resolveCustomerName(customer, appointment));
order.setCustomerPhone(resolveCustomerPhone(customer, appointment));
order.setServiceName(resolveServiceName(request.getServiceName(), appointment));
order.setAppointmentTime(resolveAppointmentTime(request.getAppointmentTime(), appointment));
order.setAmount(amount);
order.setDepositAmount(depositAmount);
order.setReceivedAmount(receivedAmount);
order.setPaymentStatus(normalizePaymentStatus(request.getPaymentStatus(), amount, receivedAmount));
order.setCompletedAt(resolveCompletedAt(request.getCompletedAt(), order.getPaymentStatus()));
order.setNotes(trimToNull(request.getNotes()));
}
private void linkAppointment(ServiceOrderDO order) {
if (order.getAppointmentId() == null) {
return;
}
AppointmentDO appointment = appointmentMapper.selectById(order.getAppointmentId());
if (appointment == null) {
return;
}
appointment.setOrderId(order.getId());
appointment.setOrderReference("ORD-" + order.getId());
appointmentMapper.updateById(appointment);
}
private ServiceOrderVO toVO(ServiceOrderDO order) {
ServiceOrderVO vo = new ServiceOrderVO();
BeanUtils.copyProperties(order, vo);
vo.setOutstandingAmount(normalizeAmount(order.getAmount()).subtract(normalizeAmount(order.getReceivedAmount())).max(BigDecimal.ZERO));
return vo;
}
private void assertExpectedUpdateTime(ServiceOrderDO existing, LocalDateTime expectedUpdateTime) {
if (expectedUpdateTime != null && existing.getUpdateTime() != null && !existing.getUpdateTime().equals(expectedUpdateTime)) {
throw new ConflictException("订单已在其他设备变更,请先处理冲突");
}
}
private String resolveCustomerName(CustomerDO customer, AppointmentDO appointment) {
if (customer != null && StringUtils.hasText(customer.getName())) {
return customer.getName().trim();
}
if (appointment != null && StringUtils.hasText(appointment.getCustomerName())) {
return appointment.getCustomerName().trim();
}
return "未命名客户";
}
private String resolveCustomerPhone(CustomerDO customer, AppointmentDO appointment) {
if (customer != null && StringUtils.hasText(customer.getPhone())) {
return customer.getPhone().trim();
}
if (appointment != null && StringUtils.hasText(appointment.getCustomerPhone())) {
return appointment.getCustomerPhone().trim();
}
return null;
}
private String resolveServiceName(String serviceName, AppointmentDO appointment) {
if (StringUtils.hasText(serviceName)) {
return serviceName.trim();
}
if (appointment != null && StringUtils.hasText(appointment.getServiceName())) {
return appointment.getServiceName().trim();
}
throw new IllegalArgumentException("服务项目不能为空");
}
private LocalDateTime resolveAppointmentTime(LocalDateTime appointmentTime, AppointmentDO appointment) {
if (appointmentTime != null) {
return appointmentTime;
}
if (appointment != null) {
return appointment.getAppointmentStartTime();
}
return null;
}
private LocalDateTime resolveCompletedAt(LocalDateTime completedAt, String paymentStatus) {
if (completedAt != null) {
return completedAt;
}
if (PAYMENT_PAID.equals(paymentStatus) || PAYMENT_PARTIALLY_PAID.equals(paymentStatus)) {
return LocalDateTime.now();
}
return null;
}
private String normalizePaymentStatus(String paymentStatus, BigDecimal amount, BigDecimal receivedAmount) {
if (StringUtils.hasText(paymentStatus)) {
String normalized = paymentStatus.trim().toUpperCase(Locale.ROOT);
if (PAYMENT_UNPAID.equals(normalized) || PAYMENT_PARTIALLY_PAID.equals(normalized)
|| PAYMENT_PAID.equals(normalized) || PAYMENT_REFUNDED.equals(normalized)) {
return normalized;
}
}
if (receivedAmount.compareTo(BigDecimal.ZERO) <= 0) {
return PAYMENT_UNPAID;
}
if (receivedAmount.compareTo(amount) < 0) {
return PAYMENT_PARTIALLY_PAID;
}
return PAYMENT_PAID;
}
private BigDecimal normalizeAmount(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
}
@@ -0,0 +1,30 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
public class AppointmentDashboardVO {
private Integer totalAppointments;
private Integer todayAppointments;
private Integer scheduledAppointments;
private Integer completedAppointments;
private Integer cancelledAppointments;
private Integer upcomingReminderCount;
private Integer pendingReminders;
private BigDecimal todayIncome;
private BigDecimal pendingReceivables;
private List<IncomeTrendPointVO> incomeTrend;
}
@@ -0,0 +1,21 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class AppointmentExportVO {
private LocalDateTime exportedAt;
private LocalDate startDate;
private LocalDate endDate;
private Integer total;
private List<AppointmentVO> appointments;
}
@@ -0,0 +1,52 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
public class AppointmentVO {
private Long id;
private Long seriesId;
private Long customerId;
private Long orderId;
private String customerName;
private String customerPhone;
private LocalDate appointmentDate;
private LocalDateTime appointmentStartTime;
private LocalDateTime appointmentEndTime;
private String serviceName;
private String appointmentType;
private String orderReference;
private String notes;
private Integer reminderMinutes;
private String repeatType;
private LocalDate repeatUntil;
private String status;
private Boolean notificationEnabled;
private String syncStatus;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,27 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Data
public class BackupExportVO {
private LocalDateTime exportedAt;
private Integer customerCount;
private Integer appointmentCount;
private Integer orderCount;
private List<CustomerVO> customers;
private List<AppointmentVO> appointments;
private List<ServiceOrderVO> orders;
private Map<String, Object> settings;
}
@@ -0,0 +1,19 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDate;
@Data
public class CalendarDaySummaryVO {
private LocalDate date;
private Integer totalCount;
private Integer scheduledCount;
private Integer completedCount;
private Integer cancelledCount;
}
@@ -0,0 +1,34 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
public class CustomerVO {
private Long id;
private String name;
private String phone;
private String notes;
private String preferences;
private String cautions;
private String tags;
private LocalDateTime lastVisitTime;
private Integer totalVisitCount;
private BigDecimal totalSpentAmount;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,14 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
@Data
public class IncomeTrendPointVO {
private LocalDate date;
private BigDecimal amount;
}
@@ -0,0 +1,42 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
public class ServiceOrderVO {
private Long id;
private Long customerId;
private Long appointmentId;
private String customerName;
private String customerPhone;
private String serviceName;
private LocalDateTime appointmentTime;
private BigDecimal amount;
private BigDecimal depositAmount;
private BigDecimal receivedAmount;
private BigDecimal outstandingAmount;
private String paymentStatus;
private LocalDateTime completedAt;
private String notes;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,32 @@
server:
port: 8097
servlet:
encoding:
charset: UTF-8
force: true
enabled: true
spring:
application:
name: yuminail-calendar-core
datasource:
url: jdbc:mysql://localhost:3306/yumi_nail_calendar?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jackson:
time-zone: Asia/Shanghai
default-property-inclusion: non_null
serialization:
write-dates-as-timestamps: false
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
global-config:
db-config:
table-underline: true
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
@@ -0,0 +1,75 @@
CREATE DATABASE IF NOT EXISTS `yumi_nail_calendar`
DEFAULT CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
USE `yumi_nail_calendar`;
CREATE TABLE IF NOT EXISTS `t_calendar_customer` (
`id` BIGINT NOT NULL,
`name` VARCHAR(50) NOT NULL COMMENT '客户姓名',
`phone` VARCHAR(20) DEFAULT NULL COMMENT '联系电话',
`notes` TEXT DEFAULT NULL COMMENT '常规备注',
`preferences` TEXT DEFAULT NULL COMMENT '偏好记录',
`cautions` TEXT DEFAULT NULL COMMENT '禁忌或注意事项',
`tags` VARCHAR(255) DEFAULT NULL COMMENT '标签',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_calendar_customer_name` (`name`),
KEY `idx_calendar_customer_phone` (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='美甲客户档案表';
CREATE TABLE IF NOT EXISTS `t_calendar_order` (
`id` BIGINT NOT NULL,
`customer_id` BIGINT DEFAULT NULL COMMENT '客户ID',
`appointment_id` BIGINT DEFAULT NULL COMMENT '预约ID',
`customer_name` VARCHAR(50) NOT NULL COMMENT '客户姓名快照',
`customer_phone` VARCHAR(20) DEFAULT NULL COMMENT '客户电话快照',
`service_name` VARCHAR(100) NOT NULL COMMENT '服务项目快照',
`appointment_time` DATETIME DEFAULT NULL COMMENT '预约时间快照',
`amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '成交金额',
`deposit_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '定金金额',
`received_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '实收金额',
`payment_status` VARCHAR(32) NOT NULL DEFAULT 'UNPAID' COMMENT '支付状态',
`completed_at` DATETIME DEFAULT NULL COMMENT '订单完成时间',
`notes` TEXT DEFAULT NULL COMMENT '备注',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_calendar_order_customer_id` (`customer_id`),
KEY `idx_calendar_order_appointment_id` (`appointment_id`),
KEY `idx_calendar_order_payment_status` (`payment_status`),
KEY `idx_calendar_order_appointment_time` (`appointment_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='美甲服务订单表';
CREATE TABLE IF NOT EXISTS `t_calendar_appointment` (
`id` BIGINT NOT NULL,
`series_id` BIGINT DEFAULT NULL COMMENT '重复预约系列ID',
`customer_id` BIGINT DEFAULT NULL COMMENT '客户ID',
`order_id` BIGINT DEFAULT NULL COMMENT '关联订单ID',
`customer_name` VARCHAR(50) NOT NULL COMMENT '客户姓名快照',
`customer_phone` VARCHAR(20) DEFAULT NULL COMMENT '联系电话快照',
`appointment_date` DATE NOT NULL COMMENT '预约日期',
`appointment_start_time` DATETIME NOT NULL COMMENT '预约开始时间',
`appointment_end_time` DATETIME NOT NULL COMMENT '预约结束时间',
`service_name` VARCHAR(100) NOT NULL COMMENT '服务项目',
`appointment_type` VARCHAR(32) NOT NULL COMMENT '预约类型',
`order_reference` VARCHAR(64) DEFAULT NULL COMMENT '对应订单号',
`notes` TEXT DEFAULT NULL COMMENT '备注',
`reminder_minutes` INT NOT NULL DEFAULT 60 COMMENT '提前提醒分钟数',
`repeat_type` VARCHAR(32) NOT NULL DEFAULT 'NONE' COMMENT '重复类型',
`repeat_until` DATE DEFAULT NULL COMMENT '重复截止日期',
`status` VARCHAR(32) NOT NULL DEFAULT 'SCHEDULED' COMMENT '预约状态',
`notification_enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用提醒',
`sync_status` VARCHAR(32) NOT NULL DEFAULT 'SYNCED' COMMENT '同步状态',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_calendar_appointment_date` (`appointment_date`),
KEY `idx_calendar_appointment_start_time` (`appointment_start_time`),
KEY `idx_calendar_appointment_series_id` (`series_id`),
KEY `idx_calendar_appointment_customer_id` (`customer_id`),
KEY `idx_calendar_appointment_order_id` (`order_id`),
KEY `idx_calendar_appointment_status` (`status`),
KEY `idx_calendar_appointment_customer_name` (`customer_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='美甲师日历预约表';
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
<Property name="LOG_HOME">E:/code/xiaowang/YumiNail-Core/logs</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<RollingFile name="RollingFile" fileName="${LOG_HOME}/yuminail-core.log"
filePattern="${LOG_HOME}/yuminail-core-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30">
<Delete basePath="${LOG_HOME}" maxDepth="1">
<IfFileName glob="yuminail-core-*.log.gz"/>
<IfLastModified age="30d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="ErrorRollingFile" fileName="${LOG_HOME}/yuminail-core-error.log"
filePattern="${LOG_HOME}/yuminail-core-error-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${LOG_PATTERN}"/>
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30">
<Delete basePath="${LOG_HOME}" maxDepth="1">
<IfFileName glob="yuminail-core-error-*.log.gz"/>
<IfLastModified age="30d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingFile"/>
<AppenderRef ref="ErrorRollingFile"/>
</Root>
<Logger name="com.xiaowang.yuminailcore" level="DEBUG" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingFile"/>
<AppenderRef ref="ErrorRollingFile"/>
</Logger>
<Logger name="org.springframework" level="INFO"/>
<Logger name="com.alibaba.nacos" level="INFO"/>
<Logger name="org.mybatis" level="DEBUG"/>
</Loggers>
</Configuration>
@@ -0,0 +1,13 @@
# YumiNail-Calendar-Core 项目说明
`YumiNail-Calendar-Core` 是“美甲师日历表”独立系统的后端服务,当前提供以下能力:
- 预约 CRUD
- 月视图汇总数据
- 按日/按范围查询、搜索、排序
- 重复预约批量展开
- 单条/批量删除
- 预约状态更新
- 导入导出
默认端口为 `8097`,数据库脚本位于 `src/main/resources/files/YumiNail-Calendar.sql`。