Merge remote-tracking branch 'origin/dyf-device'

# Conflicts:
#	fys-modules/fys-equipment/src/main/java/com/fuyuanshen/equipment/service/impl/DeviceServiceImpl.java
#	fys-modules/fys-equipment/src/main/resources/mapper/equipment/DeviceMapper.xml
This commit is contained in:
2025-07-09 13:45:27 +08:00
12 changed files with 430 additions and 183 deletions

View File

@ -16,12 +16,12 @@
<!-- 控制台输出 --> <!-- 控制台输出 -->
<appender name="file_console" class="ch.qos.logback.core.rolling.RollingFileAppender"> <appender name="file_console" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-console.log</file> <file>${log.path}/sys-console.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<!-- 日志文件名格式 --> <!-- &lt;!&ndash; 日志文件名格式 &ndash;&gt; -->
<fileNamePattern>${log.path}/sys-console.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- <fileNamePattern>${log.path}/sys-console.%d{yyyy-MM-dd}.log</fileNamePattern> -->
<!-- 日志最大 1天 --> <!-- &lt;!&ndash; 日志最大 1天 &ndash;&gt; -->
<maxHistory>1</maxHistory> <!-- <maxHistory>1</maxHistory> -->
</rollingPolicy> <!-- </rollingPolicy> -->
<encoder> <encoder>
<pattern>${log.pattern}</pattern> <pattern>${log.pattern}</pattern>
<charset>utf-8</charset> <charset>utf-8</charset>
@ -36,12 +36,12 @@
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender"> <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file> <file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 --> <!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<!-- 日志文件名格式 --> <!-- &lt;!&ndash; 日志文件名格式 &ndash;&gt; -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- <fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern> -->
<!-- 日志最大的历史 60天 --> <!-- &lt;!&ndash; 日志最大的历史 60天 &ndash;&gt; -->
<maxHistory>60</maxHistory> <!-- <maxHistory>60</maxHistory> -->
</rollingPolicy> <!-- </rollingPolicy> -->
<encoder> <encoder>
<pattern>${log.pattern}</pattern> <pattern>${log.pattern}</pattern>
</encoder> </encoder>
@ -58,12 +58,12 @@
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender"> <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file> <file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 --> <!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<!-- 日志文件名格式 --> <!-- &lt;!&ndash; 日志文件名格式 &ndash;&gt; -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- <fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern> -->
<!-- 日志最大的历史 60天 --> <!-- &lt;!&ndash; 日志最大的历史 60天 &ndash;&gt; -->
<maxHistory>60</maxHistory> <!-- <maxHistory>60</maxHistory> -->
</rollingPolicy> <!-- </rollingPolicy> -->
<encoder> <encoder>
<pattern>${log.pattern}</pattern> <pattern>${log.pattern}</pattern>
</encoder> </encoder>

View File

@ -44,7 +44,7 @@ import java.util.List;
* @Date: 2025/5/16 * @Date: 2025/5/16
**/ **/
@Slf4j @Slf4j
@Tag(name = "设备管理", description = "设备:设备管理") @Tag(name = "web:设备管理", description = "web:设备管理")
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/api/device") @RequestMapping("/api/device")

View File

@ -0,0 +1,54 @@
package com.fuyuanshen.equipment.domain.query;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
/**
* @author: 默苍璃
* @date: 2025-07-0910:27
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DeviceAssignmentQuery implements Serializable {
/**
* 表示这个 serialVersionUID 字段是专门为 Java 序列化机制服务的。
*/
@Serial
private static final long serialVersionUID = 1L;
private Long deviceId;
/**
* 分配者
*/
private Long assignerId;
/**
* 接收者
*/
private Long assigneeId;
/**
* 0 否
* 1 是
* 设备是否有效
*/
private Integer active;
/**
* 分配等级(用于失效)
*/
private String lever;
// Getters and Setters
}

View File

@ -0,0 +1,27 @@
package com.fuyuanshen.equipment.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.domain.query.DeviceAssignmentQuery;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author 97433
* @description 针对表【device_assignments】的数据库操作Mapper
* @createDate 2025-06-19 18:19:13
* @Entity system.domain.DeviceAssignments
*/
@Mapper
public interface DeviceAssignmentsMapper extends BaseMapper<DeviceAssignments> {
/**
* 查询设备分配信息
*
* @param deviceAssignmentQuery
* @return
*/
List<DeviceAssignments> deviceAssignmentsMapper(@Param("query") DeviceAssignmentQuery deviceAssignmentQuery);
}

View File

@ -0,0 +1,13 @@
package com.fuyuanshen.equipment.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
/**
* @author 97433
* @description 针对表【device_assignments】的数据库操作Service
* @createDate 2025-06-19 18:19:13
*/
public interface DeviceAssignmentsService extends IService<DeviceAssignments> {
}

View File

@ -0,0 +1,14 @@
package com.fuyuanshen.equipment.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fuyuanshen.equipment.domain.DeviceTypeGrants;
/**
* @author 97433
* @description 针对表【device_type_grants】的数据库操作Service
* @createDate 2025-06-19 13:49:33
*/
public interface DeviceTypeGrantsService extends IService<DeviceTypeGrants> {
}

View File

@ -0,0 +1,17 @@
package com.fuyuanshen.equipment.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.service.DeviceAssignmentsService;
import org.springframework.stereotype.Service;
/**
* @author 97433
* @description 针对表【device_assignments】的数据库操作Service实现
* @createDate 2025-06-19 18:19:13
*/
@Service
public class DeviceAssignmentsServiceImpl extends ServiceImpl<DeviceAssignmentsMapper, DeviceAssignments> implements DeviceAssignmentsService {
}

View File

@ -1,6 +1,7 @@
package com.fuyuanshen.equipment.service.impl; package com.fuyuanshen.equipment.service.impl;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID; import cn.hutool.core.lang.UUID;
import cn.hutool.core.lang.generator.SnowflakeGenerator; import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@ -18,21 +19,30 @@ import com.fuyuanshen.customer.domain.Customer;
import com.fuyuanshen.customer.mapper.CustomerMapper; import com.fuyuanshen.customer.mapper.CustomerMapper;
import com.fuyuanshen.equipment.constants.DeviceConstants; import com.fuyuanshen.equipment.constants.DeviceConstants;
import com.fuyuanshen.equipment.domain.Device; import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.domain.DeviceType; import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.DeviceTypeGrants;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo; import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.form.DeviceForm; import com.fuyuanshen.equipment.domain.form.DeviceForm;
import com.fuyuanshen.equipment.domain.query.DeviceAssignmentQuery;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria; import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.query.DeviceTypeQueryCriteria; import com.fuyuanshen.equipment.domain.query.DeviceTypeQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo; import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.domain.vo.CustomerVo; import com.fuyuanshen.equipment.domain.vo.CustomerVo;
import com.fuyuanshen.equipment.enums.BindingStatusEnum; import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.enums.CommunicationModeEnum; import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
import com.fuyuanshen.equipment.enums.DeviceActiveStatusEnum;
import com.fuyuanshen.equipment.enums.DeviceStatusEnum; import com.fuyuanshen.equipment.enums.DeviceStatusEnum;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper; import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeGrantsMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper; import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.service.DeviceAssignmentsService;
import com.fuyuanshen.equipment.service.DeviceService; import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.equipment.service.DeviceTypeGrantsService;
import com.fuyuanshen.system.domain.vo.SysOssVo; import com.fuyuanshen.system.domain.vo.SysOssVo;
import com.fuyuanshen.system.service.ISysOssService; import com.fuyuanshen.system.service.ISysOssService;
import com.fuyuanshen.system.service.ISysUserService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -43,6 +53,7 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*; import java.util.*;
/** /**
@ -55,6 +66,8 @@ import java.util.*;
@RequiredArgsConstructor @RequiredArgsConstructor
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService { public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {
public static final String USER_ID_SEPARATOR = ":";
@Value("${file.device.pic}") @Value("${file.device.pic}")
private String filePath; private String filePath;
@Value("${file.device.ip}") @Value("${file.device.ip}")
@ -62,11 +75,16 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
private final DeviceMapper deviceMapper; private final DeviceMapper deviceMapper;
private final DeviceTypeMapper deviceTypeMapper; private final DeviceTypeMapper deviceTypeMapper;
private final CustomerMapper customerMapper; private final CustomerMapper customerMapper;
private final ISysOssService ossService; private final ISysOssService ossService;
private final DeviceAssignmentsService deviceAssignmentsService;
private final DeviceAssignmentsMapper deviceAssignmentsMapper;
private final DeviceTypeGrantsService deviceTypeGrantsService;
private final DeviceTypeGrantsMapper deviceTypeGrantsMapper;
/** /**
* 分页查询设备 * 分页查询设备
@ -79,7 +97,6 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
@Override @Override
public TableDataInfo<Device> queryAll(DeviceQueryCriteria criteria, Page<Device> page) throws IOException { public TableDataInfo<Device> queryAll(DeviceQueryCriteria criteria, Page<Device> page) throws IOException {
// criteria.setCustomerId(LoginHelper.getUserId());
criteria.setCurrentOwnerId(LoginHelper.getUserId()); criteria.setCurrentOwnerId(LoginHelper.getUserId());
IPage<Device> devices = deviceMapper.findAll(criteria, page); IPage<Device> devices = deviceMapper.findAll(criteria, page);
@ -90,7 +107,6 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
} }
} }
// return PageUtil.toPage(devices);
return new TableDataInfo<Device>(records, devices.getTotal()); return new TableDataInfo<Device>(records, devices.getTotal());
} }
@ -125,13 +141,13 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria(); DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria();
queryCriteria.setDeviceTypeId(deviceForm.getDeviceType()); queryCriteria.setDeviceTypeId(deviceForm.getDeviceType());
queryCriteria.setCustomerId(LoginHelper.getUserId()); queryCriteria.setCustomerId(LoginHelper.getUserId());
List<DeviceType> deviceTypes = deviceTypeMapper.findAll(queryCriteria); DeviceTypeGrants typeGrants = deviceTypeGrantsMapper.selectById(queryCriteria.getDeviceTypeId());
if (deviceTypes.isEmpty()) { DeviceType deviceTypes = deviceTypeMapper.selectById(typeGrants.getDeviceTypeId());
if (deviceTypes == null) {
throw new Exception("设备类型不存在!!!"); throw new Exception("设备类型不存在!!!");
} }
// 保存图片并获取URL // 保存图片并获取URL
// String imageUrl = saveDeviceImage(deviceForm.getFile(), deviceForm.getDeviceName());
if (deviceForm.getFile() != null) { if (deviceForm.getFile() != null) {
SysOssVo upload = ossService.upload(deviceForm.getFile()); SysOssVo upload = ossService.upload(deviceForm.getFile());
// 设置图片路径 // 设置图片路径
@ -140,22 +156,39 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
// 转换对象并插入数据库 // 转换对象并插入数据库
Device device = new Device(); Device device = new Device();
BeanUtil.copyProperties(deviceForm, device, true);
device.setDeviceNo(createDeviceNo());
LoginUser loginUser = LoginHelper.getLoginUser(); LoginUser loginUser = LoginHelper.getLoginUser();
device.setCurrentOwnerId(loginUser.getUserId()); device.setCurrentOwnerId(loginUser.getUserId());
device.setOriginalOwnerId(loginUser.getUserId()); device.setOriginalOwnerId(loginUser.getUserId());
device.setCreateByName(loginUser.getNickname()); device.setCreateByName(loginUser.getNickname());
device.setTypeName(deviceTypes.get(0).getTypeName()); device.setTypeName(deviceTypes.getTypeName());
BeanUtil.copyProperties(deviceForm, device, true); device.setDeviceType(deviceTypes.getId());
device.setDeviceNo(createDeviceNo());
deviceMapper.insert(device); deviceMapper.insert(device);
// 新增设备类型记录
DeviceAssignments assignments = new DeviceAssignments();
assignments.setDeviceId(device.getId());
assignments.setAssignedAt(LocalDateTime.now());
// 分配者
assignments.setAssignerId(loginUser.getUserId());
assignments.setAssignerName(loginUser.getUsername());
// 接收者
assignments.setAssigneeId(loginUser.getUserId());
assignments.setActive(DeviceActiveStatusEnum.ACTIVE.getCode());
String lever = USER_ID_SEPARATOR + loginUser.getUserId();
assignments.setLever(lever);
deviceAssignmentsService.save(assignments);
} }
private String createDeviceNo() { private String createDeviceNo() {
String uuidStr = UUID.fastUUID().toString(); // 获取带 - 的标准格式字符串 String uuidStr = UUID.fastUUID().toString(); // 获取带 - 的标准格式字符串
return uuidStr.replaceAll("-", ""); return uuidStr.replaceAll("-", "");
} }
/** /**
* 更新设备信息 * 更新设备信息
* *
@ -165,9 +198,10 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void update(DeviceForm deviceForm) throws Exception { public void update(DeviceForm deviceForm) throws Exception {
DeviceAssignments deviceAssignments = deviceAssignmentsMapper.selectById(deviceForm.getId());
DeviceTypeQueryCriteria deviceTypeQueryCriteria = new DeviceTypeQueryCriteria(); DeviceTypeQueryCriteria deviceTypeQueryCriteria = new DeviceTypeQueryCriteria();
deviceTypeQueryCriteria.setDeviceTypeId(deviceForm.getDeviceType()); deviceTypeQueryCriteria.setDeviceTypeId(deviceAssignments.getDeviceId());
deviceTypeQueryCriteria.setCustomerId(LoginHelper.getUserId()); deviceTypeQueryCriteria.setCustomerId(LoginHelper.getUserId());
List<DeviceType> deviceTypes = deviceTypeMapper.findAll(deviceTypeQueryCriteria); List<DeviceType> deviceTypes = deviceTypeMapper.findAll(deviceTypeQueryCriteria);
if (deviceTypes.isEmpty()) { if (deviceTypes.isEmpty()) {
@ -175,8 +209,9 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
} }
DeviceQueryCriteria queryCriteria = new DeviceQueryCriteria(); DeviceQueryCriteria queryCriteria = new DeviceQueryCriteria();
queryCriteria.setDeviceId(deviceForm.getId()); queryCriteria.setDeviceId(deviceAssignments.getDeviceId());
queryCriteria.setCustomerId(LoginHelper.getUserId()); queryCriteria.setCustomerId(LoginHelper.getUserId());
queryCriteria.setCurrentOwnerId(LoginHelper.getUserId());
List<Device> devices = deviceMapper.findAll(queryCriteria); List<Device> devices = deviceMapper.findAll(queryCriteria);
if (devices.isEmpty()) { if (devices.isEmpty()) {
throw new Exception("设备不存在!!!"); throw new Exception("设备不存在!!!");
@ -184,7 +219,6 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
Device device = devices.get(0); Device device = devices.get(0);
// 处理上传的图片 // 处理上传的图片
// String imageUrl = saveDeviceImage(deviceForm.getFile(), device.getDeviceName());
if (deviceForm.getFile() != null) { if (deviceForm.getFile() != null) {
SysOssVo upload = ossService.upload(deviceForm.getFile()); SysOssVo upload = ossService.upload(deviceForm.getFile());
// 设置图片路径 // 设置图片路径
@ -193,6 +227,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
// 更新字段 // 更新字段
BeanUtil.copyProperties(deviceForm, device, true); BeanUtil.copyProperties(deviceForm, device, true);
device.setId(deviceAssignments.getDeviceId());
device.setUpdateTime(new Timestamp(System.currentTimeMillis())); device.setUpdateTime(new Timestamp(System.currentTimeMillis()));
deviceMapper.updateById(device); deviceMapper.updateById(device);
} }
@ -237,17 +272,20 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
public void deleteAll(List<Long> ids) { public void deleteAll(List<Long> ids) {
List<Long> invalidIds = new ArrayList<>(); List<Long> invalidIds = new ArrayList<>();
for (Long id : ids) { deviceAssignmentsMapper.deleteByIds(ids);
Device deviceType = deviceMapper.selectById(id); //
if (deviceType == null || !Objects.equals(deviceType.getCurrentOwnerId(), LoginHelper.getUserId())) { // for (Long id : ids) {
invalidIds.add(id); //
} // Device deviceType = deviceMapper.selectById(id);
} // if (deviceType == null || !Objects.equals(deviceType.getCurrentOwnerId(), LoginHelper.getUserId())) {
if (!invalidIds.isEmpty()) { // invalidIds.add(id);
throw new RuntimeException("以下设备无法删除ID 不存在或无权限): " + invalidIds); // }
} // }
// if (!invalidIds.isEmpty()) {
deviceMapper.deleteByIds(ids); // throw new RuntimeException("以下设备无法删除ID 不存在或无权限): " + invalidIds);
// }
//
// deviceMapper.deleteByIds(ids);
} }
@ -256,137 +294,106 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
* *
* @param customerVo * @param customerVo
*/ */
// @Override
// @Transactional(rollbackFor = Exception.class)
// public void assignCustomer1(CustomerVo customerVo) {
// List<Long> deviceIds = customerVo.getDeviceIds();
// Long customerId = customerVo.getCustomerId();
//
// Customer customer = customerMapper.queryCustomerById(customerId, LoginHelper.getLoginUser().getPid());
// if (customer == null) {
// throw new RuntimeException("待分配的客户不存在!!!");
// }
//
// List<Long> invalidIds = new ArrayList<>();
// List<Device> devices = new ArrayList<>();
// for (Long id : deviceIds) {
// Device device = deviceMapper.selectById(id);
// if (device == null || !Objects.equals(device.getCurrentOwnerId(), LoginHelper.getUserId())) {
// invalidIds.add(id);
// continue;
// }
// Device assignCustomer = deviceMapper.getAssignCustomer(device.getId());
// if (assignCustomer != null) {
// invalidIds.add(id);
// continue;
// }
// device.setCustomerId(customerId);
// device.setCustomerName(customer.getNickName());
// devices.add(device);
// }
// if (!invalidIds.isEmpty()) {
// throw new RuntimeException("以下设备无法分配ID 不存在或无权限): " + invalidIds);
// }
//
// devices.forEach((device) -> {
//
// deviceMapper.updateById(device);
// device.setCurrentOwnerId(customerId);
// if (device.getDeviceType() == null) {
// throw new RuntimeException("设备类型有问题!!! ");
// }
// DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
// SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator();
// device.setOriginalDeviceId(device.getId());
// Long next = snowflakeGenerator.next();
// device.setId(next);
// device.setDeviceType(next);
//
// DeviceType assignType = deviceTypeMapper.getAssignType(device.getDeviceType(), customerId);
// if (assignType == null) {
// deviceType.setOriginalDeviceId(deviceType.getId());
// deviceType.setId(next);
// deviceType.setOwnerCustomerId(customerId);
// deviceTypeMapper.insert(deviceType);
// }
//
// deviceMapper.insert(device);
//
// });
// }
@Override @Override
@Transactional(rollbackFor = Exception.class)
public void assignCustomer(CustomerVo customerVo) { public void assignCustomer(CustomerVo customerVo) {
List<Long> deviceIds = customerVo.getDeviceIds();
Long customerId = customerVo.getCustomerId();
Customer customer = customerMapper.queryCustomerById(customerId, LoginHelper.getLoginUser().getPid()); if (customerVo.getDeviceIds().isEmpty() || customerVo.getCustomerId() == null) {
if (customer == null) { throw new RuntimeException("请选择设备或客户");
throw new RuntimeException("待分配的客户不存在!!!");
} }
List<Device> devicesToAssign = new ArrayList<>(); // 获取当前登录用户
List<Long> invalidIds = new ArrayList<>(); LoginUser loginUser = LoginHelper.getLoginUser();
// 获取分配用户信息
Customer assignUser = customerMapper.selectById(customerVo.getCustomerId());
// 获取分配设备信息
List<DeviceAssignments> assignments = deviceAssignmentsMapper.selectByIds(customerVo.getDeviceIds());
for (Long id : deviceIds) { // 批量更新设备状态
Device device = deviceMapper.selectById(id); List<DeviceTypeGrants> deviceTypeGrants = new ArrayList<>();
if (device == null || !Objects.equals(device.getCurrentOwnerId(), LoginHelper.getUserId())) { for (DeviceAssignments assignment : assignments) {
invalidIds.add(id); Device device = deviceMapper.selectById(assignment.getDeviceId());
// 如果设备已分配给需要分配的客户,则跳过
DeviceAssignmentQuery dq = DeviceAssignmentQuery.builder().deviceId(device.getId()).assigneeId(customerVo.getCustomerId())
.active(DeviceActiveStatusEnum.ACTIVE.getCode()).lever(assignment.getLever() + USER_ID_SEPARATOR).build();
// 查询分配
List<DeviceAssignments> assignmentsList = deviceAssignmentsMapper.deviceAssignmentsMapper(dq);
if (CollectionUtil.isNotEmpty(assignmentsList)) {
log.info("设备 {} 已分配给客户 {}", device.getDeviceName(), device.getCustomerName());
continue; continue;
} }
Device assignCustomer = deviceMapper.getAssignCustomer(device.getId());
if (assignCustomer != null) { // 更改分配客户
invalidIds.add(id); assignment.setAssigneeName(assignUser.getNickName());
deviceAssignmentsMapper.updateById(assignment);
// 设备失效
// 获取用户的设备记录
DeviceAssignmentQuery dq1 = DeviceAssignmentQuery.builder().deviceId(device.getId()).assignerId(loginUser.getUserId())
.active(DeviceActiveStatusEnum.ACTIVE.getCode()).lever(assignment.getLever() + USER_ID_SEPARATOR).build();
List<DeviceAssignments> ag = deviceAssignmentsMapper.deviceAssignmentsMapper(dq1);
if (CollectionUtil.isNotEmpty(ag)) {
for (DeviceAssignments d : ag) {
d.setActive(DeviceActiveStatusEnum.INACTIVE.getCode());
deviceAssignmentsMapper.updateById(d);
}
}
// 新增设备类型记录
DeviceAssignments dam = new DeviceAssignments();
dam.setDeviceId(device.getId());
dam.setAssignedAt(LocalDateTime.now());
// 分配者
dam.setAssignerId(loginUser.getUserId());
dam.setAssignerName(loginUser.getUsername());
// 接收者
dam.setAssigneeId(assignUser.getCustomerId());
// assignments.setAssigneeName(assignUser.getUsername());
dam.setActive(DeviceActiveStatusEnum.ACTIVE.getCode());
String lever = assignment.getLever() + USER_ID_SEPARATOR + assignUser.getCustomerId();
dam.setLever(lever);
deviceAssignmentsService.save(dam);
// 判断设备类型是否存在
DeviceTypeGrants dtg = deviceTypeGrantsMapper.selectOne(new LambdaQueryWrapper<DeviceTypeGrants>().eq(DeviceTypeGrants::getDeviceTypeId, device.getId()));
if (dtg != null) {
continue; continue;
} }
device.setCustomerId(customerId); // 创建并保存设备类型授权记录
device.setCustomerName(customer.getNickName()); DeviceTypeGrants deviceTypeGrant = new DeviceTypeGrants();
devicesToAssign.add(device); deviceTypeGrant.setGrantedAt(new Date());
deviceTypeGrant.setDeviceTypeId(device.getDeviceType());
// 关联分配记录
deviceTypeGrant.setAssignmentId(dam.getId());
// 被授权的客户
deviceTypeGrant.setCustomerId(customerVo.getCustomerId());
// 授权方客户
deviceTypeGrant.setGrantorCustomerId(loginUser.getUserId());
deviceTypeGrants.add(deviceTypeGrant);
} }
if (!invalidIds.isEmpty()) { deviceTypeGrantsService.saveBatch(deviceTypeGrants);
throw new RuntimeException("以下设备无法分配ID 不存在或无权限): " + invalidIds);
}
// 批量处理设备分配
batchAssignDevices(devicesToAssign, customer);
} }
@Transactional(rollbackFor = Exception.class) /**
public void batchAssignDevices(List<Device> devicesToAssign, Customer customer) { * 创建并保存设备类型授权记录
Long userId = LoginHelper.getUserId(); *
SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator(); * @param device 当前设备对象
for (Device device : devicesToAssign) { * @param currentUser 当前登录用户
if (device.getDeviceType() == null) { * @param customerVo 客户信息
throw new RuntimeException("设备类型有问题!!! "); * @param deviceTypeGrants 授权记录集合
} */
private void createAndSaveDeviceTypeGrants(Device device, LoginUser currentUser, CustomerVo customerVo, List<DeviceTypeGrants> deviceTypeGrants) {
deviceMapper.updateById(device); // Long generatedId = NanoId.generate(NanoIdLengthEnum.HIGH_CONCURRENCY.getLength());
DeviceTypeGrants deviceTypeGrant = new DeviceTypeGrants();
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType()); deviceTypeGrant.setGrantedAt(new Date());
DeviceType assignType = deviceTypeMapper.getAssignType(device.getDeviceType(), customer.getCustomerId()); deviceTypeGrant.setDeviceTypeId(device.getDeviceType());
// deviceTypeGrant.setAssignmentId(generatedId);
Long next = snowflakeGenerator.next(); deviceTypeGrant.setCustomerId(customerVo.getCustomerId());
deviceTypeGrant.setGrantorCustomerId(currentUser.getUserId());
device.setOriginalDeviceId(device.getId()); deviceTypeGrants.add(deviceTypeGrant);
device.setCurrentOwnerId(customer.getCustomerId());
device.setOriginalOwnerId(device.getCurrentOwnerId());
device.setCustomerId(null);
device.setCustomerName("");
device.setId(next);
if (assignType == null) {
deviceType.setOriginalDeviceId(deviceType.getId());
deviceType.setOriginalOwnerId(deviceType.getOwnerCustomerId());
deviceType.setId(next);
device.setDeviceType(next);
deviceType.setOwnerCustomerId(customer.getCustomerId());
deviceTypeMapper.insert(deviceType);
} else {
device.setDeviceType(assignType.getId());
}
deviceMapper.insert(device);
}
} }
@ -449,6 +456,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
} }
@Override @Override
public TableDataInfo<AppDeviceVo> queryAppDeviceList(DeviceQueryCriteria bo, PageQuery pageQuery) { public TableDataInfo<AppDeviceVo> queryAppDeviceList(DeviceQueryCriteria bo, PageQuery pageQuery) {
Long userId = AppLoginHelper.getUserId(); Long userId = AppLoginHelper.getUserId();
@ -461,43 +469,44 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
public int bindDevice(AppDeviceBo bo) { public int bindDevice(AppDeviceBo bo) {
Integer mode = bo.getCommunicationMode(); Integer mode = bo.getCommunicationMode();
Long userId = AppLoginHelper.getUserId(); Long userId = AppLoginHelper.getUserId();
if(mode == CommunicationModeEnum.FOUR_G.getValue()){ if (mode == CommunicationModeEnum.FOUR_G.getValue()) {
String deviceImei = bo.getDeviceImei(); String deviceImei = bo.getDeviceImei();
QueryWrapper<Device> qw = new QueryWrapper<Device>() QueryWrapper<Device> qw = new QueryWrapper<Device>()
.eq("device_imei", deviceImei); .eq("device_imei", deviceImei);
List<Device> devices = baseMapper.selectList(qw); List<Device> devices = baseMapper.selectList(qw);
if(devices.isEmpty()){ if (devices.isEmpty()) {
throw new RuntimeException("请先将设备入库!!!"); throw new RuntimeException("请先将设备入库!!!");
} }
Device device = devices.get(0); Device device = devices.get(0);
if(device.getBindingStatus()!=null && device.getBindingStatus() == BindingStatusEnum.BOUND.getCode()){ if (device.getBindingStatus() != null && device.getBindingStatus() == BindingStatusEnum.BOUND.getCode()) {
throw new RuntimeException("设备已绑定"); throw new RuntimeException("设备已绑定");
} }
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>(); UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId()) deviceUpdateWrapper.eq("id", device.getId())
.set("binding_status", BindingStatusEnum.BOUND.getCode()) .set("binding_status", BindingStatusEnum.BOUND.getCode())
.set("binding_user_id",userId);; .set("binding_user_id", userId);
;
return baseMapper.update(null, deviceUpdateWrapper); return baseMapper.update(null, deviceUpdateWrapper);
}else if(mode == CommunicationModeEnum.BLUETOOTH.getValue()){ } else if (mode == CommunicationModeEnum.BLUETOOTH.getValue()) {
String deviceMac = bo.getDeviceMac(); String deviceMac = bo.getDeviceMac();
QueryWrapper<Device> qw = new QueryWrapper<Device>() QueryWrapper<Device> qw = new QueryWrapper<Device>()
.eq("device_mac", deviceMac); .eq("device_mac", deviceMac);
List<Device> devices = baseMapper.selectList(qw); List<Device> devices = baseMapper.selectList(qw);
if(devices.isEmpty()){ if (devices.isEmpty()) {
throw new RuntimeException("请先将设备入库!!!"); throw new RuntimeException("请先将设备入库!!!");
} }
Device device = devices.get(0); Device device = devices.get(0);
if(device.getBindingStatus() != null && device.getBindingStatus() == BindingStatusEnum.BOUND.getCode()){ if (device.getBindingStatus() != null && device.getBindingStatus() == BindingStatusEnum.BOUND.getCode()) {
throw new RuntimeException("设备已绑定"); throw new RuntimeException("设备已绑定");
} }
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>(); UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId()) deviceUpdateWrapper.eq("id", device.getId())
.set("binding_status", BindingStatusEnum.BOUND.getCode()) .set("binding_status", BindingStatusEnum.BOUND.getCode())
.set("binding_user_id",userId); .set("binding_user_id", userId);
return baseMapper.update(null, deviceUpdateWrapper); return baseMapper.update(null, qw);
}else{ } else {
throw new RuntimeException("通讯方式错误"); throw new RuntimeException("通讯方式错误");
} }
@ -506,13 +515,14 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
@Override @Override
public int unBindDevice(Long id) { public int unBindDevice(Long id) {
Device device = baseMapper.selectById(id); Device device = baseMapper.selectById(id);
if(device == null){ if (device == null) {
throw new RuntimeException("请先将设备入库!!!"); throw new RuntimeException("请先将设备入库!!!");
} }
// DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
// String mode = deviceType.getCommunicationMode();
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>(); UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId()) deviceUpdateWrapper.eq("id", device.getId())
.set("binding_status", BindingStatusEnum.UNBOUND.getCode()); .set("binding_status", BindingStatusEnum.UNBOUND.getCode());
return baseMapper.update(null, deviceUpdateWrapper); return baseMapper.update(null, deviceUpdateWrapper);
} }

View File

@ -0,0 +1,18 @@
package com.fuyuanshen.equipment.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.equipment.domain.DeviceTypeGrants;
import com.fuyuanshen.equipment.mapper.DeviceTypeGrantsMapper;
import com.fuyuanshen.equipment.service.DeviceTypeGrantsService;
import org.springframework.stereotype.Service;
/**
* @author 97433
* @description 针对表【device_type_grants】的数据库操作Service实现
* @createDate 2025-06-19 13:49:33
*/
@Service
public class DeviceTypeGrantsServiceImpl extends ServiceImpl<DeviceTypeGrantsMapper, DeviceTypeGrants>
implements DeviceTypeGrantsService {
}

View File

@ -175,13 +175,20 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
*/ */
@Override @Override
public DeviceType getCommunicationMode(Long id) { public DeviceType getCommunicationMode(Long id) {
DeviceType deviceType = deviceTypeMapper.selectById(id);
DeviceTypeGrants deviceTypeGrants = deviceTypeGrantsMapper.selectById(id);
if (deviceTypeGrants == null) {
throw new RuntimeException("设备类型不存在");
}
DeviceType deviceType = deviceTypeMapper.selectById(deviceTypeGrants.getDeviceTypeId());
if (deviceType == null) { if (deviceType == null) {
throw new RuntimeException("设备类型不存在"); throw new RuntimeException("设备类型不存在");
} }
if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) { //
throw new RuntimeException("无权获取该设备类型通讯方式"); // if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
} // throw new RuntimeException("无权获取该设备类型通讯方式");
// }
return deviceType; return deviceType;
} }

View File

@ -0,0 +1,45 @@
<?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.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper">
<resultMap id="BaseResultMap" type="com.fuyuanshen.equipment.domain.DeviceAssignments">
<id property="id" column="id"/>
<result property="deviceId" column="device_id"/>
<result property="fromCustomerId" column="from_customer_id"/>
<result property="toCustomerId" column="to_customer_id"/>
<result property="assignedAt" column="assigned_at"/>
<result property="deviceTypeGranted" column="device_type_granted"/>
</resultMap>
<sql id="Base_Column_List">
id
,device_id,from_customer_id,to_customer_id,assigned_at,device_type_granted
</sql>
<!-- 查询设备分配信息 -->
<select id="deviceAssignmentsMapper" resultType="com.fuyuanshen.equipment.domain.DeviceAssignments"
parameterType="com.fuyuanshen.equipment.domain.query.DeviceAssignmentQuery">
SELECT *
FROM device_assignments
<where>
<if test="query.deviceId != null">
AND device_id = #{query.deviceId}
</if>
<if test="query.assigneeId != null">
AND assignee_id = #{query.assigneeId}
</if>
<if test="query.active != null">
AND active = #{query.active}
</if>
<if test="query.assignerId != null">
AND assigner_id = #{query.assignerId}
</if>
<if test="query.lever != null">
AND lever LIKE CONCAT('%', #{query.lever}, '%')
</if>
</where>
</select>
</mapper>

View File

@ -37,7 +37,7 @@
</sql> </sql>
<!-- 分页查询设备 --> <!-- 分页查询设备 -->
<select id="findAll" resultType="com.fuyuanshen.equipment.domain.Device"> <select id="findAll1" resultType="com.fuyuanshen.equipment.domain.Device">
select d.* , t.type_name select d.* , t.type_name
FROM device d FROM device d
LEFT JOIN device_type t ON d.device_type = t.id LEFT JOIN device_type t ON d.device_type = t.id
@ -71,6 +71,45 @@
order by d.create_time desc order by d.create_time desc
</select> </select>
<!-- 分页查询设备 -->
<select id="findAll" resultType="com.fuyuanshen.equipment.domain.Device">
select
da.id AS id,d.device_name,
d.device_pic, d.device_mac, d.device_sn, d.update_by,d.device_imei,
d.update_time, dg.id AS device_type, d.remark, d.binding_status,d.type_name AS typeName,
da.assignee_id AS customerId, da.assignee_name AS customerName, da.active AS deviceStatus,
da.create_time AS create_time , da.assigner_name AS createByName , da.id AS assignId
from device d
LEFT JOIN device_type t ON d.device_type = t.id
LEFT JOIN device_type_grants dg ON dg.device_type_id = t.id
LEFT JOIN device_assignments da ON da.device_id = d.id
<where>
<!-- 时间范围等其他条件保持原样 -->
<if test="criteria.deviceName != null and criteria.deviceName.trim() != ''">
and d.device_name like concat('%', TRIM(#{criteria.deviceName}), '%')
</if>
<if test="criteria.deviceMac != null">
and d.device_mac = #{criteria.deviceMac}
</if>
<if test="criteria.deviceImei != null">
and d.device_imei = #{criteria.deviceImei}
</if>
<if test="criteria.deviceType != null">
and d.device_type = #{criteria.deviceType}
</if>
<if test="criteria.deviceStatus != null">
and da.active = #{criteria.deviceStatus}
</if>
<if test="criteria.params.beginTime != null and criteria.params.endTime != null">
and da.create_time between #{criteria.params.beginTime} and #{criteria.params.endTime}
</if>
AND da.assignee_id = #{criteria.currentOwnerId}
</where>
ORDER BY da.create_time DESC
</select>
<select id="findAllDevices" resultType="com.fuyuanshen.equipment.domain.Device"> <select id="findAllDevices" resultType="com.fuyuanshen.equipment.domain.Device">
select select
d.id, d.customer_id, d.device_name, d.id, d.customer_id, d.device_name,
@ -93,15 +132,18 @@
</where> </where>
order by d.id desc order by d.id desc
</select> </select>
<select id="queryAppDeviceList" resultType="com.fuyuanshen.equipment.domain.vo.AppDeviceVo"> <select id="queryAppDeviceList" resultType="com.fuyuanshen.equipment.domain.vo.AppDeviceVo">
select select d.id,
d.id, d.device_name, d.device_mac, d.device_sn, d.device_name,
d.device_imei, d.device_mac ,dt.communication_mode,d.device_pic d.device_mac,
from device d inner join device_type dt on d.device_type = dt.id d.device_sn,
where d.binding_user_id = #{criteria.bindingUserId} and d.binding_status = 1 d.device_imei,
<if test="criteria.deviceType != null"> d.device_mac,
and d.device_type = #{criteria.deviceType} dt.communication_mode
</if> from device d
inner join device_type dt on d.device_type = dt.id
where d.binding_user_id = #{criteria.bindingUserId}
</select> </select>
<!-- 获取分配设备的客户 --> <!-- 获取分配设备的客户 -->