diff --git a/README.md b/README.md index e69de29..bc77888 100644 --- a/README.md +++ b/README.md @@ -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` + +## 功能覆盖 +- 用户注册/登录/个人中心/收货地址 +- 商品首页展示/搜索/列表/详情 +- 购物车/订单确认/在线支付(模拟)/订单状态 +- 管理员登录/用户管理/商品与分类管理/订单管理/轮播图/公告管理 diff --git a/backend/pom.xml b/backend/pom.xml new file mode 100644 index 0000000..7d222a8 --- /dev/null +++ b/backend/pom.xml @@ -0,0 +1,64 @@ + + 4.0.0 + com.toyshop + backend + 1.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + 17 + 0.11.5 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + com.mysql + mysql-connector-j + runtime + + + io.jsonwebtoken + jjwt-api + ${jjwt.version} + + + io.jsonwebtoken + jjwt-impl + ${jjwt.version} + runtime + + + io.jsonwebtoken + jjwt-jackson + ${jjwt.version} + runtime + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/backend/src/main/java/com/toyshop/ToyShopApplication.java b/backend/src/main/java/com/toyshop/ToyShopApplication.java new file mode 100644 index 0000000..8a9e377 --- /dev/null +++ b/backend/src/main/java/com/toyshop/ToyShopApplication.java @@ -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); + } +} diff --git a/backend/src/main/java/com/toyshop/config/DataInitializer.java b/backend/src/main/java/com/toyshop/config/DataInitializer.java new file mode 100644 index 0000000..9dbf480 --- /dev/null +++ b/backend/src/main/java/com/toyshop/config/DataInitializer.java @@ -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); + } + }; + } +} diff --git a/backend/src/main/java/com/toyshop/config/RestExceptionHandler.java b/backend/src/main/java/com/toyshop/config/RestExceptionHandler.java new file mode 100644 index 0000000..8d5bfb9 --- /dev/null +++ b/backend/src/main/java/com/toyshop/config/RestExceptionHandler.java @@ -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); + } +} diff --git a/backend/src/main/java/com/toyshop/config/SecurityConfig.java b/backend/src/main/java/com/toyshop/config/SecurityConfig.java new file mode 100644 index 0000000..7b1bf84 --- /dev/null +++ b/backend/src/main/java/com/toyshop/config/SecurityConfig.java @@ -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; + } +} diff --git a/backend/src/main/java/com/toyshop/controller/AuthController.java b/backend/src/main/java/com/toyshop/controller/AuthController.java new file mode 100644 index 0000000..3714d93 --- /dev/null +++ b/backend/src/main/java/com/toyshop/controller/AuthController.java @@ -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 register(@Valid @RequestBody RegisterRequest request) { + String token = authService.register(request); + return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername())); + } + + @PostMapping("/login") + public ApiResponse login(@Valid @RequestBody AuthRequest request) { + String token = authService.login(request); + return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername())); + } + + @PostMapping("/admin/login") + public ApiResponse 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())); + } +} diff --git a/backend/src/main/java/com/toyshop/controller/PublicController.java b/backend/src/main/java/com/toyshop/controller/PublicController.java new file mode 100644 index 0000000..449937c --- /dev/null +++ b/backend/src/main/java/com/toyshop/controller/PublicController.java @@ -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> home() { + Map 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> productDetail(@PathVariable Long id) { + Product product = productRepository.findById(id).orElseThrow(); + Map data = new HashMap<>(); + data.put("product", product); + data.put("images", productService.getImages(product)); + return ApiResponse.ok(data); + } +} diff --git a/backend/src/main/java/com/toyshop/controller/admin/AdminController.java b/backend/src/main/java/com/toyshop/controller/admin/AdminController.java new file mode 100644 index 0000000..4396cb3 --- /dev/null +++ b/backend/src/main/java/com/toyshop/controller/admin/AdminController.java @@ -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> users() { + return ApiResponse.ok(userRepository.findAll()); + } + + @PutMapping("/users/{id}") + public ApiResponse 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> categories() { + return ApiResponse.ok(categoryRepository.findAll()); + } + + @PostMapping("/categories") + public ApiResponse 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 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> products() { + return ApiResponse.ok(productRepository.findAll()); + } + + @PostMapping("/products") + public ApiResponse 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 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> productImages(@PathVariable Long id) { + Product product = productRepository.findById(id).orElseThrow(); + return ApiResponse.ok(productImageRepository.findByProduct(product)); + } + + @PostMapping("/products/{id}/images") + public ApiResponse 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> orders() { + return ApiResponse.ok(orderRepository.findAll()); + } + + @PutMapping("/orders/status") + public ApiResponse 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> carousels() { + return ApiResponse.ok(carouselRepository.findAllByOrderBySortOrderAsc()); + } + + @PostMapping("/carousels") + public ApiResponse 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 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> notices() { + return ApiResponse.ok(noticeRepository.findAll()); + } + + @PostMapping("/notices") + public ApiResponse 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 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); + } +} diff --git a/backend/src/main/java/com/toyshop/controller/user/UserController.java b/backend/src/main/java/com/toyshop/controller/user/UserController.java new file mode 100644 index 0000000..ca36ca6 --- /dev/null +++ b/backend/src/main/java/com/toyshop/controller/user/UserController.java @@ -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 profile() { + User user = userService.getCurrentUser(); + user.setPassword("***"); + return ApiResponse.ok(user); + } + + @PutMapping("/profile") + public ApiResponse 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> addresses() { + User user = userService.getCurrentUser(); + return ApiResponse.ok(addressRepository.findByUser(user)); + } + + @PostMapping("/addresses") + public ApiResponse
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
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> 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 createOrder(@Valid @RequestBody OrderCreateRequest request) { + User user = userService.getCurrentUser(); + return ApiResponse.ok(orderService.createOrder(user, request.getAddressId())); + } + + @GetMapping("/orders") + public ApiResponse> listOrders() { + User user = userService.getCurrentUser(); + return ApiResponse.ok(orderService.listOrders(user)); + } + + @GetMapping("/orders/{id}") + public ApiResponse> 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 items = orderItemRepository.findByOrder(order); + Map 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); + } +} diff --git a/backend/src/main/java/com/toyshop/dto/AddressRequest.java b/backend/src/main/java/com/toyshop/dto/AddressRequest.java new file mode 100644 index 0000000..d6c2987 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/AddressRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/AdminOrderUpdateRequest.java b/backend/src/main/java/com/toyshop/dto/AdminOrderUpdateRequest.java new file mode 100644 index 0000000..af6db7a --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/AdminOrderUpdateRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/ApiResponse.java b/backend/src/main/java/com/toyshop/dto/ApiResponse.java new file mode 100644 index 0000000..ebd76f1 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/ApiResponse.java @@ -0,0 +1,34 @@ +package com.toyshop.dto; + +public class ApiResponse { + 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 ApiResponse ok(T data) { + return new ApiResponse<>(true, "ok", data); + } + + public static ApiResponse ok(String message, T data) { + return new ApiResponse<>(true, message, data); + } + + public static ApiResponse 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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/AuthRequest.java b/backend/src/main/java/com/toyshop/dto/AuthRequest.java new file mode 100644 index 0000000..f5f946c --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/AuthRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/AuthResponse.java b/backend/src/main/java/com/toyshop/dto/AuthResponse.java new file mode 100644 index 0000000..6fb723e --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/AuthResponse.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/CarouselRequest.java b/backend/src/main/java/com/toyshop/dto/CarouselRequest.java new file mode 100644 index 0000000..945626c --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/CarouselRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/CartItemRequest.java b/backend/src/main/java/com/toyshop/dto/CartItemRequest.java new file mode 100644 index 0000000..addbbe1 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/CartItemRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/CategoryRequest.java b/backend/src/main/java/com/toyshop/dto/CategoryRequest.java new file mode 100644 index 0000000..e4835fe --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/CategoryRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/NoticeRequest.java b/backend/src/main/java/com/toyshop/dto/NoticeRequest.java new file mode 100644 index 0000000..20fba69 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/NoticeRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/OrderCreateRequest.java b/backend/src/main/java/com/toyshop/dto/OrderCreateRequest.java new file mode 100644 index 0000000..9471ed3 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/OrderCreateRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/ProductRequest.java b/backend/src/main/java/com/toyshop/dto/ProductRequest.java new file mode 100644 index 0000000..3ae5c87 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/ProductRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/RegisterRequest.java b/backend/src/main/java/com/toyshop/dto/RegisterRequest.java new file mode 100644 index 0000000..fe85b2e --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/RegisterRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/dto/UserStatusRequest.java b/backend/src/main/java/com/toyshop/dto/UserStatusRequest.java new file mode 100644 index 0000000..7a6a517 --- /dev/null +++ b/backend/src/main/java/com/toyshop/dto/UserStatusRequest.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/Address.java b/backend/src/main/java/com/toyshop/entity/Address.java new file mode 100644 index 0000000..3ea2c0c --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/Address.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/Carousel.java b/backend/src/main/java/com/toyshop/entity/Carousel.java new file mode 100644 index 0000000..74b8a8f --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/Carousel.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/CartItem.java b/backend/src/main/java/com/toyshop/entity/CartItem.java new file mode 100644 index 0000000..ea85e15 --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/CartItem.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/Category.java b/backend/src/main/java/com/toyshop/entity/Category.java new file mode 100644 index 0000000..3f9f3dc --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/Category.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/Notice.java b/backend/src/main/java/com/toyshop/entity/Notice.java new file mode 100644 index 0000000..e5c2725 --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/Notice.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/Order.java b/backend/src/main/java/com/toyshop/entity/Order.java new file mode 100644 index 0000000..a4c703c --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/Order.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/OrderItem.java b/backend/src/main/java/com/toyshop/entity/OrderItem.java new file mode 100644 index 0000000..4d36521 --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/OrderItem.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/OrderStatus.java b/backend/src/main/java/com/toyshop/entity/OrderStatus.java new file mode 100644 index 0000000..220b633 --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/OrderStatus.java @@ -0,0 +1,8 @@ +package com.toyshop.entity; + +public enum OrderStatus { + PENDING_PAYMENT, + PENDING_SHIPMENT, + SHIPPED, + COMPLETED +} diff --git a/backend/src/main/java/com/toyshop/entity/Product.java b/backend/src/main/java/com/toyshop/entity/Product.java new file mode 100644 index 0000000..8c04f8d --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/Product.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/ProductImage.java b/backend/src/main/java/com/toyshop/entity/ProductImage.java new file mode 100644 index 0000000..45da6ee --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/ProductImage.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/User.java b/backend/src/main/java/com/toyshop/entity/User.java new file mode 100644 index 0000000..0818435 --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/User.java @@ -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; } +} diff --git a/backend/src/main/java/com/toyshop/entity/UserRole.java b/backend/src/main/java/com/toyshop/entity/UserRole.java new file mode 100644 index 0000000..d7c284c --- /dev/null +++ b/backend/src/main/java/com/toyshop/entity/UserRole.java @@ -0,0 +1,6 @@ +package com.toyshop.entity; + +public enum UserRole { + USER, + ADMIN +} diff --git a/backend/src/main/java/com/toyshop/repository/AddressRepository.java b/backend/src/main/java/com/toyshop/repository/AddressRepository.java new file mode 100644 index 0000000..ff0849f --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/AddressRepository.java @@ -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 { + List
findByUser(User user); +} diff --git a/backend/src/main/java/com/toyshop/repository/CarouselRepository.java b/backend/src/main/java/com/toyshop/repository/CarouselRepository.java new file mode 100644 index 0000000..292db0f --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/CarouselRepository.java @@ -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 { + List findAllByOrderBySortOrderAsc(); +} diff --git a/backend/src/main/java/com/toyshop/repository/CartItemRepository.java b/backend/src/main/java/com/toyshop/repository/CartItemRepository.java new file mode 100644 index 0000000..b40a205 --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/CartItemRepository.java @@ -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 { + List findByUser(User user); + Optional findByUserAndProduct(User user, Product product); + void deleteByUser(User user); +} diff --git a/backend/src/main/java/com/toyshop/repository/CategoryRepository.java b/backend/src/main/java/com/toyshop/repository/CategoryRepository.java new file mode 100644 index 0000000..c3268a0 --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/CategoryRepository.java @@ -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 { + boolean existsByName(String name); +} diff --git a/backend/src/main/java/com/toyshop/repository/NoticeRepository.java b/backend/src/main/java/com/toyshop/repository/NoticeRepository.java new file mode 100644 index 0000000..862eeb2 --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/NoticeRepository.java @@ -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 { +} diff --git a/backend/src/main/java/com/toyshop/repository/OrderItemRepository.java b/backend/src/main/java/com/toyshop/repository/OrderItemRepository.java new file mode 100644 index 0000000..5433c7f --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/OrderItemRepository.java @@ -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 { + List findByOrder(Order order); +} diff --git a/backend/src/main/java/com/toyshop/repository/OrderRepository.java b/backend/src/main/java/com/toyshop/repository/OrderRepository.java new file mode 100644 index 0000000..e5c2592 --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/OrderRepository.java @@ -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 { + List findByUserOrderByCreatedAtDesc(User user); +} diff --git a/backend/src/main/java/com/toyshop/repository/ProductImageRepository.java b/backend/src/main/java/com/toyshop/repository/ProductImageRepository.java new file mode 100644 index 0000000..5fc16e3 --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/ProductImageRepository.java @@ -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 { + List findByProduct(Product product); +} diff --git a/backend/src/main/java/com/toyshop/repository/ProductRepository.java b/backend/src/main/java/com/toyshop/repository/ProductRepository.java new file mode 100644 index 0000000..cdd6401 --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/ProductRepository.java @@ -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, JpaSpecificationExecutor { +} diff --git a/backend/src/main/java/com/toyshop/repository/UserRepository.java b/backend/src/main/java/com/toyshop/repository/UserRepository.java new file mode 100644 index 0000000..9d5ab4d --- /dev/null +++ b/backend/src/main/java/com/toyshop/repository/UserRepository.java @@ -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 { + Optional findByUsername(String username); + long countByRole(UserRole role); +} diff --git a/backend/src/main/java/com/toyshop/security/CustomUserDetailsService.java b/backend/src/main/java/com/toyshop/security/CustomUserDetailsService.java new file mode 100644 index 0000000..686e765 --- /dev/null +++ b/backend/src/main/java/com/toyshop/security/CustomUserDetailsService.java @@ -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(); + } +} diff --git a/backend/src/main/java/com/toyshop/security/JwtAuthenticationFilter.java b/backend/src/main/java/com/toyshop/security/JwtAuthenticationFilter.java new file mode 100644 index 0000000..c7026d8 --- /dev/null +++ b/backend/src/main/java/com/toyshop/security/JwtAuthenticationFilter.java @@ -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); + } +} diff --git a/backend/src/main/java/com/toyshop/security/JwtTokenProvider.java b/backend/src/main/java/com/toyshop/security/JwtTokenProvider.java new file mode 100644 index 0000000..b5133c1 --- /dev/null +++ b/backend/src/main/java/com/toyshop/security/JwtTokenProvider.java @@ -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(); + } +} diff --git a/backend/src/main/java/com/toyshop/service/AuthService.java b/backend/src/main/java/com/toyshop/service/AuthService.java new file mode 100644 index 0000000..a0760f2 --- /dev/null +++ b/backend/src/main/java/com/toyshop/service/AuthService.java @@ -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()); + } +} diff --git a/backend/src/main/java/com/toyshop/service/CartService.java b/backend/src/main/java/com/toyshop/service/CartService.java new file mode 100644 index 0000000..b927b62 --- /dev/null +++ b/backend/src/main/java/com/toyshop/service/CartService.java @@ -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 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); + } +} diff --git a/backend/src/main/java/com/toyshop/service/OrderService.java b/backend/src/main/java/com/toyshop/service/OrderService.java new file mode 100644 index 0000000..685a469 --- /dev/null +++ b/backend/src/main/java/com/toyshop/service/OrderService.java @@ -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 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 listOrders(User user) { + return orderRepository.findByUserOrderByCreatedAtDesc(user); + } +} diff --git a/backend/src/main/java/com/toyshop/service/ProductService.java b/backend/src/main/java/com/toyshop/service/ProductService.java new file mode 100644 index 0000000..2504042 --- /dev/null +++ b/backend/src/main/java/com/toyshop/service/ProductService.java @@ -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 search(String keyword, Long categoryId, String sort) { + Specification spec = (root, query, cb) -> { + List 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 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 allCategories() { + return categoryRepository.findAll(); + } +} diff --git a/backend/src/main/java/com/toyshop/service/UserService.java b/backend/src/main/java/com/toyshop/service/UserService.java new file mode 100644 index 0000000..439c4e6 --- /dev/null +++ b/backend/src/main/java/com/toyshop/service/UserService.java @@ -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(); + } +} diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml new file mode 100644 index 0000000..ad4c609 --- /dev/null +++ b/backend/src/main/resources/application.yml @@ -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 diff --git a/db/schema.sql b/db/schema.sql new file mode 100644 index 0000000..fdf4441 --- /dev/null +++ b/db/schema.sql @@ -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()); diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..1e9341c --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,12 @@ + + + + + + 童飞玩具购物网站 + + +
+ + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..bd91e7d --- /dev/null +++ b/frontend/package.json @@ -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" + } +} diff --git a/frontend/src/App.vue b/frontend/src/App.vue new file mode 100644 index 0000000..7dcf773 --- /dev/null +++ b/frontend/src/App.vue @@ -0,0 +1,3 @@ + diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js new file mode 100644 index 0000000..a5819e7 --- /dev/null +++ b/frontend/src/api/index.js @@ -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 diff --git a/frontend/src/layouts/AdminLayout.vue b/frontend/src/layouts/AdminLayout.vue new file mode 100644 index 0000000..4135f92 --- /dev/null +++ b/frontend/src/layouts/AdminLayout.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/frontend/src/layouts/MainLayout.vue b/frontend/src/layouts/MainLayout.vue new file mode 100644 index 0000000..9a5ff4d --- /dev/null +++ b/frontend/src/layouts/MainLayout.vue @@ -0,0 +1,69 @@ + + + + + diff --git a/frontend/src/main.js b/frontend/src/main.js new file mode 100644 index 0000000..a968469 --- /dev/null +++ b/frontend/src/main.js @@ -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') diff --git a/frontend/src/pages/admin/AdminCarousels.vue b/frontend/src/pages/admin/AdminCarousels.vue new file mode 100644 index 0000000..e6c4247 --- /dev/null +++ b/frontend/src/pages/admin/AdminCarousels.vue @@ -0,0 +1,51 @@ + + + diff --git a/frontend/src/pages/admin/AdminCategories.vue b/frontend/src/pages/admin/AdminCategories.vue new file mode 100644 index 0000000..96645b4 --- /dev/null +++ b/frontend/src/pages/admin/AdminCategories.vue @@ -0,0 +1,48 @@ + + + diff --git a/frontend/src/pages/admin/AdminLogin.vue b/frontend/src/pages/admin/AdminLogin.vue new file mode 100644 index 0000000..1b99f8b --- /dev/null +++ b/frontend/src/pages/admin/AdminLogin.vue @@ -0,0 +1,29 @@ + + + diff --git a/frontend/src/pages/admin/AdminNotices.vue b/frontend/src/pages/admin/AdminNotices.vue new file mode 100644 index 0000000..637d606 --- /dev/null +++ b/frontend/src/pages/admin/AdminNotices.vue @@ -0,0 +1,48 @@ + + + diff --git a/frontend/src/pages/admin/AdminOrders.vue b/frontend/src/pages/admin/AdminOrders.vue new file mode 100644 index 0000000..dd02ee9 --- /dev/null +++ b/frontend/src/pages/admin/AdminOrders.vue @@ -0,0 +1,47 @@ + + + diff --git a/frontend/src/pages/admin/AdminProducts.vue b/frontend/src/pages/admin/AdminProducts.vue new file mode 100644 index 0000000..b59173e --- /dev/null +++ b/frontend/src/pages/admin/AdminProducts.vue @@ -0,0 +1,80 @@ + + + diff --git a/frontend/src/pages/admin/AdminUsers.vue b/frontend/src/pages/admin/AdminUsers.vue new file mode 100644 index 0000000..58c6b51 --- /dev/null +++ b/frontend/src/pages/admin/AdminUsers.vue @@ -0,0 +1,35 @@ + + + diff --git a/frontend/src/pages/user/Cart.vue b/frontend/src/pages/user/Cart.vue new file mode 100644 index 0000000..081d4f2 --- /dev/null +++ b/frontend/src/pages/user/Cart.vue @@ -0,0 +1,54 @@ + + + diff --git a/frontend/src/pages/user/Checkout.vue b/frontend/src/pages/user/Checkout.vue new file mode 100644 index 0000000..c7022de --- /dev/null +++ b/frontend/src/pages/user/Checkout.vue @@ -0,0 +1,38 @@ + + + diff --git a/frontend/src/pages/user/Home.vue b/frontend/src/pages/user/Home.vue new file mode 100644 index 0000000..bf402e7 --- /dev/null +++ b/frontend/src/pages/user/Home.vue @@ -0,0 +1,80 @@ + + + + + diff --git a/frontend/src/pages/user/Login.vue b/frontend/src/pages/user/Login.vue new file mode 100644 index 0000000..3b6efbb --- /dev/null +++ b/frontend/src/pages/user/Login.vue @@ -0,0 +1,29 @@ + + + diff --git a/frontend/src/pages/user/Orders.vue b/frontend/src/pages/user/Orders.vue new file mode 100644 index 0000000..1b8ee3a --- /dev/null +++ b/frontend/src/pages/user/Orders.vue @@ -0,0 +1,46 @@ + + + diff --git a/frontend/src/pages/user/ProductDetail.vue b/frontend/src/pages/user/ProductDetail.vue new file mode 100644 index 0000000..2ebbc1a --- /dev/null +++ b/frontend/src/pages/user/ProductDetail.vue @@ -0,0 +1,71 @@ + + + + + diff --git a/frontend/src/pages/user/ProductList.vue b/frontend/src/pages/user/ProductList.vue new file mode 100644 index 0000000..f3a607b --- /dev/null +++ b/frontend/src/pages/user/ProductList.vue @@ -0,0 +1,63 @@ + + + + + diff --git a/frontend/src/pages/user/Profile.vue b/frontend/src/pages/user/Profile.vue new file mode 100644 index 0000000..7254184 --- /dev/null +++ b/frontend/src/pages/user/Profile.vue @@ -0,0 +1,68 @@ + + + diff --git a/frontend/src/pages/user/Register.vue b/frontend/src/pages/user/Register.vue new file mode 100644 index 0000000..4c4b561 --- /dev/null +++ b/frontend/src/pages/user/Register.vue @@ -0,0 +1,31 @@ + + + diff --git a/frontend/src/router/index.js b/frontend/src/router/index.js new file mode 100644 index 0000000..509371c --- /dev/null +++ b/frontend/src/router/index.js @@ -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 diff --git a/frontend/vite.config.js b/frontend/vite.config.js new file mode 100644 index 0000000..6a8b5f4 --- /dev/null +++ b/frontend/vite.config.js @@ -0,0 +1,9 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +export default defineConfig({ + plugins: [vue()], + server: { + port: 5173 + } +}) diff --git a/开题报告.md b/开题报告.md new file mode 100644 index 0000000..92ec435 --- /dev/null +++ b/开题报告.md @@ -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 本课题实施计划 + +
周数进度计划
第1周确定毕业设计题目,在网络上对“宠物医院管理平台”进行调研
第2周根据前期的调研情况,查阅相关资料完成开题报告撰写
第3周选择与课题相关的外文文献,完成外文翻译。进行前期资料自查,进行系统可行性分析和需求分析
第4周完成毕设前期检查。依据系统功能需求和业务流程分析,完成用例图和用例说明
第5周进行系统分析,以用例图为基础进行类图、活动图和顺序图的绘制,确保系统的一致性和可维护性
第6周完成数据库设计、界面设计,根据反馈意见进行修改
第7周系统实现,按功能模块进行编码
第8周完成毕设中期检查。系统实现,按功能模块进行编码
第9周系统测试,测试本系统各业务功能运行是否正常,验证功能需求是否都符合规范要求。完成论文主体部分
第10周按照系统测试结果修改代码完善功能,并完成论文剩余相关内容编写
第11周提交论文初稿,根据反馈意见修改论文
第12周继续修改论文,完成论文查重稿定稿。检查系统功能,为软件验收做好准备
第13周进行软件验收,参加校级论文查重,根据论文内容制作答辩PPT
+ +第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. + + + +指导教师意见: + +指导教师: + +年月日 + +教研室意见: + +审查结果:口同意开题 + +□不同意开题 + +教研室主任: + +年月日 \ No newline at end of file