This commit is contained in:
王子琦
2026-01-13 16:58:45 +08:00
parent 511c3bfdbe
commit 0387b43083
81 changed files with 3451 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
# 童飞玩具购物网站
## 技术栈
- 前端Vue 3 + Vite + Ant Design Vue
- 后端Spring Boot 3 + JPA + MySQL
## 运行说明
### 1. 数据库
- 创建数据库并导入 `db/schema.sql`
- 修改 `backend/src/main/resources/application.yml` 中的数据库账号密码
### 2. 后端
```powershell
cd D:\bs\shopping\backend
mvn spring-boot:run
```
默认管理员账号:`admin` / `admin123`
### 3. 前端
```powershell
cd D:\bs\shopping\frontend
npm install
npm run dev
```
访问:`http://localhost:5173`
## 功能覆盖
- 用户注册/登录/个人中心/收货地址
- 商品首页展示/搜索/列表/详情
- 购物车/订单确认/在线支付(模拟)/订单状态
- 管理员登录/用户管理/商品与分类管理/订单管理/轮播图/公告管理

64
backend/pom.xml Normal file
View File

@@ -0,0 +1,64 @@
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.toyshop</groupId>
<artifactId>backend</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
</parent>
<properties>
<java.version>17</java.version>
<jjwt.version>0.11.5</jjwt.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,11 @@
package com.toyshop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ToyShopApplication {
public static void main(String[] args) {
SpringApplication.run(ToyShopApplication.class, args);
}
}

View File

@@ -0,0 +1,25 @@
package com.toyshop.config;
import com.toyshop.entity.User;
import com.toyshop.entity.UserRole;
import com.toyshop.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class DataInitializer {
@Bean
public CommandLineRunner initAdmin(UserRepository userRepository, PasswordEncoder passwordEncoder) {
return args -> {
if (userRepository.countByRole(UserRole.ADMIN) == 0) {
User admin = new User();
admin.setUsername("admin");
admin.setPassword(passwordEncoder.encode("admin123"));
admin.setRole(UserRole.ADMIN);
userRepository.save(admin);
}
};
}
}

View File

@@ -0,0 +1,26 @@
package com.toyshop.config;
import com.toyshop.dto.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<?> handleIllegalArgument(IllegalArgumentException ex) {
return ApiResponse.fail(ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<?> handleValidation(MethodArgumentNotValidException ex) {
String msg = ex.getBindingResult().getAllErrors().isEmpty()
? "参数错误"
: ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
return ApiResponse.fail(msg);
}
}

View File

@@ -0,0 +1,70 @@
package com.toyshop.config;
import com.toyshop.security.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final com.toyshop.security.CustomUserDetailsService userDetailsService;
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
com.toyshop.security.CustomUserDetailsService userDetailsService) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
this.userDetailsService = userDetailsService;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**", "/api/public/**").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public AuthenticationManager authenticationManager() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(provider);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("*"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}

View File

@@ -0,0 +1,49 @@
package com.toyshop.controller;
import com.toyshop.dto.*;
import com.toyshop.entity.User;
import com.toyshop.entity.UserRole;
import com.toyshop.repository.UserRepository;
import com.toyshop.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthService authService;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public AuthController(AuthService authService, UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.authService = authService;
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@PostMapping("/register")
public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
String token = authService.register(request);
return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername()));
}
@PostMapping("/login")
public ApiResponse<AuthResponse> login(@Valid @RequestBody AuthRequest request) {
String token = authService.login(request);
return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername()));
}
@PostMapping("/admin/login")
public ApiResponse<AuthResponse> adminLogin(@Valid @RequestBody AuthRequest request) {
User user = userRepository.findByUsername(request.getUsername()).orElseThrow();
if (user.getRole() != UserRole.ADMIN) {
return ApiResponse.fail("非管理员账号");
}
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
return ApiResponse.fail("用户名或密码错误");
}
String token = authService.login(request);
return ApiResponse.ok(new AuthResponse(token, "ADMIN", request.getUsername()));
}
}

View File

@@ -0,0 +1,60 @@
package com.toyshop.controller;
import com.toyshop.dto.ApiResponse;
import com.toyshop.entity.Product;
import com.toyshop.repository.CarouselRepository;
import com.toyshop.repository.NoticeRepository;
import com.toyshop.repository.ProductRepository;
import com.toyshop.repository.CategoryRepository;
import com.toyshop.service.ProductService;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/public")
public class PublicController {
private final ProductService productService;
private final CategoryRepository categoryRepository;
private final ProductRepository productRepository;
private final CarouselRepository carouselRepository;
private final NoticeRepository noticeRepository;
public PublicController(ProductService productService, CategoryRepository categoryRepository,
ProductRepository productRepository, CarouselRepository carouselRepository,
NoticeRepository noticeRepository) {
this.productService = productService;
this.categoryRepository = categoryRepository;
this.productRepository = productRepository;
this.carouselRepository = carouselRepository;
this.noticeRepository = noticeRepository;
}
@GetMapping("/home")
public ApiResponse<Map<String, Object>> home() {
Map<String, Object> data = new HashMap<>();
data.put("carousels", carouselRepository.findAllByOrderBySortOrderAsc());
data.put("notices", noticeRepository.findAll());
data.put("categories", categoryRepository.findAll());
data.put("hot", productService.search(null, null, "sales"));
data.put("newest", productService.search(null, null, null));
return ApiResponse.ok(data);
}
@GetMapping("/products")
public ApiResponse<?> products(@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long categoryId,
@RequestParam(required = false) String sort) {
return ApiResponse.ok(productService.search(keyword, categoryId, sort));
}
@GetMapping("/products/{id}")
public ApiResponse<Map<String, Object>> productDetail(@PathVariable Long id) {
Product product = productRepository.findById(id).orElseThrow();
Map<String, Object> data = new HashMap<>();
data.put("product", product);
data.put("images", productService.getImages(product));
return ApiResponse.ok(data);
}
}

View File

@@ -0,0 +1,219 @@
package com.toyshop.controller.admin;
import com.toyshop.dto.*;
import com.toyshop.entity.*;
import com.toyshop.repository.*;
import com.toyshop.service.ProductService;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {
private final UserRepository userRepository;
private final CategoryRepository categoryRepository;
private final ProductRepository productRepository;
private final ProductImageRepository productImageRepository;
private final OrderRepository orderRepository;
private final CarouselRepository carouselRepository;
private final NoticeRepository noticeRepository;
private final ProductService productService;
public AdminController(UserRepository userRepository, CategoryRepository categoryRepository,
ProductRepository productRepository, ProductImageRepository productImageRepository,
OrderRepository orderRepository, CarouselRepository carouselRepository,
NoticeRepository noticeRepository, ProductService productService) {
this.userRepository = userRepository;
this.categoryRepository = categoryRepository;
this.productRepository = productRepository;
this.productImageRepository = productImageRepository;
this.orderRepository = orderRepository;
this.carouselRepository = carouselRepository;
this.noticeRepository = noticeRepository;
this.productService = productService;
}
@GetMapping("/users")
public ApiResponse<List<User>> users() {
return ApiResponse.ok(userRepository.findAll());
}
@PutMapping("/users/{id}")
public ApiResponse<User> updateUserStatus(@PathVariable Long id, @Valid @RequestBody UserStatusRequest request) {
User user = userRepository.findById(id).orElseThrow();
user.setEnabled(request.getEnabled());
return ApiResponse.ok(userRepository.save(user));
}
@GetMapping("/categories")
public ApiResponse<List<Category>> categories() {
return ApiResponse.ok(categoryRepository.findAll());
}
@PostMapping("/categories")
public ApiResponse<Category> createCategory(@Valid @RequestBody CategoryRequest request) {
if (categoryRepository.existsByName(request.getName())) {
return ApiResponse.fail("分类已存在");
}
Category category = new Category();
category.setName(request.getName());
category.setDescription(request.getDescription());
return ApiResponse.ok(categoryRepository.save(category));
}
@PutMapping("/categories/{id}")
public ApiResponse<Category> updateCategory(@PathVariable Long id, @Valid @RequestBody CategoryRequest request) {
Category category = categoryRepository.findById(id).orElseThrow();
category.setName(request.getName());
category.setDescription(request.getDescription());
return ApiResponse.ok(categoryRepository.save(category));
}
@DeleteMapping("/categories/{id}")
public ApiResponse<?> deleteCategory(@PathVariable Long id) {
categoryRepository.deleteById(id);
return ApiResponse.ok("删除成功", null);
}
@GetMapping("/products")
public ApiResponse<List<Product>> products() {
return ApiResponse.ok(productRepository.findAll());
}
@PostMapping("/products")
public ApiResponse<Product> createProduct(@Valid @RequestBody ProductRequest request) {
Product product = new Product();
product.setName(request.getName());
product.setDescription(request.getDescription());
product.setPrice(request.getPrice());
product.setStock(request.getStock());
product.setAgeRange(request.getAgeRange());
product.setSafetyInfo(request.getSafetyInfo());
product.setOnSale(request.isOnSale());
if (request.getCategoryId() != null) {
product.setCategory(productService.getCategory(request.getCategoryId()));
}
return ApiResponse.ok(productRepository.save(product));
}
@PutMapping("/products/{id}")
public ApiResponse<Product> updateProduct(@PathVariable Long id, @Valid @RequestBody ProductRequest request) {
Product product = productRepository.findById(id).orElseThrow();
product.setName(request.getName());
product.setDescription(request.getDescription());
if (request.getPrice() != null) {
product.setPrice(request.getPrice());
}
if (request.getStock() != null) {
product.setStock(request.getStock());
}
product.setAgeRange(request.getAgeRange());
product.setSafetyInfo(request.getSafetyInfo());
product.setOnSale(request.isOnSale());
if (request.getCategoryId() != null) {
product.setCategory(productService.getCategory(request.getCategoryId()));
}
return ApiResponse.ok(productRepository.save(product));
}
@DeleteMapping("/products/{id}")
public ApiResponse<?> deleteProduct(@PathVariable Long id) {
productRepository.deleteById(id);
return ApiResponse.ok("删除成功", null);
}
@GetMapping("/products/{id}/images")
public ApiResponse<List<ProductImage>> productImages(@PathVariable Long id) {
Product product = productRepository.findById(id).orElseThrow();
return ApiResponse.ok(productImageRepository.findByProduct(product));
}
@PostMapping("/products/{id}/images")
public ApiResponse<ProductImage> addProductImage(@PathVariable Long id, @RequestBody ProductImage body) {
Product product = productRepository.findById(id).orElseThrow();
ProductImage image = new ProductImage();
image.setProduct(product);
image.setUrl(body.getUrl());
image.setSortOrder(body.getSortOrder() == null ? 0 : body.getSortOrder());
return ApiResponse.ok(productImageRepository.save(image));
}
@DeleteMapping("/product-images/{imageId}")
public ApiResponse<?> deleteProductImage(@PathVariable Long imageId) {
productImageRepository.deleteById(imageId);
return ApiResponse.ok("删除成功", null);
}
@GetMapping("/orders")
public ApiResponse<List<Order>> orders() {
return ApiResponse.ok(orderRepository.findAll());
}
@PutMapping("/orders/status")
public ApiResponse<Order> updateOrderStatus(@Valid @RequestBody AdminOrderUpdateRequest request) {
Order order = orderRepository.findById(request.getOrderId()).orElseThrow();
order.setStatus(OrderStatus.valueOf(request.getStatus()));
order.setLogisticsNo(request.getLogisticsNo());
return ApiResponse.ok(orderRepository.save(order));
}
@GetMapping("/carousels")
public ApiResponse<List<Carousel>> carousels() {
return ApiResponse.ok(carouselRepository.findAllByOrderBySortOrderAsc());
}
@PostMapping("/carousels")
public ApiResponse<Carousel> createCarousel(@Valid @RequestBody CarouselRequest request) {
Carousel carousel = new Carousel();
carousel.setImageUrl(request.getImageUrl());
carousel.setLinkUrl(request.getLinkUrl());
carousel.setSortOrder(request.getSortOrder());
return ApiResponse.ok(carouselRepository.save(carousel));
}
@PutMapping("/carousels/{id}")
public ApiResponse<Carousel> updateCarousel(@PathVariable Long id, @Valid @RequestBody CarouselRequest request) {
Carousel carousel = carouselRepository.findById(id).orElseThrow();
carousel.setImageUrl(request.getImageUrl());
carousel.setLinkUrl(request.getLinkUrl());
carousel.setSortOrder(request.getSortOrder());
return ApiResponse.ok(carouselRepository.save(carousel));
}
@DeleteMapping("/carousels/{id}")
public ApiResponse<?> deleteCarousel(@PathVariable Long id) {
carouselRepository.deleteById(id);
return ApiResponse.ok("删除成功", null);
}
@GetMapping("/notices")
public ApiResponse<List<Notice>> notices() {
return ApiResponse.ok(noticeRepository.findAll());
}
@PostMapping("/notices")
public ApiResponse<Notice> createNotice(@Valid @RequestBody NoticeRequest request) {
Notice notice = new Notice();
notice.setTitle(request.getTitle());
notice.setContent(request.getContent());
return ApiResponse.ok(noticeRepository.save(notice));
}
@PutMapping("/notices/{id}")
public ApiResponse<Notice> updateNotice(@PathVariable Long id, @Valid @RequestBody NoticeRequest request) {
Notice notice = noticeRepository.findById(id).orElseThrow();
notice.setTitle(request.getTitle());
notice.setContent(request.getContent());
return ApiResponse.ok(noticeRepository.save(notice));
}
@DeleteMapping("/notices/{id}")
public ApiResponse<?> deleteNotice(@PathVariable Long id) {
noticeRepository.deleteById(id);
return ApiResponse.ok("删除成功", null);
}
}

View File

@@ -0,0 +1,176 @@
package com.toyshop.controller.user;
import com.toyshop.dto.*;
import com.toyshop.entity.*;
import com.toyshop.repository.*;
import com.toyshop.service.*;
import jakarta.validation.Valid;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/user")
public class UserController {
private final UserService userService;
private final UserRepository userRepository;
private final AddressRepository addressRepository;
private final CartService cartService;
private final OrderService orderService;
private final OrderRepository orderRepository;
private final OrderItemRepository orderItemRepository;
private final PasswordEncoder passwordEncoder;
public UserController(UserService userService, UserRepository userRepository, AddressRepository addressRepository,
CartService cartService, OrderService orderService, OrderRepository orderRepository,
OrderItemRepository orderItemRepository, PasswordEncoder passwordEncoder) {
this.userService = userService;
this.userRepository = userRepository;
this.addressRepository = addressRepository;
this.cartService = cartService;
this.orderService = orderService;
this.orderRepository = orderRepository;
this.orderItemRepository = orderItemRepository;
this.passwordEncoder = passwordEncoder;
}
@GetMapping("/profile")
public ApiResponse<User> profile() {
User user = userService.getCurrentUser();
user.setPassword("***");
return ApiResponse.ok(user);
}
@PutMapping("/profile")
public ApiResponse<User> updateProfile(@RequestBody User body) {
User user = userService.getCurrentUser();
user.setPhone(body.getPhone());
user.setEmail(body.getEmail());
user.setAvatar(body.getAvatar());
userRepository.save(user);
user.setPassword("***");
return ApiResponse.ok(user);
}
@PutMapping("/password")
public ApiResponse<?> changePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
User user = userService.getCurrentUser();
if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
return ApiResponse.fail("原密码错误");
}
user.setPassword(passwordEncoder.encode(newPassword));
userRepository.save(user);
return ApiResponse.ok("修改成功", null);
}
@GetMapping("/addresses")
public ApiResponse<List<Address>> addresses() {
User user = userService.getCurrentUser();
return ApiResponse.ok(addressRepository.findByUser(user));
}
@PostMapping("/addresses")
public ApiResponse<Address> addAddress(@Valid @RequestBody AddressRequest request) {
User user = userService.getCurrentUser();
Address address = new Address();
address.setUser(user);
address.setReceiverName(request.getReceiverName());
address.setReceiverPhone(request.getReceiverPhone());
address.setDetail(request.getDetail());
address.setDefault(request.isDefault());
return ApiResponse.ok(addressRepository.save(address));
}
@PutMapping("/addresses/{id}")
public ApiResponse<Address> updateAddress(@PathVariable Long id, @Valid @RequestBody AddressRequest request) {
User user = userService.getCurrentUser();
Address address = addressRepository.findById(id).orElseThrow();
if (!address.getUser().getId().equals(user.getId())) {
return ApiResponse.fail("无权限");
}
address.setReceiverName(request.getReceiverName());
address.setReceiverPhone(request.getReceiverPhone());
address.setDetail(request.getDetail());
address.setDefault(request.isDefault());
return ApiResponse.ok(addressRepository.save(address));
}
@DeleteMapping("/addresses/{id}")
public ApiResponse<?> deleteAddress(@PathVariable Long id) {
User user = userService.getCurrentUser();
Address address = addressRepository.findById(id).orElseThrow();
if (!address.getUser().getId().equals(user.getId())) {
return ApiResponse.fail("无权限");
}
addressRepository.delete(address);
return ApiResponse.ok("删除成功", null);
}
@GetMapping("/cart")
public ApiResponse<List<CartItem>> cartList() {
User user = userService.getCurrentUser();
return ApiResponse.ok(cartService.list(user));
}
@PostMapping("/cart")
public ApiResponse<?> addToCart(@Valid @RequestBody CartItemRequest request) {
User user = userService.getCurrentUser();
cartService.add(user, request.getProductId(), request.getQuantity());
return ApiResponse.ok("加入成功", null);
}
@PutMapping("/cart/{itemId}")
public ApiResponse<?> updateCart(@PathVariable Long itemId, @RequestBody CartItemRequest request) {
User user = userService.getCurrentUser();
cartService.update(user, itemId, request.getQuantity());
return ApiResponse.ok("更新成功", null);
}
@DeleteMapping("/cart/{itemId}")
public ApiResponse<?> deleteCart(@PathVariable Long itemId) {
User user = userService.getCurrentUser();
cartService.remove(user, itemId);
return ApiResponse.ok("删除成功", null);
}
@PostMapping("/orders")
public ApiResponse<Order> createOrder(@Valid @RequestBody OrderCreateRequest request) {
User user = userService.getCurrentUser();
return ApiResponse.ok(orderService.createOrder(user, request.getAddressId()));
}
@GetMapping("/orders")
public ApiResponse<List<Order>> listOrders() {
User user = userService.getCurrentUser();
return ApiResponse.ok(orderService.listOrders(user));
}
@GetMapping("/orders/{id}")
public ApiResponse<Map<String, Object>> orderDetail(@PathVariable Long id) {
User user = userService.getCurrentUser();
Order order = orderRepository.findById(id).orElseThrow();
if (!order.getUser().getId().equals(user.getId())) {
return ApiResponse.fail("无权限");
}
List<OrderItem> items = orderItemRepository.findByOrder(order);
Map<String, Object> data = new HashMap<>();
data.put("order", order);
data.put("items", items);
return ApiResponse.ok(data);
}
@PostMapping("/orders/{id}/pay")
public ApiResponse<?> pay(@PathVariable Long id) {
User user = userService.getCurrentUser();
Order order = orderRepository.findById(id).orElseThrow();
if (!order.getUser().getId().equals(user.getId())) {
return ApiResponse.fail("无权限");
}
order.setStatus(OrderStatus.PENDING_SHIPMENT);
orderRepository.save(order);
return ApiResponse.ok("支付成功", null);
}
}

View File

@@ -0,0 +1,22 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
public class AddressRequest {
@NotBlank
private String receiverName;
@NotBlank
private String receiverPhone;
@NotBlank
private String detail;
private boolean isDefault;
public String getReceiverName() { return receiverName; }
public void setReceiverName(String receiverName) { this.receiverName = receiverName; }
public String getReceiverPhone() { return receiverPhone; }
public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; }
public String getDetail() { return detail; }
public void setDetail(String detail) { this.detail = detail; }
public boolean isDefault() { return isDefault; }
public void setDefault(boolean aDefault) { isDefault = aDefault; }
}

View File

@@ -0,0 +1,19 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class AdminOrderUpdateRequest {
@NotNull
private Long orderId;
@NotBlank
private String status;
private String logisticsNo;
public Long getOrderId() { return orderId; }
public void setOrderId(Long orderId) { this.orderId = orderId; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getLogisticsNo() { return logisticsNo; }
public void setLogisticsNo(String logisticsNo) { this.logisticsNo = logisticsNo; }
}

View File

@@ -0,0 +1,34 @@
package com.toyshop.dto;
public class ApiResponse<T> {
private boolean success;
private String message;
private T data;
public ApiResponse() {}
public ApiResponse(boolean success, String message, T data) {
this.success = success;
this.message = message;
this.data = data;
}
public static <T> ApiResponse<T> ok(T data) {
return new ApiResponse<>(true, "ok", data);
}
public static <T> ApiResponse<T> ok(String message, T data) {
return new ApiResponse<>(true, message, data);
}
public static <T> ApiResponse<T> fail(String message) {
return new ApiResponse<>(false, message, null);
}
public boolean isSuccess() { return success; }
public void setSuccess(boolean success) { this.success = success; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public T getData() { return data; }
public void setData(T data) { this.data = data; }
}

View File

@@ -0,0 +1,15 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
public class AuthRequest {
@NotBlank
private String username;
@NotBlank
private String password;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}

View File

@@ -0,0 +1,22 @@
package com.toyshop.dto;
public class AuthResponse {
private String token;
private String role;
private String username;
public AuthResponse() {}
public AuthResponse(String token, String role, String username) {
this.token = token;
this.role = role;
this.username = username;
}
public String getToken() { return token; }
public void setToken(String token) { this.token = token; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}

View File

@@ -0,0 +1,17 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
public class CarouselRequest {
@NotBlank
private String imageUrl;
private String linkUrl;
private Integer sortOrder = 0;
public String getImageUrl() { return imageUrl; }
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
public String getLinkUrl() { return linkUrl; }
public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; }
public Integer getSortOrder() { return sortOrder; }
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
}

View File

@@ -0,0 +1,15 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotNull;
public class CartItemRequest {
@NotNull
private Long productId;
@NotNull
private Integer quantity;
public Long getProductId() { return productId; }
public void setProductId(Long productId) { this.productId = productId; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
}

View File

@@ -0,0 +1,14 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
public class CategoryRequest {
@NotBlank
private String name;
private String description;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}

View File

@@ -0,0 +1,15 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
public class NoticeRequest {
@NotBlank
private String title;
@NotBlank
private String content;
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
}

View File

@@ -0,0 +1,11 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotNull;
public class OrderCreateRequest {
@NotNull
private Long addressId;
public Long getAddressId() { return addressId; }
public void setAddressId(Long addressId) { this.addressId = addressId; }
}

View File

@@ -0,0 +1,33 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
import java.math.BigDecimal;
public class ProductRequest {
@NotBlank
private String name;
private Long categoryId;
private String description;
private BigDecimal price;
private Integer stock;
private String ageRange;
private String safetyInfo;
private boolean onSale = true;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Long getCategoryId() { return categoryId; }
public void setCategoryId(Long categoryId) { this.categoryId = categoryId; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
public String getAgeRange() { return ageRange; }
public void setAgeRange(String ageRange) { this.ageRange = ageRange; }
public String getSafetyInfo() { return safetyInfo; }
public void setSafetyInfo(String safetyInfo) { this.safetyInfo = safetyInfo; }
public boolean isOnSale() { return onSale; }
public void setOnSale(boolean onSale) { this.onSale = onSale; }
}

View File

@@ -0,0 +1,21 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotBlank;
public class RegisterRequest {
@NotBlank
private String username;
@NotBlank
private String password;
private String phone;
private String email;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

View File

@@ -0,0 +1,11 @@
package com.toyshop.dto;
import jakarta.validation.constraints.NotNull;
public class UserStatusRequest {
@NotNull
private Boolean enabled;
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
}

View File

@@ -0,0 +1,50 @@
package com.toyshop.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "addresses")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false, length = 50)
private String receiverName;
@Column(nullable = false, length = 20)
private String receiverPhone;
@Column(nullable = false, length = 255)
private String detail;
@Column(nullable = false)
private boolean isDefault = false;
@Column(nullable = false)
private LocalDateTime createdAt;
@PrePersist
public void prePersist() {
createdAt = LocalDateTime.now();
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public String getReceiverName() { return receiverName; }
public void setReceiverName(String receiverName) { this.receiverName = receiverName; }
public String getReceiverPhone() { return receiverPhone; }
public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; }
public String getDetail() { return detail; }
public void setDetail(String detail) { this.detail = detail; }
public boolean isDefault() { return isDefault; }
public void setDefault(boolean aDefault) { isDefault = aDefault; }
public LocalDateTime getCreatedAt() { return createdAt; }
}

View File

@@ -0,0 +1,29 @@
package com.toyshop.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "carousels")
public class Carousel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 255)
private String imageUrl;
@Column(length = 255)
private String linkUrl;
@Column(nullable = false)
private Integer sortOrder = 0;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getImageUrl() { return imageUrl; }
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
public String getLinkUrl() { return linkUrl; }
public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; }
public Integer getSortOrder() { return sortOrder; }
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
}

View File

@@ -0,0 +1,31 @@
package com.toyshop.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "cart_items")
public class CartItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id", nullable = false)
private Product product;
@Column(nullable = false)
private Integer quantity = 1;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Product getProduct() { return product; }
public void setProduct(Product product) { this.product = product; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
}

View File

@@ -0,0 +1,24 @@
package com.toyshop.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 50)
private String name;
@Column(length = 255)
private String description;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}

View File

@@ -0,0 +1,34 @@
package com.toyshop.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "notices")
public class Notice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String title;
@Column(columnDefinition = "text")
private String content;
@Column(nullable = false)
private LocalDateTime createdAt;
@PrePersist
public void prePersist() {
createdAt = LocalDateTime.now();
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public LocalDateTime getCreatedAt() { return createdAt; }
}

View File

@@ -0,0 +1,78 @@
package com.toyshop.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 50)
private String orderNo;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 30)
private OrderStatus status = OrderStatus.PENDING_PAYMENT;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal totalAmount;
@Column(nullable = false, length = 50)
private String receiverName;
@Column(nullable = false, length = 20)
private String receiverPhone;
@Column(nullable = false, length = 255)
private String receiverAddress;
@Column(length = 50)
private String logisticsNo;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime updatedAt;
@PrePersist
public void prePersist() {
LocalDateTime now = LocalDateTime.now();
createdAt = now;
updatedAt = now;
}
@PreUpdate
public void preUpdate() {
updatedAt = LocalDateTime.now();
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getOrderNo() { return orderNo; }
public void setOrderNo(String orderNo) { this.orderNo = orderNo; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public OrderStatus getStatus() { return status; }
public void setStatus(OrderStatus status) { this.status = status; }
public BigDecimal getTotalAmount() { return totalAmount; }
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
public String getReceiverName() { return receiverName; }
public void setReceiverName(String receiverName) { this.receiverName = receiverName; }
public String getReceiverPhone() { return receiverPhone; }
public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; }
public String getReceiverAddress() { return receiverAddress; }
public void setReceiverAddress(String receiverAddress) { this.receiverAddress = receiverAddress; }
public String getLogisticsNo() { return logisticsNo; }
public void setLogisticsNo(String logisticsNo) { this.logisticsNo = logisticsNo; }
public LocalDateTime getCreatedAt() { return createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; }
}

View File

@@ -0,0 +1,37 @@
package com.toyshop.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "order_items")
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", nullable = false)
private Order order;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id", nullable = false)
private Product product;
@Column(nullable = false)
private Integer quantity;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal price;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Order getOrder() { return order; }
public void setOrder(Order order) { this.order = order; }
public Product getProduct() { return product; }
public void setProduct(Product product) { this.product = product; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
}

View File

@@ -0,0 +1,8 @@
package com.toyshop.entity;
public enum OrderStatus {
PENDING_PAYMENT,
PENDING_SHIPMENT,
SHIPPED,
COMPLETED
}

View File

@@ -0,0 +1,82 @@
package com.toyshop.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
private Category category;
@Column(nullable = false, length = 100)
private String name;
@Column(columnDefinition = "text")
private String description;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal price;
@Column(nullable = false)
private Integer stock = 0;
@Column(nullable = false)
private Integer sales = 0;
@Column(length = 50)
private String ageRange;
@Column(length = 255)
private String safetyInfo;
@Column(nullable = false)
private boolean onSale = true;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime updatedAt;
@PrePersist
public void prePersist() {
LocalDateTime now = LocalDateTime.now();
createdAt = now;
updatedAt = now;
}
@PreUpdate
public void preUpdate() {
updatedAt = LocalDateTime.now();
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Category getCategory() { return category; }
public void setCategory(Category category) { this.category = category; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
public Integer getSales() { return sales; }
public void setSales(Integer sales) { this.sales = sales; }
public String getAgeRange() { return ageRange; }
public void setAgeRange(String ageRange) { this.ageRange = ageRange; }
public String getSafetyInfo() { return safetyInfo; }
public void setSafetyInfo(String safetyInfo) { this.safetyInfo = safetyInfo; }
public boolean isOnSale() { return onSale; }
public void setOnSale(boolean onSale) { this.onSale = onSale; }
public LocalDateTime getCreatedAt() { return createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; }
}

View File

@@ -0,0 +1,30 @@
package com.toyshop.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "product_images")
public class ProductImage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id", nullable = false)
private Product product;
@Column(nullable = false, length = 255)
private String url;
@Column(nullable = false)
private Integer sortOrder = 0;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Product getProduct() { return product; }
public void setProduct(Product product) { this.product = product; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public Integer getSortOrder() { return sortOrder; }
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
}

View File

@@ -0,0 +1,71 @@
package com.toyshop.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 50)
private String username;
@Column(nullable = false)
private String password;
@Column(length = 20)
private String phone;
@Column(length = 100)
private String email;
@Column(length = 255)
private String avatar;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private UserRole role = UserRole.USER;
@Column(nullable = false)
private boolean enabled = true;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime updatedAt;
@PrePersist
public void prePersist() {
LocalDateTime now = LocalDateTime.now();
createdAt = now;
updatedAt = now;
}
@PreUpdate
public void preUpdate() {
updatedAt = LocalDateTime.now();
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getAvatar() { return avatar; }
public void setAvatar(String avatar) { this.avatar = avatar; }
public UserRole getRole() { return role; }
public void setRole(UserRole role) { this.role = role; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public LocalDateTime getCreatedAt() { return createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; }
}

View File

@@ -0,0 +1,6 @@
package com.toyshop.entity;
public enum UserRole {
USER,
ADMIN
}

View File

@@ -0,0 +1,10 @@
package com.toyshop.repository;
import com.toyshop.entity.Address;
import com.toyshop.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface AddressRepository extends JpaRepository<Address, Long> {
List<Address> findByUser(User user);
}

View File

@@ -0,0 +1,9 @@
package com.toyshop.repository;
import com.toyshop.entity.Carousel;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CarouselRepository extends JpaRepository<Carousel, Long> {
List<Carousel> findAllByOrderBySortOrderAsc();
}

View File

@@ -0,0 +1,14 @@
package com.toyshop.repository;
import com.toyshop.entity.CartItem;
import com.toyshop.entity.User;
import com.toyshop.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
List<CartItem> findByUser(User user);
Optional<CartItem> findByUserAndProduct(User user, Product product);
void deleteByUser(User user);
}

View File

@@ -0,0 +1,8 @@
package com.toyshop.repository;
import com.toyshop.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository<Category, Long> {
boolean existsByName(String name);
}

View File

@@ -0,0 +1,7 @@
package com.toyshop.repository;
import com.toyshop.entity.Notice;
import org.springframework.data.jpa.repository.JpaRepository;
public interface NoticeRepository extends JpaRepository<Notice, Long> {
}

View File

@@ -0,0 +1,10 @@
package com.toyshop.repository;
import com.toyshop.entity.OrderItem;
import com.toyshop.entity.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface OrderItemRepository extends JpaRepository<OrderItem, Long> {
List<OrderItem> findByOrder(Order order);
}

View File

@@ -0,0 +1,10 @@
package com.toyshop.repository;
import com.toyshop.entity.Order;
import com.toyshop.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByUserOrderByCreatedAtDesc(User user);
}

View File

@@ -0,0 +1,10 @@
package com.toyshop.repository;
import com.toyshop.entity.ProductImage;
import com.toyshop.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProductImageRepository extends JpaRepository<ProductImage, Long> {
List<ProductImage> findByProduct(Product product);
}

View File

@@ -0,0 +1,8 @@
package com.toyshop.repository;
import com.toyshop.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
}

View File

@@ -0,0 +1,11 @@
package com.toyshop.repository;
import com.toyshop.entity.User;
import com.toyshop.entity.UserRole;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
long countByRole(UserRole role);
}

View File

@@ -0,0 +1,29 @@
package com.toyshop.security;
import com.toyshop.entity.User;
import com.toyshop.repository.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
return org.springframework.security.core.userdetails.User
.withUsername(user.getUsername())
.password(user.getPassword())
.roles(user.getRole().name())
.disabled(!user.isEnabled())
.build();
}
}

View File

@@ -0,0 +1,46 @@
package com.toyshop.security;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
private final UserDetailsService userDetailsService;
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, UserDetailsService userDetailsService) {
this.jwtTokenProvider = jwtTokenProvider;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
String token = header.substring(7);
try {
Claims claims = jwtTokenProvider.parseClaims(token);
String username = claims.getSubject();
var userDetails = userDetailsService.loadUserByUsername(username);
var auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (Exception ignored) {
}
}
filterChain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,40 @@
package com.toyshop.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.time.Instant;
import java.util.Date;
@Component
public class JwtTokenProvider {
private final Key key;
private final long expireSeconds;
public JwtTokenProvider(@Value("${app.jwt.secret}") String secret,
@Value("${app.jwt.expire-hours}") long expireHours) {
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
this.expireSeconds = expireHours * 3600L;
}
public String generateToken(String username, String role) {
Instant now = Instant.now();
return Jwts.builder()
.setSubject(username)
.claim("role", role)
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(now.plusSeconds(expireSeconds)))
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
public Claims parseClaims(String token) {
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
}
}

View File

@@ -0,0 +1,51 @@
package com.toyshop.service;
import com.toyshop.dto.AuthRequest;
import com.toyshop.dto.RegisterRequest;
import com.toyshop.entity.User;
import com.toyshop.entity.UserRole;
import com.toyshop.repository.UserRepository;
import com.toyshop.security.JwtTokenProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
private final JwtTokenProvider jwtTokenProvider;
public AuthService(UserRepository userRepository, PasswordEncoder passwordEncoder,
AuthenticationManager authenticationManager, JwtTokenProvider jwtTokenProvider) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authenticationManager = authenticationManager;
this.jwtTokenProvider = jwtTokenProvider;
}
public String register(RegisterRequest request) {
if (userRepository.findByUsername(request.getUsername()).isPresent()) {
throw new IllegalArgumentException("用户名已存在");
}
User user = new User();
user.setUsername(request.getUsername());
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setPhone(request.getPhone());
user.setEmail(request.getEmail());
user.setRole(UserRole.USER);
userRepository.save(user);
return jwtTokenProvider.generateToken(user.getUsername(), user.getRole().name());
}
public String login(AuthRequest request) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
var userDetails = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
var user = userRepository.findByUsername(userDetails.getUsername()).orElseThrow();
return jwtTokenProvider.generateToken(user.getUsername(), user.getRole().name());
}
}

View File

@@ -0,0 +1,53 @@
package com.toyshop.service;
import com.toyshop.entity.*;
import com.toyshop.repository.*;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CartService {
private final CartItemRepository cartItemRepository;
private final ProductRepository productRepository;
public CartService(CartItemRepository cartItemRepository, ProductRepository productRepository) {
this.cartItemRepository = cartItemRepository;
this.productRepository = productRepository;
}
public List<CartItem> list(User user) {
return cartItemRepository.findByUser(user);
}
public void add(User user, Long productId, Integer quantity) {
Product product = productRepository.findById(productId).orElseThrow();
CartItem item = cartItemRepository.findByUserAndProduct(user, product)
.orElseGet(() -> {
CartItem c = new CartItem();
c.setUser(user);
c.setProduct(product);
c.setQuantity(0);
return c;
});
item.setQuantity(item.getQuantity() + quantity);
cartItemRepository.save(item);
}
public void update(User user, Long itemId, Integer quantity) {
CartItem item = cartItemRepository.findById(itemId).orElseThrow();
if (!item.getUser().getId().equals(user.getId())) {
throw new IllegalArgumentException("无权限");
}
item.setQuantity(quantity);
cartItemRepository.save(item);
}
public void remove(User user, Long itemId) {
CartItem item = cartItemRepository.findById(itemId).orElseThrow();
if (!item.getUser().getId().equals(user.getId())) {
throw new IllegalArgumentException("无权限");
}
cartItemRepository.delete(item);
}
}

View File

@@ -0,0 +1,65 @@
package com.toyshop.service;
import com.toyshop.entity.*;
import com.toyshop.repository.*;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final OrderItemRepository orderItemRepository;
private final CartItemRepository cartItemRepository;
private final AddressRepository addressRepository;
public OrderService(OrderRepository orderRepository, OrderItemRepository orderItemRepository,
CartItemRepository cartItemRepository, AddressRepository addressRepository) {
this.orderRepository = orderRepository;
this.orderItemRepository = orderItemRepository;
this.cartItemRepository = cartItemRepository;
this.addressRepository = addressRepository;
}
public Order createOrder(User user, Long addressId) {
Address address = addressRepository.findById(addressId).orElseThrow();
if (!address.getUser().getId().equals(user.getId())) {
throw new IllegalArgumentException("无权限");
}
List<CartItem> cartItems = cartItemRepository.findByUser(user);
if (cartItems.isEmpty()) {
throw new IllegalArgumentException("购物车为空");
}
BigDecimal total = BigDecimal.ZERO;
for (CartItem item : cartItems) {
BigDecimal line = item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
total = total.add(line);
}
Order order = new Order();
order.setOrderNo("T" + UUID.randomUUID().toString().replace("-", "").substring(0, 16));
order.setUser(user);
order.setTotalAmount(total);
order.setReceiverName(address.getReceiverName());
order.setReceiverPhone(address.getReceiverPhone());
order.setReceiverAddress(address.getDetail());
order.setStatus(OrderStatus.PENDING_PAYMENT);
orderRepository.save(order);
for (CartItem item : cartItems) {
OrderItem orderItem = new OrderItem();
orderItem.setOrder(order);
orderItem.setProduct(item.getProduct());
orderItem.setQuantity(item.getQuantity());
orderItem.setPrice(item.getProduct().getPrice());
orderItemRepository.save(orderItem);
}
cartItemRepository.deleteByUser(user);
return order;
}
public List<Order> listOrders(User user) {
return orderRepository.findByUserOrderByCreatedAtDesc(user);
}
}

View File

@@ -0,0 +1,62 @@
package com.toyshop.service;
import com.toyshop.entity.*;
import com.toyshop.repository.*;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import jakarta.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
@Service
public class ProductService {
private final ProductRepository productRepository;
private final ProductImageRepository productImageRepository;
private final CategoryRepository categoryRepository;
public ProductService(ProductRepository productRepository, ProductImageRepository productImageRepository,
CategoryRepository categoryRepository) {
this.productRepository = productRepository;
this.productImageRepository = productImageRepository;
this.categoryRepository = categoryRepository;
}
public List<Product> search(String keyword, Long categoryId, String sort) {
Specification<Product> spec = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
if (keyword != null && !keyword.isBlank()) {
predicates.add(cb.like(root.get("name"), "%" + keyword + "%"));
}
if (categoryId != null) {
predicates.add(cb.equal(root.get("category").get("id"), categoryId));
}
predicates.add(cb.isTrue(root.get("onSale")));
return cb.and(predicates.toArray(new Predicate[0]));
};
Sort sortObj = Sort.by(Sort.Direction.DESC, "createdAt");
if ("price".equalsIgnoreCase(sort)) {
sortObj = Sort.by(Sort.Direction.ASC, "price");
} else if ("sales".equalsIgnoreCase(sort)) {
sortObj = Sort.by(Sort.Direction.DESC, "sales");
}
return productRepository.findAll(spec, sortObj);
}
public List<ProductImage> getImages(Product product) {
return productImageRepository.findByProduct(product);
}
public Product saveProduct(Product product) {
return productRepository.save(product);
}
public Category getCategory(Long id) {
return categoryRepository.findById(id).orElse(null);
}
public List<Category> allCategories() {
return categoryRepository.findAll();
}
}

View File

@@ -0,0 +1,25 @@
package com.toyshop.service;
import com.toyshop.entity.User;
import com.toyshop.repository.UserRepository;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("未登录");
}
String username = authentication.getName();
return userRepository.findByUsername(username).orElseThrow();
}
}

View File

@@ -0,0 +1,20 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/toyshop?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: root
jpa:
hibernate:
ddl-auto: update
open-in-view: false
properties:
hibernate:
format_sql: true
jackson:
time-zone: Asia/Shanghai
server:
port: 8080
app:
jwt:
secret: change-this-secret-for-prod-change-this-secret
expire-hours: 24

126
db/schema.sql Normal file
View File

@@ -0,0 +1,126 @@
CREATE DATABASE IF NOT EXISTS toyshop DEFAULT CHARSET utf8mb4;
USE toyshop;
CREATE TABLE IF NOT EXISTS users (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
phone VARCHAR(20),
email VARCHAR(100),
avatar VARCHAR(255),
role VARCHAR(20) NOT NULL,
enabled TINYINT(1) NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS categories (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL UNIQUE,
description VARCHAR(255)
);
CREATE TABLE IF NOT EXISTS products (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
category_id BIGINT,
name VARCHAR(100) NOT NULL,
description TEXT,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL,
sales INT NOT NULL,
age_range VARCHAR(50),
safety_info VARCHAR(255),
on_sale TINYINT(1) NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (category_id) REFERENCES categories(id)
);
CREATE TABLE IF NOT EXISTS product_images (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
product_id BIGINT NOT NULL,
url VARCHAR(255) NOT NULL,
sort_order INT NOT NULL,
FOREIGN KEY (product_id) REFERENCES products(id)
);
CREATE TABLE IF NOT EXISTS carousels (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
image_url VARCHAR(255) NOT NULL,
link_url VARCHAR(255),
sort_order INT NOT NULL
);
CREATE TABLE IF NOT EXISTS notices (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
content TEXT,
created_at DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS addresses (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL,
receiver_name VARCHAR(50) NOT NULL,
receiver_phone VARCHAR(20) NOT NULL,
detail VARCHAR(255) NOT NULL,
is_default TINYINT(1) NOT NULL,
created_at DATETIME NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS cart_items (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL,
product_id BIGINT NOT NULL,
quantity INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
CREATE TABLE IF NOT EXISTS orders (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
order_no VARCHAR(50) NOT NULL UNIQUE,
user_id BIGINT NOT NULL,
status VARCHAR(30) NOT NULL,
total_amount DECIMAL(10,2) NOT NULL,
receiver_name VARCHAR(50) NOT NULL,
receiver_phone VARCHAR(20) NOT NULL,
receiver_address VARCHAR(255) NOT NULL,
logistics_no VARCHAR(50),
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS order_items (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
order_id BIGINT NOT NULL,
product_id BIGINT NOT NULL,
quantity INT NOT NULL,
price DECIMAL(10,2) NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
INSERT INTO categories (name, description) VALUES
('益智玩具', '启发思维与逻辑'),
('拼装积木', '动手能力训练'),
('毛绒玩具', '柔软安全');
INSERT INTO products (category_id, name, description, price, stock, sales, age_range, safety_info, on_sale, created_at, updated_at) VALUES
(1, '多功能益智盒', '多模块益智训练', 129.00, 100, 10, '3-6岁', 'CCC认证', 1, NOW(), NOW()),
(2, '创意拼装积木', '提升动手与空间感', 89.00, 200, 25, '4-8岁', '环保材质', 1, NOW(), NOW()),
(3, '可爱毛绒熊', '亲子陪伴', 59.00, 150, 30, '2-6岁', '亲肤材质', 1, NOW(), NOW());
INSERT INTO product_images (product_id, url, sort_order) VALUES
(1, 'https://picsum.photos/seed/toy1/600/400', 1),
(2, 'https://picsum.photos/seed/toy2/600/400', 1),
(3, 'https://picsum.photos/seed/toy3/600/400', 1);
INSERT INTO carousels (image_url, link_url, sort_order) VALUES
('https://picsum.photos/seed/banner1/1200/400', '', 1),
('https://picsum.photos/seed/banner2/1200/400', '', 2);
INSERT INTO notices (title, content, created_at) VALUES
('欢迎来到童飞玩具商城', '全场新品上架,欢迎选购。', NOW());

12
frontend/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>童飞玩具购物网站</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

22
frontend/package.json Normal file
View File

@@ -0,0 +1,22 @@
{
"name": "toyshop-frontend",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"ant-design-vue": "^4.1.2",
"axios": "^1.6.7",
"dayjs": "^1.11.10",
"vue": "^3.4.21",
"vue-router": "^4.2.5"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.0.4",
"vite": "^5.2.0"
}
}

3
frontend/src/App.vue Normal file
View File

@@ -0,0 +1,3 @@
<template>
<router-view />
</template>

24
frontend/src/api/index.js Normal file
View File

@@ -0,0 +1,24 @@
import axios from 'axios'
const api = axios.create({
baseURL: 'http://localhost:8080',
timeout: 10000
})
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
api.interceptors.response.use(
(res) => res.data,
(err) => {
const message = err?.response?.data?.message || '请求失败'
return Promise.reject(new Error(message))
}
)
export default api

View File

@@ -0,0 +1,52 @@
<template>
<a-layout style="min-height: 100vh">
<a-layout-sider collapsible>
<div class="logo">后台管理</div>
<a-menu theme="dark" mode="inline" :selectedKeys="[active]">
<a-menu-item key="users" @click="go('/admin/users')">用户管理</a-menu-item>
<a-menu-item key="categories" @click="go('/admin/categories')">分类管理</a-menu-item>
<a-menu-item key="products" @click="go('/admin/products')">商品管理</a-menu-item>
<a-menu-item key="orders" @click="go('/admin/orders')">订单管理</a-menu-item>
<a-menu-item key="carousels" @click="go('/admin/carousels')">轮播图管理</a-menu-item>
<a-menu-item key="notices" @click="go('/admin/notices')">公告管理</a-menu-item>
</a-menu>
</a-layout-sider>
<a-layout>
<a-layout-header class="header">
<a-button type="link" @click="logout">退出</a-button>
</a-layout-header>
<a-layout-content style="margin: 16px">
<router-view />
</a-layout-content>
</a-layout>
</a-layout>
</template>
<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const active = computed(() => route.path.split('/')[2] || 'users')
const go = (path) => router.push(path)
const logout = () => {
localStorage.removeItem('token')
localStorage.removeItem('role')
router.push('/admin/login')
}
</script>
<style scoped>
.logo {
color: #fff;
padding: 16px;
text-align: center;
font-weight: 600;
}
.header {
background: #fff;
text-align: right;
padding: 0 16px;
}
</style>

View File

@@ -0,0 +1,69 @@
<template>
<a-layout>
<a-layout-header class="header">
<div class="logo">童飞玩具购物网站</div>
<a-menu theme="dark" mode="horizontal" :selectedKeys="[active]">
<a-menu-item key="home" @click="go('/')">首页</a-menu-item>
<a-menu-item key="products" @click="go('/products')">商品</a-menu-item>
<a-menu-item key="cart" @click="go('/cart')">购物车</a-menu-item>
<a-menu-item key="orders" @click="go('/orders')">我的订单</a-menu-item>
<a-menu-item key="profile" @click="go('/profile')">个人中心</a-menu-item>
</a-menu>
<div class="actions">
<a-button type="link" v-if="!token" @click="go('/login')">登录</a-button>
<a-button type="link" v-if="!token" @click="go('/register')">注册</a-button>
<a-button type="link" v-if="token" @click="logout">退出</a-button>
</div>
</a-layout-header>
<a-layout-content class="content">
<router-view />
</a-layout-content>
<a-layout-footer class="footer">© 2026 童飞玩具购物网站</a-layout-footer>
</a-layout>
</template>
<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const token = localStorage.getItem('token')
const active = computed(() => {
if (route.path.startsWith('/products')) return 'products'
if (route.path.startsWith('/cart')) return 'cart'
if (route.path.startsWith('/orders')) return 'orders'
if (route.path.startsWith('/profile')) return 'profile'
return 'home'
})
const go = (path) => router.push(path)
const logout = () => {
localStorage.removeItem('token')
localStorage.removeItem('role')
router.push('/')
}
</script>
<style scoped>
.header {
display: flex;
align-items: center;
gap: 24px;
}
.logo {
color: #fff;
font-weight: 600;
}
.actions {
margin-left: auto;
}
.content {
min-height: 80vh;
padding: 24px;
background: #f5f5f5;
}
.footer {
text-align: center;
}
</style>

10
frontend/src/main.js Normal file
View File

@@ -0,0 +1,10 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
const app = createApp(App)
app.use(router)
app.use(Antd)
app.mount('#app')

View File

@@ -0,0 +1,51 @@
<template>
<a-card title="轮播图管理">
<a-form layout="inline">
<a-form-item label="图片URL"><a-input v-model:value="form.imageUrl" /></a-form-item>
<a-form-item label="链接"><a-input v-model:value="form.linkUrl" /></a-form-item>
<a-form-item label="排序"><a-input-number v-model:value="form.sortOrder" /></a-form-item>
<a-button type="primary" @click="create">新增</a-button>
</a-form>
<a-table :dataSource="list" :columns="columns" rowKey="id" style="margin-top: 16px">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-button type="link" danger @click="remove(record)">删除</a-button>
</template>
</template>
</a-table>
</a-card>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import api from '../../api'
const list = ref([])
const form = reactive({ imageUrl: '', linkUrl: '', sortOrder: 0 })
const columns = [
{ title: '图片', dataIndex: 'imageUrl' },
{ title: '链接', dataIndex: 'linkUrl' },
{ title: '排序', dataIndex: 'sortOrder' },
{ title: '操作', key: 'action' }
]
const load = async () => {
const res = await api.get('/api/admin/carousels')
if (res.success) list.value = res.data
}
const create = async () => {
await api.post('/api/admin/carousels', form)
form.imageUrl = ''
form.linkUrl = ''
form.sortOrder = 0
load()
}
const remove = async (record) => {
await api.delete(`/api/admin/carousels/${record.id}`)
load()
}
onMounted(load)
</script>

View File

@@ -0,0 +1,48 @@
<template>
<a-card title="分类管理">
<a-form layout="inline">
<a-form-item label="名称"><a-input v-model:value="form.name" /></a-form-item>
<a-form-item label="描述"><a-input v-model:value="form.description" /></a-form-item>
<a-button type="primary" @click="create">新增</a-button>
</a-form>
<a-table :dataSource="list" :columns="columns" rowKey="id" style="margin-top: 16px">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-button type="link" danger @click="remove(record)">删除</a-button>
</template>
</template>
</a-table>
</a-card>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import api from '../../api'
const list = ref([])
const form = reactive({ name: '', description: '' })
const columns = [
{ title: '名称', dataIndex: 'name' },
{ title: '描述', dataIndex: 'description' },
{ title: '操作', key: 'action' }
]
const load = async () => {
const res = await api.get('/api/admin/categories')
if (res.success) list.value = res.data
}
const create = async () => {
await api.post('/api/admin/categories', form)
form.name = ''
form.description = ''
load()
}
const remove = async (record) => {
await api.delete(`/api/admin/categories/${record.id}`)
load()
}
onMounted(load)
</script>

View File

@@ -0,0 +1,29 @@
<template>
<a-card title="管理员登录" style="max-width: 360px; margin: 80px auto;">
<a-form layout="vertical">
<a-form-item label="用户名"><a-input v-model:value="form.username" /></a-form-item>
<a-form-item label="密码"><a-input-password v-model:value="form.password" /></a-form-item>
<a-button type="primary" block @click="submit">登录</a-button>
</a-form>
</a-card>
</template>
<script setup>
import { reactive } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const router = useRouter()
const form = reactive({ username: 'admin', password: 'admin123' })
const submit = async () => {
const res = await api.post('/api/auth/admin/login', form)
if (res.success) {
localStorage.setItem('token', res.data.token)
localStorage.setItem('role', res.data.role)
message.success('登录成功')
router.push('/admin/users')
}
}
</script>

View File

@@ -0,0 +1,48 @@
<template>
<a-card title="公告管理">
<a-form layout="inline">
<a-form-item label="标题"><a-input v-model:value="form.title" /></a-form-item>
<a-form-item label="内容"><a-input v-model:value="form.content" /></a-form-item>
<a-button type="primary" @click="create">新增</a-button>
</a-form>
<a-table :dataSource="list" :columns="columns" rowKey="id" style="margin-top: 16px">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-button type="link" danger @click="remove(record)">删除</a-button>
</template>
</template>
</a-table>
</a-card>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import api from '../../api'
const list = ref([])
const form = reactive({ title: '', content: '' })
const columns = [
{ title: '标题', dataIndex: 'title' },
{ title: '内容', dataIndex: 'content' },
{ title: '操作', key: 'action' }
]
const load = async () => {
const res = await api.get('/api/admin/notices')
if (res.success) list.value = res.data
}
const create = async () => {
await api.post('/api/admin/notices', form)
form.title = ''
form.content = ''
load()
}
const remove = async (record) => {
await api.delete(`/api/admin/notices/${record.id}`)
load()
}
onMounted(load)
</script>

View File

@@ -0,0 +1,47 @@
<template>
<a-card title="订单管理">
<a-table :dataSource="orders" :columns="columns" rowKey="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-select v-model:value="record.status" style="width: 120px" @change="val => updateStatus(record, val)">
<a-select-option value="PENDING_PAYMENT">待付款</a-select-option>
<a-select-option value="PENDING_SHIPMENT">待发货</a-select-option>
<a-select-option value="SHIPPED">已发货</a-select-option>
<a-select-option value="COMPLETED">已完成</a-select-option>
</a-select>
</template>
<template v-else-if="column.key === 'logistics'">
<a-input v-model:value="record.logisticsNo" @blur="saveLogistics(record)" />
</template>
</template>
</a-table>
</a-card>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import api from '../../api'
const orders = ref([])
const columns = [
{ title: '订单号', dataIndex: 'orderNo' },
{ title: '金额', dataIndex: 'totalAmount' },
{ title: '状态', key: 'status' },
{ title: '物流单号', key: 'logistics' }
]
const load = async () => {
const res = await api.get('/api/admin/orders')
if (res.success) orders.value = res.data
}
const updateStatus = async (record, val) => {
await api.put('/api/admin/orders/status', { orderId: record.id, status: val, logisticsNo: record.logisticsNo })
}
const saveLogistics = async (record) => {
await api.put('/api/admin/orders/status', { orderId: record.id, status: record.status, logisticsNo: record.logisticsNo })
}
onMounted(load)
</script>

View File

@@ -0,0 +1,80 @@
<template>
<a-card title="商品管理">
<a-form layout="inline">
<a-form-item label="名称"><a-input v-model:value="form.name" /></a-form-item>
<a-form-item label="价格"><a-input-number v-model:value="form.price" /></a-form-item>
<a-form-item label="库存"><a-input-number v-model:value="form.stock" /></a-form-item>
<a-form-item label="分类">
<a-select v-model:value="form.categoryId" style="width: 120px" allowClear>
<a-select-option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
</a-select>
</a-form-item>
<a-button type="primary" @click="create">新增</a-button>
</a-form>
<a-table :dataSource="list" :columns="columns" rowKey="id" style="margin-top: 16px">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-button type="link" @click="addImage(record)">图片</a-button>
<a-button type="link" danger @click="remove(record)">删除</a-button>
</template>
</template>
</a-table>
<a-modal v-model:open="imgVisible" title="新增图片" @ok="saveImage">
<a-input v-model:value="imgForm.url" placeholder="图片URL" />
<a-input-number v-model:value="imgForm.sortOrder" style="margin-top: 8px" />
</a-modal>
</a-card>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import api from '../../api'
const list = ref([])
const categories = ref([])
const form = reactive({ name: '', price: 0, stock: 0, categoryId: null })
const columns = [
{ title: '名称', dataIndex: 'name' },
{ title: '价格', dataIndex: 'price' },
{ title: '库存', dataIndex: 'stock' },
{ title: '操作', key: 'action' }
]
const imgVisible = ref(false)
const imgForm = reactive({ productId: null, url: '', sortOrder: 0 })
const load = async () => {
const res = await api.get('/api/admin/products')
if (res.success) list.value = res.data
const res2 = await api.get('/api/admin/categories')
if (res2.success) categories.value = res2.data
}
const create = async () => {
await api.post('/api/admin/products', form)
form.name = ''
form.price = 0
form.stock = 0
form.categoryId = null
load()
}
const remove = async (record) => {
await api.delete(`/api/admin/products/${record.id}`)
load()
}
const addImage = (record) => {
imgForm.productId = record.id
imgForm.url = ''
imgForm.sortOrder = 0
imgVisible.value = true
}
const saveImage = async () => {
await api.post(`/api/admin/products/${imgForm.productId}/images`, imgForm)
imgVisible.value = false
}
onMounted(load)
</script>

View File

@@ -0,0 +1,35 @@
<template>
<a-card title="用户管理">
<a-table :dataSource="users" :columns="columns" rowKey="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-switch :checked="record.enabled" @change="val => updateStatus(record, val)" />
</template>
</template>
</a-table>
</a-card>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import api from '../../api'
const users = ref([])
const columns = [
{ title: '用户名', dataIndex: 'username' },
{ title: '角色', dataIndex: 'role' },
{ title: '状态', key: 'status' }
]
const load = async () => {
const res = await api.get('/api/admin/users')
if (res.success) users.value = res.data
}
const updateStatus = async (record, val) => {
await api.put(`/api/admin/users/${record.id}`, { enabled: val })
load()
}
onMounted(load)
</script>

View File

@@ -0,0 +1,54 @@
<template>
<a-card title="购物车">
<a-table :dataSource="items" :columns="columns" rowKey="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'product'">
{{ record.product.name }}
</template>
<template v-else-if="column.key === 'quantity'">
<a-input-number :min="1" v-model:value="record.quantity" @change="val => updateQuantity(record, val)" />
</template>
<template v-else-if="column.key === 'price'">
{{ record.product.price }}
</template>
<template v-else-if="column.key === 'action'">
<a-button type="link" danger @click="remove(record)">删除</a-button>
</template>
</template>
</a-table>
<a-button type="primary" style="margin-top: 16px" @click="goCheckout">去结算</a-button>
</a-card>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const router = useRouter()
const items = ref([])
const columns = [
{ title: '商品', key: 'product' },
{ title: '数量', key: 'quantity' },
{ title: '单价', key: 'price' },
{ title: '操作', key: 'action' }
]
const load = async () => {
const res = await api.get('/api/user/cart')
if (res.success) items.value = res.data
}
const updateQuantity = async (record, val) => {
await api.put(`/api/user/cart/${record.id}`, { productId: record.product.id, quantity: val })
}
const remove = async (record) => {
await api.delete(`/api/user/cart/${record.id}`)
load()
}
const goCheckout = () => router.push('/checkout')
onMounted(load)
</script>

View File

@@ -0,0 +1,38 @@
<template>
<a-card title="订单确认">
<a-list :data-source="addresses">
<template #renderItem="{ item }">
<a-list-item>
<a-radio v-model:checked="selected" :value="item.id">
{{ item.receiverName }} {{ item.receiverPhone }} {{ item.detail }}
</a-radio>
</a-list-item>
</template>
</a-list>
<a-button type="primary" @click="createOrder" :disabled="!selected">提交订单</a-button>
</a-card>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const addresses = ref([])
const selected = ref(null)
const router = useRouter()
const load = async () => {
const res = await api.get('/api/user/addresses')
if (res.success) addresses.value = res.data
}
const createOrder = async () => {
await api.post('/api/user/orders', { addressId: selected.value })
message.success('下单成功')
router.push('/orders')
}
onMounted(load)
</script>

View File

@@ -0,0 +1,80 @@
<template>
<a-spin :spinning="loading">
<a-card title="轮播与公告">
<a-carousel autoplay>
<div v-for="item in home.carousels" :key="item.id" class="banner">
<img :src="item.imageUrl" alt="banner" />
</div>
</a-carousel>
<a-list :data-source="home.notices" style="margin-top: 16px">
<template #renderItem="{ item }">
<a-list-item>{{ item.title }}</a-list-item>
</template>
</a-list>
</a-card>
<a-card title="热门商品" style="margin-top: 16px">
<a-row :gutter="16">
<a-col :span="6" v-for="item in home.hot" :key="item.id">
<a-card hoverable @click="goDetail(item.id)">
<div class="title">{{ item.name }}</div>
<div class="price">{{ item.price }}</div>
</a-card>
</a-col>
</a-row>
</a-card>
<a-card title="新品上架" style="margin-top: 16px">
<a-row :gutter="16">
<a-col :span="6" v-for="item in home.newest" :key="item.id">
<a-card hoverable @click="goDetail(item.id)">
<div class="title">{{ item.name }}</div>
<div class="price">{{ item.price }}</div>
</a-card>
</a-col>
</a-row>
</a-card>
</a-spin>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const loading = ref(false)
const home = reactive({ carousels: [], notices: [], hot: [], newest: [] })
const router = useRouter()
const load = async () => {
loading.value = true
try {
const res = await api.get('/api/public/home')
if (res.success) Object.assign(home, res.data)
} finally {
loading.value = false
}
}
const goDetail = (id) => router.push(`/products/${id}`)
onMounted(load)
</script>
<style scoped>
.banner {
height: 240px;
overflow: hidden;
}
.banner img {
width: 100%;
height: 240px;
object-fit: cover;
}
.title {
font-weight: 600;
}
.price {
color: #f5222d;
}
</style>

View File

@@ -0,0 +1,29 @@
<template>
<a-card title="用户登录" style="max-width: 360px; margin: 0 auto;">
<a-form layout="vertical">
<a-form-item label="用户名"><a-input v-model:value="form.username" /></a-form-item>
<a-form-item label="密码"><a-input-password v-model:value="form.password" /></a-form-item>
<a-button type="primary" block @click="submit">登录</a-button>
</a-form>
</a-card>
</template>
<script setup>
import { reactive } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const router = useRouter()
const form = reactive({ username: '', password: '' })
const submit = async () => {
const res = await api.post('/api/auth/login', form)
if (res.success) {
localStorage.setItem('token', res.data.token)
localStorage.setItem('role', res.data.role)
message.success('登录成功')
router.push('/')
}
}
</script>

View File

@@ -0,0 +1,46 @@
<template>
<a-card title="我的订单">
<a-table :dataSource="orders" :columns="columns" rowKey="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
{{ statusMap[record.status] || record.status }}
</template>
<template v-else-if="column.key === 'action'">
<a-button type="link" v-if="record.status === 'PENDING_PAYMENT'" @click="pay(record)">去支付</a-button>
</template>
</template>
</a-table>
</a-card>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import api from '../../api'
const orders = ref([])
const columns = [
{ title: '订单号', dataIndex: 'orderNo' },
{ title: '金额', dataIndex: 'totalAmount' },
{ title: '状态', key: 'status' },
{ title: '操作', key: 'action' }
]
const statusMap = {
PENDING_PAYMENT: '待付款',
PENDING_SHIPMENT: '待发货',
SHIPPED: '已发货',
COMPLETED: '已完成'
}
const load = async () => {
const res = await api.get('/api/user/orders')
if (res.success) orders.value = res.data
}
const pay = async (record) => {
await api.post(`/api/user/orders/${record.id}/pay`)
load()
}
onMounted(load)
</script>

View File

@@ -0,0 +1,71 @@
<template>
<a-spin :spinning="loading">
<a-card>
<a-row :gutter="16">
<a-col :span="10">
<a-carousel>
<div v-for="img in images" :key="img.id" class="banner">
<img :src="img.url" alt="img" />
</div>
</a-carousel>
</a-col>
<a-col :span="14">
<h2>{{ product.name }}</h2>
<p>{{ product.description }}</p>
<div class="price">{{ product.price }}</div>
<div>库存{{ product.stock }}</div>
<div>适龄{{ product.ageRange }}</div>
<div>安全认证{{ product.safetyInfo }}</div>
<a-space style="margin-top: 16px">
<a-input-number v-model:value="quantity" :min="1" />
<a-button type="primary" @click="addToCart">加入购物车</a-button>
</a-space>
</a-col>
</a-row>
</a-card>
</a-spin>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import api from '../../api'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const product = ref({})
const images = ref([])
const quantity = ref(1)
const load = async () => {
loading.value = true
try {
const res = await api.get(`/api/public/products/${route.params.id}`)
if (res.success) {
product.value = res.data.product
images.value = res.data.images
}
} finally {
loading.value = false
}
}
const addToCart = async () => {
if (!localStorage.getItem('token')) {
router.push('/login')
return
}
await api.post('/api/user/cart', { productId: product.value.id, quantity: quantity.value })
message.success('已加入购物车')
}
onMounted(load)
</script>
<style scoped>
.banner { height: 260px; }
.banner img { width: 100%; height: 260px; object-fit: cover; }
.price { color: #f5222d; font-size: 20px; margin: 8px 0; }
</style>

View File

@@ -0,0 +1,63 @@
<template>
<a-card>
<a-space>
<a-input v-model:value="keyword" placeholder="搜索商品" style="width: 200px" />
<a-select v-model:value="categoryId" placeholder="分类" style="width: 160px" allowClear>
<a-select-option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
</a-select>
<a-select v-model:value="sort" placeholder="排序" style="width: 160px" allowClear>
<a-select-option value="price">价格</a-select-option>
<a-select-option value="sales">销量</a-select-option>
</a-select>
<a-button type="primary" @click="load">搜索</a-button>
</a-space>
</a-card>
<a-row :gutter="16" style="margin-top: 16px">
<a-col :span="6" v-for="item in list" :key="item.id">
<a-card hoverable @click="goDetail(item.id)">
<div class="title">{{ item.name }}</div>
<div class="price">{{ item.price }}</div>
<div class="meta">销量 {{ item.sales }}</div>
</a-card>
</a-col>
</a-row>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const router = useRouter()
const list = ref([])
const categories = ref([])
const keyword = ref('')
const categoryId = ref(null)
const sort = ref(null)
const load = async () => {
const res = await api.get('/api/public/products', {
params: { keyword: keyword.value, categoryId: categoryId.value, sort: sort.value }
})
if (res.success) list.value = res.data
}
const loadCategories = async () => {
const res = await api.get('/api/public/home')
if (res.success) categories.value = res.data.categories
}
const goDetail = (id) => router.push(`/products/${id}`)
onMounted(() => {
load()
loadCategories()
})
</script>
<style scoped>
.title { font-weight: 600; }
.price { color: #f5222d; }
.meta { color: #999; }
</style>

View File

@@ -0,0 +1,68 @@
<template>
<a-card title="个人中心">
<a-form layout="vertical">
<a-form-item label="手机号"><a-input v-model:value="profile.phone" /></a-form-item>
<a-form-item label="邮箱"><a-input v-model:value="profile.email" /></a-form-item>
<a-form-item label="头像URL"><a-input v-model:value="profile.avatar" /></a-form-item>
<a-button type="primary" @click="save">保存</a-button>
</a-form>
</a-card>
<a-card title="收货地址" style="margin-top: 16px">
<a-form layout="inline">
<a-form-item label="姓名"><a-input v-model:value="addr.receiverName" /></a-form-item>
<a-form-item label="电话"><a-input v-model:value="addr.receiverPhone" /></a-form-item>
<a-form-item label="地址"><a-input v-model:value="addr.detail" /></a-form-item>
<a-button type="primary" @click="addAddress">新增</a-button>
</a-form>
<a-list :data-source="addresses" style="margin-top: 16px">
<template #renderItem="{ item }">
<a-list-item>
{{ item.receiverName }} {{ item.receiverPhone }} {{ item.detail }}
<a-button type="link" danger @click="remove(item)">删除</a-button>
</a-list-item>
</template>
</a-list>
</a-card>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import api from '../../api'
const profile = reactive({ phone: '', email: '', avatar: '' })
const addresses = ref([])
const addr = reactive({ receiverName: '', receiverPhone: '', detail: '' })
const load = async () => {
const res = await api.get('/api/user/profile')
if (res.success) {
profile.phone = res.data.phone || ''
profile.email = res.data.email || ''
profile.avatar = res.data.avatar || ''
}
const res2 = await api.get('/api/user/addresses')
if (res2.success) addresses.value = res2.data
}
const save = async () => {
await api.put('/api/user/profile', profile)
message.success('保存成功')
}
const addAddress = async () => {
await api.post('/api/user/addresses', addr)
addr.receiverName = ''
addr.receiverPhone = ''
addr.detail = ''
load()
}
const remove = async (item) => {
await api.delete(`/api/user/addresses/${item.id}`)
load()
}
onMounted(load)
</script>

View File

@@ -0,0 +1,31 @@
<template>
<a-card title="用户注册" style="max-width: 360px; margin: 0 auto;">
<a-form layout="vertical">
<a-form-item label="用户名"><a-input v-model:value="form.username" /></a-form-item>
<a-form-item label="密码"><a-input-password v-model:value="form.password" /></a-form-item>
<a-form-item label="手机号"><a-input v-model:value="form.phone" /></a-form-item>
<a-form-item label="邮箱"><a-input v-model:value="form.email" /></a-form-item>
<a-button type="primary" block @click="submit">注册</a-button>
</a-form>
</a-card>
</template>
<script setup>
import { reactive } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import api from '../../api'
const router = useRouter()
const form = reactive({ username: '', password: '', phone: '', email: '' })
const submit = async () => {
const res = await api.post('/api/auth/register', form)
if (res.success) {
localStorage.setItem('token', res.data.token)
localStorage.setItem('role', res.data.role)
message.success('注册成功')
router.push('/')
}
}
</script>

View File

@@ -0,0 +1,74 @@
import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../layouts/MainLayout.vue'
import AdminLayout from '../layouts/AdminLayout.vue'
import Home from '../pages/user/Home.vue'
import ProductList from '../pages/user/ProductList.vue'
import ProductDetail from '../pages/user/ProductDetail.vue'
import Cart from '../pages/user/Cart.vue'
import Checkout from '../pages/user/Checkout.vue'
import Orders from '../pages/user/Orders.vue'
import Profile from '../pages/user/Profile.vue'
import Login from '../pages/user/Login.vue'
import Register from '../pages/user/Register.vue'
import AdminLogin from '../pages/admin/AdminLogin.vue'
import AdminUsers from '../pages/admin/AdminUsers.vue'
import AdminCategories from '../pages/admin/AdminCategories.vue'
import AdminProducts from '../pages/admin/AdminProducts.vue'
import AdminOrders from '../pages/admin/AdminOrders.vue'
import AdminCarousels from '../pages/admin/AdminCarousels.vue'
import AdminNotices from '../pages/admin/AdminNotices.vue'
const routes = [
{
path: '/',
component: MainLayout,
children: [
{ path: '', component: Home },
{ path: 'products', component: ProductList },
{ path: 'products/:id', component: ProductDetail },
{ path: 'cart', component: Cart },
{ path: 'checkout', component: Checkout },
{ path: 'orders', component: Orders },
{ path: 'profile', component: Profile },
{ path: 'login', component: Login },
{ path: 'register', component: Register }
]
},
{
path: '/admin/login',
component: AdminLogin
},
{
path: '/admin',
component: AdminLayout,
children: [
{ path: 'users', component: AdminUsers },
{ path: 'categories', component: AdminCategories },
{ path: 'products', component: AdminProducts },
{ path: 'orders', component: AdminOrders },
{ path: 'carousels', component: AdminCarousels },
{ path: 'notices', component: AdminNotices }
]
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token')
const role = localStorage.getItem('role')
if (to.path.startsWith('/admin') && to.path !== '/admin/login') {
if (!token || role !== 'ADMIN') return next('/admin/login')
}
if (['/cart', '/checkout', '/orders', '/profile'].includes(to.path)) {
if (!token) return next('/login')
}
next()
})
export default router

9
frontend/vite.config.js Normal file
View File

@@ -0,0 +1,9 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
port: 5173
}
})

282
开题报告.md Normal file
View File

@@ -0,0 +1,282 @@
# 大连科技学院
# 毕业设计(论文)开题报告
学院 信息科学与技术学院
专业班级 网络工程专升本24-1
学生姓名 赵大可
学生学号 2406490129
指导教师 张旗
导师职称 教授
# 1 选题的意义和研究现状
# 1.1 选题的意义
随着互联网技术的普及与电子商务模式的成熟,已经将网络购物推向了现代消费生活的前沿。无论是淘宝、京东这样的综合性电商巨头,还是众多垂直领域的专业平台,都在深刻地重塑着商品的流通方式与人们的消费习惯。在这样的大背景下,作为儿童成长中重要一环的玩具产业,其市场规模亦在稳步增长。然而,传统的线下销售渠道却日益暴露出其固有的局限性,不仅受到地理位置的束缚,还常常面临着库存积压与信息更新迟缓的双重压力。
于是,玩具行业的线上化转型便成了题中应有之义。然而,眼下的市场现实是,绝大多数玩具销售都依附于大型综合电商平台。这些平台虽然商品琳琅满目,但在专业的筛选机制和导购服务上却常常力有不逮。可以想见,如今的家长在为孩子选购玩具时,早已不是只看“好不好玩”,而是愈发关注其安全性、教育价值和年龄适宜性。这种更加精细化的消费需求,恰恰是综合平台的“大卖场”模式所难以满足的。与此同时,这背后也折射出众多中小玩具生产商和品牌商的困境。对他们而言,缺乏必要的技术能力,再加上高
昂的平台入驻费用,建立有效的线上销售渠道几乎成了一种奢望,其市场竞争力自然备受掣肘。
因此开发一个专注于玩具领域的垂直电商网站——“童飞玩具购物网站”通过B/S浏览器/服务器架构运用Java Web技术构建一个连接优质玩具商家与广大家长的专业平台
对消费者(家长):对于广大家长用户而言,我们致力于打造一个既便捷又值得信赖的玩具选购入口。在我们的网站上,家长可以围绕孩子的年龄、兴趣等个人特征,并结合玩具的安全认证、益智类型等关键维度,对海量商品进行快速筛选,从而精准锁定目标产品。这一过程不仅显著提升了购物效率,更能帮助家长做出更明智的消费决策,有效回应了当下新生代父母对于高品质育儿体验的深切向往。
对玩具商家(尤其是中小商家):对于广大玩具商家,特别是那些长期以来受困于地域限制的中小型品牌而言,本平台则为其开辟了一条全新的发展路径。我们提供了一个成本可控且运营高效的线上展示与销售窗口,商家能够借助便捷的后台系统轻松完成商品管理、订单处理及营销公告等一系列操作。这不仅能帮助他们有效突破地域限制,拓宽客源,还能在提升品牌知名度和产品销量的同时,为自身在激烈的市场博弈中赢得宝贵
的生存与发展空间。
对玩具行业:推动玩具行业的数字化和线上化转型。通过建立一个专业的线上玩具交易平台,可以促进信息流通,优化资源配置,引导行业向更加注重品质、安全和教育价值的方向发展,从而促进行业的整体健康与均衡发展。
# 1.2本课题所涉及问题在国内外设计或研究的现状
# 1.2.1 国内外研究现状
我国电子商务生态已高度成熟,而玩具作为其中的重要构成,其线上销售格局也呈现出综合性平台主导、新兴模式并存的鲜明特点。目前,绝大部分的线上玩具交易量都集中在淘宝/天猫、京东与拼多多这三大巨头平台。具体来看,淘宝/天猫凭借其无与伦比的商品丰富度,构建了一个从国际大牌旗舰店到各类中小商家、手工作坊及潮流玩具店的多元生态,已成为消费者“逛”和发现新奇玩具的主要入口。京东则以其强大的自营体系和卓越的物流效率,牢牢抓住了那些追求正品保障与收货时效的家长群体,使其成为选购品牌玩具的省心之选,这一优势在大促期间尤为凸显。拼多多则另辟蹊径,以极致的性价比和社交裂变玩法,在平价及白牌玩具市场中占据了重要一席,精准满足了价格敏感型消费者的需求。
与此同时一股新的增长力量正在重塑玩具的销售路径——那便是以抖音、小红书、B站为代表的内容电商。“内容种草”结合“直播带货”的模式让母婴博主与玩具测评达人能够以生动直观的方式展现产品魅力消费者在被内容激发兴趣后可直接完成购买整个决策链条也因此变得更为直接和感性。除此之外市场上还活跃着一些更具专业深度的垂直平台例如“孩子王”等母婴连锁品牌它们通过线上APP与线下门店的协同提供经过严格筛选的高品质玩具由此构建了坚实的用户信任壁垒。
这样的市场格局其实也反映了消费者需求的日趋成熟与多元。如今家长在选购玩具时决策天平上除了传统的品牌与价格已越来越多地加入了教育意义、IP属性、安全认证乃至亲子互动性等维度。这就反过来要求所有平台和商家都必须提供更为丰富、透明的商品信息。综上所述国内玩具电商市场是一个由综合平台领跑内容电商与垂直平台协同发展、竞争激烈的多元化生态。对于任何意欲进入这一赛道的新玩家而言找到差异化的独特定位将是其谋求生存与发展的关键所在。
在国外电子商务市场起步早已进入高度成熟和细分的阶段玩具作为儿童消费市场的重要组成部分其线上销售模式也经历了从综合平台到垂直深耕的演变。以亚马逊Amazon为首的全球性电商巨头凭借其雄厚的技术实力、高效的物流体系和庞大的用
户基础,成为玩具销售的主要渠道,但其“大而全”的模式也存在局限性,即商品信息繁
杂,难以满足家长对玩具教育价值、材质安全等更深层次的个性化筛选需求。与此同时,
许多传统的国际玩具零售商如乐高LEGO、孩之宝Hasbro也成功转型线上
立了强大的官方B2C网站这些网站不仅是销售渠道更是品牌文化和用户社区的延伸
通过内容生态来增强用户粘性。更为引人注目的是,近年来涌现出一批专注于特定品类
或理念的垂直电商平台。例如美国的Fat Brain Toys以其强大的产品筛选系统脱颖而出
允许用户根据精细动作、逻辑思维等具体技能发展目标来寻找益智玩具,专业性极强;而
高端儿童精品买手电商Maisonette则通过专业的买手团队精选全球高品质、设计独特的
玩具,并强调内容驱动和生活方式引领。在技术应用层面,这些先进平台普遍采用响应式
设计以确保跨设备体验的一致性并积极探索个性化推荐、AR试玩、订阅制玩具盒子等
创新模式,旨在不断提升用户参与度和复购率。
综合梳理国内外的研究动态不难发现,电子商务平台在技术架构与开发范式上已然
十分成熟。一个明显的趋势是,国外的玩具电商正朝着专业化、内容化与精细化的路径深
化, 它们通过诸如技能筛选这类高度定制化的功能, 或是引领生活方式的内容生态, 来构
建并维系用户粘性。反观国内市场,尽管体量庞大,但在兼具专业导购能力的垂直玩具电
商领域,仍存在可观的探索空间。本课题正是在这一背景下展开,其核心目标在于将成熟
的Web技术与玩具行业的特定需求进行深度融合以期填补当前市场的空白从而打造
一个功能完善、体验友好且富有专业特色的玩具购物平台,其市场需求和实践价值也因
此而十分明确。
# 2.1 要设计或研究的主要内容方案论证分析
# 2.1.1 主要研究内容
本课题的研究核心将聚焦于“童飞玩具购物网站”的设计与实现。我们观察到当前的玩具电商市场普遍存在信息过载的困扰用户往往难以高效地筛选出真正契合教育意义与适龄需求的玩具。面对这一痛点本研究致力于融合现代Web技术与先进的电商设计理念旨在构建一个功能完善、体验优良并具备专业导购特色的玩具购物平台具体功能模块如下
# 1用户功能
用户模块:
1. 注册与登录:提供用户注册账号、登录和退出功能。
2. 个人中心:用户可以查看和修改个人基本信息、管理收货地址、修改密码。
3. 我的订单:用户可以查看历史订单列表、订单详情以及订单的实时状态(如待付
款、待发货、已发货、已完成)。
首页与商品展示模块:
1首页网站的门户展示推荐玩具、新品上架、热门商品、促销活动横幅等。
2. 商品搜索:提供关键词搜索功能,帮助用户快速找到想要的玩具。
3. 商品列表页:按分类展示商品,支持按价格、销量等条件进行排序和筛选。
4. 商品详情页:展示单个玩具的详细信息,包括多角度图片、描述、规格参数、价格库存以及用户评价。
# 购物流程模块:
1. 购物车:用户可以将心仪的商品加入购物车,并能在购物车中修改商品数量或删除商品。
2. 订单确认:从购物车进入结算,用户在此页面确认购买的商品、选择收货地址、查看总金额。
3. 在线支付:用户结算时引导用户完成在线付款。
# 2管理员功能
管理员登录模块:提供管理员专用的登录入口。
用户管理模块:管理员可以查看所有注册用户的列表,并能对特定用户进行账户管理(如禁用或启用账户)。
# 商品管理模块:
1. 商品信息管理:管理员可以进行商品的上架(新增)、编辑、下架和删除操作。
2. 商品分类管理:管理员可以对网站的商品分类进行增、删、改、查。
# 订单管理模块:
1. 管理员可以查看所有用户的订单列表, 按条件 (如订单号、用户、时间) 搜索订单
2. 可以修改订单状态,例如将“待发货”更新为“已发货”并填写物流信息。
内容与系统管理模块:
1. 轮播图管理:管理员可以更换首页的轮播广告图。
2. 公告管理:发布网站公告或促销信息
![image](https://cdn-mineru.openxlab.org.cn/result/2026-01-13/9b68e32e-0ef5-4a29-aab9-9a45eb623701/a97bf11b3e8e6613cc6272be672bda1bad2ab36edd942337b107b74c7c841657.jpg)
图1总体功能图
# 2.1.2 研究方案及可行性分析
本课题旨在打造一个集内容导购、智能推荐与在线销售于一体的“童飞玩具购物网站”,以应对现代家长面对海量玩具信息时的“选择焦虑”。其核心特色在于深耕儿童益智玩具垂直领域,通过专业测评与专家专栏,结合智能推荐算法,为家长提供科学的购买决
策支持。为实现此目标系统将采用前后端分离的模块化架构前端基于Vue构建后端使用Spring Boot和MySQL确保稳定与高效。最终本项目期望交付一个稳定、安全的平台探索“产品销售”与“教育服务”深度融合的新零售模式推动行业向专业化、内容化方向转型。
# 2.1.3 可行性分析
# (1) 技术可行性
本项目选用的技术栈均为当前业界主流且成熟的技术。SpringBoot凭借其简化的配置、强大的生态和微服务友好性是Java后端开发的首选框架Vue.js则以其轻量、易学、组件化的特点在前端领域广受欢迎。MySQL作为关系型数据库性能稳定且拥有庞大的用户基础。这些技术的开源社区活跃相关文档、教程和解决方案非常丰富开发过程中遇到的技术难题基本都能找到有效的解决方法因此在技术上完全可行。
# (2) 经济可行性
本项目在经济投入上具有极高的可行性。核心的开发工具如IntelliJIDEA社区版VSCode、JDK、Node.js、MySQL社区版等均为免费软件。项目开发阶段仅需一台性能中等的个人电脑即可满足需求。项目部署阶段可以选用云服务商提供的低成本或免费试
用的云服务器和数据库服务,前期运营成本极低。因此,该项目无需大量的资金投入,在经济上是完全可行的。
# (3) 社会可行性
本系统可以满足现代家庭对高质量、个性化、教育化玩具的强烈需求,推动传统玩具零售向内容化、专业化的新零售方向发展。从社会可行性来看,系统能够显著提高家长为孩子选购玩具的效率和准确性,缓解普遍存在的“育儿选择焦虑”,增强用户在育儿消费过程中的满意度和获得感,具有较大的社会价值。
# 2.2本课题选题特色及预期的目标
本课题的独特之处在于,它并未走泛化电商平台的老路,而是将目光精准投向儿童益智玩具这一垂直细分领域,打造了一个融内容导购、智能推荐与在线销售为一体的专业化服务网站。其核心创新在于采用了内容驱动的导购模式,借助专家测评与智能算法,真正将家长从纷繁的信息海洋中解放出来,辅助其做出更为科学、高效的购买决策。与此同时,系统后台也为运营方配备了数据驱动的精细化管理工具,并依托其模块化设计,为未来的技术扩展奠定了坚实的基础。
本课题旨在实现玩具选购与家庭教育服务的智能化、个性化。我们将通过优化服务
流程,提升用户在线体验与满意度;并借助精准推荐与优质内容,将平台打造为家长的
“育儿助手”,切实提升其育儿效能。最终,本项目希望探索一种“产品销售”与“教育
服务”深度融合的新零售模式,推动儿童玩具行业向专业化、内容化的方向转型升级。
# 2.3 本课题实施计划
<table><tr><td>周数</td><td>进度计划</td></tr><tr><td>第1周</td><td>确定毕业设计题目,在网络上对“宠物医院管理平台”进行调研</td></tr><tr><td>第2周</td><td>根据前期的调研情况,查阅相关资料完成开题报告撰写</td></tr><tr><td>第3周</td><td>选择与课题相关的外文文献,完成外文翻译。进行前期资料自查,进行系统可行性分析和需求分析</td></tr><tr><td>第4周</td><td>完成毕设前期检查。依据系统功能需求和业务流程分析,完成用例图和用例说明</td></tr><tr><td>第5周</td><td>进行系统分析,以用例图为基础进行类图、活动图和顺序图的绘制,确保系统的一致性和可维护性</td></tr><tr><td>第6周</td><td>完成数据库设计、界面设计,根据反馈意见进行修改</td></tr><tr><td>第7周</td><td>系统实现,按功能模块进行编码</td></tr><tr><td>第8周</td><td>完成毕设中期检查。系统实现,按功能模块进行编码</td></tr><tr><td>第9周</td><td>系统测试,测试本系统各业务功能运行是否正常,验证功能需求是否都符合规范要求。完成论文主体部分</td></tr><tr><td>第10周</td><td>按照系统测试结果修改代码完善功能,并完成论文剩余相关内容编写</td></tr><tr><td>第11周</td><td>提交论文初稿,根据反馈意见修改论文</td></tr><tr><td>第12周</td><td>继续修改论文,完成论文查重稿定稿。检查系统功能,为软件验收做好准备</td></tr><tr><td>第13周</td><td>进行软件验收,参加校级论文查重,根据论文内容制作答辩PPT</td></tr></table>
第14周 进行毕业设计答辩,并按照答辩组意见修改论文定稿,完成毕设资料存档
# 3 主要参考文献
[1].周贵香.面向纺织图案设计的纹样资源网站设计研究与实践[D].湖南大学,2023.
[2].张曰花.基于JavaWeb的山东地方特色产品销售网站设计[J].现代信息科技,2025,9(04),118-123.
[3].詹丽红.基于Web前端的化工企业网站设计研究——评《HTML5移动Web开发》[J].应用化工,2024,53(09),2260.
[4].刘靓丽.基于PHP技术的动态网页设计和实现[J].科学技术创新,2025,(17),104-107.
[5].王燕.基于PHP的内容管理系统设计与实现[J].集成电路应用,2025,42(08),194-195.
[6].赵停停.基于MySQL数据库技术的Web动态网页设计研究[J].信息与电脑(理论版),20 23,35(17),174-176.
[7].刘靓丽. HTML5 与 CSS3 在网页前端设计优化中的应用研究[J]. 电脑知识与技术, 2025, 21(22), 51-53.
[8].杨明.基于JavaScript的商城网页前端购物车功能设计[J].信息脑,2025,37(11),118-120.
[9].翟宝峰,邓明亮. HTML5+CSS3 网页设计基础与实战[M].人民邮电出版社,2024,250.
[10].张晓颖,石磊. Web 交互界面设计与制作[M].人民邮电出版社:2024,449.
[11].孙文江,陈义辉. JavaScript 交互式网页设计[M].人民邮电出版社:2023,419.
[12].Gowrigari Sudheer Kumar Reddy, and Pandey Nakul. Responsive Web Development:Web and mobile development with HTML5, CSS3, and performance guide (English Edition). 2024, 10.
指导教师意见:
指导教师:
年月日
教研室意见:
审查结果:口同意开题
□不同意开题
教研室主任:
年月日