初始化

This commit is contained in:
xuelijun
2025-11-04 18:08:36 +08:00
parent 2dff5e25de
commit daa020f1ec
1370 changed files with 127388 additions and 1 deletions

13
ygsx-shop-api/Dockerfile Normal file
View File

@@ -0,0 +1,13 @@
FROM openjdk:17.0.2
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN mkdir -p /opt/projects/mall4j
WORKDIR /opt/projects/mall4j
EXPOSE 8086
ADD ./target/yami-shop-api-0.0.1-SNAPSHOT.jar ./
CMD java -jar -Xms1024m -Xmx1024m -Xmn256m -Xss256k -XX:SurvivorRatio=8 -Dspring.profiles.active=dev yami-shop-api-0.0.1-SNAPSHOT.jar

62
ygsx-shop-api/pom.xml Normal file
View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ygsx-mall</artifactId>
<groupId>com.yami.shop</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ygsx-shop-api</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.yami.shop</groupId>
<artifactId>ygsx-shop-service</artifactId>
<version>${yami.shop.version}</version>
</dependency>
<dependency>
<groupId>com.yami.shop</groupId>
<artifactId>ygsx-shop-security-api</artifactId>
<version>${yami.shop.version}</version>
</dependency>
<dependency>
<groupId>com.yami.shop</groupId>
<artifactId>ygsx-shop-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.15.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,26 @@
package com.yami.shop.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
/**
* @author lgh
*/
@SpringBootApplication
@ComponentScan(basePackages = {"com.yami.shop"})
public class ApiApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
System.out.println("启动成功");
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ApiApplication.class);
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
* https://www.mall4j.com/
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.config;
import cn.hutool.core.lang.Snowflake;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author lanhai
*/
@Configuration
@AllArgsConstructor
public class ApiBeanConfig {
private final ApiConfig apiConfig;
@Bean
public Snowflake snowflake() {
return new Snowflake(apiConfig.getWorkerId(), apiConfig.getDatacenterId());
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 商城配置文件
* @author lgh
*/
@Data
@Component
@PropertySource("classpath:api.properties")
@ConfigurationProperties(prefix = "api")
public class ApiConfig {
/**
* 数据中心ID
*/
private Integer datacenterId;
/**
* 终端ID
*/
private Integer workerId;
/**
* 域名
*/
private String domainName;
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Swagger文档只有在测试环境才会使用
* @author LGH
*/
@Configuration
public class SwaggerConfiguration {
@Bean
public GroupedOpenApi createRestApi() {
return GroupedOpenApi.builder()
.group("接口文档")
.packagesToScan("com.yami.shop.api").build();
}
@Bean
public OpenAPI springShopOpenApi() {
return new OpenAPI()
.info(new Info().title("Mall4j接口文档")
.description("Mall4j接口文档openapi3.0 接口,用于前端对接")
.version("v0.0.1")
.license(new License().name("使用请遵守AGPL3.0授权协议").url("https://www.mall4j.com")));
}
}

View File

@@ -0,0 +1,156 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.dto.UserAddrDto;
import com.yami.shop.bean.app.param.AddrParam;
import com.yami.shop.bean.model.UserAddr;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.UserAddrService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.Date;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/address")
@Tag(name = "地址接口")
@AllArgsConstructor
public class AddrController {
@Autowired
private UserAddrService userAddrService;
/**
* 选择订单配送地址
*/
@GetMapping("/list")
@Operation(summary = "用户地址列表" , description = "获取用户的所有地址信息")
public ServerResponseEntity<List<UserAddrDto>> dvyList() {
String userId = SecurityUtils.getUser().getUserId();
List<UserAddr> userAddrs = userAddrService.list(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId).orderByDesc(UserAddr::getCommonAddr).orderByDesc(UserAddr::getUpdateTime));
return ServerResponseEntity.success(BeanUtil.copyToList(userAddrs, UserAddrDto.class));
}
@PostMapping("/addAddr")
@Operation(summary = "新增用户地址" , description = "新增用户地址")
public ServerResponseEntity<String> addAddr(@Valid @RequestBody AddrParam addrParam) {
String userId = SecurityUtils.getUser().getUserId();
// String userId = "2363e378a8254f968c4296ba4cb764db";
if (addrParam.getAddrId() != null && addrParam.getAddrId() != 0) {
return ServerResponseEntity.showFailMsg("该地址已存在");
}
long addrCount = userAddrService.count(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId));
UserAddr userAddr = BeanUtil.copyProperties(addrParam, UserAddr.class);
if (addrCount == 0) {
userAddr.setCommonAddr(1);
} else {
userAddr.setCommonAddr(0);
}
userAddr.setUserId(userId);
userAddr.setStatus(1);
userAddr.setCreateTime(new Date());
userAddr.setUpdateTime(new Date());
userAddrService.save(userAddr);
if (userAddr.getCommonAddr() == 1) {
// 清除默认地址缓存
userAddrService.removeUserAddrByUserId(0L, userId);
}
return ServerResponseEntity.success("添加地址成功");
}
/**
* 修改订单配送地址
*/
@PutMapping("/updateAddr")
@Operation(summary = "修改订单用户地址" , description = "修改用户地址")
public ServerResponseEntity<String> updateAddr(@Valid @RequestBody AddrParam addrParam) {
String userId = SecurityUtils.getUser().getUserId();
UserAddr dbUserAddr = userAddrService.getUserAddrByUserId(addrParam.getAddrId(), userId);
if (dbUserAddr == null) {
return ServerResponseEntity.showFailMsg("该地址已被删除");
}
UserAddr userAddr = BeanUtil.copyProperties(addrParam, UserAddr.class);
userAddr.setUserId(userId);
userAddr.setUpdateTime(new Date());
userAddrService.updateById(userAddr);
// 清除当前地址缓存
userAddrService.removeUserAddrByUserId(addrParam.getAddrId(), userId);
// 清除默认地址缓存
userAddrService.removeUserAddrByUserId(0L, userId);
return ServerResponseEntity.success("修改地址成功");
}
/**
* 删除订单配送地址
*/
@DeleteMapping("/deleteAddr/{addrId}")
@Operation(summary = "删除订单用户地址" , description = "根据地址id删除用户地址")
@Parameter(name = "addrId", description = "地址ID" , required = true)
public ServerResponseEntity<String> deleteDvy(@PathVariable("addrId") Long addrId) {
String userId = SecurityUtils.getUser().getUserId();
UserAddr userAddr = userAddrService.getUserAddrByUserId(addrId, userId);
if (userAddr == null) {
return ServerResponseEntity.showFailMsg("该地址已被删除");
}
if (userAddr.getCommonAddr() == 1) {
return ServerResponseEntity.showFailMsg("默认地址无法删除");
}
userAddrService.removeById(addrId);
userAddrService.removeUserAddrByUserId(addrId, userId);
return ServerResponseEntity.success("删除地址成功");
}
/**
* 设置默认地址
*/
@PutMapping("/defaultAddr/{addrId}")
@Operation(summary = "设置默认地址" , description = "根据地址id设置默认地址")
public ServerResponseEntity<String> defaultAddr(@PathVariable("addrId") Long addrId) {
String userId = SecurityUtils.getUser().getUserId();
userAddrService.updateDefaultUserAddr(addrId, userId);
userAddrService.removeUserAddrByUserId(0L, userId);
userAddrService.removeUserAddrByUserId(addrId, userId);
return ServerResponseEntity.success("修改地址成功");
}
/**
* 获取地址信息订单配送地址
*/
@GetMapping("/addrInfo/{addrId}")
@Operation(summary = "获取地址信息" , description = "根据地址id获取地址信息")
@Parameter(name = "addrId", description = "地址ID" , required = true)
public ServerResponseEntity<UserAddrDto> addrInfo(@PathVariable("addrId") Long addrId) {
String userId = SecurityUtils.getUser().getUserId();
UserAddr userAddr = userAddrService.getUserAddrByUserId(addrId, userId);
if (userAddr == null) {
throw new YamiShopBindException("该地址已被删除");
}
return ServerResponseEntity.success(BeanUtil.copyProperties(userAddr, UserAddrDto.class));
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import java.util.List;
import com.yami.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yami.shop.bean.model.Area;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
/**
*
* @author lgh on 2018/10/26.
*/
@RestController
@RequestMapping("/p/area")
@Tag(name = "省市区接口")
public class AreaController {
@Autowired
private AreaService areaService;
/**
* 分页获取
*/
@GetMapping("/listByPid")
@Operation(summary = "获取省市区信息" , description = "根据省市区的pid获取地址信息")
@Parameter(name = "pid", description = "省市区的pid(pid为0获取所有省份)" , required = true)
public ServerResponseEntity<List<Area>> listByPid(Long pid){
List<Area> list = areaService.listByPid(pid);
return ServerResponseEntity.success(list);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.yami.shop.bean.app.dto.CategoryDto;
import com.yami.shop.bean.model.Category;
import com.yami.shop.service.CategoryService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import cn.hutool.core.bean.BeanUtil;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/category")
@Tag(name = "分类接口")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 分类信息列表接口
*/
@GetMapping("/categoryInfo")
@Operation(summary = "分类信息列表" , description = "获取所有的产品分类信息顶级分类的parentId为0,默认为顶级分类")
@Parameter(name = "parentId", description = "分类ID", required = false)
public ServerResponseEntity<List<Category>> categoryInfo(@RequestParam(value = "parentId", defaultValue = "0") Long parentId) {
List<Category> categories = categoryService.listByParentId(parentId);
return ServerResponseEntity.success(categories);
}
@GetMapping("/listByProd")
@Operation(summary = "获取商品表中有的分类" , description = "获取商品表中有的分类")
@Parameter(name = "parentId", description = "分类ID", required = false)
public ServerResponseEntity<List<Category>> listByProd(@RequestParam(value = "type", defaultValue = "3") Integer type) {
List<Category> categories = categoryService.listByProd(type);
return ServerResponseEntity.success(categories);
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.yami.shop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yami.shop.bean.app.dto.DeliveryDto;
import com.yami.shop.bean.model.Delivery;
import com.yami.shop.bean.model.Order;
import com.yami.shop.common.util.Json;
import com.yami.shop.service.DeliveryService;
import cn.hutool.http.HttpUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/delivery")
@Tag(name = "查看物流接口")
public class DeliveryController {
@Autowired
private DeliveryService deliveryService;
@Autowired
private OrderService orderService;
/**
* 查看物流接口
*/
@GetMapping("/check")
@Operation(summary = "查看物流" , description = "根据订单号查看物流")
@Parameter(name = "orderNumber", description = "订单号" , required = true)
public ServerResponseEntity<DeliveryDto> checkDelivery(String orderNumber) {
Order order = orderService.getOrderByOrderNumber(orderNumber);
Delivery delivery = deliveryService.getById(order.getDvyId());
String url = delivery.getQueryUrl().replace("{dvyFlowId}", order.getDvyFlowId());
String deliveryJson = HttpUtil.get(url);
DeliveryDto deliveryDto = Json.parseObject(deliveryJson, DeliveryDto.class);
deliveryDto.setDvyFlowId(order.getDvyFlowId());
deliveryDto.setCompanyHomeUrl(delivery.getCompanyHomeUrl());
deliveryDto.setCompanyName(delivery.getDvyName());
return ServerResponseEntity.success(deliveryDto);
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.yami.shop.bean.app.dto.IndexImgDto;
import com.yami.shop.bean.model.IndexImg;
import com.yami.shop.service.IndexImgService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@Tag(name = "首页轮播图接口")
public class IndexImgController {
@Autowired
private IndexImgService indexImgService;
/**
* 首页轮播图接口
*/
@GetMapping("/indexImgs")
@Operation(summary = "首页轮播图" , description = "获取首页轮播图列表信息")
public ServerResponseEntity<List<IndexImgDto>> indexImgs() {
List<IndexImg> indexImgList = indexImgService.listIndexImg();
List<IndexImgDto> indexImgDtos = BeanUtil.copyToList(indexImgList, IndexImgDto.class);
return ServerResponseEntity.success(indexImgDtos);
}
}

View File

@@ -0,0 +1,120 @@
package com.yami.shop.api.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.dto.UserOtherDto;
import com.yami.shop.bean.app.param.CurrencyParam;
import com.yami.shop.bean.model.Invitation;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.InvitationService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.InputStream;
import java.util.Date;
/**
* 邀请码
*
* @author user
* @since 2025-01-07 15:41
*/
@RestController
@Tag(name = "邀请码", description = "邀请码相关接口")
@RequestMapping("/p/invitation")
public class InvitationController {
@Autowired
private InvitationService invitationService;
@Autowired
private UserService userService;
/**
* 邀请码服务
*/
@ApiResponse(responseCode = "200", description = "获取邀请码成功")
@GetMapping("/getInvitation")
@Operation(summary = "获取邀请码", description = "获取邀请码")
public ServerResponseEntity<String> getInvitationCode(Date expireDate) {
String userId = SecurityUtils.getUser().getUserId();
Invitation invitation = invitationService.getInvitationCode(userId,expireDate);
return ServerResponseEntity.success(invitation.getInvitationCode());
}
/**
* 根据当前用户id获取邀请码列表
*/
@ApiResponse(responseCode = "200", description = "获取邀请码列表成功")
@GetMapping("/list")
@Operation(summary = "获取邀请码列表", description = "获取邀请码列表")
public ServerResponseEntity<IPage<Invitation>> getInvitationCodeList(PageParam<Invitation> page) {
String userId = SecurityUtils.getUser().getUserId();
return ServerResponseEntity.success(invitationService.getInvitationList(page, userId));
}
/**
* 校验邀请码是否可用
*/
@ApiResponse(responseCode = "200", description = "校验邀请码是否可用成功")
@GetMapping("/check")
@Operation(summary = "校验邀请码是否可用", description = "校验邀请码是否可用")
public ServerResponseEntity<Boolean> checkInvitationCode(String invitationCode) {
return ServerResponseEntity.success(invitationService.checkInvitationCode(invitationCode));
}
/**
* 获取邀请码二维码
*/
@ApiResponse(responseCode = "200", description = "获取邀请码二维码")
@GetMapping("/generateQrCode")
@Operation(summary = "获取邀请码二维码", description = "获取邀请码二维码")
public ServerResponseEntity<String> generateQrCode(@RequestParam(value = "type") Integer type) {
String userId = SecurityUtils.getUser().getUserId();
return ServerResponseEntity.success(invitationService.generateQrCode(userId,type));
}
/**
* 获取邀请码二维码
*/
@ApiResponse(responseCode = "200", description = "绑定上级邀请码")
@PostMapping("/bindToSuperiors")
@Operation(summary = "绑定上级邀请码", description = "绑定上级邀请码")
public ServerResponseEntity<String> generateQrCode(@RequestBody CurrencyParam currencyParam) {
if(invitationService.getInviterIdByCode(currencyParam.getInvitationCode())!=null){
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
if(ObjectUtil.equal(currencyParam.getInvitationCode(),user.getInviteCode())){
throw new YamiShopBindException("不能绑定自己");
}
if(StringUtils.isNotEmpty(user.getInviterCode())){
throw new YamiShopBindException("已经绑定过上级了");
}
user.setInviterCode(currencyParam.getInvitationCode());
userService.updateById(user);
Invitation oldInvitation = invitationService.getOne(new QueryWrapper<Invitation>().eq("invitation_code", user.getInviterCode()));
return ServerResponseEntity.success(oldInvitation.getInvitationUserId());
}else {
throw new YamiShopBindException("邀请码错误");
}
}
@GetMapping("/getOtherUserInfo")
@Operation(summary = "查看用户信息", description = "根据用户IDuserId获取用户信息")
public ServerResponseEntity<UserOtherDto> getOtherUserInfo(@RequestParam(value = "userId") String userId) {
User user = userService.getById(userId);
UserOtherDto userDto = BeanUtil.copyProperties(user, UserOtherDto.class);
return ServerResponseEntity.success(userDto);
}
}

View File

@@ -0,0 +1,238 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.enums.BaseEnum;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.VipType;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.OrderSettlementMapper;
import com.yami.shop.dao.RecommendVipMapper;
import com.yami.shop.factory.MemberRecommendationProgress;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/myOrder")
@Tag(name = "我的订单接口")
@AllArgsConstructor
public class MyOrderController {
private final OrderService orderService;
private final UserAddrOrderService userAddrOrderService;
private final ProductService productService;
private final SkuService skuService;
private final MyOrderService myOrderService;
private final ShopDetailService shopDetailService;
private final OrderItemService orderItemService;
private final UserService userService;
private final OrderSettlementMapper orderSettlementMapper;
private final VipPackageService vipPackageService;
private final ScoreDetailService scoreDetailService;
private final InvitationService invitationService;
private final RecommendVipMapper recommendVipMapper;
/**
* 订单详情信息接口
*/
@GetMapping("/orderDetail")
@Operation(summary = "订单详情信息", description = "根据订单号获取订单详情信息")
@Parameter(name = "orderNumber", description = "订单号", required = true)
public ServerResponseEntity<OrderShopDto> orderDetail(@RequestParam(value = "orderNumber") String orderNumber) {
String userId = SecurityUtils.getUser().getUserId();
OrderShopDto orderShopDto = new OrderShopDto();
Order order = orderService.getOrderByOrderNumber(orderNumber);
if (order == null) {
throw new RuntimeException("该订单不存在");
}
if (!Objects.equals(order.getUserId(), userId)) {
throw new RuntimeException("你没有权限获取该订单信息");
}
ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(order.getShopId());
UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
UserAddrDto userAddrDto = BeanUtil.copyProperties(userAddrOrder, UserAddrDto.class);
List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
List<OrderItemDto> orderItemList = BeanUtil.copyToList(orderItems, OrderItemDto.class);
orderShopDto.setShopId(shopDetail.getShopId());
orderShopDto.setShopName(shopDetail.getShopName());
orderShopDto.setActualTotal(order.getActualTotal());
orderShopDto.setUserAddrDto(userAddrDto);
orderShopDto.setOrderItemDtos(orderItemList);
orderShopDto.setTransfee(order.getFreightAmount());
orderShopDto.setReduceAmount(order.getReduceAmount());
orderShopDto.setCreateTime(order.getCreateTime());
orderShopDto.setRemarks(order.getRemarks());
orderShopDto.setStatus(order.getStatus());
double total = 0.0;
Integer totalNum = 0;
for (OrderItemDto orderItem : orderShopDto.getOrderItemDtos()) {
total = Arith.add(total, orderItem.getProductTotalAmount());
totalNum += orderItem.getProdCount();
}
orderShopDto.setTotal(total);
orderShopDto.setTotalNum(totalNum);
return ServerResponseEntity.success(orderShopDto);
}
/**
* 订单列表接口
*/
@GetMapping("/myOrder")
@Operation(summary = "订单列表信息", description = "根据订单状态获取订单列表信息状态为0时获取所有订单")
@Parameters({
@Parameter(name = "status", description = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败")
})
public ServerResponseEntity<IPage<MyOrderDto>> myOrder(@RequestParam(value = "status") String status, PageParam<MyOrderDto> page) {
String userId = SecurityUtils.getUser().getUserId();
List<String> statusList = new ArrayList<>();
if(StringUtils.isNotEmpty(status)&&!status.equals("0")){
statusList = Arrays.asList(status.split(","));
}
IPage<MyOrderDto> myOrderDtoIpage = myOrderService.pageMyOrderByUserIdAndStatus(page, userId, statusList);
return ServerResponseEntity.success(myOrderDtoIpage);
}
/**
* 取消订单
*/
@PutMapping("/cancel/{orderNumber}")
@Operation(summary = "根据订单号取消订单", description = "根据订单号取消订单")
@Parameter(name = "orderNumber", description = "订单号", required = true)
public ServerResponseEntity<String> cancel(@PathVariable("orderNumber") String orderNumber) {
String userId = SecurityUtils.getUser().getUserId();
Order order = orderService.getOrderByOrderNumber(orderNumber);
if (!Objects.equals(order.getUserId(), userId)) {
throw new YamiShopBindException("你没有权限获取该订单信息");
}
if (!Objects.equals(order.getStatus(), OrderStatus.UNPAY.value())) {
throw new YamiShopBindException("订单已支付,无法取消订单");
}
List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
order.setOrderItems(orderItems);
// 取消订单
orderService.cancelOrders(Collections.singletonList(order));
// 清除缓存
for (OrderItem orderItem : orderItems) {
productService.removeProductCacheByProdId(orderItem.getProdId());
skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
}
return ServerResponseEntity.success();
}
/**
* 确认收货
*/
@PutMapping("/receipt/{orderNumber}")
@Operation(summary = "根据订单号确认收货", description = "根据订单号确认收货")
public ServerResponseEntity<String> receipt(@PathVariable("orderNumber") String orderNumber) {
String userId = SecurityUtils.getUser().getUserId();
//String userId="2363e378a8254f968c4296ba4cb764db";
Order order = orderService.getOrderByOrderNumber(orderNumber);
if (!Objects.equals(order.getUserId(), userId)) {
throw new YamiShopBindException("你没有权限获取该订单信息");
}
if (!Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value())) {
throw new YamiShopBindException("订单未发货,无法确认收货");
}
List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
order.setOrderItems(orderItems);
// 确认收货
orderService.confirmOrder(Collections.singletonList(order));
for (OrderItem orderItem : orderItems) {
productService.removeProductCacheByProdId(orderItem.getProdId());
skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
}
orderService.receipt(order);
return ServerResponseEntity.success();
}
/**
* 删除订单
*/
@DeleteMapping("/{orderNumber}")
@Operation(summary = "根据订单号删除订单", description = "根据订单号删除订单")
@Parameter(name = "orderNumber", description = "订单号", required = true)
public ServerResponseEntity<String> delete(@PathVariable("orderNumber") String orderNumber) {
String userId = SecurityUtils.getUser().getUserId();
Order order = orderService.getOrderByOrderNumber(orderNumber);
if (order == null) {
throw new YamiShopBindException("该订单不存在");
}
if (!Objects.equals(order.getUserId(), userId)) {
throw new YamiShopBindException("你没有权限获取该订单信息");
}
if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value()) && !Objects.equals(order.getStatus(), OrderStatus.CLOSE.value())) {
throw new YamiShopBindException("订单未完成或未关闭,无法删除订单");
}
// 删除订单
orderService.deleteOrders(Collections.singletonList(order));
return ServerResponseEntity.success("删除成功");
}
/**
* 获取我的订单订单数量
*/
@GetMapping("/orderCount")
@Operation(summary = "获取我的订单订单数量", description = "获取我的订单订单数量")
public ServerResponseEntity<OrderCountData> getOrderCount() {
String userId = SecurityUtils.getUser().getUserId();
OrderCountData orderCountMap = orderService.getOrderCount(userId);
return ServerResponseEntity.success(orderCountMap);
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.NoticeDto;
import com.yami.shop.bean.model.Notice;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.NoticeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/shop/notice")
@Tag(name = "公告管理接口")
@AllArgsConstructor
public class NoticeController {
private NoticeService noticeService;
/**
* 置顶公告列表接口
*/
@GetMapping("/topNoticeList")
@Operation(summary = "置顶公告列表信息" , description = "获取所有置顶公告列表信息")
public ServerResponseEntity<List<NoticeDto>> getTopNoticeList() {
List<Notice> noticeList = noticeService.listNotice();
List<NoticeDto> noticeDtoList = BeanUtil.copyToList(noticeList, NoticeDto.class);
return ServerResponseEntity.success(noticeDtoList);
}
/**
* 获取公告详情
*/
@GetMapping("/info/{id}")
@Operation(summary = "公告详情" , description = "获取公告id公告详情")
public ServerResponseEntity<NoticeDto> getNoticeById(@PathVariable("id") Long id) {
Notice notice = noticeService.getNoticeById(id);
NoticeDto noticeDto = BeanUtil.copyProperties(notice, NoticeDto.class);
return ServerResponseEntity.success(noticeDto);
}
/**
* 公告列表
*/
@GetMapping("/noticeList")
@Operation(summary = "公告列表信息" , description = "获取所有公告列表信息")
@Parameters({
})
public ServerResponseEntity<IPage<NoticeDto>> pageNotice(PageParam<NoticeDto> page) {
return ServerResponseEntity.success(noticeService.pageNotice(page));
}
}

View File

@@ -0,0 +1,470 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.param.CurrencyParam;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.app.param.OrderShopParam;
import com.yami.shop.bean.app.param.SubmitOrderParam;
import com.yami.shop.bean.constant.CurrencyConstant;
import com.yami.shop.bean.dto.AddOrderDto;
import com.yami.shop.bean.enums.BizCodeEnum;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.ProdTypeEnum;
import com.yami.shop.bean.event.ConfirmOrderEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.bean.PayNoticeResponse;
import com.yami.shop.common.constants.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.*;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.sys.dao.TzSysConfigMapper;
import com.yami.shop.sys.service.SysConfigService;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.*;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/order")
@Tag(name = "订单接口")
public class OrderController {
@Autowired
PayUtil payUtil;
@Autowired
private OrderService orderService;
@Autowired
private SkuService skuService;
@Autowired
private ProductService productService;
@Autowired
private UserAddrService userAddrService;
@Autowired
private BasketService basketService;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private UserService userService;
@Autowired
private TzSysConfigMapper sysConfigMapper;
private final ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
@PostMapping("/clearAllCaches")
@Operation(summary = "清理缓存", description = "clearAllCaches")
public ServerResponseEntity<String> clearAllCaches() {
basketService.clearAllCaches();
return ServerResponseEntity.success();
}
@GetMapping("/test")
public ServerResponseEntity<String> test(String userId) {
orderService.fahuo();
//orderService.fahuo();
/*if (RedisUtil.reUsed(RedisUtil.ADDORDER + userId, 2)) {
System.out.println("进来了============");
}else {
System.out.println("请勿重复提交订单");
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}*/
System.out.println("========");
return ServerResponseEntity.success();
}
@PostMapping("/getVipPice")
@Operation(summary = "获取开通会员的价格", description = "获取开通会员的价格传套餐id")
public ServerResponseEntity<Double> getVipPice(@RequestParam(value = "vipPackageId") Long vipPackageId) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
return ServerResponseEntity.success(orderService.getVipPice(user, vipPackageId));
}
@PostMapping("/cancelOrder")
@Operation(summary = "待发货取消订单", description = "待发货取消订单")
public ServerResponseEntity<Double> cancelOrder(@RequestBody CurrencyParam currencyParam) {
String userId =SecurityUtils.getUser().getUserId(); //"72f511eaef894fd7a7f60158899ac6b4";//
User user = userService.getById(userId);
orderService.cancelOrder(user, currencyParam.getOrderNumber());
return ServerResponseEntity.success();
}
@PostMapping("/userApplyRefund")
@Operation(summary = "用户申请退款", description = "用户申请退款")
public ServerResponseEntity<Void> userApplyRefund(@RequestBody CurrencyParam currencyParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
orderService.userApplyRefund(user, currencyParam.getOrderNumber(),currencyParam.getBuyerMsg());
return ServerResponseEntity.success();
}
@PostMapping("/addVipOrder")
@Operation(summary = "开通会员提交订单", description = "开通会员提交订单")
public ServerResponseEntity<Map<String, String>> addVipOrder(@RequestBody CurrencyParam currencyParam) {
String userId = SecurityUtils.getUser().getUserId();
if (!RedisUtil.reUsed(RedisUtil.ADDORDER + userId, 3)) {
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}
User user = userService.getById(userId);
return ServerResponseEntity.success(orderService.addVipOrder(user, currencyParam.getVipPackageId()));
}
@PostMapping("/claimRewards")
@Operation(summary = "领取奖励", description = "领取奖励")
public ServerResponseEntity<String> claimRewards(@RequestBody CurrencyParam currencyParam) {
String userId = SecurityUtils.getUser().getUserId();
if (!RedisUtil.reUsed(RedisUtil.ADDORDER + userId, 3)) {
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}
User user = userService.getById(userId);
orderService.claimRewards(user, currencyParam);
return ServerResponseEntity.success();
}
@PostMapping("/pointsAddOrder")
@Operation(summary = "积分下单", description = "积分下单")
public ServerResponseEntity<String> pointsAddOrder(@RequestBody CurrencyParam currencyParam) {
String userId = SecurityUtils.getUser().getUserId();
if (!RedisUtil.reUsed(RedisUtil.ADDORDER + userId, 3)) {
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}
User user = userService.getById(userId);
orderService.pointsAddOrder(user, currencyParam);
return ServerResponseEntity.success();
}
/**
* 微信回调
*/
@PostMapping("/payNotify")
public String payNotify(String orderSn) {
try {
//验签
if (RedisUtil.reUsed(RedisUtil.ADDORDER + orderSn, 3)) {
return "success";
}
Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderSn));
if (order == null) {
return "fail";
}
User user = userService.getById(order.getUserId());
order.setPayTime(new Date());
order.setStatus(OrderStatus.PADYED.value());
order.setThirdTradeNo("");
orderService.consume(order, user);
} catch (Exception x) {
System.out.println("异常信息" + x);
}
return "success";
}
/**
* 生成订单
*/
@PostMapping("/confirm")
@Operation(summary = "结算,生成订单信息", description = "传入下单所需要的参数进行下单")
public ServerResponseEntity<ShopCartOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
// 订单的地址信息
/* UserAddrDto userAddrDto = null;
if (orderParam.getAddrId() != null) {
UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);
userAddrDto = BeanUtil.copyProperties(userAddr, UserAddrDto.class);
}*/
// 订单的地址信息
UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);
UserAddrDto userAddrDto = BeanUtil.copyProperties(userAddr, UserAddrDto.class);
String orderNumber = OrderUtils.genOrderSn(CurrencyConstant.ORDINARY_MALL);
Double sysConfigPriceRatio =Double.valueOf(sysConfigMapper.queryOneByKey("pointsRatio").getConfigValue());
// 组装获取用户提交的购物车商品项
List<ShopCartItemDto> shopCartItems = basketService.getShopCartItemsByOrderItems(orderParam.getBasketIds(),
orderParam.getOrderItem(), user,sysConfigPriceRatio,orderParam.getFlag());
if (CollectionUtil.isEmpty(shopCartItems)) {
throw new YamiShopBindException("请选择您需要的商品加入购物车");
}
// 根据店铺组装购车中的商品信息,返回每个店铺中的购物车商品信息
List<ShopCartDto> shopCarts = basketService.getShopCarts(shopCartItems);
// 将要返回给前端的完整的订单信息
ShopCartOrderMergerDto shopCartOrderMergerDto = new ShopCartOrderMergerDto();
shopCartOrderMergerDto.setUserAddr(userAddrDto);
// 所有店铺的订单信息
List<ShopCartOrderDto> shopCartOrders = new ArrayList<>();
double actualTotal = 0.0;
double total = 0.0;
int totalCount = 0;
double orderReduce = 0.0;
double pointsTotal = 0;
for (ShopCartDto shopCart : shopCarts) {
// 每个店铺的订单信息
ShopCartOrderDto shopCartOrder = new ShopCartOrderDto();
shopCartOrder.setShopId(shopCart.getShopId());
shopCartOrder.setShopName(shopCart.getShopName());
List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();
// 店铺中的所有商品项信息
List<ShopCartItemDto> shopAllShopCartItems = new ArrayList<>();
for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
List<ShopCartItemDto> discountShopCartItems = shopCartItemDiscount.getShopCartItems();
shopAllShopCartItems.addAll(discountShopCartItems);
}
shopCartOrder.setShopCartItemDiscounts(shopCartItemDiscounts);
applicationContext.publishEvent(new ConfirmOrderEvent(shopCartOrder, orderParam, shopAllShopCartItems));
actualTotal = Arith.add(actualTotal, shopCartOrder.getActualTotal());
pointsTotal = pointsTotal + shopCartOrder.getPointsTotal();
total = Arith.add(total, shopCartOrder.getTotal());
totalCount = totalCount + shopCartOrder.getTotalCount();
orderReduce = Arith.add(orderReduce, shopCartOrder.getShopReduce());
shopCartOrders.add(shopCartOrder);
}
shopCartOrderMergerDto.setActualTotal(actualTotal);
shopCartOrderMergerDto.setTotal(total);
shopCartOrderMergerDto.setPointsTotal(pointsTotal);
shopCartOrderMergerDto.setTotalCount(totalCount);
shopCartOrderMergerDto.setShopCartOrders(shopCartOrders);
shopCartOrderMergerDto.setOrderReduce(orderReduce);
shopCartOrderMergerDto.setOrderNumber(orderNumber);
//shopCartOrderMergerDto = orderService.putConfirmOrderCache(orderNumber, shopCartOrderMergerDto);
//30分钟后失效
String key = String.format(Constant.ORDER_INFO, orderNumber);
RedisUtil.set(key,shopCartOrderMergerDto,1800);
return ServerResponseEntity.success(shopCartOrderMergerDto);
}
/**
* 购物车/立即购买 提交订单,根据店铺拆单
*/
@PostMapping("/submit")
@Operation(summary = "提交订单,返回支付流水号", description = "根据传入的参数判断是否为购物车提交订单,同时对购物车进行删除,用户开始进行支付")
public ServerResponseEntity<Map<String, String>> submitOrders(@Valid @RequestBody SubmitOrderParam submitOrderParam) {
YamiUser yamiUser = SecurityUtils.getUser();
String userId = yamiUser.getUserId();
if (!RedisUtil.reUsed(RedisUtil.ADDORDER + submitOrderParam.getOrderNumber(), 2)) {
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}
//ShopCartOrderMergerDto mergerOrder = orderService.getConfirmOrderCache(submitOrderParam.getOrderNumber());
//Object orderInfo = RedisUtil.get(submitOrderParam.getOrderNumber());
String key = String.format(Constant.ORDER_INFO, submitOrderParam.getOrderNumber());
Object orderInfo = RedisUtil.get(key);
if (orderInfo == null) {
throw new YamiShopBindException("订单已过期,请重新下单");
}
ShopCartOrderMergerDto mergerOrder = JSONObject.parseObject(JSON.toJSONString(orderInfo), ShopCartOrderMergerDto.class);
if (submitOrderParam.getAddressId() == null) {
throw new YamiShopBindException("请填写收货地址");
//mergerOrder.setAddressId(submitOrderParam.getAddressId());
}else {
// 订单的地址信息
UserAddr userAddr = userAddrService.getUserAddrByUserId(submitOrderParam.getAddressId(), userId);
UserAddrDto userAddrDto = BeanUtil.copyProperties(userAddr, UserAddrDto.class);
mergerOrder.setUserAddr(userAddrDto);
}
mergerOrder.setAddressId(submitOrderParam.getAddressId());
mergerOrder.setUserId(userId);
List<OrderShopParam> orderShopParams = submitOrderParam.getOrderShopParam();
List<ShopCartOrderDto> shopCartOrders = mergerOrder.getShopCartOrders();
// 设置备注
if (CollectionUtil.isNotEmpty(orderShopParams)) {
for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
for (OrderShopParam orderShopParam : orderShopParams) {
if (Objects.equals(shopCartOrder.getShopId(), orderShopParam.getShopId())) {
shopCartOrder.setRemarks(orderShopParam.getRemarks());
}
}
}
}
List<Order> orders = orderService.submit(userId, mergerOrder);
StringBuilder orderNumbers = new StringBuilder();
for (Order order : orders) {
orderNumbers.append(order.getOrderNumber()).append(",");
}
orderNumbers.deleteCharAt(orderNumbers.length() - 1);
boolean isShopCartOrder = false;
// 移除缓存
for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
for (ShopCartItemDto shopCartItem : shopCartItemDiscount.getShopCartItems()) {
Long basketId = shopCartItem.getBasketId();
if (basketId != null && basketId != 0) {
isShopCartOrder = true;
}
skuService.removeSkuCacheBySkuId(shopCartItem.getSkuId(), shopCartItem.getProdId());
productService.removeProductCacheByProdId(shopCartItem.getProdId());
}
}
}
// 购物车提交订单时(即有购物车ID时)
if (isShopCartOrder) {
basketService.removeShopCartItemsCacheByUserId(userId);
}
orderService.removeConfirmOrderCache(submitOrderParam.getOrderNumber());
double actualTotal = Arith.mul(mergerOrder.getActualTotal(),100);
double actualTotalMath = Math.round(actualTotal);
int longValue = 0;
if(actualTotal<1){
longValue = 1;
}else {
longValue = (int) actualTotalMath;
}
//待付款订单存储
String failKey = String.format(Constant.FAIL_ORDER_INFO, submitOrderParam.getOrderNumber());
RedisUtil.set(failKey,longValue,1800);
Map<String, String> payMap = payUtil.createOrder("易购优享商城下单",
longValue,submitOrderParam.getOrderNumber(),yamiUser.getOpenid());
return ServerResponseEntity.success(payMap);
}
@PostMapping("/obligationPay")
public ServerResponseEntity<Map<String, String>> obligationPay(@Valid @RequestBody SubmitOrderParam submitOrderParam) {
YamiUser yamiUser = SecurityUtils.getUser();
String key = String.format(Constant.FAIL_ORDER_INFO, submitOrderParam.getOrderNumber());
Object longValue = RedisUtil.get(key);
if (longValue == null) {
throw new YamiShopBindException("订单已过期,请重新下单");
}
Map<String, String> payMap = payUtil.createOrder("易购优享商城下单",
Integer.parseInt(longValue.toString()),submitOrderParam.getOrderNumber(),yamiUser.getOpenid());
return ServerResponseEntity.success(payMap);
}
/*@PostMapping("/pointsSubmit")
@Operation(summary = "提交订单,返回支付流水号", description = "根据传入的参数判断是否为购物车提交订单,同时对购物车进行删除,用户开始进行支付")
public ServerResponseEntity<Map<String, String>> pointsSubmit(@Valid @RequestBody SubmitOrderParam submitOrderParam) {
YamiUser yamiUser = SecurityUtils.getUser();
String userId = yamiUser.getUserId();
if (!RedisUtil.reUsed(RedisUtil.ADDORDER + submitOrderParam.getOrderNumber(), 2)) {
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}
//ShopCartOrderMergerDto mergerOrder = orderService.getConfirmOrderCache(submitOrderParam.getOrderNumber());
//Object orderInfo = RedisUtil.get(submitOrderParam.getOrderNumber());
String key = String.format(Constant.ORDER_INFO, submitOrderParam.getOrderNumber());
Object orderInfo = RedisUtil.get(key);
if (orderInfo == null) {
throw new YamiShopBindException("订单已过期,请重新下单");
}
ShopCartOrderMergerDto mergerOrder = JSONObject.parseObject(JSON.toJSONString(orderInfo), ShopCartOrderMergerDto.class);
if (submitOrderParam.getAddressId() == null) {
throw new YamiShopBindException("请填写收货地址");
//mergerOrder.setAddressId(submitOrderParam.getAddressId());
}else {
// 订单的地址信息
UserAddr userAddr = userAddrService.getUserAddrByUserId(submitOrderParam.getAddressId(), userId);
UserAddrDto userAddrDto = BeanUtil.copyProperties(userAddr, UserAddrDto.class);
mergerOrder.setUserAddr(userAddrDto);
}
mergerOrder.setAddressId(submitOrderParam.getAddressId());
mergerOrder.setUserId(userId);
List<OrderShopParam> orderShopParams = submitOrderParam.getOrderShopParam();
List<ShopCartOrderDto> shopCartOrders = mergerOrder.getShopCartOrders();
// 设置备注
if (CollectionUtil.isNotEmpty(orderShopParams)) {
for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
for (OrderShopParam orderShopParam : orderShopParams) {
if (Objects.equals(shopCartOrder.getShopId(), orderShopParam.getShopId())) {
shopCartOrder.setRemarks(orderShopParam.getRemarks());
}
}
}
}
List<Order> orders = orderService.submit(userId, mergerOrder);
StringBuilder orderNumbers = new StringBuilder();
for (Order order : orders) {
orderNumbers.append(order.getOrderNumber()).append(",");
}
orderNumbers.deleteCharAt(orderNumbers.length() - 1);
boolean isShopCartOrder = false;
// 移除缓存
for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
for (ShopCartItemDto shopCartItem : shopCartItemDiscount.getShopCartItems()) {
Long basketId = shopCartItem.getBasketId();
if (basketId != null && basketId != 0) {
isShopCartOrder = true;
}
skuService.removeSkuCacheBySkuId(shopCartItem.getSkuId(), shopCartItem.getProdId());
productService.removeProductCacheByProdId(shopCartItem.getProdId());
}
}
}
// 购物车提交订单时(即有购物车ID时)
if (isShopCartOrder) {
basketService.removeShopCartItemsCacheByUserId(userId);
}
orderService.removeConfirmOrderCache(submitOrderParam.getOrderNumber());
return ServerResponseEntity.success();
}*/
@Operation(summary = "查询物流信息", description = "根据订单号查询物流公司和物流单号")
@GetMapping("/logistics")
public ServerResponseEntity<Map<String, String>> getLogistics(@RequestParam("orderNumber") String orderNumber) {
Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
.eq(Order::getOrderNumber, orderNumber));
if (order == null) {
throw new RuntimeException("订单不存在");
}
Map<String, String> logisticsInfo = new HashMap<>();
logisticsInfo.put("dvyName", order.getDvyName());
logisticsInfo.put("dvyFlowId", order.getDvyFlowId());
return ServerResponseEntity.success(logisticsInfo);
}
}

View File

@@ -0,0 +1,85 @@
package com.yami.shop.api.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yami.shop.bean.app.param.UserInfoParam;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.ImgUploadUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.AttachFileMapper;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Date;
@RestController
@RequestMapping("/p/other")
@Tag(name = "通用接口")
@AllArgsConstructor
public class OtherController {
@Resource
private AttachFileMapper attachFileMapper;
@Autowired
private UploadManager uploadManager;
@Autowired
private BucketManager bucketManager;
@Autowired
private Qiniu qiniu;
@Autowired
private Auth auth;
@Autowired
private ImgUploadUtil imgUploadUtil;
public final static String NORM_MONTH_PATTERN = "yyyy/MM/";
@Autowired
private UserService userService;
@PostMapping("/updateAvatar")
@Operation(summary = "更新用户头像", description = "更新用户的头像图片地址")
public ServerResponseEntity<Boolean> updateAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile files) {
String userId = SecurityUtils.getUser().getUserId();
// 获取文件的原始名称
String oldName = files.getOriginalFilename();
String extensionName = "";
// 获取文件扩展名
if (oldName != null && oldName.length() > 0) {
int dot = oldName.lastIndexOf('.');
if (dot > -1 && dot < oldName.length() - 1) {
extensionName = oldName.substring(dot);
}
}
String fileName ="";
// 直接通过文件流上传到七牛云
try (InputStream inputStream = files.getInputStream()) {
fileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + extensionName;
String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
Response response = uploadManager.put(inputStream.readAllBytes(), fileName, upToken);
Json.parseObject(response.bodyString(), DefaultPutRet.class);
System.out.println("===="+qiniu.getResourcesUrl()+fileName);
} catch (Exception e) {
e.printStackTrace();
}
User user = userService.getById(userId);
user.setPic(fileName);
return ServerResponseEntity.success(userService.updateById(user));
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.yami.shop.bean.app.param.PayParam;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/order")
@Tag(name = "订单接口")
@AllArgsConstructor
public class PayController {
private final PayService payService;
/**
* 支付接口
*/
@PostMapping("/pay")
@Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付")
public ServerResponseEntity<Void> pay(@RequestBody PayParam payParam) {
YamiUser user = SecurityUtils.getUser();
String userId = user.getUserId();
PayInfoDto payInfo = payService.pay(userId, payParam);
payService.paySuccess(payInfo.getPayNo(), "");
return ServerResponseEntity.success();
}
/**
* 普通支付接口
*/
@PostMapping("/normalPay")
@Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付")
public ServerResponseEntity<Boolean> normalPay(@RequestBody PayParam payParam) {
YamiUser user = SecurityUtils.getUser();
String userId = user.getUserId();
PayInfoDto pay = payService.pay(userId, payParam);
// 根据内部订单号更新order settlement
payService.paySuccess(pay.getPayNo(), "");
return ServerResponseEntity.success(true);
}
}

View File

@@ -0,0 +1,315 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Result;
import com.yami.shop.bean.dto.UserScoreDto;
import com.yami.shop.bean.enums.BaseEnum;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.PayType;
import com.yami.shop.bean.enums.ProdTypeEnum;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.bean.Amount;
import com.yami.shop.common.bean.WechatLogisticsRequest;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PayUtil;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.common.util.WeiXinUtil;
import com.yami.shop.dao.OrderRefundMapper;
import com.yami.shop.dao.OrderSettlementMapper;
import com.yami.shop.factory.Member;
import com.yami.shop.factory.OrdinaryMall;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.yami.shop.common.bean.PayNoticeResponse;
/**
* @author lanhai
*/
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/p/pay")
public class PayNoticeController {
@Autowired
private OrderService orderService;
@Autowired
private UserService userService;
@Autowired
private OrderSettlementService orderSettlementService;
@Autowired
private PayService payService;
@Autowired
PayUtil payUtil;
@Autowired
private OrderRefundMapper orderRefundMapper;
@Autowired
private OrderSettlementMapper orderSettlementMapper;
@Autowired
private ScoreDetailService scoreDetailService;
private final ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
/* @GetMapping(value = "create_order", produces = "application/json;charset=UTF-8")
public Map createOrder(@RequestParam int amount,@RequestParam String desc) throws Exception {
String orderId = System.currentTimeMillis() + "";
String opendId = "o6PpW7F-3ebVmq2ZC0-9f7tg0SYk";
return payUtil.createOrder(desc, amount,orderId,opendId);
}*/
@PostMapping("/callback")
public WxPayNotifyV3Result callback(HttpServletRequest request) throws IOException {
try {
// 读取请求体数据
BufferedReader reader = request.getReader();
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
// 解析回调结果
WxPayNotifyV3Result result = payUtil.payNotifyParser(builder.toString());
// 处理订单
if (result != null) {
// 获取订单信息
String outTradeNo = result.getResult().getOutTradeNo();
// 使用Redis防止重复回调
if (!RedisUtil.reUsed(RedisUtil.CALLBACKORDER + outTradeNo, 10)) {
System.out.println("支付成功,防止重复回调:" + outTradeNo);
return result;
}
String transactionId = result.getResult().getTransactionId();
String tradeState = result.getResult().getTradeState();
System.out.println("=== 支付结果详情 ===");
System.out.println("商户订单号:" + outTradeNo);
System.out.println("微信支付单号:" + transactionId);
System.out.println("交易状态:" + tradeState);
Order order = orderService.getOne(
new LambdaQueryWrapper<Order>()
.eq(Order::getPayOrder, outTradeNo)
);
if (order != null) {
// 检查订单是否已支付
if (Objects.equals(OrderStatus.PADYED.value(), order.getStatus())) {
System.out.println("订单已支付,无需重复处理");
return result;
}
// 更新订单状态
order.setPayTime(new Date());
order.setThirdTradeNo(transactionId);
if ("SUCCESS".equals(tradeState)) {
System.out.println("支付成功,开始处理订单");
order.setStatus(OrderStatus.PADYED.value());
order.setIsPayed(BaseEnum.YES_ONE.getKey());
orderService.updateById(order);
// 获取用户信息
User user = userService.getById(order.getUserId());
// 处理会员订单
if (Objects.equals(order.getOrderType(), ProdTypeEnum.BIZ_CODE_MEMBER.type)) {
System.out.println("处理会员订单");
orderService.vipConsume(order, user, transactionId);
} else {
System.out.println("处理普通订单");
orderService.orderConsume(order, user);
}
// 保存交易信息
payService.updateToPayInfo(order.getPayOrder(), transactionId);
System.out.println("订单处理完成");
} else {
System.out.println("支付失败,关闭订单");
order.setStatus(OrderStatus.CLOSE.value());
orderService.updateById(order);
}
} else {
System.out.println("未找到对应的订单信息:" + outTradeNo);
}
} else {
System.out.println("解析支付结果为空");
}
return result;
} catch (Exception e) {
System.out.println("处理支付回调异常:" + e.getMessage());
e.printStackTrace();
throw new RuntimeException("微信支付回调处理失败", e);
}
}
@PostMapping("/guoCallback")
public WxPayNotifyV3Result guoCallback(HttpServletRequest request) throws IOException {
try {
// 读取请求体数据
BufferedReader reader = request.getReader();
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
// 解析回调结果
WxPayNotifyV3Result result = payUtil.payGuoNotifyParser(builder.toString());
// 处理订单
if (result != null) {
// 获取订单信息
String outTradeNo = result.getResult().getOutTradeNo();
// 使用Redis防止重复回调
if (!RedisUtil.reUsed(RedisUtil.CALLBACKORDER + outTradeNo, 10)) {
System.out.println("订单支付成功,防止重复回调:" + outTradeNo);
return result;
}
String transactionId = result.getResult().getTransactionId();
String tradeState = result.getResult().getTradeState();
System.out.println("=== 支付结果详情 ===");
System.out.println("商户订单号:" + outTradeNo);
System.out.println("微信支付单号:" + transactionId);
System.out.println("交易状态:" + tradeState);
Order order = orderService.getOne(
new LambdaQueryWrapper<Order>()
.eq(Order::getPayOrder, outTradeNo)
);
if (order != null) {
// 检查订单是否已支付
if (Objects.equals(OrderStatus.PADYED.value(), order.getStatus())) {
System.out.println("订单已支付,无需重复处理");
return result;
}
// 更新订单状态
order.setPayTime(new Date());
order.setThirdTradeNo(transactionId);
if ("SUCCESS".equals(tradeState)) {
System.out.println("支付成功,开始处理订单");
order.setStatus(OrderStatus.PADYED.value());
order.setIsPayed(BaseEnum.YES_ONE.getKey());
orderService.updateById(order);
// 获取用户信息
User user = userService.getById(order.getUserId());
// 处理会员订单
if (Objects.equals(order.getOrderType(), ProdTypeEnum.BIZ_CODE_MEMBER.type)) {
System.out.println("处理会员订单");
orderService.vipConsume(order, user, transactionId);
} else {
System.out.println("处理普通订单");
orderService.orderConsume(order, user);
}
// 保存交易信息
payService.updateToPayInfo(order.getPayOrder(), transactionId);
System.out.println("订单处理完成");
} else {
System.out.println("支付失败,关闭订单");
order.setStatus(OrderStatus.CLOSE.value());
orderService.updateById(order);
}
} else {
System.out.println("未找到对应的订单信息:" + outTradeNo);
}
} else {
System.out.println("解析支付结果为空");
}
return result;
} catch (Exception e) {
System.out.println("处理支付回调异常:" + e.getMessage());
e.printStackTrace();
throw new RuntimeException("微信支付回调处理失败", e);
}
}
/*退款回调*/
@PostMapping("/refundCallback")
public WxPayNotifyV3Result refundCallback(HttpServletRequest request) throws IOException {
try {
// 读取请求体数据
BufferedReader reader = request.getReader();
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
// 解析回调结果
WxPayNotifyV3Result result = payUtil.payGuoNotifyParser(builder.toString());
System.out.println("退款回调信息:"+result.toString());
// 处理订单
if (result != null) {
// 获取订单信息
String outRefundNo = result.getRawData().getId();
String outTradeNo = result.getResult().getOutTradeNo();
String transactionId = result.getResult().getTransactionId();
// 使用Redis防止重复回调
if (!RedisUtil.reUsed(RedisUtil.CALLBACKORDER + outTradeNo, 10)) {
System.out.println("退款回调成功,防止重复回调:" + outTradeNo);
return result;
}
orderService.refundCallback(outRefundNo,outTradeNo,transactionId);
} else {
System.out.println("解析退款结果为空");
}
System.out.println("退款回调成功");
return result;
} catch (Exception e) {
System.out.println("处理支付回调异常:" + e.getMessage());
e.printStackTrace();
throw new RuntimeException("微信支付回调处理失败", e);
}
}
@GetMapping("/paytest")
public ServerResponseEntity<String> test() {
if (RedisUtil.reUsed(RedisUtil.ADDORDER + "123456", 2)) {
System.out.println("进来了============");
}else {
System.out.println("请勿重复提交订单");
return ServerResponseEntity.showFailMsg("请勿重复提交订单");
}
return ServerResponseEntity.success("jin来了啊135");
/* String userId ="2363e378a8254f968c4296ba4cb764db";
User user =userService.getById(userId);
Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getPayOrder, "poi20250227110218842"));
orderService.vipConsume(order, user);
return ServerResponseEntity.success();*/
}
@PostMapping("/insertLogistics")
public Map insertLogistics(@RequestBody WechatLogisticsRequest request) {
return payUtil.insertLogistics(request);
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.ProdCommDataDto;
import com.yami.shop.bean.app.dto.ProdCommDto;
import com.yami.shop.bean.app.param.ProdCommParam;
import com.yami.shop.bean.model.ProdComm;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ProdCommService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/prodComm")
@Tag(name = "评论接口")
@AllArgsConstructor
public class ProdCommController {
private final ProdCommService prodCommService;
@GetMapping("/prodCommData")
@Operation(summary = "返回商品评论数据(好评率 好评数量 中评数 差评数)" , description = "根据商品id获取")
public ServerResponseEntity<ProdCommDataDto> getProdCommData(Long prodId) {
return ServerResponseEntity.success(prodCommService.getProdCommDataByProdId(prodId));
}
@GetMapping("/prodCommPageByUser")
@Operation(summary = "根据用户返回评论分页数据" , description = "传入页码")
public ServerResponseEntity<IPage<ProdCommDto>> getProdCommPage(PageParam page) {
return ServerResponseEntity.success(prodCommService.getProdCommDtoPageByUserId(page, SecurityUtils.getUser().getUserId()));
}
@GetMapping("/prodCommPageByProd")
@Operation(summary = "根据商品返回评论分页数据" , description = "传入商品id和页码")
@Parameters({
@Parameter(name = "prodId", description = "商品id" , required = true),
@Parameter(name = "evaluate", description = "-1或null 全部0好评 1中评 2差评 3有图" , required = true),
})
public ServerResponseEntity<IPage<ProdCommDto>> getProdCommPageByProdId(PageParam page, Long prodId, Integer evaluate) {
return ServerResponseEntity.success(prodCommService.getProdCommDtoPageByProdId(page, prodId, evaluate));
}
@PostMapping
@Operation(summary = "添加评论")
public ServerResponseEntity<Void> saveProdCommPage(ProdCommParam prodCommParam) {
ProdComm prodComm = new ProdComm();
prodComm.setProdId(prodCommParam.getProdId());
prodComm.setOrderItemId(prodCommParam.getOrderItemId());
prodComm.setUserId(SecurityUtils.getUser().getUserId());
prodComm.setScore(prodCommParam.getScore());
prodComm.setContent(prodCommParam.getContent());
prodComm.setPics(prodCommParam.getPics());
prodComm.setIsAnonymous(prodCommParam.getIsAnonymous());
prodComm.setRecTime(new Date());
prodComm.setStatus(0);
prodComm.setEvaluate(prodCommParam.getEvaluate());
prodCommService.save(prodComm);
return ServerResponseEntity.success();
}
@DeleteMapping
@Operation(summary = "删除评论" , description = "根据id删除")
public ServerResponseEntity<Void> deleteProdComm(Long prodCommId) {
prodCommService.removeById(prodCommId);
return ServerResponseEntity.success();
}
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.ProductDto;
import com.yami.shop.bean.app.dto.TagProductDto;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.model.Transport;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import com.yami.shop.service.TransportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author lgh on 2018/11/26.
*/
@RestController
@RequestMapping("/prod")
@Tag(name = "商品接口")
public class ProdController {
@Autowired
private ProductService prodService;
@Autowired
private SkuService skuService;
@Autowired
private TransportService transportService;
@GetMapping("/pageProd")
@Operation(summary = "通过分类id商品列表信息" , description = "根据分类ID获取该分类下所有的商品列表信息")
@Parameters({
@Parameter(name = "categoryId", description = "分类ID" , required = true),
})
public ServerResponseEntity<IPage<ProductDto>> prodList(Long categoryId, Integer type,PageParam<ProductDto> page) {
IPage<ProductDto> productPage = prodService.pageByCategoryId(page, categoryId,type);
return ServerResponseEntity.success(productPage);
}
@GetMapping("/prodInfo")
@Operation(summary = "商品详情信息" , description = "根据商品IDprodId获取商品信息")
@Parameter(name = "prodId", description = "商品ID" , required = true)
public ServerResponseEntity<ProductDto> prodInfo(Long prodId) {
Product product = prodService.getProductByProdId(prodId);
if (product == null) {
return ServerResponseEntity.success();
}
List<Sku> skuList = skuService.listByProdId(prodId);
// 启用的sku列表
List<Sku> useSkuList = skuList.stream().filter(sku -> sku.getStatus() == 1).collect(Collectors.toList());
product.setSkuList(useSkuList);
ProductDto productDto = BeanUtil.copyProperties(product, ProductDto.class);
// 商品的配送方式
Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
// 有店铺配送的方式, 且存在运费模板,才返回运费模板的信息,供前端查阅
if (deliveryModeVO.getHasShopDelivery() && product.getDeliveryTemplateId() != null) {
Transport transportAndAllItems = transportService.getTransportAndAllItems(product.getDeliveryTemplateId());
productDto.setTransport(transportAndAllItems);
}
return ServerResponseEntity.success(productDto);
}
@GetMapping("/lastedProdPage")
@Operation(summary = "新品推荐" , description = "获取新品推荐商品列表")
@Parameters({
})
public ServerResponseEntity<IPage<ProductDto>> lastedProdPage(PageParam<ProductDto> page) {
IPage<ProductDto> productPage = prodService.pageByPutAwayTime(page);
return ServerResponseEntity.success(productPage);
}
@GetMapping("/prodListByTagId")
@Operation(summary = "通过分组标签获取商品列表" , description = "通过分组标签idtagId获取商品列表")
@Parameters({
@Parameter(name = "tagId", description = "当前页默认为1" , required = true),
})
public ServerResponseEntity<IPage<ProductDto>> prodListByTagId(
@RequestParam(value = "tagId") Long tagId,PageParam<ProductDto> page) {
IPage<ProductDto> productPage = prodService.pageByTagId(page, tagId);
return ServerResponseEntity.success(productPage);
}
@GetMapping("/moreBuyProdList")
@Operation(summary = "每日疯抢" , description = "获取销量最多的商品列表")
@Parameters({})
public ServerResponseEntity<IPage<ProductDto>> moreBuyProdList(PageParam<ProductDto> page) {
IPage<ProductDto> productPage = prodService.moreBuyProdList(page);
return ServerResponseEntity.success(productPage);
}
@GetMapping("/tagProdList")
@Operation(summary = "首页所有标签商品接口" , description = "获取首页所有标签商品接口")
public ServerResponseEntity<List<TagProductDto>> getTagProdList() {
List<TagProductDto> productDtoList = prodService.tagProdList();
return ServerResponseEntity.success(productDtoList);
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.yami.shop.bean.app.dto.ProdTagDto;
import com.yami.shop.bean.model.ProdTag;
import com.yami.shop.service.ProdTagService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/prod/tag")
@Tag(name = "商品分组标签接口")
@AllArgsConstructor
public class ProdTagController {
private ProdTagService prodTagService;
/**
* 商品分组标签列表接口
*/
@GetMapping("/prodTagList")
@Operation(summary = "商品分组标签列表" , description = "获取所有的商品分组列表")
public ServerResponseEntity<List<ProdTagDto>> getProdTagList() {
List<ProdTag> prodTagList = prodTagService.listProdTag();
List<ProdTagDto> prodTagDtoList = BeanUtil.copyToList(prodTagList, ProdTagDto.class);
return ServerResponseEntity.success(prodTagDtoList);
}
}

View File

@@ -0,0 +1,160 @@
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.app.dto.ProdCommDto;
import com.yami.shop.bean.model.ScoreDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ScoreDetailService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* (ScoreDetail)表控制层
*
* @author makejava
* @since 2025-01-10 11:22:50
*/
@RestController
@RequestMapping("/p/scoreDetail")
@Tag(name = "积分及明细管理", description = "积分及明细管理")
@AllArgsConstructor
public class ScoreDetailController {
/**
* 服务对象
*/
@Resource
private ScoreDetailService scoreDetailService;
private final UserService userService;
/**
* 分页查询所有数据
*
* @param page 分页对象
* @param scoreDetail 查询实体
* @return 所有数据
*/
@Operation(summary = "分页查询所有数据", description = "分页查询所有数据")
@GetMapping("/list")
public ServerResponseEntity<Page<ScoreDetail>> selectAll(Page<ScoreDetail> page, ScoreDetail scoreDetail) {
return ServerResponseEntity.success(this.scoreDetailService.page(page, new QueryWrapper<>(scoreDetail)));
}
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@Operation(summary = "通过主键查询单条数据", description = "通过主键查询单条数据")
@GetMapping("{id}")
public ServerResponseEntity<ScoreDetail> selectOne(@PathVariable Serializable id) {
return ServerResponseEntity.success(this.scoreDetailService.getById(id));
}
/**
* 新增数据
*
* @param scoreDetail 实体对象
* @return 新增结果
*/
@Operation(summary = "新增数据", description = "新增数据")
@PostMapping("/insert")
public ServerResponseEntity<Boolean> insert(@RequestBody ScoreDetail scoreDetail) {
return ServerResponseEntity.success(this.scoreDetailService.save(scoreDetail));
}
/**
* 修改数据
*
* @param scoreDetail 实体对象
* @return 修改结果
*/
@Operation(summary = "修改数据", description = "修改数据")
@PutMapping("/update")
public ServerResponseEntity<Boolean> update(@RequestBody ScoreDetail scoreDetail) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
scoreDetail.setUserId(userId);
return ServerResponseEntity.success(this.scoreDetailService.updateById(scoreDetail));
}
/**
* 删除数据
*
* @param idList 主键结合
* @return 删除结果
*/
@Operation(summary = "删除数据", description = "删除数据")
@DeleteMapping("/delete")
public ServerResponseEntity<Boolean> delete(@RequestParam("idList") List<Long> idList) {
return ServerResponseEntity.success(this.scoreDetailService.removeByIds(idList));
}
/**
* 根据用户id发放积分
*
* @param userId 用户id
*
*/
@Operation(summary = "根据用户id发放积分", description = "根据用户id发放积分")
@PostMapping("/grantScore")
public ServerResponseEntity<Boolean> grantScore(@RequestBody ScoreDetail scoreDetail) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
scoreDetail.setUserId(userId);
scoreDetail.setType(1);
scoreDetail.setCreateTime(new Date());
return ServerResponseEntity.success(this.scoreDetailService.grantScore(scoreDetail));
}
/**
* 根据用户id扣除积分
*
* @param userId 用户id
*
*/
@Operation(summary = "根据用户id扣除积分", description = "根据用户id扣除积分")
@PostMapping("/deductScore")
public ServerResponseEntity<Boolean> deductScore(@RequestBody ScoreDetail scoreDetail) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
scoreDetail.setUserId(userId);
scoreDetail.setType(0);
scoreDetail.setCreateTime(new Date());
return ServerResponseEntity.success(this.scoreDetailService.deductScore(scoreDetail));
}
@GetMapping("/prodCommPageByProd")
@Operation(summary = "根据时间查询积分记录" , description = "根据时间查询积分记录")
@Parameters({
@Parameter(name = "createTime", description = "查询时间" , required = true),
})
public ServerResponseEntity<IPage<ScoreDetail>> getProdCommPageByProdId(PageParam page, String createTime) {
String userId = SecurityUtils.getUser().getUserId();
return ServerResponseEntity.success(scoreDetailService.getScoreDetailListByDate(page, userId, createTime));
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.bean.dto.HotSearchDto;
import com.yami.shop.bean.dto.SearchProdDto;
import com.yami.shop.service.HotSearchService;
import com.yami.shop.service.ProductService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/search")
@Tag(name = "搜索接口")
@AllArgsConstructor
public class SearchController {
private final HotSearchService hotSearchService;
private final ProductService productService;
@GetMapping("/hotSearchByShopId")
@Operation(summary = "查看店铺热搜" , description = "根据店铺id,热搜数量获取热搜")
@Parameters({
@Parameter(name = "shopId", description = "店铺id" , required = true),
@Parameter(name = "number", description = "取数" , required = true),
@Parameter(name = "sort", description = "是否按照顺序(0 否 1是)"),
})
public ServerResponseEntity<List<HotSearchDto>> hotSearchByShopId(Long shopId,Integer number,Integer sort) {
List<HotSearchDto> list = hotSearchService.getHotSearchDtoByShopId(shopId);
return getListResponseEntity(number, sort, list);
}
@GetMapping("/hotSearch")
@Operation(summary = "查看全局热搜" , description = "根据店铺id,热搜数量获取热搜")
@Parameters({
@Parameter(name = "number", description = "取数" , required = true),
@Parameter(name = "sort", description = "是否按照顺序(0 否 1是)", required = false ),
})
public ServerResponseEntity<List<HotSearchDto>> hotSearch(Integer number,Integer sort) {
List<HotSearchDto> list = hotSearchService.getHotSearchDtoByShopId(0L);
return getListResponseEntity(number, sort, list);
}
private ServerResponseEntity<List<HotSearchDto>> getListResponseEntity(Integer number, Integer sort, List<HotSearchDto> list) {
if(sort == null || sort == 0){
Collections.shuffle(list);
}
if(!CollectionUtil.isNotEmpty(list) || list.size()< number){
return ServerResponseEntity.success(list);
}
return ServerResponseEntity.success(list.subList(0, number));
}
@GetMapping("/searchProdPage")
@Operation(summary = "分页排序搜索商品" , description = "根据商品名搜索")
@Parameters({
@Parameter(name = "prodName", description = "商品名" , required = true),
@Parameter(name = "sort", description = "排序(0 默认排序 1销量排序 2价格排序)"),
@Parameter(name = "orderBy", description = "排序(0升序 1降序)"),
@Parameter(name = "orderBy", description = "排序(0升序 1降序)"),
@Parameter(name = "type", description = "商品类型 0普通商品 1:积分商品 2福利商品 3积分和普通通用商品"),
@Parameter(name = "shopId", description = "店铺id" , required = true),
})
public ServerResponseEntity<IPage<SearchProdDto>> searchProdPage(PageParam page, String prodName, Integer sort, Integer orderBy, Long shopId, Integer type) {
return ServerResponseEntity.success(productService.getSearchProdDtoPageByProdName(page,prodName,sort,orderBy,type));
}
}

View File

@@ -0,0 +1,242 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.google.common.collect.Lists;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.param.ChangeShopCartParam;
import com.yami.shop.bean.app.param.ShopCartParam;
import com.yami.shop.bean.event.ShopCartEvent;
import com.yami.shop.bean.model.Basket;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.common.util.Arith;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.BasketService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationContext;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/shopCart")
@Tag(name = "购物车接口")
@AllArgsConstructor
public class ShopCartController {
private final BasketService basketService;
private final ProductService productService;
private final SkuService skuService;
private final ApplicationContext applicationContext;
/**
* 获取用户购物车信息
*
* @param basketIdShopCartParamMap 购物车参数对象列表
* @return
*/
@PostMapping("/info")
@Operation(summary = "获取用户购物车信息" , description = "获取用户购物车信息,参数为用户选中的活动项数组,以购物车id为key")
public ServerResponseEntity<List<ShopCartDto>> info(@RequestBody Map<Long, ShopCartParam> basketIdShopCartParamMap) {
String userId = SecurityUtils.getUser().getUserId();
// 更新购物车信息,
if (MapUtil.isNotEmpty(basketIdShopCartParamMap)) {
basketService.updateBasketByShopCartParam(userId, basketIdShopCartParamMap);
}
// 拿到购物车的所有item
List<ShopCartItemDto> shopCartItems = basketService.getShopCartItems(userId);
return ServerResponseEntity.success(basketService.getShopCarts(shopCartItems));
}
@DeleteMapping("/deleteItem")
@Operation(summary = "删除用户购物车物品" , description = "通过购物车id删除用户购物车物品")
public ServerResponseEntity<Void> deleteItem(@RequestBody List<Long> basketIds) {
String userId = SecurityUtils.getUser().getUserId();
basketService.deleteShopCartItemsByBasketIds(userId, basketIds);
return ServerResponseEntity.success();
}
@DeleteMapping("/deleteAll")
@Operation(summary = "清空用户购物车所有物品" , description = "清空用户购物车所有物品")
public ServerResponseEntity<String> deleteAll() {
String userId = SecurityUtils.getUser().getUserId();
basketService.deleteAllShopCartItems(userId);
return ServerResponseEntity.success("删除成功");
}
@PostMapping("/changeItem")
@Operation(summary = "添加、修改用户购物车物品", description = "通过商品id(prodId)、skuId、店铺Id(shopId),添加/修改用户购物车商品,并传入改变的商品个数(count)" +
"当count为正值时增加商品数量当count为负值时将减去商品的数量当最终count值小于0时会将商品从购物车里面删除")
public ServerResponseEntity<String> addItem(@Valid @RequestBody ChangeShopCartParam param) {
if (param.getCount() == 0) {
return ServerResponseEntity.showFailMsg("输入更改数量");
}
String userId = SecurityUtils.getUser().getUserId();
List<ShopCartItemDto> shopCartItems = basketService.getShopCartItems(userId);
Product prodParam = productService.getProductByProdId(param.getProdId());
Sku skuParam = skuService.getSkuBySkuId(param.getSkuId());
// 当商品状态不正常时,不能添加到购物车
if (prodParam.getStatus() != 1 || skuParam.getStatus() != 1) {
return ServerResponseEntity.showFailMsg("当前商品已下架");
}
for (ShopCartItemDto shopCartItemDto : shopCartItems) {
if (Objects.equals(param.getSkuId(), shopCartItemDto.getSkuId())) {
Basket basket = new Basket();
basket.setUserId(userId);
basket.setBasketCount(param.getCount() + shopCartItemDto.getProdCount());
basket.setBasketId(shopCartItemDto.getBasketId());
// 防止购物车变成负数
if (basket.getBasketCount() <= 0) {
basketService.deleteShopCartItemsByBasketIds(userId, Collections.singletonList(basket.getBasketId()));
return ServerResponseEntity.success();
}
// 当sku实际库存不足时不能添加到购物车
if (skuParam.getStocks() < basket.getBasketCount() && shopCartItemDto.getProdCount() > 0) {
return ServerResponseEntity.showFailMsg("库存不足");
}
basketService.updateShopCartItem(basket);
return ServerResponseEntity.success();
}
}
// 防止购物车已被删除的情况下,添加了负数的商品
if (param.getCount() < 0) {
return ServerResponseEntity.showFailMsg("商品已从购物车移除");
}
// 当sku实际库存不足时不能添加到购物车
if (skuParam.getStocks() < param.getCount()) {
return ServerResponseEntity.showFailMsg("库存不足");
}
// 所有都正常时
basketService.addShopCartItem(param,userId);
return ServerResponseEntity.success("添加成功");
}
@GetMapping("/prodCount")
@Operation(summary = "获取购物车商品数量" , description = "获取所有购物车商品数量")
public ServerResponseEntity<Integer> prodCount() {
String userId = SecurityUtils.getUser().getUserId();
List<ShopCartItemDto> shopCartItems = basketService.getShopCartItems(userId);
if (CollectionUtil.isEmpty(shopCartItems)) {
return ServerResponseEntity.success(0);
}
Integer totalCount = shopCartItems.stream().map(ShopCartItemDto::getProdCount).reduce(0, Integer::sum);
return ServerResponseEntity.success(totalCount);
}
@GetMapping("/expiryProdList")
@Operation(summary = "获取购物车失效商品信息" , description = "获取购物车失效商品列表")
public ServerResponseEntity<List<ShopCartExpiryItemDto>> expiryProdList() {
String userId = SecurityUtils.getUser().getUserId();
List<ShopCartItemDto> shopCartItems = basketService.getShopCartExpiryItems(userId);
//根据店铺ID划分item
Map<Long, List<ShopCartItemDto>> shopCartItemDtoMap = shopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemDto::getShopId));
// 返回一个店铺对应的所有信息
List<ShopCartExpiryItemDto> shopcartExpiryitems = Lists.newArrayList();
for (Long key : shopCartItemDtoMap.keySet()) {
ShopCartExpiryItemDto shopCartExpiryItemDto = new ShopCartExpiryItemDto();
shopCartExpiryItemDto.setShopId(key);
List<ShopCartItemDto> shopCartItemDtos = Lists.newArrayList();
for (ShopCartItemDto tempShopCartItemDto : shopCartItemDtoMap.get(key)) {
shopCartExpiryItemDto.setShopName(tempShopCartItemDto.getShopName());
shopCartItemDtos.add(tempShopCartItemDto);
}
shopCartExpiryItemDto.setShopCartItemDtoList(shopCartItemDtos);
shopcartExpiryitems.add(shopCartExpiryItemDto);
}
return ServerResponseEntity.success(shopcartExpiryitems);
}
@DeleteMapping("/cleanExpiryProdList")
@Operation(summary = "清空用户失效商品" , description = "清空用户失效商品")
public ServerResponseEntity<Void> cleanExpiryProdList() {
String userId = SecurityUtils.getUser().getUserId();
basketService.cleanExpiryProdList(userId);
return ServerResponseEntity.success();
}
@PostMapping("/totalPay")
@Operation(summary = "获取选中购物项总计、选中的商品数量" , description = "获取选中购物项总计、选中的商品数量,参数为购物车id数组")
public ServerResponseEntity<ShopCartAmountDto> getTotalPay(@RequestBody List<Long> basketIds) {
// 拿到购物车的所有item
List<ShopCartItemDto> dbShopCartItems = basketService.getShopCartItems(SecurityUtils.getUser().getUserId());
List<ShopCartItemDto> chooseShopCartItems = dbShopCartItems
.stream()
.filter(shopCartItemDto -> {
for (Long basketId : basketIds) {
if (Objects.equals(basketId,shopCartItemDto.getBasketId())) {
return true;
}
}
return false;
})
.toList();
// 根据店铺ID划分item
Map<Long, List<ShopCartItemDto>> shopCartMap = chooseShopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemDto::getShopId));
double total = 0.0;
int count = 0;
double reduce = 0.0;
for (Long shopId : shopCartMap.keySet()) {
//获取店铺的所有商品项
List<ShopCartItemDto> shopCartItemDtoList = shopCartMap.get(shopId);
// 构建每个店铺的购物车信息
ShopCartDto shopCart = new ShopCartDto();
shopCart.setShopId(shopId);
applicationContext.publishEvent(new ShopCartEvent(shopCart, shopCartItemDtoList));
List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();
for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
List<ShopCartItemDto> shopCartItems = shopCartItemDiscount.getShopCartItems();
for (ShopCartItemDto shopCartItem : shopCartItems) {
count = shopCartItem.getProdCount() + count;
total = Arith.add(shopCartItem.getProductTotalAmount(), total);
}
}
}
ShopCartAmountDto shopCartAmountDto = new ShopCartAmountDto();
shopCartAmountDto.setCount(count);
shopCartAmountDto.setTotalMoney(total);
shopCartAmountDto.setSubtractMoney(reduce);
shopCartAmountDto.setFinalMoney(Arith.sub(shopCartAmountDto.getTotalMoney(), shopCartAmountDto.getSubtractMoney()));
return ServerResponseEntity.success(shopCartAmountDto);
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.dto.SkuDto;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.service.SkuService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/sku")
@Tag(name = "sku规格接口")
@AllArgsConstructor
public class SkuController {
private final SkuService skuService;
@GetMapping("/getSkuList")
@Operation(summary = "通过prodId获取商品全部规格列表" , description = "通过prodId获取商品全部规格列表")
@Parameter(name = "prodId", description = "商品id" )
public ServerResponseEntity<List<SkuDto>> getSkuListByProdId(Long prodId) {
List<Sku> skus = skuService.list(new LambdaQueryWrapper<Sku>()
.eq(Sku::getStatus, 1)
.eq(Sku::getIsDelete, 0)
.eq(Sku::getProdId, prodId)
);
List<SkuDto> skuDtoList = BeanUtil.copyToList(skus, SkuDto.class);
return ServerResponseEntity.success(skuDtoList);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.google.common.collect.Maps;
import com.yami.shop.bean.app.param.SendSmsParam;
import com.yami.shop.bean.enums.SmsType;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.SmsLogService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/sms")
@Tag(name = "发送验证码接口")
public class SmsController {
@Autowired
private SmsLogService smsLogService;
/**
* 发送验证码接口
*/
@PostMapping("/send")
@Operation(summary = "发送验证码" , description = "用户的发送验证码")
public ServerResponseEntity<Void> audit(@RequestBody SendSmsParam sendSmsParam) {
String userId = SecurityUtils.getUser().getUserId();
smsLogService.sendSms(SmsType.VALID, userId, sendSmsParam.getMobile(),Maps.newHashMap());
return ServerResponseEntity.success();
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.ProductDto;
import com.yami.shop.bean.app.dto.UserCollectionDto;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.UserCollection;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.UserCollectionService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Objects;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/user/collection")
@Tag(name = "收藏接口")
@AllArgsConstructor
public class UserCollectionController {
private final UserCollectionService userCollectionService;
private final ProductService productService;
@GetMapping("/page")
@Operation(summary = "分页返回收藏数据" , description = "根据用户id获取")
public ServerResponseEntity<IPage<UserCollectionDto>> getUserCollectionDtoPageByUserId(PageParam page) {
return ServerResponseEntity.success(userCollectionService.getUserCollectionDtoPageByUserId(page, SecurityUtils.getUser().getUserId()));
}
@GetMapping("isCollection")
@Operation(summary = "根据商品id获取该商品是否在收藏夹中" , description = "传入收藏商品id")
public ServerResponseEntity<Boolean> isCollection(Long prodId) {
if (productService.count(new LambdaQueryWrapper<Product>()
.eq(Product::getProdId, prodId)) < 1) {
throw new YamiShopBindException("该商品不存在");
}
return ServerResponseEntity.success(userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
.eq(UserCollection::getProdId, prodId)
.eq(UserCollection::getUserId, SecurityUtils.getUser().getUserId())) > 0);
}
@PostMapping("/addOrCancel")
@Operation(summary = "添加/取消收藏" , description = "传入收藏商品id,如果商品未收藏则收藏商品,已收藏则取消收藏")
@Parameter(name = "prodId", description = "商品id" , required = true)
public ServerResponseEntity<Void> addOrCancel(@RequestBody Long prodId) {
if (Objects.isNull(productService.getProductByProdId(prodId))) {
throw new YamiShopBindException("该商品不存在");
}
String userId = SecurityUtils.getUser().getUserId();
if (userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
.eq(UserCollection::getProdId, prodId)
.eq(UserCollection::getUserId, userId)) > 0) {
userCollectionService.remove(new LambdaQueryWrapper<UserCollection>()
.eq(UserCollection::getProdId, prodId)
.eq(UserCollection::getUserId, userId));
} else {
UserCollection userCollection = new UserCollection();
userCollection.setCreateTime(new Date());
userCollection.setUserId(userId);
userCollection.setProdId(prodId);
userCollectionService.save(userCollection);
}
return ServerResponseEntity.success();
}
/**
* 查询用户收藏商品数量
*/
@GetMapping("count")
@Operation(summary = "查询用户收藏商品数量" , description = "查询用户收藏商品数量")
public ServerResponseEntity<Long> findUserCollectionCount() {
String userId = SecurityUtils.getUser().getUserId();
return ServerResponseEntity.success(userCollectionService.count(new LambdaQueryWrapper<UserCollection>().eq(UserCollection::getUserId, userId)));
}
@GetMapping("/prods")
@Operation(summary = "获取用户收藏商品列表" , description = "获取用户收藏商品列表")
public ServerResponseEntity<IPage<ProductDto>> collectionProds(PageParam page) {
String userId = SecurityUtils.getUser().getUserId();
IPage<ProductDto> productDtoPage = productService.collectionProds(page, userId);
return ServerResponseEntity.success(productDtoPage);
}
}

View File

@@ -0,0 +1,264 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.dto.UserOtherDto;
import com.yami.shop.bean.app.param.UserInfoParam;
import com.yami.shop.bean.dto.UserRankDto;
import com.yami.shop.bean.dto.UserScoreDto;
import com.yami.shop.bean.dto.WelfareGiftRecordDto;
import com.yami.shop.bean.model.RecommendVip;
import com.yami.shop.bean.model.ScoreDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.VipPackage;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.sys.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
/**
* @author lanhai
*/
@RestController
@RequestMapping("/p/user")
@Tag(name = "用户接口")
@AllArgsConstructor
public class UserController {
private final UserService userService;
private final ScoreDetailService scoreDetailService;
private final InvitationService invitationService;
private final VipPackageService vipPackageService;
private final SysConfigService sysConfigService;
private final WelfareGiftRecordService welfareGiftRecordService;
/**
* 查看用户接口
*/
@GetMapping("/userInfo")
@Operation(summary = "查看用户信息", description = "根据用户IDuserId获取用户信息")
public ServerResponseEntity<UserDto> userInfo() {
String userId =SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
UserDto userDto = userService.getUserInfo(user);
return ServerResponseEntity.success(userDto);
}
/**
* 获取可提现金额
*/
@GetMapping("/getWithdrawalAmount")
@Operation(summary = "获取可提现金额", description = "获取可提现金额")
public ServerResponseEntity<Double> getWithdrawalAmount() {
String userId = SecurityUtils.getUser().getUserId();
return ServerResponseEntity.success(userService.getWithdrawalAmount(userId));
}
@GetMapping("/OtherUserInfo")
@Operation(summary = "查看其他用户信息", description = "根据用户IDuserId获取用户信息")
public ServerResponseEntity<UserOtherDto> OtherUserInfo(@RequestParam(value = "userId") String userId) {
User user = userService.getById(userId);
UserOtherDto userDto = BeanUtil.copyProperties(user, UserOtherDto.class);
return ServerResponseEntity.success(userDto);
}
@PostMapping("/updateAvatar")
@Operation(summary = "更新用户头像", description = "更新用户的头像图片地址")
public ServerResponseEntity<Boolean> updateAvatar(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
user.setPic(userInfoParam.getAvatarUrl());
return ServerResponseEntity.success(userService.updateById(user));
}
@PostMapping("/updatePhoneAndNickName")
@Operation(summary = "更新用户手机号和昵称", description = "更新用户的手机号和昵称")
public ServerResponseEntity<Boolean> updatePhoneAndNickName(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
user.setUserMobile(userInfoParam.getPhone());
user.setNickName(userInfoParam.getNickName());
return ServerResponseEntity.success(userService.updateById(user));
}
@PostMapping("/updatePhone")
@Operation(summary = "更新用户手机号", description = "更新用户的手机号")
public ServerResponseEntity<Boolean> updatePhone(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
user.setUserMobile(userInfoParam.getPhone());
return ServerResponseEntity.success(userService.updateById(user));
}
@PostMapping("/transferPoints")
@Operation(summary = "转赠积分", description = "转赠积分")
public ServerResponseEntity<Boolean> transferPoints(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
User user1 = new User();
User one = userService.lambdaQuery(user1).eq(User::getUserMobile, userInfoParam.getReceiverPhone()).one();
if (one == null) {
return ServerResponseEntity.fail("413", "未找到使用该手机号的用户");
}
ScoreDetail scoreDetail = new ScoreDetail();
scoreDetail.setUserId(one.getUserId());
scoreDetail.setQuantity(userInfoParam.getPoints());
scoreDetail.setCreateTime(new Date());
scoreDetail.setType(1);
scoreDetail.setScoreDescription("来自尾号" + user.getUserMobile().substring(user.getUserMobile().length() - 4) + "的用户转赠的积分");
scoreDetailService.grantScore(scoreDetail);
ScoreDetail scoreDetail1 = new ScoreDetail();
scoreDetail1.setUserId(userId);
scoreDetail1.setQuantity(userInfoParam.getPoints());
scoreDetail1.setCreateTime(new Date());
scoreDetail1.setType(0);
scoreDetail1.setScoreDescription("赠送给尾号" + one.getUserMobile().substring(user.getUserMobile().length() - 4) + "的用户的积分");
scoreDetailService.deductScore(scoreDetail1);
return ServerResponseEntity.success(true);
}
@PostMapping("/updateNickname")
@Operation(summary = "更新用户昵称", description = "更新用户的昵称")
public ServerResponseEntity<Boolean> updateNickname(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
user.setNickName(userInfoParam.getNickName());
return ServerResponseEntity.success(userService.updateById(user));
}
@PostMapping("/exchangeInviteCode")
@Operation(summary = "邀请码兑换红包", description = "邀请码兑换红包")
public ServerResponseEntity<Boolean> exchangeInviteCode(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
user.setNickName(userInfoParam.getNickName());
if (user.getIfUseCode() == 1) {
return ServerResponseEntity.fail("412", "该帐号已使用过邀请码");
}
User one = userService.lambdaQuery().eq(User::getInviteCode, userInfoParam.getInviteCode()).one();
if (one != null) {
user.setRedCard(50);
one.setRedCard(50 + one.getRedCard());
one.setInviterCode(userInfoParam.getInviteCode());
user.setIfUseCode(1);
userService.updateById(one);
userService.updateById(user);
} else {
return ServerResponseEntity.fail("411", "该邀请码不存在");
}
return ServerResponseEntity.success(userService.updateById(user));
}
@PutMapping("/setUserInfo")
@Operation(summary = "设置用户信息", description = "设置用户信息")
public ServerResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
String userId = SecurityUtils.getUser().getUserId();
User user = new User();
user.setUserId(userId);
user.setPic(userInfoParam.getAvatarUrl());
user.setNickName(userInfoParam.getNickName());
userService.updateById(user);
return ServerResponseEntity.success();
}
@Operation(summary = "根据用户id查询积分", description = "根据用户id查询积分")
@GetMapping("/getScoreByUserId")
public ServerResponseEntity<Double> getScoreByUserId() {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
return ServerResponseEntity.success(user.getScore());
}
@Operation(summary = "根据用户查积分记录", description = "根据用户查积分记录")
@GetMapping("/points/list")
public ServerResponseEntity<IPage<ScoreDetail>> getScoreDetailListByUserId(PageParam page) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
return ServerResponseEntity.success(scoreDetailService.getScoreDetailListByUserId(page,userId));
}
@Operation(summary = "获取用户红包", description = "获取红包")
@GetMapping("/redPacketCount")
public ServerResponseEntity<Integer> redPacketCount() {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
return ServerResponseEntity.success(user.getRedCard());
}
@Operation(summary = "获取福利赠送列表",description = "获取福利赠送列表")
@GetMapping("/getWelfareGiftRecordList")
public ServerResponseEntity<List<WelfareGiftRecordDto>> getWelfareGiftRecordList() {
String userId = SecurityUtils.getUser().getUserId();
List<WelfareGiftRecordDto> vipPackageDtoList = welfareGiftRecordService.getWelfareGiftRecordList(userId);
return ServerResponseEntity.success(vipPackageDtoList);
}
@Operation(summary = "获取客服电话号码",description = "获取客服电话号码")
@GetMapping("/getCustomerServiceTel")
public ServerResponseEntity<String> getCustomerServiceTel() {
String customerServiceTel =sysConfigService.getValue("customerServiceTel");
return ServerResponseEntity.success(customerServiceTel);
}
@Operation(summary = "获取VIP套餐列表",description = "获取VIP套餐列表")
@GetMapping("/getVipPackageList")
public ServerResponseEntity<List<VipPackage>> getVipPackageList() {
List<VipPackage> VipPackageList =vipPackageService.getVipPackageList();
return ServerResponseEntity.success(VipPackageList);
}
@Operation(summary = "获取会员排行榜",description = "获取积分首页信息")
@GetMapping("/getVipRank")
public ServerResponseEntity<IPage<UserRankDto>> getVipRank(PageParam page) {
return ServerResponseEntity.success(userService.getVipRank(page));
}
@Operation(summary = "获取积分首页信息",description = "获取VIP套餐列表")
@GetMapping("/getUserScoreInfo")
public ServerResponseEntity<UserScoreDto> getUserScoreInfo() {
String userId = SecurityUtils.getUser().getUserId();
UserScoreDto usersser =userService.getUserScoreInfo(userId);
return ServerResponseEntity.success(usersser);
}
@Operation(summary = "获取拉人进度是否满了",description = "获取VIP套餐列表")
@GetMapping("/getProgress")
public ServerResponseEntity<Double> getProgress() {
String userId = SecurityUtils.getUser().getUserId();
Double progress =userService.getProgress(userId);
return ServerResponseEntity.success(progress);
}
@Operation(summary = "拉人进度记录",description = "拉人进度记录")
@GetMapping("/getRecommendVipList")
public ServerResponseEntity<IPage<RecommendVip>> getRecommendVipList(PageParam page) {
String userId = SecurityUtils.getUser().getUserId();
User user = userService.getById(userId);
return ServerResponseEntity.success(userService.getRecommendVipList(page,user));
}
}

View File

@@ -0,0 +1,171 @@
package com.yami.shop.api.controller;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.UserRegisterParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.InvitationCodeGenerator;
import com.yami.shop.common.util.WeiXinUtil;
import com.yami.shop.security.api.model.Phone;
import com.yami.shop.security.api.wx.AES;
import com.yami.shop.security.api.wx.WxPKCS7Encoder;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.enums.SysTypeEnum;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.common.vo.TokenInfoVO;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.yami.shop.common.util.SpringContextUtils.applicationContext;
/**
* 用户信息
*
* @author SJL
*/
@RestController
@RequestMapping("/user")
@Tag(name = "用户注册相关接口")
@AllArgsConstructor
public class UserRegisterController {
private final UserService userService;
private final UserExtendService userExtendService;
private final PasswordEncoder passwordEncoder;
private final TokenStore tokenStore;
private final PasswordManager passwordManager;
private final InvitationService invitationService;
private final ScoreDetailService scoreDetailService;
private final VipPackageService vipPackageService;
private final WelfareGiftRecordService welfareGiftRecordService;
private static final String WATERMARK = "watermark";
private static final String APPID = "appid";
@Resource
private InvitationCodeGenerator invitationCodeGenerator;
@Autowired
private RestTemplate restTemplate;
@PostMapping("/register")
@Operation(summary = "注册" , description = "用户注册或绑定手机号接口")
public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterParam userRegisterParam) {
if (StrUtil.isBlank(userRegisterParam.getNickName())) {
userRegisterParam.setNickName(userRegisterParam.getUserName());
}
// 正在进行申请注册
if (userService.count(new LambdaQueryWrapper<User>().eq(User::getNickName, userRegisterParam.getNickName())) > 0) {
// 该用户名已注册,无法重新注册
throw new YamiShopBindException("该用户名已注册,无法重新注册");
}
// 校验邀请码
if (StrUtil.isNotBlank(userRegisterParam.getInviteCode())) {
Boolean checkInvitationCode = invitationService.checkInvitationCode(userRegisterParam.getInviteCode());
if (!checkInvitationCode) {
// 邀请码错误
throw new YamiShopBindException("邀请码错误");
}
}
Date now = new Date();
User user = new User();
user.setModifyTime(now);
user.setUserRegtime(now);
user.setStatus(1);
user.setNickName(userRegisterParam.getNickName());
user.setUserMobile(userRegisterParam.getMobile());
//String decryptPassword = passwordManager.decryptPassword(userRegisterParam.getPassWord());
//user.setLoginPassword(passwordEncoder.encode(decryptPassword));
String userId = IdUtil.simpleUUID();
user.setUserId(userId);
userService.save(user);
//添加扩展表
UserExtend userExtend = new UserExtend();
userExtend.setUserId(user.getUserId());
userExtend.setInvitedCode(userRegisterParam.getInviteCode());
userExtendService.save(userExtend);
//新人福利赠送
//赠送酒品
VipPackage vipPackage = vipPackageService.getOne(new LambdaQueryWrapper<VipPackage>().eq(VipPackage::getGrade, 0));
WelfareGiftRecord welfareGiftRecord =new WelfareGiftRecord();
welfareGiftRecord.setUserId(user.getUserId());
welfareGiftRecord.setProdId(vipPackage.getId());
welfareGiftRecord.setCreateTime(new Date());
welfareGiftRecordService.save(welfareGiftRecord);
//赠送积分
ScoreDetail scoreDetail= new ScoreDetail();
scoreDetail.setScoreDescription("新人福利赠送");
scoreDetail.setUserId(user.getUserId());
scoreDetail.setQuantity(vipPackage.getPoints());
scoreDetail.setCreateTime(new Date());
scoreDetailService.save(scoreDetail);
// 2. 登录
UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
userInfoInTokenBO.setUserId(user.getUserId());
userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value());
userInfoInTokenBO.setIsAdmin(0);
userInfoInTokenBO.setEnabled(true);
// 3. 登录成功后,发放酒 todo
// 4. 登录成功
return ServerResponseEntity.success(tokenStore.storeAndGetVo(userInfoInTokenBO));
}
@PutMapping("/updatePwd")
@Operation(summary = "修改密码" , description = "修改密码")
public ServerResponseEntity<Void> updatePwd(@Valid @RequestBody UserRegisterParam userPwdUpdateParam) {
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getNickName, userPwdUpdateParam.getNickName()));
if (user == null) {
// 无法获取用户信息
throw new YamiShopBindException("无法获取用户信息");
}
String decryptPassword = passwordManager.decryptPassword(userPwdUpdateParam.getPassWord());
if (StrUtil.isBlank(decryptPassword)) {
// 新密码不能为空
throw new YamiShopBindException("新密码不能为空");
}
String password = passwordEncoder.encode(decryptPassword);
if (StrUtil.equals(password, user.getLoginPassword())) {
// 新密码不能与原密码相同
throw new YamiShopBindException("新密码不能与原密码相同");
}
user.setModifyTime(new Date());
user.setLoginPassword(password);
userService.updateById(user);
return ServerResponseEntity.success();
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.listener;
import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.app.dto.ShopCartOrderDto;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.event.ConfirmOrderEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.order.ConfirmOrderOrder;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import com.yami.shop.service.TransportManagerService;
import com.yami.shop.service.UserAddrService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 确认订单信息时的默认操作
* @author LGH
*/
@Component("defaultConfirmOrderListener")
@AllArgsConstructor
public class ConfirmOrderListener {
private final UserAddrService userAddrService;
private final TransportManagerService transportManagerService;
private final ProductService productService;
private final SkuService skuService;
/**
* 计算订单金额
*/
@EventListener(ConfirmOrderEvent.class)
@Order(ConfirmOrderOrder.DEFAULT)
public void defaultConfirmOrderEvent(ConfirmOrderEvent event) {
ShopCartOrderDto shopCartOrderDto = event.getShopCartOrderDto();
OrderParam orderParam = event.getOrderParam();
// 订单的地址信息
//UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);
double total = 0.0;
int totalCount = 0;
double transfee = 0.0;
double pointsTotal = 0.0;
double originalTotal = 0.0;
for (ShopCartItemDto shopCartItem : event.getShopCartItems()) {
// 获取商品信息
Product product = productService.getProductByProdId(shopCartItem.getProdId());
// 获取sku信息
Sku sku = skuService.getSkuBySkuId(shopCartItem.getSkuId());
if (product == null || sku == null) {
throw new YamiShopBindException("购物车包含无法识别的商品");
}
if (product.getStatus() != 1 || sku.getStatus() != 1) {
throw new YamiShopBindException("商品[" + sku.getProdName() + "]已下架");
}
totalCount = shopCartItem.getProdCount() + totalCount;
total = Arith.add(shopCartItem.getProductTotalAmount(), total);
pointsTotal = shopCartItem.getPoints() + pointsTotal;
originalTotal = Arith.add(originalTotal, shopCartItem.getProductOriginalTotalAmount());
// 用户地址如果为空,则表示该用户从未设置过任何地址相关信息
/*if (userAddr != null) {
// 每个产品的运费相加
transfee = Arith.add(transfee, transportManagerService.calculateTransfee(shopCartItem, userAddr));
}*/
shopCartItem.setActualTotal(shopCartItem.getProductTotalAmount());
shopCartOrderDto.setActualTotal(Arith.add(total, transfee));
shopCartOrderDto.setTotal(originalTotal);
shopCartOrderDto.setPointsTotal(pointsTotal);
shopCartOrderDto.setProdNumber(product.getProdNumber());
shopCartOrderDto.setOrderType(product.getType());
shopCartOrderDto.setTotalCount(totalCount);
shopCartOrderDto.setTransfee(transfee);
}
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.listener;
import com.google.common.collect.Lists;
import com.yami.shop.bean.app.dto.ShopCartDto;
import com.yami.shop.bean.app.dto.ShopCartItemDiscountDto;
import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.event.ShopCartEvent;
import com.yami.shop.bean.order.ShopCartEventOrder;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 默认的购物车链进行组装时的操作
* @author LGH
*/
@Component("defaultShopCartListener")
public class ShopCartListener {
/**
* 将店铺下的所有商品归属到该店铺的购物车当中
* @param event#getShopCart() 购物车
* @param event#shopCartItemDtoList 该购物车的商品
* @return 是否继续组装
*/
@EventListener(ShopCartEvent.class)
@Order(ShopCartEventOrder.DEFAULT)
public void defaultShopCartEvent(ShopCartEvent event) {
ShopCartDto shopCart = event.getShopCartDto();
List<ShopCartItemDto> shopCartItemDtoList = event.getShopCartItemDtoList();
// 对数据进行组装
List<ShopCartItemDiscountDto> shopCartItemDiscountDtoList = Lists.newArrayList();
ShopCartItemDiscountDto shopCartItemDiscountDto = new ShopCartItemDiscountDto();
shopCartItemDiscountDto.setShopCartItems(shopCartItemDtoList);
shopCartItemDiscountDtoList.add(shopCartItemDiscountDto);
shopCart.setShopCartItemDiscounts(shopCartItemDiscountDtoList);
}
}

View File

@@ -0,0 +1,300 @@
/*
* Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
*
* https://www.mall4j.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.api.listener;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.yami.shop.bean.app.dto.ShopCartItemDiscountDto;
import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.app.dto.ShopCartOrderDto;
import com.yami.shop.bean.app.dto.ShopCartOrderMergerDto;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.event.SubmitOrderEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.order.SubmitOrderOrder;
import com.yami.shop.common.constants.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.*;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import com.yami.shop.service.UserAddrOrderService;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* 确认订单信息时的默认操作
*
* @author LGH
*/
@Component("defaultSubmitOrderListener")
@AllArgsConstructor
public class SubmitOrderListener {
private final UserAddrOrderService userAddrOrderService;
private final ProductService productService;
private final SkuService skuService;
private final Snowflake snowflake;
private final OrderItemMapper orderItemMapper;
private final SkuMapper skuMapper;
private final ProductMapper productMapper;
private final OrderMapper orderMapper;
private final OrderSettlementMapper orderSettlementMapper;
private final BasketMapper basketMapper;
/**
* 计算订单金额
*/
@EventListener(SubmitOrderEvent.class)
@Order(SubmitOrderOrder.DEFAULT)
public void defaultSubmitOrderListener(SubmitOrderEvent event) {
Date now = new Date();
ShopCartOrderMergerDto mergerOrder = event.getMergerOrder();
String userId = SecurityUtils.getUser().getUserId();
// 订单商品参数
List<ShopCartOrderDto> shopCartOrders = mergerOrder.getShopCartOrders();
List<Long> basketIds = new ArrayList<>();
// 商品skuId为key 需要更新的sku为value的map
Map<Long, Sku> skuStocksMap = new HashMap<>(16);
// 商品productId为key 需要更新的product为value的map
Map<Long, Product> prodStocksMap = new HashMap<>(16);
// 把订单地址保存到数据库
UserAddrOrder userAddrOrder = BeanUtil.copyProperties(mergerOrder.getUserAddr(), UserAddrOrder.class);
if (userAddrOrder == null) {
throw new YamiShopBindException("请填写收货地址");
}
userAddrOrder.setUserId(userId);
userAddrOrder.setCreateTime(now);
userAddrOrderService.save(userAddrOrder);
// 订单地址id
Long addrOrderId = userAddrOrder.getAddrOrderId();
// 每个店铺生成一个订单
for (ShopCartOrderDto shopCartOrderDto : shopCartOrders) {
createOrder(event, now, mergerOrder.getUserId(), basketIds, skuStocksMap, prodStocksMap, addrOrderId, shopCartOrderDto,mergerOrder.getOrderNumber());
}
// 删除购物车的商品信息
if (!basketIds.isEmpty()) {
basketMapper.deleteShopCartItemsByBasketIds(mergerOrder.getUserId(), basketIds);
}
// 更新sku库存
skuStocksMap.forEach((key, sku) -> {
if (skuMapper.updateStocks(sku) == 0) {
skuService.removeSkuCacheBySkuId(key, sku.getProdId());
throw new YamiShopBindException("商品:[" + sku.getProdName() + "]库存不足");
}
});
// 更新商品库存
prodStocksMap.forEach((prodId, prod) -> {
if (productMapper.updateStocks(prod) == 0) {
productService.removeProductCacheByProdId(prodId);
throw new YamiShopBindException("商品:[" + prod.getProdName() + "]库存不足");
}
});
}
private void createOrder(SubmitOrderEvent event, Date now, String userId, List<Long> basketIds, Map<Long, Sku> skuStocksMap, Map<Long, Product> prodStocksMap, Long addrOrderId, ShopCartOrderDto shopCartOrderDto,String payNumber) {
// 使用雪花算法生成的订单号
String orderNumber = String.valueOf(snowflake.nextId());
shopCartOrderDto.setOrderNumber(orderNumber);
Long shopId = shopCartOrderDto.getShopId();
// 订单商品名称
StringBuilder orderProdName = new StringBuilder(100);
List<OrderItem> orderItems = new ArrayList<>();
List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrderDto.getShopCartItemDiscounts();
for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
List<ShopCartItemDto> shopCartItems = shopCartItemDiscount.getShopCartItems();
for (ShopCartItemDto shopCartItem : shopCartItems) {
Sku sku = checkAndGetSku(shopCartItem.getSkuId(), shopCartItem, skuStocksMap);
Product product = checkAndGetProd(shopCartItem.getProdId(), shopCartItem, prodStocksMap);
OrderItem orderItem = getOrderItem(now, userId, orderNumber, shopId, orderProdName, shopCartItem, sku, product);
orderItems.add(orderItem);
if (shopCartItem.getBasketId() != null && shopCartItem.getBasketId() != 0) {
basketIds.add(shopCartItem.getBasketId());
}
}
}
orderProdName.subSequence(0, Math.min(orderProdName.length() - 1, 100));
if (orderProdName.lastIndexOf(Constant.COMMA) == orderProdName.length() - 1) {
orderProdName.deleteCharAt(orderProdName.length() - 1);
}
// 订单信息
com.yami.shop.bean.model.Order order = getOrder(now, userId, addrOrderId, shopCartOrderDto, orderNumber, shopId, orderProdName, orderItems,payNumber);
event.getOrders().add(order);
// 插入订单结算表
OrderSettlement orderSettlement = new OrderSettlement();
orderSettlement.setUserId(userId);
orderSettlement.setIsClearing(0);
orderSettlement.setCreateTime(now);
orderSettlement.setShopId(shopId);
orderSettlement.setOrderNumber(orderNumber);
orderSettlement.setPayNo(payNumber);
orderSettlement.setPayAmount(order.getActualTotal());
orderSettlement.setPayStatus(0);
orderSettlement.setVersion(0);
orderSettlement.setType(0);
orderSettlementMapper.insert(orderSettlement);
}
private com.yami.shop.bean.model.Order getOrder(Date now, String userId, Long addrOrderId, ShopCartOrderDto shopCartOrderDto, String orderNumber, Long shopId, StringBuilder orderProdName, List<OrderItem> orderItems,String payNumber) {
com.yami.shop.bean.model.Order order = new com.yami.shop.bean.model.Order();
order.setShopId(shopId);
order.setOrderNumber(orderNumber);
// 订单商品名称
order.setProdName(orderProdName.toString());
// 用户id
order.setUserId(userId);
// 商品总额
order.setTotal(shopCartOrderDto.getTotal());
// 实际总额
order.setActualTotal(shopCartOrderDto.getActualTotal());
order.setStatus(OrderStatus.UNPAY.value());
order.setPayOrder(payNumber);
order.setUpdateTime(now);
order.setCreateTime(now);
order.setIsPayed(0);
order.setDeleteStatus(0);
order.setPointsTotal(shopCartOrderDto.getPointsTotal());
order.setProdNumber(shopCartOrderDto.getProdNumber());
order.setProductNums(shopCartOrderDto.getTotalCount());
order.setOrderType(shopCartOrderDto.getOrderType());
order.setAddrOrderId(addrOrderId);
order.setReduceAmount(Arith.sub(shopCartOrderDto.getTotal(), shopCartOrderDto.getActualTotal()));
order.setFreightAmount(shopCartOrderDto.getTransfee());
order.setRemarks(shopCartOrderDto.getRemarks());
order.setOrderItems(orderItems);
return order;
}
private OrderItem getOrderItem(Date now, String userId, String orderNumber, Long shopId, StringBuilder orderProdName, ShopCartItemDto shopCartItem, Sku sku, Product product) {
OrderItem orderItem = new OrderItem();
orderItem.setShopId(shopId);
orderItem.setOrderNumber(orderNumber);
orderItem.setProdId(sku.getProdId());
orderItem.setSkuId(sku.getSkuId());
orderItem.setSkuName(sku.getSkuName());
orderItem.setProdCount(shopCartItem.getProdCount());
orderItem.setPoints(shopCartItem.getPoints());
orderItem.setProdName(sku.getProdName());
orderItem.setPic(StrUtil.isBlank(sku.getPic()) ? product.getPic() : sku.getPic());
orderItem.setPrice(shopCartItem.getPrice());
orderItem.setUserId(userId);
orderItem.setOriPrice(sku.getOriPrice());
orderItem.setProductTotalAmount(shopCartItem.getProductTotalAmount());
orderItem.setRecTime(now);
orderItem.setCommSts(0);
orderItem.setBasketDate(shopCartItem.getBasketDate());
orderProdName.append(orderItem.getProdName()).append(",");
//推广员卡号
orderItem.setDistributionCardNo(shopCartItem.getDistributionCardNo());
return orderItem;
}
@SuppressWarnings({"Duplicates"})
private Product checkAndGetProd(Long prodId, ShopCartItemDto shopCartItem, Map<Long, Product> prodStocksMap) {
Product product = productService.getProductByProdId(prodId);
if (product == null) {
throw new YamiShopBindException("购物车包含无法识别的商品");
}
if (product.getStatus() != 1) {
throw new YamiShopBindException("商品[" + product.getProdName() + "]已下架");
}
// 商品需要改变的库存
Product mapProduct = prodStocksMap.get(prodId);
if (mapProduct == null) {
mapProduct = new Product();
mapProduct.setTotalStocks(0);
mapProduct.setProdId(prodId);
mapProduct.setProdName(product.getProdName());
}
if (product.getTotalStocks() != -1) {
mapProduct.setTotalStocks(mapProduct.getTotalStocks() + shopCartItem.getProdCount());
prodStocksMap.put(product.getProdId(), mapProduct);
}
// -1为无限库存
if (product.getTotalStocks() != -1 && mapProduct.getTotalStocks() > product.getTotalStocks()) {
throw new YamiShopBindException("商品:[" + product.getProdName() + "]库存不足");
}
return product;
}
@SuppressWarnings({"Duplicates"})
private Sku checkAndGetSku(Long skuId, ShopCartItemDto shopCartItem, Map<Long, Sku> skuStocksMap) {
// 获取sku信息
Sku sku = skuService.getSkuBySkuId(skuId);
if (sku == null) {
throw new YamiShopBindException("购物车包含无法识别的商品");
}
if (sku.getStatus() != 1) {
throw new YamiShopBindException("商品[" + sku.getProdName() + "]已下架");
}
// -1为无限库存
if (sku.getStocks() != -1 && shopCartItem.getProdCount() > sku.getStocks()) {
throw new YamiShopBindException("商品:[" + sku.getProdName() + "]库存不足");
}
if (sku.getStocks() != -1) {
Sku mapSku = new Sku();
mapSku.setProdId(sku.getProdId());
// 这里的库存是改变的库存
mapSku.setStocks(shopCartItem.getProdCount());
mapSku.setSkuId(sku.getSkuId());
mapSku.setProdName(sku.getProdName());
skuStocksMap.put(sku.getSkuId(), mapSku);
}
return sku;
}
}

View File

@@ -0,0 +1,3 @@
api.datacenterId=1
api.workerId=1
api.domainName=http://xxx.com

View File

@@ -0,0 +1,29 @@
server:
port: 8086
spring:
datasource:
# url: jdbc:mysql://127.0.0.1:3306/yami_shops?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
# username: root
# password: root
# url: jdbc:mysql://120.55.64.3:3306/yami_shops?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
# username: mall
# password: 123456
url: jdbc:mysql://43.136.31.205:3306/yami_shops?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
username: yami_shops
password: LmBK6pR2wb35ceZh
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 0
maximum-pool-size: 20
idle-timeout: 10000
connection-test-query: select 1
data:
redis:
host: 43.136.31.205
port: 6379
database: 0
password: ygyx8888Redis
logging:
config: classpath:logback/logback-dev.xml

View File

@@ -0,0 +1,21 @@
server:
port: 8086
spring:
datasource:
url: jdbc:mysql://${MYSQL_HOST:mall4j-mysql}:${MYSQL_PORT:3306}/${MYSQL_DATABASE:yami_shops}?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
username: ${MYSQL_USERNAME:root}
password: ${MYSQL_PASSWORD:root}
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 0
maximum-pool-size: 20
connection-test-query: select 1
data:
redis:
host: ${REDIS_HOST:mall4j-redis}
port: ${REDIS_PORT:6379}
database: ${REDIS_DATABASE:0}
logging:
config: classpath:logback/logback-prod.xml

View File

@@ -0,0 +1,29 @@
server:
port: 8086
spring:
datasource:
# url: jdbc:mysql://127.0.0.1:3306/yami_shops?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
# username: root
# password: root
# url: jdbc:mysql://120.55.64.3:3306/yami_shops?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
# username: mall
# password: 123456
url: jdbc:mysql://43.136.31.205:3306/ygsx?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
username: ygsx
password: Aije2zrwC57DfMkG
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 0
maximum-pool-size: 20
idle-timeout: 10000
connection-test-query: select 1
data:
redis:
host: 43.136.31.205
port: 6379
database: 0
password: ygyx8888Redis
logging:
config: classpath:logback/logback-prod.xml

View File

@@ -0,0 +1,85 @@
spring:
# 环境 dev|test|prod
profiles:
active: prod
#文件上传设置
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
enabled: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
springdoc:
swagger-ui:
path: /swagger-ui.html # Swagger UI 的访问路径
enabled: true # 是否启用 Swagger UI
api-docs:
enabled: true # 是否启用 OpenAPI 文档
default-produces-media-type: application/json # 默认的响应类型
# mybaits-plus配置
mybatis-plus:
# MyBatis Mapper所对应的XML文件位置
mapper-locations: classpath*:/mapper/*Mapper.xml
global-config:
# 关闭MP3.0自带的banner
banner: false
db-config:
# 主键类型 0:数据库ID自增 1.未定义 2.用户输入 3 id_worker 4.uuid 5.id_worker字符串表示
id-type: AUTO
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: NOT_NULL
# 默认数据库表下划线命名
table-underline: true
management:
server:
add-application-context-header: false
sa-token:
# token名称 (同时也是cookie名称)
token-name: Authorization
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
is-concurrent: true
# 在多人登录同一账号时是否共用一个token(不共用,避免登出时导致其他用户也登出)
is-share: false
# token风格(默认可取值uuid、simple-uuid、random-32、random-64、random-128、tik)
token-style: uuid
# 是否输出操作日志
is-log: false
weixin:
appid: wxbaf1ebff9086ba2a
secret: bb323f7e812b7de68504839c416e121b
mch-id: 1717077975
mch-serial-no: 6B152DA761E83C9DBD475432C1C2C01D9D5A1B64
api-v3key: RJy16FrDXFsOXA1BnzSKMNEOx0Sf4Xhr
package-name: Sign=WXPay
notify-url: https://ygyx.tashowz.com/p/pay/callback
# notify-url: http://v4368262.natappfree.cc/p/pay/callback
public-key-id: PUB_KEY_ID_0117170779752025051500351958000803
key-path: classpath:cert/apiclient_key.pem
cert-path: classpath:cert/apiclient_cert.pem
public-key: classpath:cert/pub_key.pem
guomchId: 1652719901
guomch-serial-no: 42E0E6DCE1D1AAD2EACC8E6C3F9B58DBDC9CFF61
guoapi-v3key: UiKhk3C4KqBX6gRedobj6SfNsTsQm6xr
guopackage-name: Sign=WXPay
guokey-path: classpath:cert/apiclient_guo_key.pem
guocert-path: classpath:cert/apiclient_guo_cert.pem
# guonotify-url: http://v4368262.natappfree.cc/p/pay/guoCallback
guonotify-url: https://ygyx.tashowz.com/p/pay/guoCallback
refund_notify-url: https://ygyx.tashowz.com/p/pay/refundCallback
#refund_notify-url: http://v4368262.natappfree.cc/p/pay/refundCallback
#zhangmchId: 1707281494
#zhangmch-serial-no: 64F7515CFA320E3CC4B805512C6508A1D6391E6E
#zhangapi-v3key: 141231QWERTYUIOPasdfghjklzxcvbnm
#zhangpackage-name: Sign=WXPay
#zhangpublic-key-id: PUB_KEY_ID_0117088867612025030500298900002052
#zhangkey-path: classpath:cert/apiclient_zhang_key.pem
#zhangcert-path: classpath:cert/apiclient_zhang_cert.pem
#zhangnotify-url: http://ttqe5n.natappfree.cc/p/pay/zhangCallback
#zhangnotify-url: https://ygyx.tashowz.com/p/pay/zhangCallback

View File

@@ -0,0 +1,11 @@
.----------------. .----------------. .----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |
| | ____ ____ | || | __ | || | _____ | || | _____ | || | _ _ | || | _____ | |
| ||_ \ / _|| || | / \ | || | |_ _| | || | |_ _| | || | | | | | | || | |_ _| | |
| | | \/ | | || | / /\ \ | || | | | | || | | | | || | | |__| |_ | || | | | | |
| | | |\ /| | | || | / ____ \ | || | | | _ | || | | | _ | || | |____ _| | || | _ | | | |
| | _| |_\/_| |_ | || | _/ / \ \_ | || | _| |__/ | | || | _| |__/ | | || | _| |_ | || | | |_' | | |
| ||_____||_____|| || ||____| |____|| || | |________| | || | |________| | || | |_____| | || | `.___.' | |
| | | || | | || | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------' '----------------' '----------------'

View File

@@ -0,0 +1,25 @@
-----BEGIN CERTIFICATE-----
MIIEKDCCAxCgAwIBAgIUaxUtp2HoPJ29R1QywcLAHZ1aG2QwDQYJKoZIhvcNAQEL
BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
Q0EwHhcNMjUwNTE1MDk1OTM5WhcNMzAwNTE0MDk1OTM5WjCBgTETMBEGA1UEAwwK
MTcxNzA3Nzk3NTEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMS0wKwYDVQQL
DCTnpo/lt57mmJPotK3kvJjkuqvnp5HmioDmnInpmZDlhazlj7gxCzAJBgNVBAYT
AkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAKI8i5FihQk4788PwjVHL2W5fsGgaqudBvhqb3ZQTQq2zdymrRqaoHqQ
GJxxsO2MhCEWGEiMe3C0x4AvGdaiDGdK6Q8Tp/aamiJqJE4nwXKNI6giXiTQFGcY
wnw/jo2Vze9cq0Wtx7Km4dqhxHxJRRCu2L/NqGLRF/JEeWPW9B7WkSjWavua/Ez7
B1qbwQpFCzF4r6syK3LmGpAc2pJ3qogP5oth4U04dMdht6+44vcoO6i9L7YBmOvj
Rvo4sinHyBvoXggWnC1UVkqwU2jN3XTSGg+GfTAM+J6ZzC/8czj9mycRU/Ny9GHv
vlMNfW3sjF5TswBrd+0sRsgGyVafCRsCAwEAAaOBuTCBtjAJBgNVHRMEAjAAMAsG
A1UdDwQEAwID+DCBmwYDVR0fBIGTMIGQMIGNoIGKoIGHhoGEaHR0cDovL2V2Y2Eu
aXRydXMuY29tLmNuL3B1YmxpYy9pdHJ1c2NybD9DQT0xQkQ0MjIwRTUwREJDMDRC
MDZBRDM5NzU0OTg0NkMwMUMzRThFQkQyJnNnPUhBQ0M0NzFCNjU0MjJFMTJCMjdB
OUQzM0E4N0FEMUNERjU5MjZFMTQwMzcxMA0GCSqGSIb3DQEBCwUAA4IBAQBeyD+y
W2cC7vJKNTiNSC3kzNataj7h13bif0X7Gep5yxfg6aLql28+DtVM580s72HyYD73
DZ2CK19tlLA+OHEBcLGWbPI602UYby1apTD7coFJVu/BuvchH/Rz1PpA5pAq2vHI
harpCNEgdqSGZJG+2IICKOUT8atzbd/YsbBL67bPXcotsX1fjv/dc1Gr7W+mjtL+
OhZ2Ym4Alx5i8Q4l81n+Xm4mkJ34Ed69wBVQ1Z5lf6Q/6T2OJXt2Vaa1Jya5Wu3b
1mw4S4nEGpNfiVPAcYdq5zWH6Qfjf5dk9q6vQF6qq5tpMDxfC8OJoUBmKDyyPeKh
AkpqpPh/5jfWXQF/
-----END CERTIFICATE-----

View File

@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCiPIuRYoUJOO/P
D8I1Ry9luX7BoGqrnQb4am92UE0Kts3cpq0amqB6kBiccbDtjIQhFhhIjHtwtMeA
LxnWogxnSukPE6f2mpoiaiROJ8FyjSOoIl4k0BRnGMJ8P46Nlc3vXKtFrceypuHa
ocR8SUUQrti/zahi0RfyRHlj1vQe1pEo1mr7mvxM+wdam8EKRQsxeK+rMity5hqQ
HNqSd6qID+aLYeFNOHTHYbevuOL3KDuovS+2AZjr40b6OLIpx8gb6F4IFpwtVFZK
sFNozd100hoPhn0wDPiemcwv/HM4/ZsnEVPzcvRh775TDX1t7IxeU7MAa3ftLEbI
BslWnwkbAgMBAAECggEAN1b1uLLldF7iljvm4CuXBFkA3uVsXXujzArqWG5NyVDP
6etE8uU5xnTuoDa7xlv/GhYiVGTvGmPgBV6LrsX5+yX3V7g5vAnCd+jC15ICD6QL
PKf0exQrUXuFo8I+SxeFdpeiqJL9ongAZIZ3snl/wJATyWFKheKTC4XF7oN9JCM7
oPzJk481hEhpLCnG+ZJCljrcq8xkP2yn4IcRnL7EjkcECOvtpp7YbijhxNuxrQwH
JrRYZcH2+c49TbiBOr659Fj+O21NGXTuVmpT44Fjo+tfb8MmIynTMYaQrjV5PD4b
GetCjgD0kKPiTtEn1La5aRjIr7saLNwEbXbgFstDQQKBgQDTm2JFKZNVVeQOJoQ7
mZu4qwPgskQGslEsiYV6eTxhEJka1ZYW2lYeJnjK1t+Pj3gzxCraKNFS+nqIv0W1
Yj2tHnFm1hfTI5I3z61KhyFWNJLpbETmOqV/VyvH4ID0Iv5uapYgKJDat9GOk5xl
Mi/7NzfJvvvxAnwnRpSvBqYX+wKBgQDERai0Om+2OXmxOUevXD2ViMOtN47meCD0
yqGoRL5ERGIq+f2ZPxsacGLOHS/HcmMERvgmJAwockVytSPCoB+nru4ua+No9lAq
sgSCKscSR/EwcQXcAg8BmDZBulXWq7vS95E34LFPXZfk++C9eDqaBLHfPbRxlTkA
H3CM7G5pYQKBgQC+C4B/ky5iZshyOP9rs7KacOUDqbbUuNOUh1Icw8OJfWm0Iv0w
Oxk67Nxxd/fCrFyNSXIfCqesuY7RP8+wbrHryDqa3E77bqgEff0pwSEclg0XnQho
KWW3bye/1I6cNM2DhzCbYzNta8fGICZG8IMNQPNWurL1KoEsmQQyCWukfwKBgG19
rq9cKhWt2oVTPvpEqtZQhViMNdu8CCaHI8eLEdljjKAM9bwXyDbnmzcAcTcCSNqJ
/MTKNz4ZAUUMZ/aa/Q2+OIENDr/vKKmoxXsYAhXgrFwpsOsa+uQY1au1F026X/1A
vnI9lqx/ucyz9pu8BnUFSXUQJyl15WZ8I316J94BAoGAT/K+yjFOT4Cxl6EHQ7JV
YAgXTMauqNpxW82HiMmjxZBdUda/uvp08Soenn+NJelYiJHKW5NZaUeFJwFCOp9U
s3+jR88SsAanxWKsEYDFTo8LPOZdyE89rlJC5Qk/Vid0m0iudsjBTdVPNXB1PzhJ
oFlKzD3F2IdhU97BS5z9a/g=
-----END PRIVATE KEY-----

View File

@@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryoh+5AFxoHzJpoEaHww
+AQhlfVhtNs676+KdBVxxX86txh6BaRwQgnsK8D27xbHdiwlltKwXkmaByWL+g/q
wDiaDm2waCXZesFJn25d1bEPsC/wdBVGiR57JRYFz9r3TFTtc6gvgLM9VeaY4AlD
8DnWUrP6IdiyZGlSlWW/Zvs1q2OvShpaKwJYAWrQ0MZBpjt3NtuuTNA8yjcRtT1e
dTDuO0mYhY+uPmNtuaYZg5KV0z2MVmLRAkUEh8sIX9sbzDvrZ8exUuZCYuAAr8Jn
Qx6EbZCZLh1jWq2YcukDakPs37lHFiPuFtwmloXm3QWVNUhTePIOnLxNCZYMCMBr
HwIDAQAB
-----END PUBLIC KEY-----

View File

@@ -0,0 +1,15 @@
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="info">
<appender-ref ref="CONSOLE" />
</root>
<logger name="com.yami.shop" level="debug"/>
<logger name="springfox.documentation.swagger2" level="off"/>
<logger name="io.swagger.models.parameters" level="off"/>
<logger name="springfox.documentation.swagger.readers.operation.OperationImplicitParameterReader" level="off"/>
<logger name="springfox.documentation.spring.web.readers.operation" level="off"/>
</configuration>

View File

@@ -0,0 +1,39 @@
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="PROJECT_PATH" value="/opt/projects/yami-shops"/>
<property name="LOG_FILE_MAX_HISTORY" value="30"/>
<property name="LOG_FILE_MAX_SIZE" value="50MB"/>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<appender name="DefaultFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<append>true</append>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
<file>${PROJECT_PATH}/log/api.log</file>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${logging.level}</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${PROJECT_PATH}/log/api/%d{yyyy-MM}/api-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
<maxFileSize>${LOG_FILE_MAX_SIZE}</maxFileSize>
<maxHistory>${LOG_FILE_MAX_HISTORY}</maxHistory>
</rollingPolicy>
</appender>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DefaultFile" />
</root>
<logger name="com.yami.shop" level="debug"/>
<logger name="springfox.documentation.swagger2" level="off"/>
<logger name="io.swagger.models.parameters" level="off"/>
<logger name="springfox.documentation.swagger.readers.operation.OperationImplicitParameterReader" level="off"/>
<logger name="springfox.documentation.spring.web.readers.operation" level="off"/>
</configuration>