增加消息通知接口

This commit is contained in:
menxipeng
2025-08-24 00:24:39 +08:00
parent f30ab86f2d
commit 66dc8ce2bf
13 changed files with 1933 additions and 0 deletions

View File

@@ -0,0 +1,122 @@
package com.ruoyi.web.controller.back;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Notifications;
import com.ruoyi.common.core.domain.entity.ShopUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.INotificationRecordsService;
import com.ruoyi.system.service.INotificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 【请填写功能名称】Controller
*
* @author ruoyi
* @date 2025-08-23
*/
@RestController
@RequestMapping("/back/notifications")
public class NotificationsController extends BaseController
{
@Autowired
private INotificationsService notificationsService;
@Autowired
private INotificationRecordsService recordsService;
/**
* 查询【请填写功能名称】列表
*/
@PreAuthorize("@ss.hasPermi('system:notifications:list')")
@GetMapping("/list")
public TableDataInfo list(Notifications notifications)
{
startPage();
List<Notifications> list = notificationsService.selectNotificationsList(notifications);
return getDataTable(list);
}
/**
* 导出【请填写功能名称】列表
*/
@PreAuthorize("@ss.hasPermi('system:notifications:export')")
@Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, Notifications notifications)
{
List<Notifications> list = notificationsService.selectNotificationsList(notifications);
ExcelUtil<Notifications> util = new ExcelUtil<Notifications>(Notifications.class);
util.exportExcel(response, list, "【请填写功能名称】数据");
}
/**
* 绑定用户到通知
*/
@Log(title = "绑定通知用户", businessType = BusinessType.OTHER)
@PostMapping("/bind")
public AjaxResult bind(@RequestParam Long id, @RequestBody List<ShopUser> shopUsers){
recordsService.bind(id, shopUsers);
return AjaxResult.success("绑定用户成功");
}
/**
* 获取通知已绑定的用户列表
*/
@GetMapping("/bindUsers/{id}")
public AjaxResult getBindUsers(@PathVariable("id") Long id) {
List<ShopUser> list = recordsService.getBindUsers(id);
return AjaxResult.success(list);
}
/**
* 发布通知
*/
@Log(title = "发布通知", businessType = BusinessType.OTHER)
@PostMapping("/publish/{id}")
public AjaxResult publish(@PathVariable("id") Long id) {
return notificationsService.publishNotification(id);
}
/**
* 新增【请填写功能名称】
*/
@PreAuthorize("@ss.hasPermi('system:notifications:add')")
@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody Notifications notifications)
{
return toAjax(notificationsService.insertNotifications(notifications));
}
/**
* 修改【请填写功能名称】
*/
@PreAuthorize("@ss.hasPermi('system:notifications:edit')")
@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody Notifications notifications)
{
return toAjax(notificationsService.updateNotifications(notifications));
}
/**
* 删除【请填写功能名称】
*/
@PreAuthorize("@ss.hasPermi('system:notifications:remove')")
@Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(notificationsService.deleteNotificationsByIds(ids));
}
}

View File

@@ -0,0 +1,148 @@
package com.ruoyi.common.core.domain.entity;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* 【请填写功能名称】对象 notification_records
*
* @author ruoyi
* @date 2025-08-23
*/
public class NotificationRecords extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** $column.columnComment */
private Long id;
/** 关联通知内容ID */
@Excel(name = "关联通知内容ID")
private Long notificationId;
/** 接收用户ID关联您现有用户表 */
@Excel(name = "接收用户ID", readConverterExp = "关=联您现有用户表")
private Long userId;
/** 发送渠道 'push', 'sms', 'email', 'in-app' */
@Excel(name = "发送渠道 'push', 'sms', 'email', 'in-app'")
private String channel;
/** 发送状态 'pending', 'sent', 'delivered', 'read', 'failed' */
@Excel(name = "发送状态 'pending', 'sent', 'delivered', 'read', 'failed'")
private String status;
/** 实际发送时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "实际发送时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date sentTime;
/** 用户阅读时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "用户阅读时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date readTime;
/** 失败原因 */
@Excel(name = "失败原因")
private String failureReason;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setNotificationId(Long notificationId)
{
this.notificationId = notificationId;
}
public Long getNotificationId()
{
return notificationId;
}
public void setUserId(Long userId)
{
this.userId = userId;
}
public Long getUserId()
{
return userId;
}
public void setChannel(String channel)
{
this.channel = channel;
}
public String getChannel()
{
return channel;
}
public void setStatus(String status)
{
this.status = status;
}
public String getStatus()
{
return status;
}
public void setSentTime(Date sentTime)
{
this.sentTime = sentTime;
}
public Date getSentTime()
{
return sentTime;
}
public void setReadTime(Date readTime)
{
this.readTime = readTime;
}
public Date getReadTime()
{
return readTime;
}
public void setFailureReason(String failureReason)
{
this.failureReason = failureReason;
}
public String getFailureReason()
{
return failureReason;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("notificationId", getNotificationId())
.append("userId", getUserId())
.append("channel", getChannel())
.append("status", getStatus())
.append("sentTime", getSentTime())
.append("readTime", getReadTime())
.append("failureReason", getFailureReason())
.append("createTime", getCreateTime())
.append("updateTime", getUpdateTime())
.toString();
}
}

View File

@@ -0,0 +1,56 @@
package com.ruoyi.common.core.domain.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* 【请填写功能名称】对象 notifications
*
* @author ruoyi
* @date 2025-08-23
*/
@Data
public class Notifications extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** $column.columnComment */
private Long id;
/** 通知标题 */
@Excel(name = "通知标题")
private String title;
/** 通知内容 */
@Excel(name = "通知内容")
private String content;
/** 通知类型 system */
@Excel(name = "通知类型 system")
private String notificationType;
/** 附加数据如跳转链接、图片URL等 预留字段 */
@Excel(name = "附加数据如跳转链接、图片URL等 预留字段")
private String extraData;
/** 创建者用户ID关联您现有用户表 */
@Excel(name = "创建者用户ID", readConverterExp = "关=联您现有用户表")
private String creator;
/** $column.columnComment */
@Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()")
private Date updatedTime;
/** 计划发送时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "计划发送时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date sendTime;
private List<ShopUser> shopUsers;
}

View File

@@ -0,0 +1,70 @@
package com.ruoyi.system.mapper;
import com.ruoyi.common.core.domain.entity.NotificationRecords;
import java.util.List;
/**
* 【请填写功能名称】Mapper接口
*
* @author ruoyi
* @date 2025-08-23
*/
public interface NotificationRecordsMapper
{
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
public NotificationRecords selectNotificationRecordsById(Long id);
/**
* 查询【请填写功能名称】列表
*
* @param notificationRecords 【请填写功能名称】
* @return 【请填写功能名称】集合
*/
public List<NotificationRecords> selectNotificationRecordsList(NotificationRecords notificationRecords);
/**
* 新增【请填写功能名称】
*
* @param notificationRecords 【请填写功能名称】
* @return 结果
*/
public int insertNotificationRecords(NotificationRecords notificationRecords);
/**
* 修改【请填写功能名称】
*
* @param notificationRecords 【请填写功能名称】
* @return 结果
*/
public int updateNotificationRecords(NotificationRecords notificationRecords);
/**
* 删除【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
public int deleteNotificationRecordsById(Long id);
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的数据主键集合
* @return 结果
*/
public int deleteNotificationRecordsByIds(Long[] ids);
/**
* 批量新增通知记录
*
* @param list 通知记录列表
* @return 结果
*/
public int batchInsertNotificationRecords(List<NotificationRecords> list);
}

View File

@@ -0,0 +1,62 @@
package com.ruoyi.system.mapper;
import com.ruoyi.common.core.domain.entity.Notifications;
import java.util.List;
/**
* 【请填写功能名称】Mapper接口
*
* @author ruoyi
* @date 2025-08-23
*/
public interface NotificationsMapper
{
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
public Notifications selectNotificationsById(Long id);
/**
* 查询【请填写功能名称】列表
*
* @param notifications 【请填写功能名称】
* @return 【请填写功能名称】集合
*/
public List<Notifications> selectNotificationsList(Notifications notifications);
/**
* 新增【请填写功能名称】
*
* @param notifications 【请填写功能名称】
* @return 结果
*/
public int insertNotifications(Notifications notifications);
/**
* 修改【请填写功能名称】
*
* @param notifications 【请填写功能名称】
* @return 结果
*/
public int updateNotifications(Notifications notifications);
/**
* 删除【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
public int deleteNotificationsById(Long id);
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的数据主键集合
* @return 结果
*/
public int deleteNotificationsByIds(Long[] ids);
}

View File

@@ -0,0 +1,80 @@
package com.ruoyi.system.service;
import com.ruoyi.common.core.domain.entity.NotificationRecords;
import com.ruoyi.common.core.domain.entity.Notifications;
import com.ruoyi.common.core.domain.entity.ShopUser;
import java.util.List;
/**
* 【请填写功能名称】Service接口
*
* @author ruoyi
* @date 2025-08-23
*/
public interface INotificationRecordsService
{
/**
* 绑定用户到通知记录
*
* @param id 通知ID
* @param shopUsers 用户列表
*/
public void bind(Long id, List<ShopUser> shopUsers);
/**
* 获取通知已绑定的用户列表
*
* @param notificationId 通知ID
* @return 用户列表
*/
public List<ShopUser> getBindUsers(Long notificationId);
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
public NotificationRecords selectNotificationRecordsById(Long id);
/**
* 查询【请填写功能名称】列表
*
* @param notificationRecords 【请填写功能名称】
* @return 【请填写功能名称】集合
*/
public List<NotificationRecords> selectNotificationRecordsList(NotificationRecords notificationRecords);
/**
* 新增【请填写功能名称】
*
* @param notificationRecords 【请填写功能名称】
* @return 结果
*/
public int insertNotificationRecords(NotificationRecords notificationRecords);
/**
* 修改【请填写功能名称】
*
* @param notificationRecords 【请填写功能名称】
* @return 结果
*/
public int updateNotificationRecords(NotificationRecords notificationRecords);
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的【请填写功能名称】主键集合
* @return 结果
*/
public int deleteNotificationRecordsByIds(Long[] ids);
/**
* 删除【请填写功能名称】信息
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
public int deleteNotificationRecordsById(Long id);
}

View File

@@ -0,0 +1,71 @@
package com.ruoyi.system.service;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Notifications;
import java.util.List;
/**
* 【请填写功能名称】Service接口
*
* @author ruoyi
* @date 2025-08-23
*/
public interface INotificationsService
{
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
public Notifications selectNotificationsById(Long id);
/**
* 查询【请填写功能名称】列表
*
* @param notifications 【请填写功能名称】
* @return 【请填写功能名称】集合
*/
public List<Notifications> selectNotificationsList(Notifications notifications);
/**
* 新增【请填写功能名称】
*
* @param notifications 【请填写功能名称】
* @return 结果
*/
public int insertNotifications(Notifications notifications);
/**
* 修改【请填写功能名称】
*
* @param notifications 【请填写功能名称】
* @return 结果
*/
public int updateNotifications(Notifications notifications);
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的【请填写功能名称】主键集合
* @return 结果
*/
public int deleteNotificationsByIds(Long[] ids);
/**
* 删除【请填写功能名称】信息
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
public int deleteNotificationsById(Long id);
/**
* 发布通知
*
* @param id 通知ID
* @return 结果
*/
public AjaxResult publishNotification(Long id);
}

View File

@@ -0,0 +1,245 @@
package com.ruoyi.system.service.impl;
import com.ruoyi.common.core.domain.entity.NotificationRecords;
import com.ruoyi.common.core.domain.entity.Notifications;
import com.ruoyi.common.core.domain.entity.ShopUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.NotificationRecordsMapper;
import com.ruoyi.system.service.INotificationRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* 【请填写功能名称】Service业务层处理
*
* @author ruoyi
* @date 2025-08-23
*/
@Transactional
@Service
public class NotificationRecordsServiceImpl implements INotificationRecordsService
{
@Autowired
private NotificationRecordsMapper notificationRecordsMapper;
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
@Override
public NotificationRecords selectNotificationRecordsById(Long id)
{
return notificationRecordsMapper.selectNotificationRecordsById(id);
}
/**
* 查询【请填写功能名称】列表
*
* @param notificationRecords 【请填写功能名称】
* @return 【请填写功能名称】
*/
@Override
public List<NotificationRecords> selectNotificationRecordsList(NotificationRecords notificationRecords)
{
return notificationRecordsMapper.selectNotificationRecordsList(notificationRecords);
}
/**
* 新增【请填写功能名称】
*
* @param notificationRecords 【请填写功能名称】
* @return 结果
*/
@Override
public int insertNotificationRecords(NotificationRecords notificationRecords)
{
notificationRecords.setCreateTime(DateUtils.getNowDate());
return notificationRecordsMapper.insertNotificationRecords(notificationRecords);
}
/**
* 修改【请填写功能名称】
*
* @param notificationRecords 【请填写功能名称】
* @return 结果
*/
@Override
public int updateNotificationRecords(NotificationRecords notificationRecords)
{
notificationRecords.setUpdateTime(DateUtils.getNowDate());
return notificationRecordsMapper.updateNotificationRecords(notificationRecords);
}
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的【请填写功能名称】主键
* @return 结果
*/
@Override
public int deleteNotificationRecordsByIds(Long[] ids)
{
return notificationRecordsMapper.deleteNotificationRecordsByIds(ids);
}
/**
* 删除【请填写功能名称】信息
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
@Override
public int deleteNotificationRecordsById(Long id)
{
return notificationRecordsMapper.deleteNotificationRecordsById(id);
}
/**
* 绑定用户到通知记录
*
* @param id 通知ID
* @param shopUsers 用户列表
*/
@Override
@Transactional
public void bind(Long id, List<ShopUser> shopUsers) {
System.out.println("开始绑定用户通知ID: " + id + ", 用户数量: " + (shopUsers != null ? shopUsers.size() : 0));
if (id == null || shopUsers == null || shopUsers.isEmpty()) {
System.out.println("通知ID为空或用户列表为空无法绑定");
return;
}
// 打印用户列表信息
System.out.println("用户列表详情:");
for (ShopUser user : shopUsers) {
System.out.println("用户ID: " + (user != null ? user.getUserId() : "null") +
", 类型: " + (user != null && user.getUserId() != null ? user.getUserId().getClass().getName() : "null"));
}
// 获取当前时间
Date now = DateUtils.getNowDate();
// 查询该通知已经绑定的用户ID列表
NotificationRecords query = new NotificationRecords();
query.setNotificationId(id);
List<NotificationRecords> existingRecords = notificationRecordsMapper.selectNotificationRecordsList(query);
Set<Long> existingUserIds = existingRecords.stream()
.map(NotificationRecords::getUserId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
System.out.println("已绑定用户数量: " + existingUserIds.size());
// 创建通知记录列表
List<NotificationRecords> recordsList = new ArrayList<>();
// 遍历用户列表,为每个用户创建通知记录(排除已绑定的用户)
int validUserCount = 0;
int invalidUserCount = 0;
int duplicateUserCount = 0;
for (ShopUser user : shopUsers) {
try {
// 验证用户ID是否有效
if (user == null || user.getUserId() == null) {
System.out.println("用户或用户ID为空跳过");
invalidUserCount++;
continue;
}
if (existingUserIds.contains(user.getUserId())) {
System.out.println("用户ID: " + user.getUserId() + " 已绑定,跳过");
duplicateUserCount++;
continue;
}
// 创建通知记录
NotificationRecords record = new NotificationRecords();
record.setUserId(user.getUserId());
// 默认设置为in-app渠道
record.setChannel("in-app");
// 设置状态为待发送
record.setStatus("pending");
record.setCreateTime(now);
record.setNotificationId(id);
recordsList.add(record);
validUserCount++;
System.out.println("添加用户ID: " + user.getUserId() + " 到待绑定列表");
} catch (Exception e) {
// 记录错误日志,但继续处理其他用户
System.err.println("处理用户ID时出错: " + (user != null ? user.getUserId() : "null") + ", 错误: " + e.getMessage());
e.printStackTrace();
invalidUserCount++;
}
}
System.out.println("有效用户数: " + validUserCount + ", 无效用户数: " + invalidUserCount + ", 重复用户数: " + duplicateUserCount);
System.out.println("待插入记录数: " + recordsList.size());
// 批量插入通知记录
if (!recordsList.isEmpty()) {
try {
int insertCount = notificationRecordsMapper.batchInsertNotificationRecords(recordsList);
System.out.println("成功插入记录数: " + insertCount);
} catch (Exception e) {
System.err.println("批量插入通知记录失败: " + e.getMessage());
e.printStackTrace();
throw new RuntimeException("批量插入通知记录失败: " + e.getMessage(), e);
}
} else {
System.out.println("没有需要插入的记录");
}
}
/**
* 获取通知已绑定的用户列表
*
* @param notificationId 通知ID
* @return 用户列表
*/
@Override
public List<ShopUser> getBindUsers(Long notificationId) {
if (notificationId == null) {
return new ArrayList<>();
}
// 创建查询条件
NotificationRecords query = new NotificationRecords();
query.setNotificationId(notificationId);
// 查询通知记录
List<NotificationRecords> records = notificationRecordsMapper.selectNotificationRecordsList(query);
// 提取用户ID列表
List<Long> userIds = records.stream()
.map(NotificationRecords::getUserId)
.filter(Objects::nonNull)
.collect(Collectors.toList());
// 如果没有绑定用户,返回空列表
if (userIds.isEmpty()) {
return new ArrayList<>();
}
// 查询用户信息
// 这里需要调用ShopUserMapper来查询用户信息
// 由于没有提供ShopUserMapper这里简单处理将用户ID封装成ShopUser对象返回
List<ShopUser> users = new ArrayList<>();
for (Long userId : userIds) {
ShopUser user = new ShopUser();
user.setUserId(userId);
users.add(user);
}
return users;
}
}

View File

@@ -0,0 +1,221 @@
package com.ruoyi.system.service.impl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.NotificationRecords;
import com.ruoyi.common.core.domain.entity.Notifications;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.NotificationRecordsMapper;
import com.ruoyi.system.mapper.NotificationsMapper;
import com.ruoyi.system.service.INotificationsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
* 【请填写功能名称】Service业务层处理
*
* @author ruoyi
* @date 2025-08-23
*/
@Service
public class NotificationsServiceImpl implements INotificationsService
{
private static final Logger log = LoggerFactory.getLogger(NotificationsServiceImpl.class);
@Autowired
private NotificationsMapper notificationsMapper;
@Autowired
private NotificationRecordsMapper notificationRecordsMapper;
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
@Override
public Notifications selectNotificationsById(Long id)
{
return notificationsMapper.selectNotificationsById(id);
}
/**
* 查询【请填写功能名称】列表
*
* @param notifications 【请填写功能名称】
* @return 【请填写功能名称】
*/
@Override
public List<Notifications> selectNotificationsList(Notifications notifications)
{
return notificationsMapper.selectNotificationsList(notifications);
}
/**
* 新增【请填写功能名称】
*
* @param notifications 【请填写功能名称】
* @return 结果
*/
@Override
public int insertNotifications(Notifications notifications)
{
notifications.setCreateTime(DateUtils.getNowDate());
return notificationsMapper.insertNotifications(notifications);
}
/**
* 修改【请填写功能名称】
*
* @param notifications 【请填写功能名称】
* @return 结果
*/
@Override
public int updateNotifications(Notifications notifications)
{
return notificationsMapper.updateNotifications(notifications);
}
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的【请填写功能名称】主键
* @return 结果
*/
@Override
public int deleteNotificationsByIds(Long[] ids)
{
return notificationsMapper.deleteNotificationsByIds(ids);
}
/**
* 删除【请填写功能名称】信息
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
@Override
public int deleteNotificationsById(Long id)
{
return notificationsMapper.deleteNotificationsById(id);
}
/**
* 发布通知
*
* @param id 通知ID
* @return 结果
*/
@Override
@Transactional
public AjaxResult publishNotification(Long id)
{
// 查询通知信息
Notifications notification = notificationsMapper.selectNotificationsById(id);
if (notification == null)
{
return AjaxResult.error("通知不存在");
}
// 查询该通知的所有记录
NotificationRecords query = new NotificationRecords();
query.setNotificationId(id);
List<NotificationRecords> records = notificationRecordsMapper.selectNotificationRecordsList(query);
if (records.isEmpty())
{
return AjaxResult.error("该通知没有绑定任何用户,请先绑定用户");
}
// 当前时间
Date now = DateUtils.getNowDate();
int successCount = 0;
int failCount = 0;
// 遍历所有记录,进行发布
for (NotificationRecords record : records)
{
// 如果记录已经发送过,则不再创建新记录,只更新状态
if ("sent".equals(record.getStatus()))
{
// 调用第三方接口发送通知
boolean sendResult = sendNotificationToThirdParty(notification, record);
if (sendResult)
{
successCount++;
}
else
{
failCount++;
// 更新失败原因
record.setFailureReason("重新发送失败");
notificationRecordsMapper.updateNotificationRecords(record);
}
}
else
{
// 调用第三方接口发送通知
boolean sendResult = sendNotificationToThirdParty(notification, record);
if (sendResult)
{
// 更新记录状态为已发送
record.setStatus("sent");
record.setSentTime(now);
record.setUpdateTime(now);
notificationRecordsMapper.updateNotificationRecords(record);
successCount++;
}
else
{
// 更新记录状态为发送失败
record.setStatus("failed");
record.setFailureReason("发送失败");
record.setUpdateTime(now);
notificationRecordsMapper.updateNotificationRecords(record);
failCount++;
}
}
}
// 更新通知状态为已发布
// notification.setStatus("published");
// notification.setPublishTime(now);
notificationsMapper.updateNotifications(notification);
return AjaxResult.success("通知发布完成,成功:" + successCount + ",失败:" + failCount);
}
/**
* 调用第三方接口发送通知
*
* @param notification 通知信息
* @param record 通知记录
* @return 发送结果
*/
private boolean sendNotificationToThirdParty(Notifications notification, NotificationRecords record)
{
try
{
// TODO: 实现调用第三方接口发送通知的逻辑
// 这里是模拟实现,实际项目中需要根据具体的第三方接口进行调用
log.info("发送通知通知ID={}, 用户ID={}, 标题={}, 内容={}",
notification.getId(), record.getUserId(), notification.getTitle(), notification.getContent());
// 模拟发送成功
return true;
}
catch (Exception e)
{
log.error("发送通知失败:", e);
return false;
}
}
}

View File

@@ -0,0 +1,113 @@
<?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.ruoyi.system.mapper.NotificationRecordsMapper">
<resultMap type="NotificationRecords" id="NotificationRecordsResult">
<result property="id" column="id" />
<result property="notificationId" column="notification_id" />
<result property="userId" column="user_id" />
<result property="channel" column="channel" />
<result property="status" column="status" />
<result property="sentTime" column="sent_time" />
<result property="readTime" column="read_time" />
<result property="failureReason" column="failure_reason" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectNotificationRecordsVo">
select id, notification_id, user_id, channel, status, sent_time, read_time, failure_reason, create_time, update_time from notification_records
</sql>
<select id="selectNotificationRecordsList" parameterType="NotificationRecords" resultMap="NotificationRecordsResult">
<include refid="selectNotificationRecordsVo"/>
<where>
<if test="notificationId != null "> and notification_id = #{notificationId}</if>
<if test="userId != null "> and user_id = #{userId}</if>
<if test="channel != null and channel != ''"> and channel = #{channel}</if>
<if test="status != null and status != ''"> and status = #{status}</if>
<if test="sentTime != null "> and sent_time = #{sentTime}</if>
<if test="readTime != null "> and read_time = #{readTime}</if>
<if test="failureReason != null and failureReason != ''"> and failure_reason = #{failureReason}</if>
</where>
</select>
<select id="selectNotificationRecordsById" parameterType="Long" resultMap="NotificationRecordsResult">
<include refid="selectNotificationRecordsVo"/>
where id = #{id}
</select>
<insert id="insertNotificationRecords" parameterType="NotificationRecords" useGeneratedKeys="true" keyProperty="id">
insert into notification_records
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="notificationId != null">notification_id,</if>
<if test="userId != null">user_id,</if>
<if test="channel != null">channel,</if>
<if test="status != null">status,</if>
<if test="sentTime != null">sent_time,</if>
<if test="readTime != null">read_time,</if>
<if test="failureReason != null">failure_reason,</if>
<if test="createTime != null">create_time,</if>
<if test="updateTime != null">update_time,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="notificationId != null">#{notificationId},</if>
<if test="userId != null">#{userId},</if>
<if test="channel != null">#{channel},</if>
<if test="status != null">#{status},</if>
<if test="sentTime != null">#{sentTime},</if>
<if test="readTime != null">#{readTime},</if>
<if test="failureReason != null">#{failureReason},</if>
<if test="createTime != null">#{createTime},</if>
<if test="updateTime != null">#{updateTime},</if>
</trim>
</insert>
<update id="updateNotificationRecords" parameterType="NotificationRecords">
update notification_records
<trim prefix="SET" suffixOverrides=",">
<if test="notificationId != null">notification_id = #{notificationId},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="channel != null">channel = #{channel},</if>
<if test="status != null">status = #{status},</if>
<if test="sentTime != null">sent_time = #{sentTime},</if>
<if test="readTime != null">read_time = #{readTime},</if>
<if test="failureReason != null">failure_reason = #{failureReason},</if>
<if test="createTime != null">create_time = #{createTime},</if>
<if test="updateTime != null">update_time = #{updateTime},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteNotificationRecordsById" parameterType="Long">
delete from notification_records where id = #{id}
</delete>
<delete id="deleteNotificationRecordsByIds" parameterType="String">
delete from notification_records where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
<insert id="batchInsertNotificationRecords" parameterType="java.util.List">
insert into notification_records
(notification_id, user_id, channel, status, sent_time, read_time, failure_reason, create_time, update_time)
values
<foreach collection="list" item="item" separator=",">
(
#{item.notificationId},
#{item.userId},
#{item.channel},
#{item.status},
#{item.sentTime},
#{item.readTime},
#{item.failureReason},
#{item.createTime},
#{item.updateTime}
)
</foreach>
</insert>
</mapper>

View File

@@ -0,0 +1,90 @@
<?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.ruoyi.system.mapper.NotificationsMapper">
<resultMap type="Notifications" id="NotificationsResult">
<result property="id" column="id" />
<result property="title" column="title" />
<result property="content" column="content" />
<result property="notificationType" column="notification_type" />
<result property="extraData" column="extra_data" />
<result property="creator" column="creator" />
<result property="createTime" column="create_time" />
<result property="updatedTime" column="updated_time" />
<result property="sendTime" column="send_time" />
</resultMap>
<sql id="selectNotificationsVo">
select id, title, content, notification_type, extra_data, creator, create_time, updated_time, send_time from notifications
</sql>
<select id="selectNotificationsList" parameterType="Notifications" resultMap="NotificationsResult">
<include refid="selectNotificationsVo"/>
<where>
<if test="title != null and title != ''"> and title = #{title}</if>
<if test="content != null and content != ''"> and content = #{content}</if>
<if test="notificationType != null and notificationType != ''"> and notification_type = #{notificationType}</if>
<if test="extraData != null and extraData != ''"> and extra_data = #{extraData}</if>
<if test="creator != null and creator != ''"> and creator = #{creator}</if>
<if test="updatedTime != null "> and updated_time = #{updatedTime}</if>
<if test="sendTime != null "> and send_time = #{sendTime}</if>
</where>
</select>
<select id="selectNotificationsById" parameterType="Long" resultMap="NotificationsResult">
<include refid="selectNotificationsVo"/>
where id = #{id}
</select>
<insert id="insertNotifications" parameterType="Notifications" useGeneratedKeys="true" keyProperty="id">
insert into notifications
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="title != null and title != ''">title,</if>
<if test="content != null and content != ''">content,</if>
<if test="notificationType != null">notification_type,</if>
<if test="extraData != null">extra_data,</if>
<if test="creator != null">creator,</if>
<if test="createTime != null">create_time,</if>
<if test="updatedTime != null">updated_time,</if>
<if test="sendTime != null">send_time,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="title != null and title != ''">#{title},</if>
<if test="content != null and content != ''">#{content},</if>
<if test="notificationType != null">#{notificationType},</if>
<if test="extraData != null">#{extraData},</if>
<if test="creator != null">#{creator},</if>
<if test="createTime != null">#{createTime},</if>
<if test="updatedTime != null">#{updatedTime},</if>
<if test="sendTime != null">#{sendTime},</if>
</trim>
</insert>
<update id="updateNotifications" parameterType="Notifications">
update notifications
<trim prefix="SET" suffixOverrides=",">
<if test="title != null and title != ''">title = #{title},</if>
<if test="content != null and content != ''">content = #{content},</if>
<if test="notificationType != null">notification_type = #{notificationType},</if>
<if test="extraData != null">extra_data = #{extraData},</if>
<if test="creator != null">creator = #{creator},</if>
<if test="createTime != null">create_time = #{createTime},</if>
<if test="updatedTime != null">updated_time = #{updatedTime},</if>
<if test="sendTime != null">send_time = #{sendTime},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteNotificationsById" parameterType="Long">
delete from notifications where id = #{id}
</delete>
<delete id="deleteNotificationsByIds" parameterType="String">
delete from notifications where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>

View File

@@ -0,0 +1,71 @@
import request from '@/utils/request'
// 查询【请填写功能名称】列表
export function listNotifications(query) {
return request({
url: '/back/notifications/list',
method: 'get',
params: query
})
}
// 查询【请填写功能名称】详细
export function getNotifications(id) {
return request({
url: '/back/notifications/' + id,
method: 'get'
})
}
// 新增【请填写功能名称】
export function addNotifications(data) {
return request({
url: '/back/notifications',
method: 'post',
data: data
})
}
// 修改【请填写功能名称】
export function updateNotifications(data) {
return request({
url: '/back/notifications',
method: 'put',
data: data
})
}
// 删除【请填写功能名称】
export function delNotifications(id) {
return request({
url: '/back/notifications/' + id,
method: 'delete'
})
}
// 绑定用户
export function bindUsers(id, data) {
return request({
url: '/back/notifications/bind',
method: 'post',
params: { id: id },
data: data
})
}
// 获取通知已绑定的用户列表
export function getBindUsers(id) {
return request({
url: '/back/notifications/bindUsers/' + id,
method: 'get'
})
}
// 发布通知
export function publishNotification(id) {
return request({
url: '/back/notifications/publish/' + id,
method: 'post'
})
}

View File

@@ -0,0 +1,584 @@
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="通知标题" prop="title">
<el-input
v-model="queryParams.title"
placeholder="请输入通知标题"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="通知类型" prop="notificationType">
<el-select v-model="queryParams.notificationType" placeholder="请选择通知类型" clearable>
<el-option label="系统通知" value="system" />
</el-select>
</el-form-item>
<el-form-item label="计划发送时间" prop="sendTime">
<el-date-picker clearable
v-model="queryParams.sendTime"
type="datetime"
format="yyyy-MM-dd HH:mm:ss"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择计划发送时间">
</el-date-picker>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['system:notifications:add']"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['system:notifications:edit']"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['system:notifications:remove']"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="info"
plain
icon="el-icon-user"
size="mini"
:disabled="single"
@click="handleBindUsers"
>绑定用户</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['system:notifications:export']"
>导出</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<el-table v-loading="loading" :data="notificationsList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="ID" align="center" prop="id" />
<el-table-column label="通知标题" align="center" prop="title" />
<el-table-column label="通知内容" align="center" prop="content" :show-overflow-tooltip="true" />
<el-table-column label="通知类型" align="center" prop="notificationType">
<template slot-scope="scope">
<el-tag type="primary">系统通知</el-tag>
</template>
</el-table-column>
<el-table-column label="计划发送时间" align="center" prop="sendTime" width="180">
<template slot-scope="scope">
<span>{{ scope.row.sendTime }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
v-hasPermi="['system:notifications:edit']"
>修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
v-hasPermi="['system:notifications:remove']"
>删除</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-user"
@click="handleBindUsers(scope.row)"
>绑定用户</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-s-promotion"
@click="handlePublish(scope.row)"
>发布通知</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改通知对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="120px">
<el-form-item label="通知标题" prop="title">
<el-input v-model="form.title" placeholder="请输入通知标题" />
</el-form-item>
<el-form-item label="通知内容" prop="content">
<el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入通知内容"/>
</el-form-item>
<el-form-item label="通知类型" prop="notificationType">
<el-select v-model="form.notificationType" placeholder="请选择通知类型">
<el-option label="系统通知" value="system" />
</el-select>
</el-form-item>
<el-form-item label="计划发送时间" prop="sendTime">
<el-date-picker clearable
v-model="form.sendTime"
type="datetime"
format="yyyy-MM-dd HH:mm:ss"
value-format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择计划发送时间">
</el-date-picker>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm"> </el-button>
<el-button @click="cancel"> </el-button>
</div>
</el-dialog>
<!-- 用户选择对话框 -->
<el-dialog title="选择用户" :visible.sync="userSelectOpen" width="800px" append-to-body>
<el-form :model="userQueryParams" ref="userQueryForm" size="small" :inline="true" label-width="68px">
<el-form-item label="用户昵称" prop="nickname">
<el-input
v-model="userQueryParams.nickname"
placeholder="请输入用户昵称"
clearable
@keyup.enter.native="handleUserQuery"
/>
</el-form-item>
<el-form-item label="手机号码" prop="phone">
<el-input
v-model="userQueryParams.phone"
placeholder="请输入手机号码"
clearable
@keyup.enter.native="handleUserQuery"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-check"
size="mini"
@click="confirmBindUsers"
>确认绑定</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="info"
plain
icon="el-icon-user"
size="mini"
@click="bindAllUsers"
>绑定全部用户</el-button>
</el-col>
</el-row>
<el-table v-loading="userLoading" :data="userList" @selection-change="handleUserSelectionChange" ref="userTable">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="用户ID" align="center" prop="userId" />
<el-table-column label="用户昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
<el-table-column label="手机号码" align="center" prop="phone" />
<el-table-column label="性别" align="center" prop="sex">
<template slot-scope="scope">
<span v-if="scope.row.sex === 1"></span>
<span v-else-if="scope.row.sex === 2"></span>
<span v-else>未知</span>
</template>
</el-table-column>
<el-table-column label="状态" align="center" prop="status">
<template slot-scope="scope">
<el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
<el-tag v-else-if="scope.row.status === 2" type="danger">黑名单</el-tag>
</template>
</el-table-column>
<el-table-column label="VIP" align="center" prop="vip">
<template slot-scope="scope">
<el-tag v-if="scope.row.vip === 1" type="warning">VIP</el-tag>
<span v-else>普通用户</span>
</template>
</el-table-column>
</el-table>
<pagination
v-show="userTotal>0"
:total="userTotal"
:page.sync="userQueryParams.pageNum"
:limit.sync="userQueryParams.pageSize"
@pagination="getUserList"
/>
</el-dialog>
</div>
</template>
<script>
import { listNotifications, getNotifications, delNotifications, addNotifications, updateNotifications, bindUsers, getBindUsers, publishNotification } from "@/api/notify/notifications"
import { listShopUser } from "@/api/member/shopuser"
export default {
name: "Notifications",
data() {
return {
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
// 【请填写功能名称】表格数据
notificationsList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 是否显示用户选择弹出层
userSelectOpen: false,
// 当前选中的通知ID
currentNotificationId: null,
// 用户列表数据
userList: [],
// 用户列表加载状态
userLoading: false,
// 用户列表选中数据
userIds: [],
// 用户查询参数
userQueryParams: {
pageNum: 1,
pageSize: 10,
nickname: null,
phone: null
},
// 用户总条数
userTotal: 0,
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 10,
title: null,
content: null,
notificationType: null,
creator: null,
sendTime: null
},
// 表单参数
form: {},
// 表单校验
rules: {
title: [
{ required: true, message: "通知标题不能为空", trigger: "blur" }
],
content: [
{ required: true, message: "通知内容不能为空", trigger: "blur" }
],
notificationType: [
{ required: true, message: "通知类型不能为空", trigger: "change" }
],
sendTime: [
{ required: true, message: "计划发送时间不能为空", trigger: "blur" }
]
}
}
},
created() {
this.getList()
},
methods: {
/** 查询【请填写功能名称】列表 */
getList() {
this.loading = true
listNotifications(this.queryParams).then(response => {
this.notificationsList = response.rows
this.total = parseInt(response.total) || 0
this.loading = false
})
},
// 取消按钮
cancel() {
this.open = false
this.reset()
},
// 表单重置
reset() {
this.form = {
id: null,
title: null,
content: null,
notificationType: "system",
creator: null,
sendTime: null
}
this.resetForm("form")
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1
this.getList()
},
/** 重置按钮操作 */
resetQuery() {
this.resetForm("queryForm")
this.handleQuery()
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.id)
this.single = selection.length!==1
this.multiple = !selection.length
},
/** 新增按钮操作 */
handleAdd() {
this.reset()
this.open = true
this.title = "添加通知"
},
/** 修改按钮操作 */
handleUpdate(row) {
this.reset()
const id = row.id || this.ids
getNotifications(id).then(response => {
this.form = response.data
this.open = true
this.title = "修改通知"
})
},
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
if (this.form.id != null) {
updateNotifications(this.form).then(response => {
this.$modal.msgSuccess("修改成功")
this.open = false
this.getList()
})
} else {
addNotifications(this.form).then(response => {
this.$modal.msgSuccess("新增成功")
this.open = false
this.getList()
})
}
}
})
},
/** 删除按钮操作 */
handleDelete(row) {
const ids = row.id || this.ids
this.$modal.confirm('是否确认删除通知编号为"' + ids + '"的数据项?').then(function() {
return delNotifications(ids)
}).then(() => {
this.getList()
this.$modal.msgSuccess("删除成功")
}).catch(() => {})
},
/** 导出按钮操作 */
handleExport() {
this.download('system/notifications/export', {
...this.queryParams
}, `notifications_${new Date().getTime()}.xlsx`)
},
/** 绑定用户按钮操作 */
handleBindUsers(row) {
this.reset();
const id = row.id || this.ids;
if (!id) {
this.$message.warning("请选择一条通知记录");
return;
}
this.currentNotificationId = id;
this.userSelectOpen = true;
this.userIds = [];
this.getUserList();
// 注意不需要在这里调用getBindUserList因为在getUserList完成后会自动调用
},
/** 获取已绑定的用户列表 */
getBindUserList(id) {
getBindUsers(id).then(response => {
if (response.data && response.data.length > 0) {
console.log("已绑定用户列表:", response.data);
// 将用户ID转换为字符串类型确保类型一致
const bindUserIds = response.data.map(user => String(user.userId));
this.userIds = bindUserIds;
console.log("转换后的用户ID列表:", bindUserIds);
// 延迟执行,确保表格已经完全渲染
setTimeout(() => {
// 先清除所有选中状态
if (this.$refs.userTable) {
this.$refs.userTable.clearSelection();
// 为已绑定的用户设置选中状态
this.userList.forEach(row => {
// 确保类型一致,都转换为字符串进行比较
const rowUserId = String(row.userId);
console.log("比较用户ID:", rowUserId, "是否在列表中:", bindUserIds.includes(rowUserId));
if (bindUserIds.includes(rowUserId)) {
console.log("选中用户:", row);
this.$refs.userTable.toggleRowSelection(row, true);
}
});
} else {
console.error("userTable引用不存在");
}
}, 200); // 延迟200毫秒执行
} else {
console.log("没有已绑定的用户");
// 清除所有选中状态
if (this.$refs.userTable) {
this.$refs.userTable.clearSelection();
}
}
});
},
/** 获取用户列表 */
getUserList() {
this.userLoading = true;
listShopUser(this.userQueryParams).then(response => {
this.userList = response.rows;
this.userTotal = parseInt(response.total) || 0;
this.userLoading = false;
// 在用户列表加载完成后,设置已选中的用户
if (this.currentNotificationId) {
this.getBindUserList(this.currentNotificationId);
}
});
},
/** 用户搜索按钮操作 */
handleUserQuery() {
this.userQueryParams.pageNum = 1;
this.getUserList();
},
/** 用户重置按钮操作 */
resetUserQuery() {
this.resetForm("userQueryForm");
this.handleUserQuery();
},
/** 用户多选框选中数据 */
handleUserSelectionChange(selection) {
this.userIds = selection.map(item => item.userId);
},
/** 确认绑定用户 */
confirmBindUsers() {
if (this.userIds.length === 0) {
this.$message.warning("请选择要绑定的用户");
return;
}
const userList = [];
this.userIds.forEach(userId => {
userList.push({
userId: userId
});
});
// 调用绑定用户接口
bindUsers(this.currentNotificationId, userList).then(response => {
this.$modal.msgSuccess("绑定用户成功");
this.userSelectOpen = false;
});
},
/** 绑定全部用户 */
bindAllUsers() {
this.$confirm('确认要绑定全部用户吗?', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 获取所有用户并绑定
listShopUser({ pageNum: 1, pageSize: 9999 }).then(response => {
const userList = [];
response.rows.forEach(user => {
userList.push({
userId: user.userId
});
});
if (userList.length === 0) {
this.$message.warning('没有可绑定的用户');
return;
}
// 调用绑定用户接口
bindUsers(this.currentNotificationId, userList).then(response => {
this.$modal.msgSuccess("绑定全部用户成功");
this.userSelectOpen = false;
});
});
}).catch(() => {});
},
/** 发布通知按钮操作 */
handlePublish(row) {
const id = row.id || this.ids;
if (!id) {
this.$message.warning("请选择一条通知记录");
return;
}
this.$confirm('确认要发布该通知吗?发布后将向所有绑定的用户推送消息', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
publishNotification(id).then(response => {
this.$modal.msgSuccess(response.msg || "发布成功");
this.getList();
});
}).catch(() => {});
}
}
}
</script>