Commit 36bd54cc authored by chew's avatar chew

首次提交

parents
Pipeline #826 canceled with stages
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ekingwin</groupId>
<artifactId>tms_app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tms_app</name>
<description>tms_app</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-security</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- MyBatis-Plus (替代 MyBatis Framework) -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- RabbitMQ (AMQP) -->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-amqp</artifactId>-->
<!-- </dependency>-->
<!-- Jackson for JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- 工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.ekingwin.tms_app.TmsAppApplication</mainClass>
<!-- <skip>true</skip>-->
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.ekingwin.tms_app;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = {
SecurityAutoConfiguration.class,
})
@MapperScan("com.ekingwin.**.dao")
public class TmsAppApplication {
public static void main(String[] args) {
SpringApplication.run(TmsAppApplication.class, args);
}
}
package com.ekingwin.tms_app.common;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
/**
* Redis配置类,启用缓存声明,配置redisTemplate,定义CacheManager以及缓存key的序列化方式
*
* @author chenjb
*/
@Configuration
//启用缓存,这个注解很重要;
@EnableCaching
// 继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
public class RedisConfig extends CachingConfigurerSupport {
@Value("${bas.cloud.cache.redis.ttl:30}")
private int ttl;
// @Resource
// private LettuceConnectionFactory lettuceConnectionFactory;
/**
* redisTemplate需要额外进行配置
*
* @param redisConnectionFactory
* @return
*/
@Bean("redisTemplate")
public static RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
// //开启redis的事务支持
// template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
/**
* 缓存管理器.这里的配置是spring的缓存注解使用的
*
* @param redisConnectionFactory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置CacheManager的值序列化方式为json序列化
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair);
//设置默认超过期时间是30秒
defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(this.ttl)).disableCachingNullValues();
/* 配置test的超时时间为120s*/
// RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter
// (connectionFactory)).cacheDefaults(defaultCacheConfig).withInitialCacheConfigurations(singletonMap
// ("test", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(120L))
// .disableCachingNullValues())).transactionAware().build();
//初始化RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
/**
* 自定义key. 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key
* 当然如果你每次都自定义key的话,可以不用这个方法
*/
@Override
@Bean
public KeyGenerator keyGenerator() {
return (o, method, objects) -> {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
};
}
}
\ No newline at end of file
package com.ekingwin.tms_app.common.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String defaultPassword;
}
\ No newline at end of file
package com.ekingwin.tms_app.common.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "app.jwt")
public class JwtConfig {
private String secret;
private Integer expireHours; // 小时数
}
\ No newline at end of file
//package com.ekingwin.tms_app.common.config;
//
//import org.springframework.amqp.core.*;
//import org.springframework.amqp.rabbit.connection.ConnectionFactory;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
//import org.springframework.amqp.support.converter.MessageConverter;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//@Configuration
//public class RabbitMQConfig {
//
// // 定义交换器名称
// public static final String LOGIN_LOG_EXCHANGE = "tms.login.exchange";
// // 定义队列名称
// public static final String LOGIN_LOG_QUEUE = "tms.login.queue";
// // 定义路由键
// public static final String LOGIN_LOG_ROUTING_KEY = "login.log";
//
// // 声明队列(持久化)
// @Bean
// public Queue loginLogQueue() {
// return QueueBuilder.durable(LOGIN_LOG_QUEUE).build();
// }
//
// // 声明主题交换器(也可用Direct)
// @Bean
// public TopicExchange loginLogExchange() {
// return ExchangeBuilder.topicExchange(LOGIN_LOG_EXCHANGE).durable(true).build();
// }
//
// // 绑定队列到交换器
// @Bean
// public Binding loginLogBinding() {
// return BindingBuilder.bind(loginLogQueue())
// .to(loginLogExchange())
// .with(LOGIN_LOG_ROUTING_KEY);
// }
//
// // 配置 Jackson 消息转换器(自动序列化/反序列化对象为 JSON)
// @Bean
// public MessageConverter messageConverter() {
// return new Jackson2JsonMessageConverter();
// }
//
// // 自定义 RabbitTemplate,使用 JSON 转换器
// @Bean
// public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
// RabbitTemplate template = new RabbitTemplate(connectionFactory);
// template.setMessageConverter(messageConverter());
// // 开启 mandatory,确保消息不可达时返回
// template.setMandatory(true);
// return template;
// }
//}
\ No newline at end of file
package com.ekingwin.tms_app.common.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "app.security")
public class SecurityConfig {
private Integer maxFailCount = 5; // 默认5次
private Long lockDurationMinutes = 30L; // 默认30分钟
}
package com.ekingwin.tms_app.common.config;
import com.ekingwin.tms_app.common.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private JwtInterceptor jwtInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor).addPathPatterns("/**");
}
}
package com.ekingwin.tms_app.common.dto;
import lombok.Data;
import java.util.List;
@Data
public class PageResult<T> {
private long total;
private List<T> list;
public static <T> PageResult<T> of(long total, List<T> list) {
PageResult<T> result = new PageResult<>();
result.setTotal(total);
result.setList(list);
return result;
}
}
package com.ekingwin.tms_app.common.dto;
import lombok.Data;
@Data
public class Result<T> {
private Integer code;
private String msg;
private T data;
public static <T> Result<T> success(T data) {
Result<T> r = new Result<>();
r.code = 200;
r.msg = "success";
r.data = data;
return r;
}
public static <T> Result<T> error(String msg) {
Result<T> r = new Result<>();
r.code = 500;
r.msg = msg;
return r;
}
}
package com.ekingwin.tms_app.common.event;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginLogEvent implements Serializable {
private static final long serialVersionUID = 1L;
private String userId;
private String ip;
private Date loginTime;
private String token;
private String deviceInfo; // 新增:设备信息(User-Agent)
@Override
public String toString() {
return "LoginLogEvent{" +
"userId='" + userId + '\'' +
", ip='" + ip + '\'' +
", loginTime=" + loginTime +
", token='" + token + '\'' +
", deviceInfo='" + deviceInfo + '\'' +
'}';
}
}
package com.ekingwin.tms_app.common.exception;
import com.ekingwin.tms_app.common.dto.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理业务异常(如用户不存在、密码错误、账号锁定等)
*/
@ExceptionHandler(RuntimeException.class)
public Result<Void> handleRuntimeException(RuntimeException e) {
// 返回 500 业务状态码,msg 为异常信息
return Result.error(e.getMessage());
}
/**
* 处理其他未捕获的异常(可选)
*/
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
e.printStackTrace(); // 打印日志
return Result.error("系统繁忙,请稍后重试");
}
}
package com.ekingwin.tms_app.common.interceptor;
import com.ekingwin.tms_app.common.util.JwtUtil;
import com.ekingwin.tms_app.common.util.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Log4j2
@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private RedisUtil redisUtil;
@Autowired
private JwtUtil jwtUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
System.out.println(">>> [DEBUG] JwtInterceptor 拦截到请求: " + path); // <---
// 白名单:以 /auth/login、/auth/logout 结尾,或包含 /actuator
if (path.endsWith("/auth/login") || path.endsWith("/auth/logout") || path.contains("/actuator")) {
return true;
}
String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
response.setStatus(401);
response.getWriter().write("missing token");
return false;
}
String token = authHeader.substring(7);
log.info(">>> [DEBUG] 解析 Token..."+token);
try {
Claims claims = jwtUtil.parseJwt(token);
String jti = claims.getId();
if (Boolean.TRUE.equals(redisUtil.hasKey("blacklist:token:" + jti))) {
response.setStatus(401);
response.getWriter().write("token invalidated");
return false;
}
String userId = claims.getSubject();
log.info(">>> [DEBUG] 解析成功,用户 ID: " + userId);
request.setAttribute("userId", userId);
return true;
} catch (Exception e) {
response.setStatus(401);
response.getWriter().write("invalid token");
return false;
}
}
}
\ No newline at end of file
package com.ekingwin.tms_app.common.util;
import com.ekingwin.tms_app.common.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.UUID;
@Component
public class JwtUtil {
@Autowired
private JwtConfig jwtConfig;
public String generateJwt(String userId) {
long expireMillis = jwtConfig.getExpireHours() * 3600_000L;
return Jwts.builder()
.setSubject(userId)
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expireMillis))
.signWith(SignatureAlgorithm.HS256, jwtConfig.getSecret())
.compact();
}
public Claims parseJwt(String token) {
return Jwts.parser()
.setSigningKey(jwtConfig.getSecret())
.parseClaimsJws(token)
.getBody();
}
}
\ No newline at end of file
This diff is collapsed.
package com.ekingwin.tms_app.consumer;
//@Component
public class LoginLogConsumer {
//
// @Autowired
// private LoginLogMapper loginLogMapper;
//
// @RabbitListener(queues = "tms.login.queue")
// public void handleLoginLog(LoginLogEvent event, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
// try {
// LoginLog log = new LoginLog();
// BeanUtils.copyProperties(event, log);
// loginLogMapper.insert(log);
// // 手动确认消息(若配置了 manual ack)
// channel.basicAck(deliveryTag, false);
// } catch (Exception e) {
// // 处理失败,可记录日志并拒绝重新入队
// channel.basicNack(deliveryTag, false, false);
// }
// }
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.controller;
import com.ekingwin.tms_app.common.dto.Result;
import com.ekingwin.tms_app.module.auth.dto.LoginReq;
import com.ekingwin.tms_app.module.auth.dto.LoginResp;
import com.ekingwin.tms_app.module.auth.dto.UnlockReq;
import com.ekingwin.tms_app.module.auth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private AuthService authService;
@PostMapping("/login")
public Result<LoginResp> login(@Valid @RequestBody LoginReq req, HttpServletRequest request) {
System.out.println(">>> [CONTROLLER] 进入 login 方法!");
String ip = request.getRemoteAddr();
String userAgent = request.getHeader("User-Agent");
return Result.success(authService.login(req, ip,userAgent));
}
@PostMapping("/logout")
public Result<Void> logout(@RequestHeader("Authorization") String token) {
authService.logout(token);
return Result.success(null);
}
/**
* 解锁用户账号(仅管理员可调用)
*/
@PostMapping("/unlock")
public Result<Void> unlock(@Valid @RequestBody UnlockReq req,
@RequestAttribute("userId") String operatorId) {
authService.unlockUser(req.getUserId(), operatorId);
return Result.success(null);
}
/**
* 查询账号锁定状态
*/
@GetMapping("/lockStatus")
public Result<Boolean> checkLockStatus(@RequestParam String userId) {
boolean locked = authService.isLocked(userId);
return Result.success(locked);
}
}
package com.ekingwin.tms_app.module.auth.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.auth.entity.LoginLog;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LoginLogMapper extends BaseMapper<LoginLog> {
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.auth.entity.UserCredential;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface UserCredentialMapper extends BaseMapper<UserCredential> {
@Select("SELECT * FROM app_user_credential WHERE userid = #{userId}")
UserCredential selectByUserId(@Param("userId") String userId);
@Update("UPDATE app_user_credential SET password = #{password}, first_login = 0, update_time = SYSDATE WHERE userid = #{userId}")
int updatePasswordAndFirstLogin(@Param("userId") String userId, @Param("password") String password);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.auth.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 只查询基本信息,不包含密码
@Select("SELECT userid, username, organizationid, branchid, defaultRoleId " +
"FROM bsm_user WHERE userid = #{account}")
User selectByAccount(@Param("account") String account);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class LoginReq {
@NotBlank
private String userId;
@NotBlank
private String password;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class LoginResp {
private String token;
private String userId;
private Boolean firstLogin; // true:首次登录需要修改密码, false:非首次
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class UnlockReq {
@NotBlank(message = "用户ID不能为空")
private String userId;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName("app_login_log")
@KeySequence(value = "SEQ_LOGIN_LOG") // Oracle 序列
public class LoginLog {
@TableId(value = "id", type = IdType.INPUT)
private Long id;
private String userid;
private Date loginTime;
private String token;
private String ip;
private String deviceInfo; // 新增:设备信息(User-Agent)
}
package com.ekingwin.tms_app.module.auth.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("bsm_user")
public class User {
@TableId
private String userid;
private String username;
private String password;
private String organizationid;
private String branchid;
private String defaultRoleId;
private Integer status;
}
package com.ekingwin.tms_app.module.auth.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName("app_user_credential")
public class UserCredential {
@TableId
private String userid;
private String password;
private Integer firstLogin; // 1:首次,0:已改
private Integer failCount;
private Date lockTime;
private Date createTime;
private Date updateTime;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.service;
import com.ekingwin.tms_app.module.auth.dto.LoginReq;
import com.ekingwin.tms_app.module.auth.dto.LoginResp;
import com.ekingwin.tms_app.module.auth.entity.User;
public interface AuthService {
public LoginResp login(LoginReq req, String ip, String deviceInfo);
// 修改密码(已登录)
public void changePassword(String userId, String oldPassword, String newPassword);
// 首次登录修改密码(无需token)
public void firstChangePassword(String userId, String oldPassword, String newPassword);
public void logout(String token);
// 解锁用户(需校验操作者是否为管理员)
public void unlockUser(String targetUserId, String operatorId);
// 查询用户是否被锁定
public boolean isLocked(String userId);
/**
* 判断是否为管理员(可根据角色ID或用户名硬编码)
*/
public boolean isAdmin(User user);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.auth.service.impl;
import com.ekingwin.tms_app.common.config.SecurityConfig;
import com.ekingwin.tms_app.common.util.JwtUtil;
import com.ekingwin.tms_app.common.util.RedisUtil;
import com.ekingwin.tms_app.module.auth.dao.UserCredentialMapper;
import com.ekingwin.tms_app.module.auth.dao.UserMapper;
import com.ekingwin.tms_app.module.auth.dto.LoginReq;
import com.ekingwin.tms_app.module.auth.dto.LoginResp;
import com.ekingwin.tms_app.module.auth.entity.User;
import com.ekingwin.tms_app.module.auth.entity.UserCredential;
import com.ekingwin.tms_app.module.auth.service.AuthService;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Service
@Log4j2
public class AuthServiceImpl implements AuthService {
@Autowired
private UserMapper userMapper;
@Autowired
private UserCredentialMapper credentialMapper;
@Autowired
private RedisUtil redisUtil;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private SecurityConfig securityConfig;
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
public LoginResp login(LoginReq req, String ip, String deviceInfo) {
User user = userMapper.selectByAccount(req.getUserId());
if (user == null) {
throw new RuntimeException("用户不存在");
}
String userId = user.getUserid();
// 1. 锁定检查(Redis)
String lockKey = "login:lock:" + userId;
if (Boolean.TRUE.equals(redisUtil.hasKey(lockKey))) {
throw new RuntimeException("账号已锁定,请" + securityConfig.getLockDurationMinutes() + "分钟后重试");
}
// 2. 获取凭据
UserCredential credential = credentialMapper.selectByUserId(userId);
if (credential == null) {
credential = new UserCredential();
credential.setUserid(userId);
credential.setPassword(encoder.encode(req.getPassword()));
credential.setFirstLogin(1);
credential.setFailCount(0);
credential.setCreateTime(new Date());
credential.setUpdateTime(new Date());
try {
credentialMapper.insert(credential);
} catch (Exception e) {
// 并发插入导致主键冲突,重新查询
credential = credentialMapper.selectByUserId(userId);
if (credential == null) {
throw new RuntimeException("用户凭据创建失败,请稍后重试");
}
}
}
// 3. 密码校验
if (!encoder.matches(req.getPassword(), credential.getPassword())) {
// 失败计数处理(Redis)
String failKey = "login:fail:count:" + userId;
Long failCount = redisUtil.increment(failKey, 1);
if (failCount == 1) {
redisUtil.set(failKey, failCount, 30, TimeUnit.MINUTES);
}
if (failCount >= securityConfig.getMaxFailCount()) {
redisUtil.set(lockKey, "locked", securityConfig.getLockDurationMinutes(), TimeUnit.MINUTES);
throw new RuntimeException("密码错误次数过多,账号已锁定" + securityConfig.getLockDurationMinutes() + "分钟");
}
// 可选:同步失败次数到 credential.fail_count
throw new RuntimeException("密码错误,剩余尝试次数:" + (securityConfig.getMaxFailCount() - failCount));
}
// 4. 登录成功:清除失败计数和锁定标记
redisUtil.delete("login:fail:count:" + userId);
redisUtil.delete(lockKey);
// // 5. 首次登录判断(从 credential 读取)
// if (credential.getFirstLogin() != null && credential.getFirstLogin() == 1) {
// return new LoginResp(null, userId, true);
// }
// 6. 生成 token
String jwt = jwtUtil.generateJwt(userId);
// 记录日志(略)
return new LoginResp(jwt, userId, false);
}
// 修改密码(已登录)
public void changePassword(String userId, String oldPassword, String newPassword) {
UserCredential credential = credentialMapper.selectByUserId(userId);
if (credential == null) {
throw new RuntimeException("用户凭据不存在");
}
if (!encoder.matches(oldPassword, credential.getPassword())) {
throw new RuntimeException("旧密码错误");
}
String encryptedNew = encoder.encode(newPassword);
credentialMapper.updatePasswordAndFirstLogin(userId, encryptedNew);
}
// 首次登录修改密码(无需token)
public void firstChangePassword(String userId, String oldPassword, String newPassword) {
UserCredential credential = credentialMapper.selectByUserId(userId);
if (credential == null) {
throw new RuntimeException("用户凭据不存在");
}
if (!encoder.matches(oldPassword, credential.getPassword())) {
throw new RuntimeException("旧密码错误");
}
String encryptedNew = encoder.encode(newPassword);
credentialMapper.updatePasswordAndFirstLogin(userId, encryptedNew);
}
public void logout(String token) {
String jwt = token.replace("Bearer ", "");
Claims claims = jwtUtil.parseJwt(jwt);
String jti = claims.getId();
long ttl = claims.getExpiration().getTime() - System.currentTimeMillis();
if (ttl > 0) {
redisUtil.set("blacklist:token:" + jti, "1", ttl, TimeUnit.MILLISECONDS);
}
}
// 解锁用户(需校验操作者是否为管理员)
public void unlockUser(String targetUserId, String operatorId) {
// 1. 校验操作者是否为管理员(根据角色判断)
User operator = userMapper.selectById(operatorId);
if (operator == null || !isAdmin(operator)) {
throw new RuntimeException("无权限执行解锁操作,仅管理员可操作");
}
// 2. 清除锁定标记
String lockKey = "login:lock:" + targetUserId;
redisUtil.delete(lockKey);
// 3. 清除失败计数(可选)
String failKey = "login:fail:count:" + targetUserId;
redisUtil.delete(failKey);
}
// 查询用户是否被锁定
public boolean isLocked(String userId) {
String lockKey = "login:lock:" + userId;
return Boolean.TRUE.equals(redisUtil.hasKey(lockKey));
}
public boolean isAdmin(User user) {
// 方式1:通过角色ID判断(假设管理员角色ID为 'ROLE_ADMIN' 或 'admin')
String adminRoleId = "ROLE_ADMIN";
return adminRoleId.equals(user.getDefaultRoleId());
}
}
package com.ekingwin.tms_app.module.cargo.controller;
import com.ekingwin.tms_app.common.dto.PageResult;
import com.ekingwin.tms_app.common.dto.Result;
import com.ekingwin.tms_app.module.cargo.dto.CustomerQueryReq;
import com.ekingwin.tms_app.module.cargo.service.CustomerService;
import com.ekingwin.tms_app.module.cargo.vo.CustomerVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* 客户信息
*/
@Log4j2
@RestController
@RequestMapping("/cargo/customers")
public class CustomerController {
@Autowired
private CustomerService customerService;
@PostMapping("/list")
public Result<PageResult<CustomerVo>> listCustomers(
@RequestAttribute("userId") String userId,
@RequestBody @Valid CustomerQueryReq req) {
log.info("listCustomers: userId={}, customerName={}, customerId={}, pageNum={}, pageSize={}",
userId, req.getCustomerName(), req.getCustomerId(), req.getPageNum(), req.getPageSize());
return Result.success(customerService.listCustomers(userId, req.getCustomerName(),req.getCustomerId(), req.getPageNum(), req.getPageSize()));
}
}
package com.ekingwin.tms_app.module.cargo.controller;
import com.ekingwin.tms_app.common.dto.Result;
import com.ekingwin.tms_app.common.dto.PageResult;
import com.ekingwin.tms_app.module.cargo.service.OrderProductService;
import com.ekingwin.tms_app.module.cargo.vo.OrderProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
/**
* 订单信息
*/
@RestController
@RequestMapping("/cargo/order")
public class OrderProductController {
@Autowired
private OrderProductService orderProductService;
/**
* 订单信息列表
*/
@PostMapping("/products")
public Result<PageResult<OrderProductVo>> listOrderProducts(
@RequestAttribute("userId") String userId,
@RequestParam(required = false) String orderNo,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize) {
return Result.success(orderProductService.listOrderProducts(
userId, orderNo, startDate, endDate, pageNum, pageSize));
}
/**
* 订单信息列表
*/
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.controller;
import com.ekingwin.tms_app.common.dto.Result;
import com.ekingwin.tms_app.module.cargo.service.TraceService;
import com.ekingwin.tms_app.module.cargo.vo.TraceProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 条形码查询商品
*/
@RestController
@RequestMapping("/cargo/trace")
public class TraceController {
@Autowired
private TraceService traceService;
@GetMapping("/product")
public Result<TraceProductVo> getProductByTraceCode(@RequestParam String traceCode) {
return Result.success(traceService.getByTraceCode(traceCode));
}
}
package com.ekingwin.tms_app.module.cargo.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.cargo.entity.Customer;
import com.ekingwin.tms_app.module.cargo.vo.CustomerVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CustomerMapper extends BaseMapper<Customer> {
List<CustomerVo> selectCustomerList(@Param("orgId") String orgId,
@Param("branchId") String branchId,
@Param("customerName") String customerName,
@Param("customerId") String customerId
);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.dao;
import com.ekingwin.tms_app.module.cargo.vo.OrderProductVo;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
public interface OrderProductMapper {
List<OrderProductVo> selectOrderProducts(@Param("orgId") String orgId,
@Param("branchId") String branchId,
@Param("orderNo") String orderNo,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.dao;
import com.ekingwin.tms_app.module.cargo.vo.TraceProductVo;
import org.apache.ibatis.annotations.Param;
public interface TraceProductMapper {
TraceProductVo selectByTraceCode(@Param("traceId") String traceId);
}
package com.ekingwin.tms_app.module.cargo.dto;
import lombok.Data;
@Data
public class CustomerQueryReq {
private String customerName;
private String customerId;
private Integer pageNum = 1;
private Integer pageSize = 10;
}
package com.ekingwin.tms_app.module.cargo.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName("t_bas_customer")
public class Customer {
@TableId
private String customerid;
private String customerdescr1;
private String organizationid;
private String branchid;
private Date createTime; // 根据实际表结构,如有该字段则保留
private Date updateTime;
}
package com.ekingwin.tms_app.module.cargo.outbound.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ekingwin.tms_app.common.dto.Result;
import com.ekingwin.tms_app.module.cargo.outbound.dto.*;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundOrderDetail;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundTracecode;
import com.ekingwin.tms_app.module.cargo.outbound.service.OutboundOrderService;
import com.ekingwin.tms_app.module.cargo.outbound.vo.BoxInfoVo;
import com.ekingwin.tms_app.module.cargo.outbound.vo.CustomerProductSummaryVo;
import com.ekingwin.tms_app.module.cargo.outbound.vo.OutboundOrderVo;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
@RestController
@RequestMapping("/cargo/outbound")
public class OutboundController {
@Autowired
private OutboundOrderService outboundOrderService;
/**
* 订单啊查询
* @param req
* @param userId
* @return
*/
@PostMapping("/orders")
public Result<IPage<OutboundOrderVo>> listOrders(@RequestBody @Valid OutboundOrderQueryReq req,
@RequestAttribute("userId") String userId) {
log.info("userid:"+userId+"-----------查询订单信息:"+req.toString());
return Result.success(outboundOrderService.listOrders(req));
}
/**
* 订单啊查询
* @param req
* @param userId
* @return
*/
@PostMapping("/customer/products")
public Result<IPage<CustomerProductSummaryVo>> getCustomerProducts(
@RequestBody @Valid CustomerProductQueryReq req,
@RequestAttribute("userId") String userId) {
return Result.success(outboundOrderService.getCustomerProductSummary(req));
}
@PostMapping("/order/detail")
public Result<List<OutboundOrderDetail>> getOrderDetail(@RequestBody @Valid OrderDetailReq req,
@RequestAttribute("userId") String userId) {
log.info("userid:"+userId+"-----------查询订单信息:"+req.toString());
return Result.success(outboundOrderService.listOrderDetails(req.getOrderNo()));
}
/**
* 箱码查询(弃用)
* @param req
* @param userId
* @return
*/
@PostMapping("/box/info")
public Result<BoxInfoVo> getBoxInfo(@RequestBody @Valid BoxInfoReq req,
@RequestAttribute("userId") String userId) {
log.info("userid:"+userId+"-----------查询箱码信息:"+req.toString());
return Result.success(outboundOrderService.getBoxInfo(req.getTraceId()));
}
/**
* 追溯码查询(弃用)
* @param req
* @param userId
* @return
*/
@PostMapping("/tracecode/info")
public Result<OutboundTracecode> getTracecodeInfo(@RequestBody @Valid TracecodeInfoReq req,
@RequestAttribute("userId") String userId) {
log.info("userid:"+userId+"-----------查询追溯码信息:"+req.toString());
return Result.success(outboundOrderService.getTracecodeInfo(req.getTraceCode()));
}
/**
* 用码分别查看是箱码还是追溯码
* @param req
* @return
*/
@PostMapping("/queryCode/info")
public Result<Object> queryCode(@RequestBody InfoQueryReq req) {
log.info("-----------用码查询:"+req.toString());
Result result = new Result();
Map<String, Object> map =new HashMap<>();
String type=outboundOrderService.getIdType(req.getCode());
if (StringUtils.isNotEmpty(type)&&"BOX".equals(type)) {
BoxInfoVo data = outboundOrderService.getBoxInfo(req.getCode());
map.put("data",data);
map.put("type","box");
if (data != null){
return result.success(data);
}
}else if (StringUtils.isNotEmpty(type)&&"TRACE".equals(type)){
OutboundTracecode outboundTracecode = outboundOrderService.getTracecodeInfo(req.getCode());
if (outboundTracecode != null) {
map.put("data", outboundTracecode);
map.put("type", "trace");
return result.success(outboundTracecode);
} else {
return result.error("未查询到");
}
}
return result.error("码不存在");
}
@PostMapping("/tally/commit")
public Result<Void> commitTally(@RequestBody @Valid TallyCommitReq req,
@RequestAttribute("userId") String userId) {
log.info("userid:"+userId+"-----------提交理货:"+req.toString());
outboundOrderService.commitTally(req, userId);
return Result.success(null);
}
@PostMapping("/tracecode/scan")
public Result<Void> scanTracecode(@RequestBody @Valid TracecodeScanReq req,
@RequestAttribute("userId") String userId) {
log.info("userid:"+userId+"-----------追溯码扫码:"+req.toString());
// 如果前端未传 scannedBy,使用 token 中的 userId
if (req.getScannedBy() == null || req.getScannedBy().isEmpty()) {
req.setScannedBy(userId);
}
outboundOrderService.scanTracecode(req, userId);
return Result.success(null);
}
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundBox;
import com.ekingwin.tms_app.module.cargo.outbound.vo.BoxInfoVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface OutboundBoxMapper extends BaseMapper<OutboundBox> {
BoxInfoVo selectBoxInfoWithDetails(@Param("traceId") String traceId);
@Select("SELECT PAK_OUTBOUND_SCAN.F_DETECT_SCAN_TYPE(#{id}) FROM DUAL")
String selectIdType(@Param("id") String ID);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundOrderDetail;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface OutboundOrderDetailMapper extends BaseMapper<OutboundOrderDetail> {
List<OutboundOrderDetail> selectByOrderNo(@Param("orderNoList") List<String> orderNo);
}
package com.ekingwin.tms_app.module.cargo.outbound.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.cargo.outbound.vo.CustomerProductSummaryVo;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundOrderHeader;
import com.ekingwin.tms_app.module.cargo.outbound.vo.OutboundOrderVo;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
public interface OutboundOrderHeaderMapper extends BaseMapper<OutboundOrderHeader> {
List<OutboundOrderVo> selectOrderList(@Param("customerName") String customerName,
@Param("orderNo") String orderNo,
@Param("statusList") List<String> statuss,
@Param("startTime") Date startTime,
@Param("endTime") Date endTime);
Integer selectOrderCount(@Param("customerName") String customerName,
@Param("orderNo") String orderNo,
@Param("statusList") List<String> status,
@Param("startTime") Date startTime,
@Param("endTime") Date endTime);
List<CustomerProductSummaryVo> selectCustomerProductSummary(
@Param("customerName") String customerName,
@Param("customerCode") String customerCode,
@Param("statusList") List<String> statusList,
@Param("startTime") Date startTime,
@Param("endTime") Date endTime
);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundTracecode;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface OutboundTracecodeMapper extends BaseMapper<OutboundTracecode> {
OutboundTracecode selectByTraceCode(@Param("traceCode") String traceCode);
}
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class BoxInfoReq {
@NotBlank
private String traceId;
}
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class CustomerProductQueryReq {
private String customerName; // 客户名称(模糊)
private String customerCode; // 客户编码(精确)
private String status; // 订单状态 PENDING/TALLYING/DONE
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime; // 订单创建开始时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime; // 订单创建结束时间
private Integer pageNum = 1;
private Integer pageSize = 10;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
@Data
public class InfoQueryReq {
private String code;
}
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class OrderDetailReq {
@NotBlank
private String orderNo;
}
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class OutboundOrderQueryReq {
private String customerName; // 模糊查询
private String orderNo; // 精确查询
private String status; // PENDING/TALLYING/DONE
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime; // 订单创建开始时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime; // 订单创建结束时间
private Integer pageNum = 1;
private Integer pageSize = 10;
@Override
public String toString() {
return "OutboundOrderQueryReq{" +
"customerName='" + customerName + '\'' +
", orderNo='" + orderNo + '\'' +
", status='" + status + '\'' +
", startTime=" + startTime +
", endTime=" + endTime +
", pageNum=" + pageNum +
", pageSize=" + pageSize +
'}';
}
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.List;
@Data
public class TallyCommitReq {
@NotBlank
private String traceId; // 箱号
private List<TallyDetail> tallyDetails;
@Data
public static class TallyDetail {
private String itemCode;
private java.math.BigDecimal tallyQty;
}
}
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class TracecodeInfoReq {
@NotBlank
private String traceCode;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class TracecodeScanReq {
@NotBlank
private String traceCode;
private String scannedBy; // 可选,默认从token获取
}
package com.ekingwin.tms_app.module.cargo.outbound.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@TableName("T_DOC_outbound_box")
public class OutboundBox {
private String organizationid;
@TableId
private Long outboundBoxId;
private String boxNo;
private String traceId;
private String orderNo;
private Integer totalItems;
private BigDecimal totalQty;
private BigDecimal tallyQty;
private String isOddLot; // C=整箱 A=零头箱
private String status; // PENDING, DONE
private Date createTime;
private Date updateTime;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@TableName("T_DOC_outbound_box_DETAIL")
public class OutboundBoxDetail {
private String organizationid;
@TableId
private Long outboundBoxDetailId;
private String traceId;
private Long lineDetailId;
private String itemCode;
private String itemName;
private BigDecimal expectQty;
private BigDecimal tallyQty;
private String batchNo;
private String lotNo;
private String status;
private Date createTime;
private Date updateTime;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@TableName("T_DOC_outbound_scan_DETAIL")
public class OutboundOrderDetail {
private String organizationid;
@TableId
private Long detailId;
private String orderNo;
private Integer lineNo;
private String itemCode;
private String itemName;
private String barcode;
private BigDecimal orderQty;
private BigDecimal tallyQty;
private String unit;
private String batchNo;
private String lotNo;
private String isOddLot; // C=整箱 A=零头
private String status; // PENDING, PARTIAL, DONE
private Date createTime;
private Date updateTime;
}
package com.ekingwin.tms_app.module.cargo.outbound.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
@TableName("T_DOC_outbound_scan_HEADER")
public class OutboundOrderHeader {
private String organizationid;
private String customerOrderNo;
private String ediKey;
private String createsource;
private String createbranchid;
private String orderNo;
private String customerName;
private String customerCode;
private Integer totalLines;
private Integer tallyLines;
private String status; // DEFAULT 'PENDING', -- PENDING=待理货 TALLYING=理货中 DONE=已完成
private Date createTime;
private Date updateTime;
@TableField(exist = false)
private List<OutboundOrderDetail> list;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName("T_DOC_outbound_tracecode")
public class OutboundTracecode {
private String organizationid;
@TableId
private Long outboundTracecodeId;
private String traceCode;
private String itemCode;
private String itemName;
private String orderNo;
private String traceId;
private String batchNo;
private String lotNo;
private String serialNo;
private Date manufactureDate;
private Date expireDate;
private String supplier;
private String origin;
private String isOddLot;
private String status; // PENDING, SCANNED
private String scannedBy;
private Date scannedTime;
private Date createTime;
}
package com.ekingwin.tms_app.module.cargo.outbound.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ekingwin.tms_app.module.cargo.outbound.dto.CustomerProductQueryReq;
import com.ekingwin.tms_app.module.cargo.outbound.dto.OutboundOrderQueryReq;
import com.ekingwin.tms_app.module.cargo.outbound.dto.TallyCommitReq;
import com.ekingwin.tms_app.module.cargo.outbound.dto.TracecodeScanReq;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundOrderDetail;
import com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundTracecode;
import com.ekingwin.tms_app.module.cargo.outbound.vo.BoxInfoVo;
import com.ekingwin.tms_app.module.cargo.outbound.vo.CustomerProductSummaryVo;
import com.ekingwin.tms_app.module.cargo.outbound.vo.OutboundOrderVo;
import java.util.List;
public interface OutboundOrderService {
public IPage<OutboundOrderVo> listOrders(OutboundOrderQueryReq req) ;
public IPage<CustomerProductSummaryVo> getCustomerProductSummary(CustomerProductQueryReq req) ;
public List<OutboundOrderDetail> listOrderDetails(String orderNo);
public BoxInfoVo getBoxInfo(String traceId);
public String getIdType(String traceId);
public OutboundTracecode getTracecodeInfo(String traceCode);
public void commitTally(TallyCommitReq req, String operatorId);
public void scanTracecode(TracecodeScanReq req, String operatorId);
}
package com.ekingwin.tms_app.module.cargo.outbound.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ekingwin.tms_app.module.cargo.outbound.dto.*;
import com.ekingwin.tms_app.module.cargo.outbound.entity.*;
import com.ekingwin.tms_app.module.cargo.outbound.dao.*;
import com.ekingwin.tms_app.module.cargo.outbound.service.OutboundOrderService;
import com.ekingwin.tms_app.module.cargo.outbound.vo.BoxInfoVo;
import com.ekingwin.tms_app.module.cargo.outbound.vo.CustomerProductSummaryVo;
import com.ekingwin.tms_app.module.cargo.outbound.vo.OutboundOrderVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Service
public class OutboundOrderServiceImpl implements OutboundOrderService {
@Autowired
private OutboundOrderHeaderMapper orderHeaderMapper;
@Autowired
private OutboundOrderDetailMapper orderDetailMapper;
@Autowired
private OutboundBoxMapper boxMapper;
@Autowired
private OutboundTracecodeMapper tracecodeMapper;
@Override
// 1. 查询订单列表(分页+时间范围)
public IPage<OutboundOrderVo> listOrders(OutboundOrderQueryReq req) {
Page<OutboundOrderVo> page = new Page<>(req.getPageNum(), req.getPageSize());
List<String> statusList=new ArrayList<>();
if(StringUtils.isNotEmpty(req.getStatus())){
statusList = Arrays.asList(req.getStatus().split(","));
}
List<OutboundOrderVo> records = orderHeaderMapper.selectOrderList(
req.getCustomerName(), req.getOrderNo(), statusList,
req.getStartTime(), req.getEndTime());
page.setRecords(records);
page.setTotal(orderHeaderMapper.selectOrderCount(req.getCustomerName(), req.getOrderNo(), statusList,
req.getStartTime(), req.getEndTime())); // 实际建议用 count 查询,此处简化
return page;
}
public IPage<CustomerProductSummaryVo> getCustomerProductSummary(CustomerProductQueryReq req) {
Page<CustomerProductSummaryVo> page = new Page<>( );
List<String> statusList=new ArrayList<>();
if(StringUtils.isNotEmpty(req.getStatus())){
statusList = Arrays.asList(req.getStatus().split(","));
}
page.setRecords(orderHeaderMapper.selectCustomerProductSummary(
req.getCustomerName(),
req.getCustomerCode(),
statusList,
req.getStartTime(),
req.getEndTime()
));
return page;
}
// 2. 查询订单明细
@Override
public List<OutboundOrderDetail> listOrderDetails(String orderNo) {
List<String> orderNos = Arrays.asList(orderNo.split(","));
return orderDetailMapper.selectByOrderNo(orderNos);
}
// 3. 查询箱信息(含箱内物料)
@Override
public BoxInfoVo getBoxInfo(String traceId) {
BoxInfoVo info = boxMapper.selectBoxInfoWithDetails(traceId);
if (info == null) {
throw new RuntimeException("箱号不存在");
}
return info;
}
@Override
public String getIdType(String traceId) {
return boxMapper.selectIdType(traceId);
}
// 4. 查询追溯码信息
@Override
public OutboundTracecode getTracecodeInfo(String traceCode) {
OutboundTracecode trace = tracecodeMapper.selectByTraceCode(traceCode);
if (trace == null) {
throw new RuntimeException("追溯码不存在");
}
return trace;
}
// 5. 提交理货(更新箱、订单明细、订单头状态)
@Transactional
@Override
public void commitTally(TallyCommitReq req, String operatorId) {
// 1) 更新箱表 tally_qty 和 status
OutboundBox box = boxMapper.selectById(req.getTraceId());
if (box == null) throw new RuntimeException("箱号不存在");
// 假设所有物料都扫描完成
box.setTallyQty(box.getTotalQty());
box.setStatus("DONE");
box.setUpdateTime(new Date());
boxMapper.updateById(box);
// 2) 更新订单明细行的 tally_qty(按 itemCode 累加)TODO
// for (TallyCommitReq.TallyDetail detail : req.getTallyDetails()) {
// // 根据 orderNo + itemCode 更新 tally_qty(需在 mapper 中实现)
// orderDetailMapper.updateTallyQty(box.getOrderNo(), detail.getItemCode(), detail.getTallyQty());
// }
// 3) 检查订单是否完成所有明细
List<OutboundOrderDetail> details = orderDetailMapper.selectByOrderNo(Arrays.asList(box.getOrderNo().split(",")));
boolean allDone = details.stream().allMatch(d -> d.getOrderQty().compareTo(d.getTallyQty()) == 0);
OutboundOrderHeader header = orderHeaderMapper.selectById(box.getOrderNo());
if (allDone) {
header.setStatus("DONE");
} else {
header.setStatus("TALLYING");
}
// 更新 tally_lines 统计(略)
orderHeaderMapper.updateById(header);
}
// 6. 追溯码扫码记录
@Transactional
@Override
public void scanTracecode(TracecodeScanReq req, String operatorId) {
OutboundTracecode trace = tracecodeMapper.selectByTraceCode(req.getTraceCode());
if (trace == null) throw new RuntimeException("追溯码不存在");
trace.setStatus("SCANNED");
trace.setScannedBy(operatorId);
trace.setScannedTime(new Date());
tracecodeMapper.updateById(trace);
}
}
package com.ekingwin.tms_app.module.cargo.outbound.vo;
import lombok.Data;
import java.math.BigDecimal;
/**
* 箱内物料明细 VO
*/
@Data
public class BoxDetailVo {
private String itemCode; // 物料编码
private String itemName; // 物料名称
private BigDecimal expectQty; // 箱内应有数量
private BigDecimal tallyQty; // 已理货数量
private String batchNo; // 批号
private String lotNo; // LOT号
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 箱信息及箱内物料列表 VO
*/
@Data
public class BoxInfoVo {
private String traceId; // 箱号(TRACEID)
private String boxNo; // 外箱条码(box_no)
private String orderNo; // 关联订单号
private Integer totalItems; // 箱内物料种数
private BigDecimal totalQty; // 箱内总数量
private BigDecimal tallyQty; // 已理货数量
private String isOddLot; // 是否整箱 C=整箱 A=零头箱
private String status; // PENDING/DONE
private List<BoxDetailVo> details; // 箱内物料明细
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class CustomerProductSummaryVo {
private String itemCode; // 商品编码
private String itemName; // 商品名称
private String unit; // 单位
private String status; //
private String isOddLot; //
private String lotNo; //
private String batchNo; //
private String lineNo; //
private String barcode; //
private BigDecimal totalOrderQty; // 总应理数量
private BigDecimal totalTallyQty; // 总已理数量
private Integer orderCount; // 涉及订单数
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.outbound.vo;
import lombok.Data;
import java.util.Date;
@Data
public class OutboundOrderVo {
private String organizationid;
private String orderNo;
private String customerName;
private String customerCode;
private Integer totalLines;
private Integer tallyLines;
private String status;
private String createTime;
private String orderType;
private String customerAddr;
private String orgName;
}
package com.ekingwin.tms_app.module.cargo.service;
import com.ekingwin.tms_app.common.dto.PageResult;
import com.ekingwin.tms_app.module.cargo.vo.CustomerVo;
public interface CustomerService {
public PageResult<CustomerVo> listCustomers(String userId, String customerName,String customerId,Integer pageNum, Integer pageSize);
}
package com.ekingwin.tms_app.module.cargo.service;
import com.ekingwin.tms_app.common.dto.PageResult;
import com.ekingwin.tms_app.module.cargo.vo.OrderProductVo;
import java.util.Date;
public interface OrderProductService {
public PageResult<OrderProductVo> listOrderProducts(String userId, String orderNo, Date startDate, Date endDate,
Integer pageNum, Integer pageSize);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.cargo.service;
import com.ekingwin.tms_app.module.cargo.vo.TraceProductVo;
public interface TraceService {
public TraceProductVo getByTraceCode(String traceCode);
}
package com.ekingwin.tms_app.module.cargo.service.impl;
import com.ekingwin.tms_app.common.dto.PageResult;
import com.ekingwin.tms_app.module.auth.entity.User;
import com.ekingwin.tms_app.module.auth.dao.UserMapper;
import com.ekingwin.tms_app.module.cargo.dao.CustomerMapper;
import com.ekingwin.tms_app.module.cargo.service.CustomerService;
import com.ekingwin.tms_app.module.cargo.vo.CustomerVo;
import com.ekingwin.tms_app.module.user.dao.UserInfoMapper;
import com.ekingwin.tms_app.module.user.vo.UserInfoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerMapper customerMapper;
@Autowired
private UserInfoMapper userMapper;
public PageResult<CustomerVo> listCustomers(String userId, String customerName,String customerId,
Integer pageNum, Integer pageSize) {
UserInfoVo user = userMapper.selectUserInfoById(userId);
PageHelper.startPage(pageNum, pageSize);
List<CustomerVo> list = customerMapper.selectCustomerList(
user.getOrganizationId(), user.getBranchid(), customerName,customerId);
PageInfo<CustomerVo> pageInfo = new PageInfo<>(list);
return PageResult.of(pageInfo.getTotal(), pageInfo.getList());
}
}
package com.ekingwin.tms_app.module.cargo.service.impl;
import com.ekingwin.tms_app.common.dto.PageResult;
import com.ekingwin.tms_app.module.auth.dao.UserMapper;
import com.ekingwin.tms_app.module.auth.entity.User;
import com.ekingwin.tms_app.module.cargo.dao.OrderProductMapper;
import com.ekingwin.tms_app.module.cargo.service.OrderProductService;
import com.ekingwin.tms_app.module.cargo.vo.OrderProductVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class OrderProductServiceImpl implements OrderProductService {
@Autowired
private OrderProductMapper orderProductMapper;
@Autowired
private UserMapper userMapper;
public PageResult<OrderProductVo> listOrderProducts(String userId, String orderNo,
Date startDate, Date endDate,
Integer pageNum, Integer pageSize) {
User user = userMapper.selectById(userId);
PageHelper.startPage(pageNum, pageSize);
List<OrderProductVo> list = orderProductMapper.selectOrderProducts(
user.getOrganizationid(), user.getBranchid(), orderNo, startDate, endDate);
PageInfo<OrderProductVo> pageInfo = new PageInfo<>(list);
return PageResult.of(pageInfo.getTotal(), pageInfo.getList());
}
}
package com.ekingwin.tms_app.module.cargo.service.impl;
import com.ekingwin.tms_app.module.cargo.dao.TraceProductMapper;
import com.ekingwin.tms_app.module.cargo.service.TraceService;
import com.ekingwin.tms_app.module.cargo.vo.TraceProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TraceServiceImpl implements TraceService {
@Autowired
private TraceProductMapper traceProductMapper;
public TraceProductVo getByTraceCode(String traceCode) {
TraceProductVo vo = traceProductMapper.selectByTraceCode(traceCode);
if (vo == null) {
throw new RuntimeException("未查询到该条码对应的商品信息");
}
return vo;
}
}
package com.ekingwin.tms_app.module.cargo.vo;
import lombok.Data;
import java.util.Date;
@Data
public class CustomerOrderVo {
private String organizationid ;
private String customerOrderNo ;
private String ediKey;
private String createSource;
private String createbranchid;
private String orderNo;
private String customerName;
private String customerCode;
private String totalLines;
private String tallyLines;
private String status;// DEFAULT 'PENDING', -- PENDING=待理货 TALLYING=理货中 DONE=已完成
private Date createTime;
private Date updateTime;
}
package com.ekingwin.tms_app.module.cargo.vo;
import lombok.Data;
@Data
public class CustomerVo {
private String customerId;
private String customerName;
private String addressNo;
private String address;
private String branchId;
private String branchName;
}
package com.ekingwin.tms_app.module.cargo.vo;
import lombok.Data;
@Data
public class OrderProductVo {
private String orderNo;
private String customerId;
private String customerName;
private Integer totalQty;
private String sku;
private String skuName;
private String spec;
private String batchNo;
private String manufacturer;
}
package com.ekingwin.tms_app.module.cargo.vo;
import lombok.Data;
@Data
public class TraceProductVo {
private String orderNo;
private String customerName;
private String shipperName;
private String address;
private String boxNo;
private String branchId;
private String productName;
private String batchNo;
private String boxType;
private Integer quantity;
private String spec;
private String manufacturer;
}
\ No newline at end of file
package com.ekingwin.tms_app.module.user.controller;
import com.ekingwin.tms_app.common.dto.Result;
import com.ekingwin.tms_app.module.auth.dto.LoginReq;
import com.ekingwin.tms_app.module.auth.dto.LoginResp;
import com.ekingwin.tms_app.module.auth.service.AuthService;
import com.ekingwin.tms_app.module.user.dao.UserInfoMapper;
import com.ekingwin.tms_app.module.user.dto.ChangePasswordReq;
import com.ekingwin.tms_app.module.user.service.UserService;
import com.ekingwin.tms_app.module.user.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserInfoMapper userInfoMapper;
@Autowired
private AuthService authService;
@Autowired
private UserService userService;
@GetMapping("/info")
public Result<UserInfoVo> getUserInfo(@RequestAttribute("userId") String userId) {
UserInfoVo vo = userInfoMapper.selectUserInfoById(userId);
return Result.success(vo);
}
/**
* 登陆
* @param req
* @param request
* @return
*/
@PostMapping("/login")
public Result<LoginResp> login(@Valid @RequestBody LoginReq req,
HttpServletRequest request) {
// 获取客户端 IP
String ip = getClientIp(request);
// 获取设备信息(User-Agent)
String userAgent = request.getHeader("User-Agent");
LoginResp resp = authService.login(req, ip, userAgent);
return Result.success(resp);
}
/**
* 修改密码
* @param userId
* @param req
* @return
*/
@PostMapping("/changePassword")
public Result<Void> changePassword(@RequestAttribute("userId") String userId,
@Valid @RequestBody ChangePasswordReq req) {
userService.changePassword(userId, req.getOldPassword(), req.getNewPassword());
return Result.success(null);
}
/**
* 获取客户端真实 IP(支持代理)
*/
private String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 多个代理时取第一个 IP
if (ip != null && ip.contains(",")) {
ip = ip.split(",")[0].trim();
}
return ip;
}
}
\ No newline at end of file
package com.ekingwin.tms_app.module.user.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ekingwin.tms_app.module.auth.entity.User;
import com.ekingwin.tms_app.module.user.vo.UserInfoVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserInfoMapper extends BaseMapper<User> {
@Select("SELECT t.userid, t.username,t.organizationId, t.branchid, bb.branchdescr, " +
"t.defaultRoleId, br.roleDescr AS defaultRoleDescr " +
"FROM bsm_user t " +
"LEFT JOIN bsm_branch bb ON t.organizationid = bb.organizationid AND t.branchid = bb.branchid " +
"LEFT JOIN bsm_role br ON t.organizationId = br.organizationId AND t.defaultRoleId = br.roleId " +
"WHERE t.userid = #{userId}")
UserInfoVo selectUserInfoById(@Param("userId") String userId);
}
\ No newline at end of file
package com.ekingwin.tms_app.module.user.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class ChangePasswordReq {
@NotBlank(message = "旧密码不能为空")
private String oldPassword;
@NotBlank(message = "新密码不能为空")
private String newPassword;
}
package com.ekingwin.tms_app.module.user.service;
public interface UserService {
public void changePassword(String userId, String oldPassword, String newPassword);
}
package com.ekingwin.tms_app.module.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ekingwin.tms_app.module.auth.dao.UserCredentialMapper;
import com.ekingwin.tms_app.module.auth.entity.User;
import com.ekingwin.tms_app.module.auth.dao.UserMapper;
import com.ekingwin.tms_app.module.auth.entity.UserCredential;
import com.ekingwin.tms_app.module.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private UserCredentialMapper credentialMapper;
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Override
public void changePassword(String userId, String oldPassword, String newPassword) {
// 1. 获取凭据
UserCredential credential = credentialMapper.selectByUserId(userId);
if (credential == null) {
throw new RuntimeException("用户凭据不存在");
}
// 2. 校验旧密码
if (!encoder.matches(oldPassword, credential.getPassword())) {
throw new RuntimeException("旧密码错误");
}
// 3. 加密新密码
String encryptedNew = encoder.encode(newPassword);
// 4. 更新凭据表:密码 和 first_login=0
credential.setPassword(encryptedNew);
credential.setFirstLogin(0);
credential.setUpdateTime(new Date());
credentialMapper.updateById(credential);
}
}
package com.ekingwin.tms_app.module.user.vo;
import lombok.Data;
@Data
public class UserInfoVo {
private String userid;
private String username;
private String organizationId;
private String branchid;
private String branchdescr;
private String defaultRoleId;
private String defaultRoleDescr;
}
\ No newline at end of file
# Oracle ?????
spring.datasource.url=jdbc:oracle:thin:@10.1.6.152:1521/qgtmstest
spring.datasource.username=TMS_FTEST
spring.datasource.password=Z9vw,3D:Q3FN
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.hikari.maximum-pool-size=20
# HikariCP ?????
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.idle-timeout=180000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.validation-timeout=5000
spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
#redis
spring.redis.host=10.1.6.124
spring.redis.port=6379
spring.redis.password=P@ssword1
spring.redis.database=8
spring.redis.jedis.pool.max-active=1000
spring.redis.jedis.pool.max-wait=5000
spring.redis.jedis.pool.max-idle=1000
spring.redis.jedis.pool.min-idle=100
spring.redis.timeout=300000
# Kafka
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer
spring.kafka.consumer.group-id=tms-app-group
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.trusted.packages=*
# ===================== MyBatis-Plus ?? =====================
mybatis-plus.mapper-locations=classpath*:/mapper/**/*.xml
mybatis-plus.global-config.db-config.id-type=input
mybatis-plus.configuration.map-underscore-to-camel-case=true
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
# ?????
spring.rabbitmq.publisher-confirm-type=correlated
spring.rabbitmq.publisher-returns=true
# ???????
spring.rabbitmq.listener.simple.acknowledge-mode=manual
# ?????SQL?????
logging.level.com.tms.auth.mapper=debug
logging.level.org.apache.ibatis=warn
logging.level.org.springframework=warn
logging.level.com.baomidou.mybatisplus=warn
\ No newline at end of file
# 应用服务 WEB 访问端口
# Oracle ?????
spring.datasource.url=jdbc:oracle:thin:@10.1.18.190:1521/qgtms
spring.datasource.username=tmsdb
spring.datasource.password=db2admin
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.hikari.maximum-pool-size=20
# Redis
spring.redis.host=10.1.6.124
spring.redis.port=6379
spring.redis.password=P@ssword1
spring.redis.database=8
spring.redis.jedis.pool.max-active=1000
spring.redis.jedis.pool.max-wait=5000
spring.redis.jedis.pool.max-idle=1000
spring.redis.jedis.pool.min-idle=100
spring.redis.timeout=300000
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
# ?????
spring.rabbitmq.publisher-confirm-type=correlated
spring.rabbitmq.publisher-returns=true
# ???????
spring.rabbitmq.listener.simple.acknowledge-mode=manual
# ===================== MyBatis-Plus ?? =====================
mybatis-plus.mapper-locations=classpath*:/mapper/**/*.xml
mybatis-plus.global-config.db-config.id-type=input
mybatis-plus.configuration.map-underscore-to-camel-case=true
# ===================== ????????????SQL? =====================
# ??????? STDOUT ??
# mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# ?????SQL?????
logging.level.com.tms.auth.mapper=debug
logging.level.org.apache.ibatis=warn
logging.level.org.springframework=warn
logging.level.com.baomidou.mybatisplus=warn
\ No newline at end of file
# ??
server.port=8080
spring.profiles.active=dev
# JWT
app.jwt.secret= your-secret-key-for-tms-app
app.jwt.expire-hours= 8
# ????
app.security.max-fail-count=5
# ????
app.security.lock-duration-minutes= 5
#
spring.application.name=tms-app
server.servlet.context-path=/tms-app
app.default-password= welcome1
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH-mm-ss}-%i.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.example" level="debug" additivity="false">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Logger>
<Root level="error">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
</Configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.dao.CustomerMapper">
<select id="selectCustomerList" resultType="com.ekingwin.tms_app.module.cargo.vo.CustomerVo">
SELECT t.customerno AS customerId,
t.consigneedescr AS customerName,
t.addressno AS addressNo,
t.toaddress AS address, --地址
t.routeno,
'S2101' AS branchId,
'上药江苏物流中心' AS branchName
from t_rul_route_d_detail t --线路明细表
where t.organizationid = 'SHYY'
and t.routeno LIKE '%SYJS%'
and t.branchid = 'S2101'
<if test="customerName != null and customerName != ''">
AND t.consigneedescr LIKE CONCAT(CONCAT('%', #{customerName}), '%')
</if>
<if test="customerId != null and customerId != ''">
AND t.customerno = #{customerId}
</if>
ORDER BY t.consigneedescr
</select>
<select id="selectCustomer" resultType="com.ekingwin.tms_app.module.cargo.vo.CustomerVo">
select * from T_DOC_outbound_scan_HEADER
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.dao.OrderProductMapper">
<select id="selectOrderProducts" resultType="com.ekingwin.tms_app.module.cargo.vo.OrderProductVo">
SELECT DISTINCT
t.reference1 AS orderNo,
t.customerId,
t.customerDescr1 AS customerName,
t.qty_c AS totalQty,
od.sku,
od.skudescr1 AS skuName,
od.lotatt12 AS spec,
op.lotnum AS batchNo,
bs.reservedfield03 AS manufacturer
FROM t_doc_order_header t
LEFT JOIN t_doc_order_detail od
ON t.organizationid = od.organizationid AND t.orderno = od.orderno
LEFT JOIN t_doc_order_packinglist op
ON t.organizationid = op.organizationid
AND t.orderno = op.orderno
AND t.operatebranchid = op.branchid
LEFT JOIN t_bas_sku bs
ON od.organizationid = bs.organizationid
AND od.customerid = bs.customerid
AND od.sku = bs.sku
WHERE t.organizationid = #{orgId}
AND t.operatebranchid = #{branchId}
<if test="orderNo != null and orderNo != ''">
AND t.reference1 = #{orderNo}
</if>
<if test="startDate != null and endDate != null">
AND t.create_time BETWEEN #{startDate} AND #{endDate}
</if>
ORDER BY t.create_time DESC
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.dao.TraceProductMapper">
<select id="selectByTraceCode" resultType="com.ekingwin.tms_app.module.cargo.vo.TraceProductVo">
SELECT
a.reference1 AS orderNo,
a.consigneedescr1 AS customerName,
a.customerdescr1 AS shipperName,
a.consigneeaddress AS address,
b.traceid AS boxNo,
a.operatebranchid AS branchId,
c.skudescr1 AS productName,
b.lotnum AS batchNo,
b.cartongroup AS boxType,
b.qty AS quantity,
c.alternate_sku2 AS spec,
c.reservedfield03 AS manufacturer
FROM t_doc_order_header a,
t_doc_order_packinglist b,
t_bas_sku c
WHERE a.organizationid = b.organizationid
AND b.organizationid = c.organizationid
AND a.orderno = b.orderno
AND b.sku = c.sku
AND a.customerid = c.customerid
AND b.traceid = #{traceId}
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.outbound.dao.OutboundBoxMapper">
<resultMap id="BoxInfoMap" type="com.ekingwin.tms_app.module.cargo.outbound.vo.BoxInfoVo">
<id column="traceId" property="traceId"/>
<result column="boxNo" property="boxNo"/>
<result column="orderNo" property="orderNo"/>
<result column="totalItems" property="totalItems"/>
<result column="totalQty" property="totalQty"/>
<result column="tallyQty" property="tallyQty"/>
<result column="isOddLot" property="isOddLot"/>
<result column="status" property="status"/>
<collection property="details" ofType="com.ekingwin.tms_app.module.cargo.outbound.vo.BoxDetailVo">
<result column="itemCode" property="itemCode"/>
<result column="itemName" property="itemName"/>
<result column="expectQty" property="expectQty"/>
<result column="tallyQtyDetail" property="tallyQty"/>
<result column="batchNo" property="batchNo"/>
</collection>
</resultMap>
<select id="selectBoxInfoWithDetails" resultMap="BoxInfoMap">
SELECT b.traceId, b.box_no AS boxNo, b.order_no AS orderNo,
b.total_items AS totalItems, b.total_qty AS totalQty, b.tally_qty AS tallyQty,
b.is_odd_lot AS isOddLot, b.status,
d.item_code AS itemCode, d.item_name AS itemName, d.expect_qty AS expectQty,
d.tally_qty AS tallyQtyDetail, d.batch_no AS batchNo
FROM T_DOC_outbound_box b
LEFT JOIN T_DOC_outbound_box_DETAIL d ON b.traceId = d.traceId
WHERE b.traceId = #{traceId}
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.outbound.dao.OutboundOrderDetailMapper">
<!-- 定义结果映射(显式映射避免字段名不一致) -->
<resultMap id="BaseResultMap" type="com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundOrderDetail">
<id column="detail_id" property="detailId"/>
<result column="organizationid" property="organizationid"/>
<result column="order_no" property="orderNo"/>
<result column="line_no" property="lineNo"/>
<result column="item_code" property="itemCode"/>
<result column="item_name" property="itemName"/>
<result column="barcode" property="barcode"/>
<result column="order_qty" property="orderQty"/>
<result column="tally_qty" property="tallyQty"/>
<result column="unit" property="unit"/>
<result column="batch_no" property="batchNo"/>
<result column="lot_no" property="lotNo"/>
<result column="is_odd_lot" property="isOddLot"/>
<result column="status" property="status"/>
<result column="create_time" property="createTime"/>
<result column="update_time" property="updateTime"/>
</resultMap>
<!-- 根据订单号查询明细列表 -->
<select id="selectByOrderNo" resultMap="BaseResultMap">
SELECT *
FROM T_DOC_outbound_scan_DETAIL
WHERE order_no in
<foreach collection="orderNoList" item="orderNo" open="(" separator="," close=")">
#{orderNo}
</foreach>
ORDER BY line_no ASC
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.outbound.dao.OutboundOrderHeaderMapper">
<select id="selectOrderList" resultType="com.ekingwin.tms_app.module.cargo.outbound.vo.OutboundOrderVo">
SELECT organizationid, order_no AS orderNo, customer_name AS customerName,
customer_code AS customerCode, total_lines AS totalLines,
tally_lines AS tallyLines, status, create_time AS createTime,
ordertype AS orderType, customer_addr AS customerAddr,org_name AS orgName
FROM T_DOC_outbound_scan_HEADER
WHERE 1=1
<if test="customerName != null and customerName != ''">
AND customer_name LIKE CONCAT(CONCAT('%', #{customerName}), '%')
</if>
<if test="orderNo != null and orderNo != ''">
AND order_no = #{orderNo}
</if>
<if test="statusList != null and statusList != ''">
AND status in
<foreach collection="statusList" item="status" open="(" separator="," close=")">
#{status}
</foreach>
</if>
<!-- <if test="startTime != null">-->
<!-- AND create_time >= #{startTime}-->
<!-- </if>-->
<!-- <if test="endTime != null">-->
<!-- AND create_time >= #{endTime}-->
<!-- </if>-->
ORDER BY customerName,create_time DESC
</select>
<select id="selectOrderCount" resultType="java.lang.Integer">
SELECT count(0)
FROM T_DOC_outbound_scan_HEADER
WHERE 1=1
<if test="customerName != null and customerName != ''">
AND customer_name LIKE CONCAT(CONCAT('%', #{customerName}), '%')
</if>
<if test="orderNo != null and orderNo != ''">
AND order_no = #{orderNo}
</if>
<if test="statusList != null and statusList != ''">
AND status in
<foreach collection="statusList" item="status" open="(" separator="," close=")">
#{status}
</foreach>
</if>
<if test="startTime != null">
AND create_time >= #{startTime}
</if>
<if test="endTime != null">
AND create_time <![CDATA[ <= ]]> #{endTime}
</if>
</select>
<select id="selectCustomerProductSummary"
resultType="com.ekingwin.tms_app.module.cargo.outbound.vo.CustomerProductSummaryVo">
SELECT
d.item_code AS itemCode,
d.item_name AS itemName,
d.unit,
d.status, -- 明确表别名
d.is_odd_lot AS isOddLot,
d.lot_no AS lotNo,
d.batch_no AS batchNo,
d.line_no AS lineNo,
d.barcode,
SUM(d.order_qty) AS totalOrderQty, -- 聚合求和
SUM(d.tally_qty) AS totalTallyQty,
COUNT(DISTINCT h.order_no) AS orderCount
FROM T_DOC_outbound_scan_HEADER h
JOIN T_DOC_outbound_scan_DETAIL d ON h.order_no = d.order_no
WHERE 1=1
<if test="statusList != null and statusList.size() > 0">
AND d.status IN
<foreach collection="statusList" item="status" open="(" separator="," close=")">
#{status}
</foreach>
</if>
<if test="customerName != null and customerName != ''">
AND h.customer_name LIKE CONCAT('%', #{customerName}, '%')
</if>
<if test="customerCode != null and customerCode != ''">
AND h.customer_code = #{customerCode}
</if>
<!-- 时间条件按需启用 -->
GROUP BY
d.item_code,
d.item_name,
d.unit,
d.status,
d.is_odd_lot,
d.lot_no,
d.batch_no,
d.line_no,
d.barcode
ORDER BY d.item_name
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.tms_app.module.cargo.outbound.dao.OutboundTracecodeMapper">
<!-- 定义结果映射(推荐显式映射,避免字段名不一致) -->
<resultMap id="BaseResultMap" type="com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundTracecode">
<id column="outbound_tracecode_id" property="outboundTracecodeId"/>
<result column="organizationid" property="organizationid"/>
<result column="trace_code" property="traceCode"/>
<result column="item_code" property="itemCode"/>
<result column="item_name" property="itemName"/>
<result column="order_no" property="orderNo"/>
<result column="trace_id" property="traceId"/>
<result column="batch_no" property="batchNo"/>
<result column="lot_no" property="lotNo"/>
<result column="serial_no" property="serialNo"/>
<result column="manufacture_date" property="manufactureDate"/>
<result column="expire_date" property="expireDate"/>
<result column="supplier" property="supplier"/>
<result column="origin" property="origin"/>
<result column="is_odd_lot" property="isOddLot"/>
<result column="status" property="status"/>
<result column="scanned_by" property="scannedBy"/>
<result column="scanned_time" property="scannedTime"/>
<result column="create_time" property="createTime"/>
</resultMap>
<select id="selectByTraceCode" resultType="com.ekingwin.tms_app.module.cargo.outbound.entity.OutboundTracecode">
SELECT
organizationid,
outbound_tracecode_id AS outboundTracecodeId,
trace_code AS traceCode,
item_code AS itemCode,
item_name AS itemName,
order_no AS orderNo,
trace_id AS traceId,
batch_no AS batchNo,
lot_no AS lotNo,
serial_no AS serialNo,
manufacture_date AS manufactureDate,
expire_date AS expireDate,
supplier,
origin,
is_odd_lot AS isOddLot,
status,
scanned_by AS scannedBy,
scanned_time AS scannedTime,
create_time AS createTime
FROM T_DOC_outbound_tracecode
WHERE trace_code = #{traceCode}
</select>
</mapper>
\ No newline at end of file
<html>
<body>
<h1>hello word!!!</h1>
<p>this is a html page</p>
</body>
</html>
\ No newline at end of file
package com.ekingwin.tms_app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TmsAppApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment