APP/小程序用户设备绑定

This commit is contained in:
2025-07-05 15:55:46 +08:00
parent 5322e84a92
commit ad82ab5fca
18 changed files with 376 additions and 98 deletions

View File

@ -216,6 +216,8 @@ springdoc:
packages-to-scan: com.fuyuanshen.equipment packages-to-scan: com.fuyuanshen.equipment
- group: 客户管理模块 - group: 客户管理模块
packages-to-scan: com.fuyuanshen.customer packages-to-scan: com.fuyuanshen.customer
- group: APP模块
packages-to-scan: com.fuyuanshen.app
# 防止XSS攻击 # 防止XSS攻击
xss: xss:

View File

@ -15,6 +15,11 @@
<dependencies> <dependencies>
<dependency>
<groupId>com.fuyuanshen</groupId>
<artifactId>fys-equipment</artifactId>
</dependency>
<!-- 通用工具--> <!-- 通用工具-->
<dependency> <dependency>
<groupId>com.fuyuanshen</groupId> <groupId>com.fuyuanshen</groupId>

View File

@ -0,0 +1,48 @@
package com.fuyuanshen.app.enums;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* 用户类型枚举
*
* @author: 默苍璃
* @date: 2025-06-1811:14
*/
public enum UserType {
APP(0, "APP"), MINI_PROGRAM(1, "小程序");
private final int value;
private final String description;
UserType(int value, String description) {
this.value = value;
this.description = description;
}
@JsonValue
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
/**
* 根据值获取对应的枚举
*
* @param value 枚举值
* @return 对应的枚举对象
*/
public static UserType fromValue(int value) {
for (UserType userType : values()) {
if (userType.getValue() == value) {
return userType;
}
}
throw new IllegalArgumentException("Invalid user type value: " + value);
}
}

View File

@ -0,0 +1,29 @@
package com.fuyuanshen.app.mapper.equipment;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fuyuanshen.app.domain.APPDeviceType;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author 97433
* @description 针对表【app_device_type(设备类型表)】的数据库操作Mapper
* @createDate 2025-06-24 11:16:18
* @Entity system.domain.AppDeviceType
*/
@Mapper
public interface AppDeviceTypeMapper extends BaseMapper<APPDeviceType> {
/**
* 查询设备类型列表
*
* @param criteria 查询条件
* @return 设备类型列表
*/
List<APPDeviceType> appTypeList(@Param("criteria") DeviceQueryCriteria criteria);
}

View File

@ -10,9 +10,19 @@ import com.fuyuanshen.app.domain.APPDevice;
import com.fuyuanshen.app.domain.APPDeviceType; import com.fuyuanshen.app.domain.APPDeviceType;
import com.fuyuanshen.app.domain.dto.APPUnbindDTO; import com.fuyuanshen.app.domain.dto.APPUnbindDTO;
import com.fuyuanshen.app.domain.query.APPDeviceQueryCriteria; import com.fuyuanshen.app.domain.query.APPDeviceQueryCriteria;
import com.fuyuanshen.app.enums.UserType;
import com.fuyuanshen.app.mapper.equipment.APPDeviceMapper; import com.fuyuanshen.app.mapper.equipment.APPDeviceMapper;
import com.fuyuanshen.app.mapper.equipment.AppDeviceTypeMapper;
import com.fuyuanshen.app.service.equipment.APPDeviceService; import com.fuyuanshen.app.service.equipment.APPDeviceService;
import com.fuyuanshen.common.core.domain.PageResult; import com.fuyuanshen.common.core.domain.PageResult;
import com.fuyuanshen.common.core.exception.BadRequestException;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -34,6 +44,9 @@ import java.util.stream.Collectors;
public class APPDeviceServiceImpl extends ServiceImpl<APPDeviceMapper, APPDevice> implements APPDeviceService { public class APPDeviceServiceImpl extends ServiceImpl<APPDeviceMapper, APPDevice> implements APPDeviceService {
private final APPDeviceMapper appDeviceMapper; private final APPDeviceMapper appDeviceMapper;
private final DeviceMapper deviceMapper;
private final AppDeviceTypeMapper appDeviceTypeMapper;
private final DeviceTypeMapper deviceTypeMapper;
/** /**
@ -72,56 +85,58 @@ public class APPDeviceServiceImpl extends ServiceImpl<APPDeviceMapper, APPDevice
@Override @Override
@Transactional @Transactional
public void appBindDevice(APPDeviceQueryCriteria criteria) { public void appBindDevice(APPDeviceQueryCriteria criteria) {
// List<Device> devices = new ArrayList<>();
// List<Device> devices = new ArrayList<>(); if (criteria.getCommunicationMode().equals(CommunicationModeEnum.BLUETOOTH.getValue())) {
// devices = deviceMapper.selectList(new QueryWrapper<Device>()
// if (criteria.getCommunicationMode().equals(CommunicationModeEnum.BLUETOOTH.getValue())) { .eq("original_device_id", null)
// devices = deviceMapper.selectList(new QueryWrapper<Device>().eq("device_mac", criteria.getDeviceMac())); .eq("device_mac", criteria.getDeviceMac()));
// if (CollectionUtil.isEmpty(devices)) { if (CollectionUtil.isEmpty(devices)) {
// throw new BadRequestException("请先将设备入库!!!"); throw new BadRequestException("请先将设备入库!!!");
// } }
// List<APPDevice> appDevices = appDeviceMapper.selectList(new QueryWrapper<APPDevice>() List<APPDevice> appDevices = appDeviceMapper.selectList(new QueryWrapper<APPDevice>()
// .eq("device_mac", criteria.getDeviceMac()).eq("binding_type", UserType.APP.getValue())); .eq("device_mac", criteria.getDeviceMac()).eq("binding_type", UserType.APP.getValue()));
// if (CollectionUtil.isNotEmpty(appDevices)) { if (CollectionUtil.isNotEmpty(appDevices)) {
// throw new BadRequestException("该设备已绑定!!!"); throw new BadRequestException("该设备已绑定!!!");
// } }
// } }
//
// if (criteria.getCommunicationMode().equals(CommunicationModeEnum.FOUR_G.getValue())) { if (criteria.getCommunicationMode().equals(CommunicationModeEnum.FOUR_G.getValue())) {
// devices = deviceMapper.selectList(new QueryWrapper<Device>().eq("device_imei", criteria.getDeviceImei())); devices = deviceMapper.selectList(new QueryWrapper<Device>()
// if (CollectionUtil.isEmpty(devices)) { .eq("original_device_id", null)
// throw new BadRequestException("请先将设备入库!!!"); .eq("device_imei", criteria.getDeviceImei()));
// } if (CollectionUtil.isEmpty(devices)) {
// List<APPDevice> appDevices = appDeviceMapper.selectList(new QueryWrapper<APPDevice>() throw new BadRequestException("请先将设备入库!!!");
// .eq("device_imei", criteria.getDeviceImei()).eq("binding_type", UserType.APP.getValue())); }
// if (CollectionUtil.isNotEmpty(appDevices)) { List<APPDevice> appDevices = appDeviceMapper.selectList(new QueryWrapper<APPDevice>()
// throw new BadRequestException("该设备已绑定!!!"); .eq("device_imei", criteria.getDeviceImei()).eq("binding_type", UserType.APP.getValue()));
// } if (CollectionUtil.isNotEmpty(appDevices)) {
// } throw new BadRequestException("该设备已绑定!!!");
// }
// Device device = devices.get(0); }
// device.setBindingStatus(BindingStatusEnum.BOUND.getCode());
// deviceMapper.updateById(device); Device device = devices.get(0);
// device.setBindingStatus(BindingStatusEnum.BOUND.getCode());
// APPDevice appDevice = new APPDevice(); deviceMapper.updateById(device);
// BeanUtil.copyProperties(device, appDevice);
// appDevice.setBindingType(UserType.APP.getValue()); APPDevice appDevice = new APPDevice();
// appDevice.setBindingStatus(BindingStatusEnum.BOUND.getCode()); BeanUtil.copyProperties(device, appDevice);
// Long currentUserId = SecurityUtils.getCurrentUserId(); appDevice.setBindingType(UserType.APP.getValue());
// appDevice.setCustomerId(currentUserId); appDevice.setBindingStatus(BindingStatusEnum.BOUND.getCode());
// appDevice.setCreateTime(new Timestamp(System.currentTimeMillis())); Long userId = LoginHelper.getUserId();
// // 设备类型名称 appDevice.setCustomerId(userId);
// appDevice.setDeviceTypeName(device.getTypeName()); appDevice.setCreateTime(new Timestamp(System.currentTimeMillis()));
// appDeviceMapper.insert(appDevice); // 设备类型名称
// appDevice.setDeviceTypeName(device.getTypeName());
// APPDeviceType appDeviceType = appDeviceTypeMapper.selectById(device.getDeviceType()); appDeviceMapper.insert(appDevice);
// if (appDeviceType == null) {
// DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType()); APPDeviceType appDeviceType = appDeviceTypeMapper.selectById(device.getDeviceType());
// APPDeviceType type = new APPDeviceType(); if (appDeviceType == null) {
// BeanUtil.copyProperties(deviceType, type); DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
// type.setCustomerId(currentUserId); APPDeviceType type = new APPDeviceType();
// appDeviceTypeMapper.insert(type); BeanUtil.copyProperties(deviceType, type);
// } type.setCustomerId(userId);
appDeviceTypeMapper.insert(type);
}
} }

View File

@ -0,0 +1,35 @@
<?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.app.mapper.equipment.AppDeviceTypeMapper">
<resultMap id="BaseResultMap" type="com.fuyuanshen.app.domain.APPDeviceType">
<id property="id" column="id"/>
<result property="typeName" column="type_name"/>
<result property="isSupportBle" column="is_support_ble"/>
<result property="locateMode" column="locate_mode"/>
<result property="networkWay" column="network_way"/>
<result property="createBy" column="create_by"/>
<result property="updateBy" column="update_by"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
<result property="customerId" column="customer_id"/>
<result property="communicationMode" column="communication_mode"/>
</resultMap>
<sql id="Base_Column_List">
id
,type_name,is_support_ble,locate_mode,network_way,create_by,
update_by,create_time,update_time,customer_id,communication_mode
</sql>
<!-- 查询设备类型列表 -->
<select id="appTypeList" resultType="com.fuyuanshen.app.domain.APPDeviceType">
select d.* from app_device_type as d
<where>
and d.customer_id = #{criteria.customerId}
</where>
order by d.create_time desc
</select>
</mapper>

View File

@ -135,7 +135,7 @@ public class DeviceController {
@PostMapping(value = "/withdraw") @PostMapping(value = "/withdraw")
public ResponseVO<Object> withdrawDevice(@RequestBody List<Long> ids) { public ResponseVO<Object> withdrawDevice(@RequestBody List<Long> ids) {
try { try {
// deviceService.withdrawDevice(deviceForm); deviceService.withdrawDevice(ids);
} catch (Exception e) { } catch (Exception e) {
log.error("updateDevice error: " + e.getMessage()); log.error("updateDevice error: " + e.getMessage());
return ResponseVO.fail("出错了"); return ResponseVO.fail("出错了");

View File

@ -1,7 +1,5 @@
package com.fuyuanshen.equipment.domain; package com.fuyuanshen.equipment.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
@ -55,6 +53,11 @@ public class Device extends TenantEntity {
@Schema(name = "原始所有者(创建者)") @Schema(name = "原始所有者(创建者)")
private Long originalOwnerId; private Long originalOwnerId;
/**
* 原始设备
*/
@Schema(name = "原始设备")
private Long originalDeviceId;
/*@Schema( name = "设备编号") /*@Schema( name = "设备编号")
private String deviceNo;*/ private String deviceNo;*/
@ -99,7 +102,6 @@ public class Device extends TenantEntity {
@Schema(name = "绑定状态") @Schema(name = "绑定状态")
private Integer bindingStatus; private Integer bindingStatus;
/** /**
* 创建人名称 * 创建人名称
*/ */

View File

@ -34,6 +34,11 @@ public class DeviceType extends TenantEntity {
@Schema(name = "原始所有者(创建者)") @Schema(name = "原始所有者(创建者)")
private Long originalOwnerId; private Long originalOwnerId;
/**
* 原始设备
*/
@Schema(name = "原始设备类型")
private Long originalDeviceId;
@NotBlank(message = "设备类型名称不能为空") @NotBlank(message = "设备类型名称不能为空")
@Schema(name = "类型名称", required = true) @Schema(name = "类型名称", required = true)

View File

@ -26,7 +26,6 @@ public class DeviceExcelImportDTO {
@ColumnWidth(20) @ColumnWidth(20)
private String deviceName; private String deviceName;
@ExcelProperty(value = "设备图片", converter = ByteArrayImageConverter.class) @ExcelProperty(value = "设备图片", converter = ByteArrayImageConverter.class)
@ColumnWidth(15) @ColumnWidth(15)
private byte[] devicePic; private byte[] devicePic;

View File

@ -29,7 +29,6 @@ import java.util.*;
@Slf4j @Slf4j
public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportDTO> { public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportDTO> {
// 存储图片数据的映射 // 存储图片数据的映射
private final Map<Integer, byte[]> rowImageMap = new HashMap<>(); private final Map<Integer, byte[]> rowImageMap = new HashMap<>();
@ -48,6 +47,7 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
this.params = params; this.params = params;
} }
public ImportResult getImportResult() { public ImportResult getImportResult() {
ImportResult result = new ImportResult(); ImportResult result = new ImportResult();
result.setSuccessCount(successCount); result.setSuccessCount(successCount);
@ -151,23 +151,26 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
Device device = rowDeviceMap.get(rowIndex); Device device = rowDeviceMap.get(rowIndex);
DeviceExcelImportDTO originalDto = rowDtoMap.get(rowIndex); DeviceExcelImportDTO originalDto = rowDtoMap.get(rowIndex);
try { try {
DeviceQueryCriteria criteria = new DeviceQueryCriteria(); // DeviceQueryCriteria criteria = new DeviceQueryCriteria();
criteria.setDeviceMac(device.getDeviceMac()); // criteria.setDeviceMac(device.getDeviceMac());
criteria.setTenantId(params.getTenantId()); // criteria.setTenantId(params.getTenantId());
List<Device> deviceList = params.getDeviceMapper().findAll(criteria); // List<Device> deviceList = params.getDeviceMapper().findAll(criteria);
if (!deviceList.isEmpty()) { // if (!deviceList.isEmpty()) {
throw new RuntimeException("设备MAC重复"); // throw new RuntimeException("设备MAC重复");
} // }
device.setTenantId(params.getTenantId()); // device.setTenantId(params.getTenantId());
// 设备类型 // 设备类型
QueryWrapper<DeviceType> wrapper = new QueryWrapper<>(); QueryWrapper<DeviceType> wrapper = new QueryWrapper<>();
wrapper.eq("type_name", device.getTypeName()); wrapper.eq("type_name", device.getTypeName());
wrapper.eq("customer_id", params.getUserId()); // wrapper.eq("customer_id", params.getUserId());
List<DeviceType> deviceTypes = params.getDeviceTypeMapper().selectList(wrapper); List<DeviceType> deviceTypes = params.getDeviceTypeMapper().selectList(wrapper);
if (CollectionUtil.isNotEmpty(deviceTypes)) { if (CollectionUtil.isNotEmpty(deviceTypes)) {
device.setDeviceType(deviceTypes.get(0).getId()); device.setDeviceType(deviceTypes.get(0).getId());
} }
device.setCurrentOwnerId(loginUser.getUserId());
device.setOriginalOwnerId(loginUser.getUserId());
device.setCreateByName(loginUser.getNickname());
params.getDeviceService().save(device); params.getDeviceService().save(device);
successCount++; successCount++;
log.info("行 {} 数据插入成功", rowIndex); log.info("行 {} 数据插入成功", rowIndex);

View File

@ -38,4 +38,12 @@ public interface DeviceMapper extends BaseMapper<Device> {
* @return * @return
*/ */
Device getAssignCustomer(Long customerId); Device getAssignCustomer(Long customerId);
/**
* 获取设备链
*
* @param originalDeviceId
* @return
*/
List<Device> findByOriginalDeviceId(Long originalDeviceId);
} }

View File

@ -36,4 +36,12 @@ public interface DeviceTypeMapper extends BaseMapper<DeviceType> {
*/ */
List<DeviceType> findAll(@Param("criteria") DeviceTypeQueryCriteria criteria); List<DeviceType> findAll(@Param("criteria") DeviceTypeQueryCriteria criteria);
/**
* 获取已经分配的设备类型
*
* @param customerId
* @return
*/
DeviceType getAssignType(@Param("deviceType") Long deviceType, @Param("customerId") Long customerId);
} }

View File

@ -73,7 +73,7 @@ public interface DeviceService extends IService<Device> {
/** /**
* 撤回设备 * 撤回设备
*/ */
void withdrawDevice(DeviceForm deviceForm); void withdrawDevice(List<Long> ids);
/** /**
* 解绑设备 * 解绑设备

View File

@ -17,6 +17,7 @@ import com.fuyuanshen.equipment.domain.form.DeviceForm;
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.CustomerVo; import com.fuyuanshen.equipment.domain.vo.CustomerVo;
import com.fuyuanshen.equipment.enums.DeviceStatusEnum;
import com.fuyuanshen.equipment.mapper.DeviceMapper; import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper; import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.service.DeviceService; import com.fuyuanshen.equipment.service.DeviceService;
@ -32,9 +33,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.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Objects;
/** /**
* @Description: * @Description:
@ -133,6 +132,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
Device device = new Device(); Device device = new Device();
LoginUser loginUser = LoginHelper.getLoginUser(); LoginUser loginUser = LoginHelper.getLoginUser();
device.setCurrentOwnerId(loginUser.getUserId()); device.setCurrentOwnerId(loginUser.getUserId());
device.setOriginalOwnerId(loginUser.getUserId());
device.setCreateByName(loginUser.getNickname()); device.setCreateByName(loginUser.getNickname());
device.setTypeName(deviceTypes.get(0).getTypeName()); device.setTypeName(deviceTypes.get(0).getTypeName());
BeanUtil.copyProperties(deviceForm, device, true); BeanUtil.copyProperties(deviceForm, device, true);
@ -171,9 +171,11 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
// 处理上传的图片 // 处理上传的图片
// String imageUrl = saveDeviceImage(deviceForm.getFile(), device.getDeviceName()); // String imageUrl = saveDeviceImage(deviceForm.getFile(), device.getDeviceName());
SysOssVo upload = ossService.upload(deviceForm.getFile()); if (deviceForm.getFile() != null) {
// 设置图片路径 SysOssVo upload = ossService.upload(deviceForm.getFile());
deviceForm.setDevicePic(upload.getUrl()); // 设置图片路径
deviceForm.setDevicePic(upload.getUrl());
}
// 更新字段 // 更新字段
BeanUtil.copyProperties(deviceForm, device, true); BeanUtil.copyProperties(deviceForm, device, true);
@ -240,8 +242,65 @@ 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(); List<Long> deviceIds = customerVo.getDeviceIds();
Long customerId = customerVo.getCustomerId(); Long customerId = customerVo.getCustomerId();
@ -251,8 +310,9 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
throw new RuntimeException("待分配的客户不存在!!!"); throw new RuntimeException("待分配的客户不存在!!!");
} }
List<Device> devicesToAssign = new ArrayList<>();
List<Long> invalidIds = new ArrayList<>(); List<Long> invalidIds = new ArrayList<>();
List<Device> devices = new ArrayList<>();
for (Long id : deviceIds) { for (Long id : deviceIds) {
Device device = deviceMapper.selectById(id); Device device = deviceMapper.selectById(id);
if (device == null || !Objects.equals(device.getCurrentOwnerId(), LoginHelper.getUserId())) { if (device == null || !Objects.equals(device.getCurrentOwnerId(), LoginHelper.getUserId())) {
@ -266,51 +326,94 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
} }
device.setCustomerId(customerId); device.setCustomerId(customerId);
device.setCustomerName(customer.getNickName()); device.setCustomerName(customer.getNickName());
devices.add(device); devicesToAssign.add(device);
} }
if (!invalidIds.isEmpty()) { if (!invalidIds.isEmpty()) {
throw new RuntimeException("以下设备无法分配ID 不存在或无权限): " + invalidIds); throw new RuntimeException("以下设备无法分配ID 不存在或无权限): " + invalidIds);
} }
devices.forEach((device) -> { // 批量处理设备分配
batchAssignDevices(devicesToAssign, customer);
}
deviceMapper.updateById(device); @Transactional(rollbackFor = Exception.class)
device.setCurrentOwnerId(customerId); public void batchAssignDevices(List<Device> devicesToAssign, Customer customer) {
Long userId = LoginHelper.getUserId();
SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator();
for (Device device : devicesToAssign) {
if (device.getDeviceType() == null) { if (device.getDeviceType() == null) {
throw new RuntimeException("设备类型有问题!!! "); throw new RuntimeException("设备类型有问题!!! ");
} }
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator();
device.setOriginalOwnerId(device.getId());
Long next = snowflakeGenerator.next();
device.setId(next);
device.setDeviceType(next);
deviceType.setOriginalOwnerId(deviceType.getId()); deviceMapper.updateById(device);
deviceType.setId(next);
deviceType.setOwnerCustomerId(customerId); DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
DeviceType assignType = deviceTypeMapper.getAssignType(device.getDeviceType(), customer.getCustomerId());
Long next = snowflakeGenerator.next();
device.setOriginalDeviceId(device.getId());
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); deviceMapper.insert(device);
deviceTypeMapper.insert(deviceType); }
});
}
public void assign(List<Long> deviceIds) {
} }
/** /**
* 撤回设备 * 撤回设备
* *
* @param deviceForm * @param ids
*/ */
@Override @Override
public void withdrawDevice(DeviceForm deviceForm) { public void withdrawDevice(List<Long> ids) {
ids.forEach((id) -> {
List<Device> deviceChain = getDeviceChain(id);
deviceChain.forEach((device) -> {
device.setDeviceStatus(DeviceStatusEnum.INVALID.getCode());
// device.setCustomerId(null);
// device.setCustomerName("");
deviceMapper.updateById(device);
});
});
}
public List<Device> getDeviceChain(Long originalDeviceId) {
List<Device> chain = new ArrayList<>();
Set<Long> visited = new HashSet<>(); // 防止循环引用
findNext(chain, visited, originalDeviceId);
return chain;
}
private void findNext(List<Device> chain, Set<Long> visited, Long currentOriginalDeviceId) {
if (visited.contains(currentOriginalDeviceId)) {
log.info("检测到循环引用,终止递归");
return;
}
visited.add(currentOriginalDeviceId);
List<Device> devices = deviceMapper.findByOriginalDeviceId(currentOriginalDeviceId);
for (Device device : devices) {
chain.add(device);
findNext(chain, visited, device.getId());
}
} }

View File

@ -85,6 +85,7 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
LoginUser loginUser = LoginHelper.getLoginUser(); LoginUser loginUser = LoginHelper.getLoginUser();
resources.setCustomerId(loginUser.getUserId()); resources.setCustomerId(loginUser.getUserId());
resources.setOwnerCustomerId(loginUser.getUserId()); resources.setOwnerCustomerId(loginUser.getUserId());
resources.setOriginalOwnerId(loginUser.getUserId());
resources.setCreateByName(loginUser.getNickname()); resources.setCreateByName(loginUser.getNickname());
deviceTypeMapper.insert(resources); deviceTypeMapper.insert(resources);
} }

View File

@ -98,8 +98,16 @@
<select id="getAssignCustomer" resultType="com.fuyuanshen.equipment.domain.Device"> <select id="getAssignCustomer" resultType="com.fuyuanshen.equipment.domain.Device">
SELECT * SELECT *
FROM device FROM device
WHERE original_owner_id = #{customerId} WHERE original_device_id = #{customerId}
AND device_status = 1 AND device_status = 1
</select> </select>
<!-- 获取设备链 -->
<select id="findByOriginalDeviceId" resultType="com.fuyuanshen.equipment.domain.Device"
parameterType="java.lang.Long">
SELECT id, original_device_id
FROM device
WHERE original_device_id = #{originalDeviceId}
</select>
</mapper> </mapper>

View File

@ -37,4 +37,11 @@
</where> </where>
ORDER BY dt.create_time DESC ORDER BY dt.create_time DESC
</select> </select>
<!-- 获取已经分配的设备类型 -->
<select id="getAssignType" resultType="com.fuyuanshen.equipment.domain.DeviceType">
SELECT *
FROM device_type
WHERE owner_customer_id = #{customerId} AND original_device_id = #{deviceType}
</select>
</mapper> </mapper>