优化通知栏,通知实时同步功能

This commit is contained in:
2026-06-27 19:15:06 +08:00
parent d38cbdbf07
commit 53b3b2c989
30 changed files with 1810 additions and 304 deletions
+144
View File
@@ -0,0 +1,144 @@
# CLAUDE.md — system-admin
Backend module: Spring Boot 3.5 admin application (port 8080, context `/system-admin`).
---
## Build & Run
```bash
mvn clean install -DskipTests # full build (tests skipped by default)
mvn clean install -DskipTests=false # build with tests
mvn -pl system-admin -DskipTests=false -Dtest=YourTestClass test # single test
```
Tests use **JUnit 4** (`@RunWith(SpringRunner.class)`), not JUnit 5. Only 2 test files exist (Redis, dynamic datasource). No Maven wrapper (`mvnw`). Maven remote repository: Aliyun mirror.
Launch from IntelliJ:
- `AdminApplication` (`system-admin/`) → port 8080, context `/system-admin`
- `GeneratorApplication` (`renren-generator/`) — commented out of build
## Service layer pattern
Two base classes in `system-common`:
| Base | Purpose |
|---|---|
| `CrudService<Dao, Entity, DTO>` | Generic CRUD: `page()`, `get()`, `save()`, `update()`, `delete()` |
| `BaseService<Dao>` | Lighter base without DTO generic |
Module convention:
```
modules/<name>/
├── controller/ → @RestController, returns Result
├── dao/ → extends BaseMapper<Entity> (MyBatis-Plus)
├── dto/ → request/query DTOs (often extends BaseEntity)
├── entity/ → @TableName JPA entity
├── service/ → interface extends CrudService/BaseService
│ └── impl/ → @Service implementation
├── excel/ → EasyExcel VO classes (optional)
└── vo/ → response VO classes (optional)
```
Mapper XMLs: `src/main/resources/mapper/<domain>/**/*.xml`
### Conventions
- Lombok used throughout: `@Data`, `@AllArgsConstructor`, `@Slf4j` are standard on entity/service classes.
- DTO/Entity/VO separation per module — request DTOs often extend `BaseEntity`.
## PK & Auth
- PK: `ASSIGN_ID` (Snowflake) via `IdUtil.getSnowflakeNextId()`. All entities extend `BaseEntity`. Exception: `WeatherStationEntity` uses `AUTO_INCREMENT`.
- Auth: Apache Shiro 1.12 (**Jakarta classifier**) + OAuth2 token. Login → `token` header.
- **Do not introduce Spring Security** — the project uses Shiro exclusively.
## Key cross-cutting mechanisms
| Mechanism | How |
|---|---|
| **Data permissions** | `@DataFilter` on controller → `DataFilterAspect` → MyBatis interceptor injects dept-based SQL |
| **Auto-fill** | `FieldMetaObjectHandler` fills creator/date via MyBatis-Plus. **Only works with `insert()`/`updateById()`** — batch inserts (e.g. `insertBatchMultiRow`) bypass auto-fill; fields must be set manually. |
| **Scheduled jobs** | Quartz. `schedule_job` table, implements `ITask`, `@Component("beanName")`. Jobs auto-register at startup via `JobCommandLineRunner`. Seed data: `testTask` (paused, every 30 min), `fileScanTask` (paused, every 5 min), `weatherSummarizeCacheTask` (**active**, daily 1 AM). |
| **File scanning** | `WatchService` (primary, background thread) + Quartz fallback (`FileScanTask`) + startup runner (`FileScanStartupRunner`). Files identified by MD5 hash. |
| **Excel import** | EasyExcel + async dual-pass via `WeatherDataImportManager`. Progress tracked in-memory (`ConcurrentHashMap`), lost on restart. |
| **API responses** | Always wrapped in `Result`. Frontend expects `code === 0` for success. |
| **Validation** | Hibernate Validator. XSS filter via `XssFilter`. i18n messages in `system-common/src/main/resources/i18n/validation.properties`. |
## Exception handling
Single `@RestControllerAdvice` handler in the admin module:
| Handler | Catches | Persists errors? |
|---|---|---|
| `CustomExceptionHandler` | `CommonException`, `DuplicateKeyException`, `UnauthorizedException`, generic `Exception` | **Yes** — saves to `SysLogErrorService` (IP, user-agent, URI, params, stack trace) |
Both return a generic error for caught `Exception` (not the exception message). `CommonException` uses i18n message lookup via `MessageUtils.getMessage(code)`. Error codes follow `int` scheme: 5 digits, first 2 = module, last 3 = business (e.g. `10001`-`10029`).
## Logging
- Logback-spring config in `system-admin/src/main/resources/logback-spring.xml`. Logger names use `io.renren` (fork legacy), **not** `com.weather`.
- Admin dev profile enables MyBatis SQL stdout logging (`StdOutImpl`).
- When adding `@Slf4j` to `com.weather.*` classes, add a `com.weather` level override or change the existing `io.renren` logger scope.
## Redis & Docs
- Redis: `project-options.redis.open: true` in dev YAML controls whether `RedisAspect` intercepts Redis calls (default `false` — Redis operations silently skipped when disabled).
- Knife4j: disabled by default (`knife4j.enable: false`). Docs at `/doc.html` when enabled.
- `RedisAspect` wraps `@RedisCache` annotations with channel publish for cache invalidation.
## MyBatis-Plus gotchas
- **Batch inserts bypass auto-fill** — `FieldMetaObjectHandler` only fires on `insert()`/`updateById()`. Custom batch methods must manually set `creator`, `createDate`, `updater`, `updateDate`, `deptId`.
- Column names with special characters (e.g. `rain_20_20`) require explicit `@TableField` annotations — MyBatis-Plus cannot auto-map them from camelCase.
- `typeAliasesPackage: com.weather.modules.*.entity` — all entity classes must reside under a `modules` sub-package.
## Weather domain
Three sub-modules under `system-admin/.../modules/weather/`:
| Module | Purpose |
|---|---|
| `dailydata/` | Daily observations, Excel batch import (async dual-pass), EasyExcel listener, summary export |
| `station/` | Weather station CRUD, linked to dept via `dept_id` |
| `filescan/` | File monitoring + serving. Format: `<地区>地区-<指标>.png` / `<地区>地区631信息.txt` |
### Weather data import flow
1. **First pass**: `AnalysisEventListener` counts total rows.
2. **Second pass**: `WeatherDataListener` processes with batch insert (2000 records/batch).
3. Progress tracked in-memory via `ConcurrentHashMap<String, ImportProgress>` (`volatile` fields + `AtomicInteger`).
4. Runs on `CompletableFuture` with manual `UserContextHolder` propagation for security context. (Note: `UserContextHolder` is in `system-admin/.../security/user/`, not the empty `system-common/.../holder/` package.)
5. On completion, clears Redis summary cache (`weather:summarize:*`).
### Weather summarize cache
`WeatherSummarizeCacheTask` (Quartz job) pre-computes daily historical summaries into Redis. Uses **MySQL-specific** SQL functions (`MONTH()`, `DAY()` on `observe_date`). Cache key: `weather:summarize:{month}:{day}`, non-expiring. Service checks cache first for queries spanning same month/day across years.
### Station priority ordering
`WeatherDailyDataServiceImpl.page()` uses custom `CASE WHEN` SQL to order stations belonging to the user's department + sub-departments first.
## System alert module
CRUD + polling notification system under `modules/sys/`:
| Layer | File |
|---|---|
| Entity | `entity/SysAlertEntity.java``sys_alert` table, Snowflake PK |
| DAO | `dao/SysAlertDao.java` + `mapper/sys/SysAlertDao.xml``selectActiveAlerts`, `selectActiveAlertsSince`, `countBySource` |
| DTO | `dto/SysAlertDTO.java``publishTime`/`createDate`/`updateDate` read-only |
| VO | `vo/SysAlertVO.java``id` as String (mapped from Long) |
| Service | `service/SysAlertService.java` + `impl/``publishIfNotExists` (dedup by source), `withdraw` (soft), CRUD |
| Controller | `controller/SysAlertController.java` — polling: `GET active`, `GET active/since` (no auth); CRUD: `page`/`get`/`save`/`update`/`delete`/`withdraw` (Shiro permissions) |
| Enums | `enums/AlertLevelEnum.java` (info/warning/danger), `enums/AlertSourceTypeEnum.java` (manual/import/schedule/datasource) |
### Data source extension
| File | Role |
|---|---|
| `alert/AlertSource.java` | SPI interface: `getName()`, `check()` returning `AlertMessage` records |
| `alert/AlertSourceCollector.java` | `@Autowired(required=false) List<AlertSource>` auto-discovery, calls `publishIfNotExists` for each |
| `alert/task/AlertSourcePollingTask.java` | Quartz job (`alertSourcePollingTask`), default paused in `schedule_job` |
To add a new alert source: implement `AlertSource`, register as `@Component`, enable the polling task.
@@ -0,0 +1,22 @@
package com.weather.modules.sys.alert;
import com.weather.modules.sys.vo.SysAlertVO;
import org.springframework.context.ApplicationEvent;
/**
* 通知创建事件。由 {@link com.weather.modules.sys.service.impl.SysAlertServiceImpl}
* 在手动发布或数据源推送成功后发布,SSE 服务监听此事件并实时推送给前端。
*/
public class AlertCreatedEvent extends ApplicationEvent {
private final SysAlertVO alert;
public AlertCreatedEvent(SysAlertVO alert) {
super(alert);
this.alert = alert;
}
public SysAlertVO getAlert() {
return alert;
}
}
@@ -0,0 +1,21 @@
package com.weather.modules.sys.alert;
import org.springframework.context.ApplicationEvent;
/**
* 通知删除事件。由 {@link com.weather.modules.sys.service.impl.SysAlertServiceImpl#delete(Long[])}
* 发布,SSE 服务监听此事件并通知前端批量移除通知。
*/
public class AlertDeletedEvent extends ApplicationEvent {
private final Long[] alertIds;
public AlertDeletedEvent(Long[] alertIds) {
super(alertIds);
this.alertIds = alertIds;
}
public Long[] getAlertIds() {
return alertIds;
}
}
@@ -0,0 +1,46 @@
package com.weather.modules.sys.alert;
import java.util.List;
/**
* 通知数据源接口。
* 任何需要自动产生通知的模块,实现此接口并注册为 Spring Bean
* AlertSourceCollector 会定时轮询所有实现并收集通知。
*
* <p>示例:
* <pre>{@code
* @Component
* public class RainWarningSource implements AlertSource {
* public String getName() { return "rain-warning"; }
* public List<AlertMessage> check() {
* // 查询数据,发现异常则返回 AlertMessage 列表
* }
* }
* }</pre>
*/
public interface AlertSource {
/**
* 数据源唯一标识,用于日志和 source_id 去重
*/
String getName();
/**
* 检查该数据源,返回本次发现的通知。
* 返回空列表或 null 表示无新通知。
* 返回的通知会通过 (sourceType=datasource, sourceId=getName():message.sourceId) 去重。
*/
List<AlertMessage> check();
/**
* 数据源产生的单条通知
*/
record AlertMessage(String level, String title, String content, String sourceId) {
public AlertMessage {
if (level == null) level = "info";
if (title == null) title = "";
if (content == null) content = "";
if (sourceId == null) sourceId = "";
}
}
}
@@ -0,0 +1,56 @@
package com.weather.modules.sys.alert;
import com.weather.modules.sys.service.SysAlertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
/**
* 通知数据源收集器。
* 自动发现所有 AlertSource 实现,轮询并发布通知。
*/
@Slf4j
@Component
public class AlertSourceCollector {
@Autowired(required = false)
private List<AlertSource> sources = Collections.emptyList();
/**
* 轮询所有数据源,通过 SysAlertService 发布去重后的通知。
*
* @param alertService 通知服务
* @return 本次新发布的通知总数
*/
public int collectAll(SysAlertService alertService) {
if (sources.isEmpty()) {
return 0;
}
int total = 0;
for (AlertSource source : sources) {
try {
List<AlertSource.AlertMessage> alerts = source.check();
if (alerts == null || alerts.isEmpty()) {
continue;
}
for (AlertSource.AlertMessage a : alerts) {
boolean isNew = alertService.publishIfNotExists(
a.level(), a.title(), a.content(),
"datasource",
source.getName() + ":" + a.sourceId()
);
if (isNew) total++;
}
} catch (Exception e) {
log.error("数据源 [{}] 检查失败", source.getName(), e);
}
}
if (total > 0) {
log.info("从 {} 个数据源收集到 {} 条新通知", sources.size(), total);
}
return total;
}
}
@@ -0,0 +1,21 @@
package com.weather.modules.sys.alert;
import org.springframework.context.ApplicationEvent;
/**
* 通知撤回事件。由 {@link com.weather.modules.sys.service.impl.SysAlertServiceImpl#withdraw(Long)}
* 发布,SSE 服务监听此事件并通知前端移除该通知。
*/
public class AlertWithdrawnEvent extends ApplicationEvent {
private final Long alertId;
public AlertWithdrawnEvent(Long alertId) {
super(alertId);
this.alertId = alertId;
}
public Long getAlertId() {
return alertId;
}
}
@@ -0,0 +1,122 @@
package com.weather.modules.sys.alert;
import com.weather.modules.sys.vo.SysAlertVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;
/**
* SSE 连接管理服务。
* 管理所有活跃的 SSE 连接,监听 {@link AlertCreatedEvent} 并实时推送给前端。
*/
@Slf4j
@Service
public class SseAlertService {
private final Set<SseEmitter> emitters = new CopyOnWriteArraySet<>();
/**
* 创建并注册一个新的 SSE 连接。
* 绑定清理回调:连接完成/超时/异常时自动移除。
*/
public SseEmitter createEmitter() {
SseEmitter emitter = new SseEmitter(0L); // 无超时
emitters.add(emitter);
log.info("SSE 连接已建立,当前连接数: {}", emitters.size());
emitter.onCompletion(() -> {
emitters.remove(emitter);
log.info("SSE 连接已关闭(completion),当前连接数: {}", emitters.size());
});
emitter.onTimeout(() -> {
emitters.remove(emitter);
log.info("SSE 连接已关闭(timeout),当前连接数: {}", emitters.size());
});
emitter.onError(e -> {
emitters.remove(emitter);
log.info("SSE 连接已关闭(error),当前连接数: {}", emitters.size());
});
// 初始连接确认事件
try {
emitter.send(SseEmitter.event().name("connected").data("ok"));
} catch (IOException e) {
emitters.remove(emitter);
}
return emitter;
}
/**
* 监听通知创建事件,广播到所有活跃 SSE 连接。
*/
@EventListener
public void onAlertCreated(AlertCreatedEvent event) {
SysAlertVO alert = event.getAlert();
if (emitters.isEmpty()) {
return;
}
log.info("广播新通知 [{}] 到 {} 个 SSE 连接", alert.getTitle(), emitters.size());
for (SseEmitter emitter : emitters) {
try {
emitter.send(SseEmitter.event().name("alert").data(alert));
} catch (IOException e) {
emitters.remove(emitter);
log.debug("SSE 发送失败,移除连接");
}
}
}
/**
* 监听通知撤回事件,广播到所有活跃 SSE 连接。
*/
@EventListener
public void onAlertWithdrawn(AlertWithdrawnEvent event) {
if (emitters.isEmpty()) return;
Map<String, String> data = Map.of("id", String.valueOf(event.getAlertId()));
log.info("广播撤回通知 [{}] 到 {} 个 SSE 连接", event.getAlertId(), emitters.size());
for (SseEmitter emitter : emitters) {
try {
emitter.send(SseEmitter.event().name("alert-withdrawn").data(data));
} catch (IOException e) {
emitters.remove(emitter);
}
}
}
/**
* 监听通知删除事件,广播到所有活跃 SSE 连接。
*/
@EventListener
public void onAlertDeleted(AlertDeletedEvent event) {
if (emitters.isEmpty()) return;
List<String> ids = Arrays.stream(event.getAlertIds())
.map(String::valueOf)
.collect(Collectors.toList());
Map<String, List<String>> data = Map.of("ids", ids);
log.info("广播删除通知 {} 条到 {} 个 SSE 连接", ids.size(), emitters.size());
for (SseEmitter emitter : emitters) {
try {
emitter.send(SseEmitter.event().name("alert-deleted").data(data));
} catch (IOException e) {
emitters.remove(emitter);
}
}
}
/**
* 当前活跃连接数。
*/
public int getActiveCount() {
return emitters.size();
}
}
@@ -0,0 +1,31 @@
package com.weather.modules.sys.alert.task;
import com.weather.modules.job.task.ITask;
import com.weather.modules.sys.alert.AlertSourceCollector;
import com.weather.modules.sys.service.SysAlertService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 通知数据源定时轮询任务。
* 通过 Quartz schedule_job 表注册:
* beanName = alertSourcePollingTask,建议 cron = 每 10 分钟。
*
* <p>默认暂停(status=0),待数据源实现就绪后启用。
*/
@Slf4j
@Component("alertSourcePollingTask")
@AllArgsConstructor
public class AlertSourcePollingTask implements ITask {
private final AlertSourceCollector collector;
private final SysAlertService sysAlertService;
@Override
public void run(String params) {
log.info("开始轮询通知数据源");
int count = collector.collectAll(sysAlertService);
log.info("通知数据源轮询完成,新增 {} 条", count);
}
}
@@ -0,0 +1,132 @@
package com.weather.modules.sys.controller;
import com.weather.common.annotation.LogOperation;
import com.weather.common.constant.Constant;
import com.weather.common.page.PageData;
import com.weather.common.utils.Result;
import com.weather.common.validator.AssertUtils;
import com.weather.common.validator.ValidatorUtils;
import com.weather.common.validator.group.AddGroup;
import com.weather.common.validator.group.DefaultGroup;
import com.weather.common.validator.group.UpdateGroup;
import com.weather.modules.sys.alert.SseAlertService;
import com.weather.modules.sys.dto.SysAlertDTO;
import com.weather.modules.sys.service.SysAlertService;
import com.weather.modules.sys.vo.SysAlertVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.util.List;
import java.util.Map;
/**
* 系统通知
*/
@RestController
@RequestMapping("sys/alert")
@Tag(name = "系统通知")
@AllArgsConstructor
public class SysAlertController {
private final SysAlertService sysAlertService;
private final SseAlertService sseAlertService;
// ===== 前端轮询接口(无需权限,登录即可访问) =====
@GetMapping("active")
@Operation(summary = "获取所有有效通知")
public Result<List<SysAlertVO>> active() {
List<SysAlertVO> list = sysAlertService.getActiveAlerts();
return new Result<List<SysAlertVO>>().ok(list);
}
@GetMapping("active/since")
@Operation(summary = "增量获取通知")
@Parameter(name = "since", description = "起始ID(返回ID大于此值的通知)", in = ParameterIn.QUERY)
public Result<List<SysAlertVO>> activeSince(@RequestParam(required = false) Long since) {
if (since == null) {
List<SysAlertVO> list = sysAlertService.getActiveAlerts();
return new Result<List<SysAlertVO>>().ok(list);
}
List<SysAlertVO> list = sysAlertService.getActiveAlertsSince(since);
return new Result<List<SysAlertVO>>().ok(list);
}
@GetMapping("stream")
@Operation(summary = "通知SSE实时推送")
public SseEmitter stream() {
return sseAlertService.createEmitter();
}
// ===== 管理后台接口 =====
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "level", description = "级别", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "title", description = "标题", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "sourceType", description = "来源类型", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:alert:page")
public Result<PageData<SysAlertVO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysAlertVO> page = sysAlertService.pageAlerts(params);
return new Result<PageData<SysAlertVO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:alert:info")
public Result<SysAlertVO> get(@PathVariable("id") Long id) {
SysAlertVO data = sysAlertService.get(id);
return new Result<SysAlertVO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("发布通知")
@RequiresPermissions("sys:alert:save")
public Result save(@RequestBody SysAlertDTO dto) {
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysAlertService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改通知")
@RequiresPermissions("sys:alert:update")
public Result update(@RequestBody SysAlertDTO dto) {
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysAlertService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除通知")
@RequiresPermissions("sys:alert:delete")
public Result delete(@RequestBody Long[] ids) {
AssertUtils.isArrayEmpty(ids, "id");
sysAlertService.delete(ids);
return new Result();
}
@PutMapping("{id}/withdraw")
@Operation(summary = "撤回通知")
@LogOperation("撤回通知")
@RequiresPermissions("sys:alert:retract")
public Result withdraw(@PathVariable Long id) {
sysAlertService.withdraw(id);
return new Result();
}
}
@@ -0,0 +1,30 @@
package com.weather.modules.sys.dao;
import com.weather.common.dao.BaseDao;
import com.weather.modules.sys.entity.SysAlertEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 系统通知
*/
@Mapper
public interface SysAlertDao extends BaseDao<SysAlertEntity> {
/**
* 查询有效且未过期的通知
*/
List<SysAlertEntity> selectActiveAlerts();
/**
* 增量查询:ID 大于 sinceId 的有效通知
*/
List<SysAlertEntity> selectActiveAlertsSince(@Param("sinceId") Long sinceId);
/**
* 检查 source_type + source_id 是否已存在
*/
int countBySource(@Param("sourceType") String sourceType, @Param("sourceId") String sourceId);
}
@@ -0,0 +1,61 @@
package com.weather.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.weather.common.validator.group.AddGroup;
import com.weather.common.validator.group.DefaultGroup;
import com.weather.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 系统通知
*/
@Data
@Schema(title = "系统通知")
public class SysAlertDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message = "{id.null}", groups = AddGroup.class)
@NotNull(message = "{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "级别: info|warning|danger")
@NotBlank(message = "通知级别不能为空", groups = DefaultGroup.class)
private String level;
@Schema(title = "通知标题")
@NotBlank(message = "通知标题不能为空", groups = DefaultGroup.class)
private String title;
@Schema(title = "通知正文")
@NotBlank(message = "通知正文不能为空", groups = DefaultGroup.class)
private String content;
@Schema(title = "来源类型")
private String sourceType;
@Schema(title = "业务关联ID")
private String sourceId;
@Schema(title = "过期时间")
private Date expireTime;
@Schema(title = "发布时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date publishTime;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "更新时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date updateDate;
}
@@ -0,0 +1,71 @@
package com.weather.modules.sys.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.weather.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 系统通知
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_alert")
public class SysAlertEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 级别: info | warning | danger
*/
private String level;
/**
* 通知标题
*/
private String title;
/**
* 通知正文
*/
private String content;
/**
* 来源: manual | import | schedule | datasource
*/
private String sourceType;
/**
* 业务关联ID
*/
private String sourceId;
/**
* 1=有效 0=已撤回
*/
private Integer isActive;
/**
* 发布时间
*/
private Date publishTime;
/**
* 过期时间(null=永不过期)
*/
private Date expireTime;
/**
* 更新者
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updater;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate;
public boolean isActive() {
return isActive != null && isActive == 1;
}
public boolean isExpired() {
return expireTime != null && expireTime.before(new Date());
}
}
@@ -0,0 +1,33 @@
package com.weather.modules.sys.enums;
/**
* 通知级别
*/
public enum AlertLevelEnum {
INFO("info", "提示"),
WARNING("warning", "警告"),
DANGER("danger", "紧急");
private final String value;
private final String label;
AlertLevelEnum(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return value;
}
public String getLabel() {
return label;
}
public static boolean isValid(String value) {
for (AlertLevelEnum e : values()) {
if (e.value.equals(value)) return true;
}
return false;
}
}
@@ -0,0 +1,27 @@
package com.weather.modules.sys.enums;
/**
* 通知来源类型
*/
public enum AlertSourceTypeEnum {
MANUAL("manual", "手动发布"),
IMPORT("import", "导入任务"),
SCHEDULE("schedule", "定时任务"),
DATASOURCE("datasource", "数据源监测");
private final String value;
private final String label;
AlertSourceTypeEnum(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return value;
}
public String getLabel() {
return label;
}
}
@@ -0,0 +1,55 @@
package com.weather.modules.sys.service;
import com.weather.common.page.PageData;
import com.weather.common.service.BaseService;
import com.weather.modules.sys.dto.SysAlertDTO;
import com.weather.modules.sys.entity.SysAlertEntity;
import com.weather.modules.sys.vo.SysAlertVO;
import java.util.List;
import java.util.Map;
/**
* 系统通知
*/
public interface SysAlertService extends BaseService<SysAlertEntity> {
// ===== 前端轮询 =====
/**
* 获取所有有效且未过期的通知
*/
List<SysAlertVO> getActiveAlerts();
/**
* 增量获取:只返回 sinceId 之后的通知
*/
List<SysAlertVO> getActiveAlertsSince(Long sinceId);
// ===== 发布与撤回 =====
/**
* 发布通知(去重:同 sourceType + sourceId 不重复发)
*
* @return true=新发布 false=已存在(跳过)
*/
boolean publishIfNotExists(String level, String title, String content,
String sourceType, String sourceId);
/**
* 撤回通知(软删除)
*/
void withdraw(Long id);
// ===== 管理后台 =====
PageData<SysAlertVO> pageAlerts(Map<String, Object> params);
SysAlertVO get(Long id);
void save(SysAlertDTO dto);
void update(SysAlertDTO dto);
void delete(Long[] ids);
}
@@ -0,0 +1,172 @@
package com.weather.modules.sys.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weather.common.constant.Constant;
import com.weather.common.page.PageData;
import com.weather.common.service.impl.BaseServiceImpl;
import com.weather.common.utils.ConvertUtils;
import cn.hutool.core.util.IdUtil;
import com.weather.modules.sys.alert.AlertCreatedEvent;
import com.weather.modules.sys.alert.AlertDeletedEvent;
import com.weather.modules.sys.alert.AlertWithdrawnEvent;
import com.weather.modules.sys.dao.SysAlertDao;
import com.weather.modules.sys.dto.SysAlertDTO;
import com.weather.modules.sys.entity.SysAlertEntity;
import com.weather.modules.sys.enums.AlertLevelEnum;
import com.weather.modules.sys.service.SysAlertService;
import com.weather.modules.sys.vo.SysAlertVO;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 系统通知
*/
@Service
@AllArgsConstructor
public class SysAlertServiceImpl extends BaseServiceImpl<SysAlertDao, SysAlertEntity> implements SysAlertService {
private final ApplicationEventPublisher eventPublisher;
@Override
public List<SysAlertVO> getActiveAlerts() {
List<SysAlertEntity> entities = baseDao.selectActiveAlerts();
return toVOList(entities);
}
@Override
public List<SysAlertVO> getActiveAlertsSince(Long sinceId) {
List<SysAlertEntity> entities = baseDao.selectActiveAlertsSince(sinceId);
return toVOList(entities);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean publishIfNotExists(String level, String title, String content,
String sourceType, String sourceId) {
if (!AlertLevelEnum.isValid(level)) {
level = AlertLevelEnum.INFO.getValue();
}
if (StrUtil.isNotBlank(sourceId)) {
int count = baseDao.countBySource(sourceType, sourceId);
if (count > 0) {
return false;
}
}
SysAlertEntity entity = new SysAlertEntity();
entity.setId(IdUtil.getSnowflakeNextId());
entity.setLevel(level);
entity.setTitle(title);
entity.setContent(content);
entity.setSourceType(sourceType);
entity.setSourceId(sourceId);
entity.setIsActive(1);
entity.setPublishTime(new Date());
entity.setCreateDate(new Date());
insert(entity);
eventPublisher.publishEvent(new AlertCreatedEvent(toVO(entity)));
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void withdraw(Long id) {
SysAlertEntity entity = new SysAlertEntity();
entity.setId(id);
entity.setIsActive(0);
entity.setUpdateDate(new Date());
updateById(entity);
eventPublisher.publishEvent(new AlertWithdrawnEvent(id));
}
@Override
public PageData<SysAlertVO> pageAlerts(Map<String, Object> params) {
IPage<SysAlertEntity> page = baseDao.selectPage(
getPage(params, "publish_time", false),
getWrapper(params)
);
List<SysAlertVO> voList = toVOList(page.getRecords());
PageData<SysAlertVO> pageData = new PageData<>(voList, page.getTotal());
return pageData;
}
private QueryWrapper<SysAlertEntity> getWrapper(Map<String, Object> params) {
String level = (String) params.get("level");
String title = (String) params.get("title");
String sourceType = (String) params.get("sourceType");
QueryWrapper<SysAlertEntity> wrapper = new QueryWrapper<>();
wrapper.eq("is_active", 1);
wrapper.eq(StrUtil.isNotBlank(level), "level", level);
wrapper.like(StrUtil.isNotBlank(title), "title", title);
wrapper.eq(StrUtil.isNotBlank(sourceType), "source_type", sourceType);
return wrapper;
}
@Override
public SysAlertVO get(Long id) {
SysAlertEntity entity = baseDao.selectById(id);
return toVO(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(SysAlertDTO dto) {
SysAlertEntity entity = ConvertUtils.sourceToTarget(dto, SysAlertEntity.class);
entity.setId(IdUtil.getSnowflakeNextId());
entity.setIsActive(1);
entity.setSourceType(StrUtil.blankToDefault(dto.getSourceType(), "manual"));
entity.setPublishTime(new Date());
entity.setCreateDate(new Date());
insert(entity);
eventPublisher.publishEvent(new AlertCreatedEvent(toVO(entity)));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysAlertDTO dto) {
SysAlertEntity entity = ConvertUtils.sourceToTarget(dto, SysAlertEntity.class);
entity.setUpdateDate(new Date());
updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long[] ids) {
deleteBatchIds(Arrays.asList(ids));
eventPublisher.publishEvent(new AlertDeletedEvent(ids));
}
// ===== 工具方法 =====
private SysAlertVO toVO(SysAlertEntity entity) {
if (entity == null) return null;
SysAlertVO vo = new SysAlertVO();
vo.setId(String.valueOf(entity.getId()));
vo.setLevel(entity.getLevel());
vo.setTitle(entity.getTitle());
vo.setContent(entity.getContent());
vo.setSourceType(entity.getSourceType());
vo.setPublishTime(entity.getPublishTime() != null
? DateUtil.formatDateTime(entity.getPublishTime())
: null);
vo.setExpireTime(entity.getExpireTime() != null
? DateUtil.formatDateTime(entity.getExpireTime())
: null);
return vo;
}
private List<SysAlertVO> toVOList(List<SysAlertEntity> entities) {
return entities.stream().map(this::toVO).collect(Collectors.toList());
}
}
@@ -0,0 +1,43 @@
package com.weather.modules.sys.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 系统通知 - 前端响应对象
*/
@Data
public class SysAlertVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 通知ID(对应前端 AlertMessage.id
*/
private String id;
/**
* 级别: info | warning | danger(对应前端 AlertMessage.level
*/
private String level;
/**
* 标题
*/
private String title;
/**
* 正文(对应前端 AlertMessage.content
*/
private String content;
/**
* 来源类型
*/
private String sourceType;
/**
* 发布时间(对应前端 AlertMessage.publishTime
*/
private String publishTime;
/**
* 过期时间
*/
private String expireTime;
}
@@ -0,0 +1,30 @@
<?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.weather.modules.sys.dao.SysAlertDao">
<sql id="activeCondition">
is_active = 1
AND (expire_time IS NULL OR expire_time > NOW())
</sql>
<select id="selectActiveAlerts" resultType="com.weather.modules.sys.entity.SysAlertEntity">
SELECT * FROM sys_alert
WHERE <include refid="activeCondition"/>
ORDER BY publish_time DESC
</select>
<select id="selectActiveAlertsSince" resultType="com.weather.modules.sys.entity.SysAlertEntity">
SELECT * FROM sys_alert
WHERE <include refid="activeCondition"/>
AND id > #{sinceId}
ORDER BY publish_time DESC
</select>
<select id="countBySource" resultType="int">
SELECT COUNT(1) FROM sys_alert
WHERE source_type = #{sourceType}
AND source_id = #{sourceId}
AND <include refid="activeCondition"/>
</select>
</mapper>
+20
View File
@@ -0,0 +1,20 @@
# CLAUDE.md — system-common
Shared Java library used by all backend modules.
---
## Service layer pattern
Two base classes defined here:
| Base | Purpose |
|---|---|
| `CrudService<Dao, Entity, DTO>` | Generic CRUD: `page()`, `get()`, `save()`, `update()`, `delete()` |
| `BaseService<Dao>` | Lighter base without DTO generic |
These are used by all service implementations in `system-admin` and other modules. See `system-admin/CLAUDE.md` for the full module convention.
## i18n validation messages
Located at `src/main/resources/i18n/validation.properties`. Hibernate Validator messages used by `@RestControllerAdvice` exception handler in `system-admin`. Error codes follow `int` scheme: 5 digits, first 2 = module, last 3 = business (e.g. `10001`-`10029`).
+70 -7
View File
@@ -4,6 +4,14 @@ Frontend module: Vue 3 / Vite 5 / TypeScript SPA.
---
## Code Style
- **No emoji in UI strings.** Plain Chinese text for labels, buttons, status.
- **No emoji in code comments or docstrings.** Plain text only.
- **Keep CLAUDE.md current** — whenever code is modified, added, deleted, or any file change affects the module structure, build, conventions, or component patterns, update this file (and the root `CLAUDE.md` if cross-cutting) in the same commit to reflect the new state. Stale documentation is a bug.
---
## Commands
```bash
@@ -55,7 +63,9 @@ Pre-commit: `lint-staged` runs `eslint --fix` on `*.ts`/`*.vue` via `yorkie` git
- `src/store/importTasks.ts`: separate store for import task tracking (computed getters: `activeTasks`, `hasActiveTasks`, `recentTasks`).
- `src/utils/router.ts`: converts backend menu records → Vue router records, supports iframe/external links with `openStyle` flags.
Layout is event-driven: `src/layout/` shell + `mitt` event bus (`src/utils/emits.ts`). The `EMitt` enum defines 13 events for sidebar, theme, tabs, layout changes. **Trace both the Pinia store and mitt events** when changing navigation/sidebar/tabs/theme.
Layout is event-driven: `src/layout/` shell + `mitt` event bus (`src/utils/emits.ts`). The `EMitt` enum defines events for sidebar, theme, tabs, layout changes. **Trace both the Pinia store and mitt events** when changing navigation/sidebar/tabs/theme.
Header right side: notification bell (combined badge) → `expand` (user menu). The old `import-task-indicator.vue` has been removed in favor of the notification center drawer.
## Common page pattern: `useView` hook
@@ -104,8 +114,8 @@ All helper functions must accept `number | null` and return `"—"` or `""` for
### 2. Heavy libraries must use dynamic imports
`html2canvas`, `jspdf`, and `echarts` are NOT imported at module level. Load them via `await import()` only when triggered by user action. This saves ~600KB from the initial bundle.
### 3. Google Fonts go in index.html, not scoped styles
Never use `@import url("https://fonts.googleapis.com/...")` inside Vue scoped styles. Use `<link rel="preconnect">` + `<link rel="stylesheet">` in `index.html`.
### 3. Fonts are self-hosted — no external network dependency
Fonts (Noto Sans SC, JetBrains Mono) are bundled via `@fontsource/*` packages, imported in `src/main.ts`. Do NOT add Google Fonts `<link>` tags or `@import` back — the system runs on intranet where external network may be unavailable. To add a new font weight, import the corresponding fontsource CSS file in `main.ts`.
### 4. Export must show user feedback
Always show `ElLoading.service` fullscreen and `ElMessage` success/failure. Disable the export button during rendering.
@@ -113,9 +123,62 @@ Always show `ElLoading.service` fullscreen and `ElMessage` success/failure. Disa
### 5. Deep watchers on filter objects are banned
Never use `watch(filters, callback, { deep: true })`. Derive a precise computed trigger key (e.g. `dataHash`, `filteredHash`, `extremesVersion`) and watch that instead.
## Import progress polling pattern
## Notification center
The global notification system (`src/components/alert-marquee/index.vue`) aggregates two feed types:
| Feed | Source | Clickable? |
|---|---|---|
| System alerts | `useAlertMarquee.ts` composable (polls `/sys/alert/active/since` every 30s) | Yes — opens detail dialog |
| Import tasks | `useImportTaskStore` Pinia store | No — shows real-time progress inline |
### Components & composables
| File | Role |
|---|---|
| `src/composables/useAlertMarquee.ts` | Module-level singleton: message queue, drawer toggle, detail dialog state, scrollbar position. Real-time delivery: SSE (`/sys/alert/stream`) primary + 10s polling fallback. Exports danger-specific computed: `dangerMessages`, `latestDangerMessage`, `dangerCount`, `hasDangerMessages` |
| `src/composables/useFloatingDrag.ts` | Pointer Events drag logic: `setPointerCapture`, viewport clamping, deferred `isDragging` (activates only on >3px move), `dragMoved` flag to distinguish drag vs click |
| `src/components/alert-marquee/index.vue` | Floating scrollbar (640px wide, centered top, draggable) + `el-drawer` notification center + `el-dialog` detail popup |
| `src/layout/header/base-header.vue` | Bell button with combined badge (alerts + active import tasks), toggles drawer |
| `src/store/importTasks.ts` | Import task CRUD: `addTask`, `updateTask`, `removeTask`, `clearCompleted`; getters: `activeTasks`, `recentTasks` |
### Level-based routing
- **danger (紧急)**: triggers the floating scrollbar + appears in notification center drawer + bell badge
- **warning / info (警告 / 提示)**: notification center drawer + bell badge only (no scrollbar)
- The bell badge in base-header always shows total count (all levels + active import tasks)
### Floating scrollbar behavior
- Visible only when logged in (`appStore.state.appIsLogin`) and has danger-level alerts (`hasDangerMessages`)
- Positioned centered at top (`y: 56` below header), draggable to reposition, re-centers on window resize
- Shows latest alert headline + count badge
- **Close button** hides the bar; **auto-reappears** when new danger alerts arrive (watch on `dangerCount`)
- **查看详情** button opens `el-dialog` with full alert text
- The old `import-task-indicator.vue` (bell icon with popover in header) has been **removed**
### Import progress integration
1. Upload via `baseService.upload()` (FormData, no explicit Content-Type).
2. On success, poll `GET .../import/progress/{backendTaskId}` every 3 seconds.
3. Update Pinia store (`useImportTaskStore`) with percentage/state.
4. Emit `refreshDataList` on completion. Header indicator (`import-task-indicator.vue`) shows active tasks with spinning badge + popover.
2. On upload start, toast: `"导入已开始,可在通知中心查看进度"`.
3. Poll `GET .../import/progress/{backendTaskId}` every 3 seconds.
4. Update Pinia store (`useImportTaskStore`) — progress bar + status tag render reactively in the drawer.
5. On completion: green checkmark; on failure: red cross + error message. Completed/failed tasks show a dismiss button.
### Alert management page
Manual alert CRUD at route `sys/system-alert`:
| File | Role |
|---|---|
| `src/views/sys/system-alert.vue` | List page: `useView`-based, search by level/title/sourceType, batch delete, per-row withdraw |
| `src/views/sys/system-alert-add-or-update.vue` | Add/edit dialog: level (info/warning/danger), title, content (textarea), sourceType, expireTime (datetime picker) |
Backend endpoints under `/sys/alert`:
- `GET /page` — paginated list (`sys:alert:page`)
- `GET /{id}` — detail (`sys:alert:info`)
- `POST /` — create (`sys:alert:save`)
- `PUT /` — update (`sys:alert:update`)
- `DELETE /` — batch delete (`sys:alert:delete`)
- `PUT /{id}/withdraw` — soft-withdraw (`sys:alert:update`)
- `GET /active`, `GET /active/since` — frontend polling (no permission required)
-7
View File
@@ -5,13 +5,6 @@
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>气象数据 - 管理系统</title>
<!-- Preload fonts to avoid blocking render (moved from home.vue @import) -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;600;700;900&family=JetBrains+Mono:wght@400;600&display=swap"
rel="stylesheet"
/>
<script>
//全局钩子
window.SITE_CONFIG = {
+155 -141
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -21,6 +21,8 @@
},
"dependencies": {
"@element-plus/icons-vue": "2.3.1",
"@fontsource/jetbrains-mono": "^5.2.8",
"@fontsource/noto-sans-sc": "^5.2.9",
"@vueuse/core": "9.1.1",
"@wangeditor/editor": "5.1.1",
"@wangeditor/editor-for-vue": "^5.1.12",
@@ -11,6 +11,7 @@ import {
} from "@element-plus/icons-vue";
import { useAlertMarquee, type AlertMessage } from "@/composables/useAlertMarquee";
import { useImportTaskStore, type ImportTask } from "@/store/importTasks";
import { useAppStore } from "@/store";
import { useFloatingDrag } from "@/composables/useFloatingDrag";
const {
@@ -19,6 +20,9 @@ const {
latestMessage,
messageCount,
hasMessages,
latestDangerMessage,
dangerCount,
hasDangerMessages,
drawerVisible,
detailTarget,
detailVisible,
@@ -48,19 +52,27 @@ function dismissScrollbar(): void {
}
function onViewDetail(): void {
if (latestMessage.value) {
showDetail(latestMessage.value);
if (latestDangerMessage.value) {
showDetail(latestDangerMessage.value);
}
}
// 监听消息数量变化:有新通知时重新显示滚动条
watch(messageCount, (now, prev) => {
// 监听紧急通知数量变化:有新紧急通知时重新显示滚动条
watch(dangerCount, (now, prev) => {
if (now > prev) {
scrollbarDismissed.value = false;
}
});
const showScrollbar = computed(() => hasMessages.value && !scrollbarDismissed.value);
// 紧急通知全部清空/过期后,重置 scrollbar 状态,确保不会残留
watch(hasDangerMessages, (val) => {
if (!val) {
scrollbarDismissed.value = true;
}
});
const appStore = useAppStore();
const showScrollbar = computed(() => appStore.state.appIsLogin && hasDangerMessages.value && !scrollbarDismissed.value);
// ---- 拖拽时跳过按钮点击 ----
@@ -211,10 +223,10 @@ function handleClearAll(): void {
<div class="alert-scrollbar__text-wrap">
<span
class="alert-scrollbar__text"
:class="{ 'is-scroll': latestMessage && latestMessage.content.length > 60 }"
>{{ latestMessage?.content ?? "" }}</span>
:class="{ 'is-scroll': latestDangerMessage && latestDangerMessage.content.length > 60 }"
>{{ latestDangerMessage?.content ?? "" }}</span>
</div>
<span class="alert-scrollbar__badge">{{ messageCount }}</span>
<span class="alert-scrollbar__badge">{{ dangerCount }}</span>
<button class="alert-scrollbar__btn-detail" @click.stop="onViewDetail">查看详情</button>
<button class="alert-scrollbar__btn-close" @click.stop="dismissScrollbar">关闭</button>
</div>
@@ -414,7 +426,7 @@ function handleClearAll(): void {
}
.alert-scrollbar__text.is-scroll {
animation: scrollbar-marquee 12s linear infinite;
animation: scrollbar-marquee 20s linear infinite;
}
@keyframes scrollbar-marquee {
+168 -114
View File
@@ -1,15 +1,19 @@
// composables/useAlertMarquee.ts
// 紧急通知状态管理 — 模块级单例
// 管理:消息队列 / 通知中心抽屉 / 详情弹窗 / 悬浮滚动条位置
// 后续接入后端时,只需修改 mockAlerts() 为真实 API 调用
// 通知状态管理 — 模块级单例
// 消息队列 / 通知中心抽屉 / 详情弹窗 / 悬浮滚动条位置
// 获取:SSE 主通道 + 10s 轮询降级 + 每60s全量对账
import { ref, computed } from "vue";
import baseService from "@/service/baseService";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
export type AlertLevel = "info" | "warning" | "danger";
export interface AlertMessage {
id: string;
level: AlertLevel;
title: string;
content: string;
publishTime: string;
}
@@ -66,6 +70,24 @@ const messageCount = computed(() => messages.value.length);
/** 是否有通知 */
const hasMessages = computed(() => messages.value.length > 0);
/** 仅紧急 (danger) 级别的通知 */
const dangerMessages = computed(() =>
messages.value.filter((m) => m.level === "danger")
);
/** 最新一条紧急通知(悬浮滚动条展示用) */
const latestDangerMessage = computed(() => {
return dangerMessages.value.length > 0
? dangerMessages.value[dangerMessages.value.length - 1]
: null;
});
/** 紧急通知数量 */
const dangerCount = computed(() => dangerMessages.value.length);
/** 是否有紧急通知 */
const hasDangerMessages = computed(() => dangerMessages.value.length > 0);
/** 详情弹窗是否可见 */
const detailVisible = computed({
get: () => detailTarget.value !== null,
@@ -77,90 +99,50 @@ const detailVisible = computed({
/** 按时间倒序排列的消息(最新在前,给通知中心和详情列表用) */
const messagesReversed = computed(() => [...messages.value].reverse());
// ---------- Mock 数据 ----------
// ---------- 后端 API ----------
let mockIdCounter = 0;
/**
* 生成模拟气象预警通知
* 后续接入后端时,替换为 baseService.get('/sys/alert/active')
*/
async function mockAlerts(): Promise<AlertMessage[]> {
mockIdCounter++;
const now = new Date();
const ts = now.toLocaleTimeString("zh-CN", { hour12: false });
const templates: Omit<AlertMessage, "id" | "publishTime">[] = [
{
level: "danger",
content: `【暴雨红色预警】省气象台${now.getHours()}时发布:预计未来6小时内将有特大暴雨,降雨量可达200毫米以上,请做好防汛准备。`
},
{
level: "warning",
content: `【台风蓝色预警】第${mockIdCounter}号台风"海燕"正在向东南沿海靠近,中心风力12级,请沿海地区密切关注。`
},
{
level: "info",
content: `【高温橙色预警】预计未来三天最高气温将达38℃以上,请做好防暑降温工作,避免高温时段户外作业。`
},
{
level: "danger",
content: `【山洪灾害红色预警】受持续降雨影响,东部山区发生山洪灾害风险极高,请立即转移安置危险区域群众。`
},
{
level: "warning",
content: `【大风黄色预警】受冷空气影响,预计今夜至明天将有8-10级大风,伴有沙尘天气,请注意防风防沙。`
},
{
level: "info",
content: `【系统维护通知】计划于${now.getMonth() + 1}${now.getDate() + 2}日凌晨2:00-4:00进行数据系统例行维护,届时查询功能可能短暂中断。`
},
{
level: "warning",
content: `【寒潮蓝色预警】北方强冷空气南下,预计48小时内气温将下降12-14℃,最低气温可达-10℃,请注意防寒保暖。`
},
{
level: "info",
content: `【雷电黄色预警】预计今天下午将出现雷电活动,并伴有短时强降水和短时大风,请注意防范。`
}
];
// 随机选取 1-3 条
const count = 1 + Math.floor(Math.random() * 3);
const shuffled = [...templates].sort(() => Math.random() - 0.5).slice(0, count);
return shuffled.map((t, i) => ({
...t,
id: `alert_${now.getTime()}_${mockIdCounter}_${i}`,
publishTime: ts
}));
async function fetchNotifications(): Promise<AlertMessage[]> {
const lastId = messages.value.length > 0
? messages.value[messages.value.length - 1].id
: getLastSeenId() || "0";
const res = await baseService.get(`/sys/alert/active/since?since=${lastId}`);
if (res.code === 0 && Array.isArray(res.data)) {
return res.data.map((item: AlertMessage) => ({
...item,
content: item.title ? `${item.title}${item.content}` : item.content
}));
}
return [];
}
// ---------- 轮询控制 ----------
/** 全量对账:从服务端拉取所有活跃通知ID,清除本地已撤回/已删除的通知 */
async function reconcileAlerts(): Promise<void> {
try {
const res = await baseService.get("/sys/alert/active");
if (res.code === 0 && Array.isArray(res.data)) {
const serverIds = new Set((res.data as AlertMessage[]).map((a) => a.id));
const before = messages.value.length;
messages.value = messages.value.filter((m) => serverIds.has(m.id));
if (messages.value.length < before && messages.value.length > 0) {
const maxId = messages.value.reduce((max, m) => (m.id > max ? m.id : max), messages.value[0].id);
setLastSeenId(maxId);
}
}
} catch {
// 静默失败
}
}
// ---------- SSE 实时推送 + 轮询降级 ----------
let eventSource: EventSource | null = null;
let pollingTimer: ReturnType<typeof setInterval> | null = null;
let started = false;
// ---------- API ----------
/**
* 拉取通知。当前使用 mock 数据,后续改为:
* const res = await baseService.get('/sys/alert/active')
* return res.data ?? []
*/
async function fetchNotifications(): Promise<AlertMessage[]> {
// TODO: 替换为真实 API 调用
// import baseService from "@/service/baseService";
// const res = await baseService.get("/sys/alert/active");
// return res.code === 0 ? (res.data as AlertMessage[]) : [];
return mockAlerts();
}
/** 检测并处理新通知 */
function checkNewAlerts(newMsgs: AlertMessage[]): void {
/** 合并新通知到队列 */
function mergeNewAlerts(newMsgs: AlertMessage[]): void {
if (newMsgs.length === 0) return;
// 合并去重
const existingIds = new Set(messages.value.map((m) => m.id));
for (const msg of newMsgs) {
if (!existingIds.has(msg.id)) {
@@ -168,13 +150,112 @@ function checkNewAlerts(newMsgs: AlertMessage[]): void {
}
}
// FIFO 截断
if (messages.value.length > MAX_QUEUE) {
messages.value = messages.value.slice(messages.value.length - MAX_QUEUE);
}
}
// 有新通知 → 只更新队列,不主动展开侧栏
// 用户通过顶栏铃铛手动打开通知中心
/** 建立 SSE 实时推送连接 */
function initSse(): void {
let token: string;
try {
token = getToken();
if (!token) return;
} catch {
return;
}
const baseUrl = app.api || "";
const url = `${baseUrl}/sys/alert/stream?token=${encodeURIComponent(token)}`;
eventSource = new EventSource(url);
eventSource.addEventListener("alert", (e: MessageEvent) => {
try {
const alert = JSON.parse(e.data) as AlertMessage;
mergeNewAlerts([alert]);
} catch {
// JSON 解析失败,忽略
}
});
eventSource.addEventListener("alert-withdrawn", (e: MessageEvent) => {
try {
const { id } = JSON.parse(e.data) as { id: string };
removeAlert(id);
} catch {
// 忽略
}
});
eventSource.addEventListener("alert-deleted", (e: MessageEvent) => {
try {
const { ids } = JSON.parse(e.data) as { ids: string[] };
for (const id of ids) {
removeAlert(id);
}
} catch {
// 忽略
}
});
eventSource.onerror = () => {
// SSE 连接失败,关闭并降级为轮询
closeSse();
startPollingFallback();
};
}
/** 关闭 SSE 连接 */
function closeSse(): void {
if (eventSource) {
eventSource.close();
eventSource = null;
}
}
/** 降级轮询(SSE 失败时自动启动,每 10 秒增量拉取 + 每 60 秒全量对账) */
function startPollingFallback(): void {
if (pollingTimer !== null) return;
let tick = 0;
pollingTimer = setInterval(async () => {
try {
const data = await fetchNotifications();
mergeNewAlerts(data);
tick++;
if (tick % 6 === 0) {
await reconcileAlerts();
}
} catch {
// 静默失败
}
}, 10000);
}
/** 启动通知获取:先 REST API 拉存量,再建立 SSE 连接 */
async function startPolling(_intervalMs?: number): Promise<void> {
if (started) return;
started = true;
// 先通过 REST API 拉取存量通知
try {
const data = await fetchNotifications();
mergeNewAlerts(data);
} catch {
// 静默失败
}
// 尝试建立 SSE 连接(失败则降级为轮询)
initSse();
}
function stopPolling(): void {
closeSse();
if (pollingTimer !== null) {
clearInterval(pollingTimer);
pollingTimer = null;
}
started = false;
}
// ---------- 通知中心抽屉 ----------
@@ -245,38 +326,6 @@ function setPosition(pos: { x: number; y: number }): void {
position.value = pos;
}
// ---------- 轮询 ----------
async function startPolling(intervalMs = 30000): Promise<void> {
if (started) return;
started = true;
// 立即拉取一次
try {
const data = await fetchNotifications();
checkNewAlerts(data);
} catch {
// 静默失败
}
pollingTimer = setInterval(async () => {
try {
const data = await fetchNotifications();
checkNewAlerts(data);
} catch {
// 静默失败
}
}, intervalMs);
}
function stopPolling(): void {
if (pollingTimer !== null) {
clearInterval(pollingTimer);
pollingTimer = null;
}
started = false;
}
// ---------- composable 导出 ----------
export function useAlertMarquee() {
@@ -287,6 +336,11 @@ export function useAlertMarquee() {
latestMessage,
messageCount,
hasMessages,
// 紧急通知(悬浮滚动条用)
dangerMessages,
latestDangerMessage,
dangerCount,
hasDangerMessages,
// 通知中心
drawerVisible,
toggleDrawer,
@@ -306,7 +360,7 @@ export function useAlertMarquee() {
clearAll,
// 轮询
fetchNotifications,
checkNewAlerts,
mergeNewAlerts,
startPolling,
stopPolling
};
@@ -145,9 +145,7 @@ export function useWeatherFilter(opts: UseWeatherFilterOptions) {
return (
FILTER_KEYS.some((k) => f[k]?.op) ||
f.rainLevel.length > 0 ||
f.decades.length > 0 ||
f.yearRange[0] !== resolveStart() ||
f.yearRange[1] !== resolveEnd()
f.decades.length > 0
);
});
@@ -156,7 +154,6 @@ export function useWeatherFilter(opts: UseWeatherFilterOptions) {
let c = FILTER_KEYS.filter((k) => f[k]?.op).length;
if (f.rainLevel.length) c++;
if (f.decades.length) c++;
if (f.yearRange[0] !== resolveStart() || f.yearRange[1] !== resolveEnd()) c++;
return c;
});
@@ -168,7 +165,6 @@ export function useWeatherFilter(opts: UseWeatherFilterOptions) {
if (!matchOp(row.tmax, f.tmaxF)) return false;
if (!matchOp(row.tmin, f.tminF)) return false;
if (!matchOp(row.tavg, f.tavgF)) return false;
if (row.year < f.yearRange[0] || row.year > f.yearRange[1]) return false;
if (f.decades.length > 0 && !f.decades.includes(Math.floor(row.year / 10) * 10)) return false;
if (f.rainLevel.length > 0 && !f.rainLevel.includes(row._rainLevel ?? "")) return false;
return true;
+10
View File
@@ -1,3 +1,13 @@
// Self-hosted fonts (no external network dependency, compatible with intranet deployment)
import "@fontsource/noto-sans-sc/300.css";
import "@fontsource/noto-sans-sc/400.css";
import "@fontsource/noto-sans-sc/500.css";
import "@fontsource/noto-sans-sc/600.css";
import "@fontsource/noto-sans-sc/700.css";
import "@fontsource/noto-sans-sc/900.css";
import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/600.css";
import "@/assets/icons/iconfont/iconfont.js";
import RenDeptTree from "@/components/sys-dept-tree";
import RenRadioGroup from "@/components/sys-radio-group";
+2 -21
View File
@@ -233,27 +233,9 @@
</div>
</div>
<div class="filter-group">
<div class="fg-title"><span class="fg-dot year-dot"></span> 份条件</div>
<div class="fg-title"><span class="fg-dot year-dot"></span> 代筛选</div>
<div class="fg-row">
<span class="fg-label">份范围</span>
<el-input-number
v-model="filters.yearRange[0]"
:min="MIN_YEAR"
:max="currentYear"
size="small"
style="width: 10ch"
/>
<span class="fg-sep">~</span>
<el-input-number
v-model="filters.yearRange[1]"
:min="MIN_YEAR"
:max="currentYear"
size="small"
style="width: 10ch"
/>
</div>
<div class="fg-row">
<span class="fg-label">年代筛选</span>
<span class="fg-label"></span>
<div class="level-chips">
<span
v-for="d in availableDecades"
@@ -709,7 +691,6 @@ function rowMatchesFilter(row: WeatherDataRow, f: typeof filters.value): boolean
if (f.tavgF.op === "lte" && n > f.tavgF.val) return false;
if (f.tavgF.op === "range" && (n < (f.tavgF.min ?? -Infinity) || n > (f.tavgF.max ?? Infinity))) return false;
}
if (row.year < f.yearRange[0] || row.year > f.yearRange[1]) return false;
if (f.decades.length > 0 && !f.decades.includes(Math.floor(row.year / 10) * 10)) return false;
if (f.rainLevel.length > 0 && !f.rainLevel.includes(rainLevelLabel(row.rainfall))) return false;
return true;
@@ -0,0 +1,116 @@
<template>
<el-dialog v-model="visible" :title="!dataForm.id ? '新增通知' : '修改通知'" :close-on-click-modal="false" :close-on-press-escape="false">
<el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="100px">
<el-form-item prop="level" label="级别">
<el-select v-model="dataForm.level" placeholder="级别">
<el-option label="提示" value="info"></el-option>
<el-option label="警告" value="warning"></el-option>
<el-option label="紧急" value="danger"></el-option>
</el-select>
</el-form-item>
<el-form-item prop="title" label="标题">
<el-input v-model="dataForm.title" placeholder="标题"></el-input>
</el-form-item>
<el-form-item prop="content" label="内容">
<el-input v-model="dataForm.content" type="textarea" :rows="5" placeholder="通知正文"></el-input>
</el-form-item>
<el-form-item prop="sourceType" label="来源类型">
<el-select v-model="dataForm.sourceType" placeholder="来源类型">
<el-option label="手动发布" value="manual"></el-option>
<el-option label="导入任务" value="import"></el-option>
<el-option label="定时任务" value="schedule"></el-option>
<el-option label="数据源监测" value="datasource"></el-option>
</el-select>
</el-form-item>
<el-form-item prop="expireTime" label="过期时间">
<el-date-picker
v-model="dataForm.expireTime"
type="datetime"
placeholder="过期时间(选填)"
value-format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
></el-date-picker>
</el-form-item>
<el-form-item v-if="dataForm.id" label="发布时间">
<span>{{ dataForm.publishTime }}</span>
</el-form-item>
</el-form>
<template v-slot:footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
</template>
</el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const defaultForm = () => ({
id: "",
level: "info",
title: "",
content: "",
sourceType: "manual",
expireTime: "",
publishTime: ""
});
const dataForm = reactive(defaultForm());
const rules = ref({
level: [{ required: true, message: "必填项不能为空", trigger: "change" }],
title: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
content: [{ required: true, message: "必填项不能为空", trigger: "blur" }]
});
const init = (id?: string) => {
visible.value = true;
Object.assign(dataForm, defaultForm());
if (dataFormRef.value) {
dataFormRef.value.resetFields();
}
if (id) {
getInfo(id);
}
};
const getInfo = (id: string) => {
baseService.get(`/sys/alert/${id}`).then((res) => {
Object.assign(dataForm, res.data);
});
};
const dataFormSubmitHandle = () => {
dataFormRef.value.validate((valid: boolean) => {
if (!valid) {
return false;
}
(!dataForm.id ? baseService.post : baseService.put)("/sys/alert", {
...dataForm,
id: dataForm.id || undefined,
expireTime: dataForm.expireTime || undefined,
publishTime: undefined
}).then(() => {
ElMessage.success({
message: "成功",
duration: 500,
onClose: () => {
visible.value = false;
emit("refreshDataList");
}
});
});
});
};
defineExpose({ init });
</script>
@@ -0,0 +1,128 @@
<template>
<div class="mod-sys__alert">
<el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
<el-form-item>
<el-select v-model="state.dataForm.level" placeholder="级别" clearable>
<el-option label="提示" value="info"></el-option>
<el-option label="警告" value="warning"></el-option>
<el-option label="紧急" value="danger"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-input v-model="state.dataForm.title" placeholder="标题" clearable></el-input>
</el-form-item>
<el-form-item>
<el-select v-model="state.dataForm.sourceType" placeholder="来源类型" clearable>
<el-option label="手动发布" value="manual"></el-option>
<el-option label="导入任务" value="import"></el-option>
<el-option label="定时任务" value="schedule"></el-option>
<el-option label="数据源监测" value="datasource"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button @click="state.getDataList()">查询</el-button>
</el-form-item>
<el-form-item>
<el-button v-if="state.hasPermission('sys:alert:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
</el-form-item>
<el-form-item>
<el-button v-if="state.hasPermission('sys:alert:delete')" type="danger" @click="state.deleteHandle()">删除</el-button>
</el-form-item>
</el-form>
<el-table
v-loading="state.dataListLoading"
:data="state.dataList"
border
@selection-change="state.dataListSelectionChangeHandle"
@sort-change="state.dataListSortChangeHandle"
style="width: 100%"
>
<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
<el-table-column prop="id" label="ID" header-align="center" align="center" width="180" show-overflow-tooltip></el-table-column>
<el-table-column prop="level" label="级别" sortable="custom" header-align="center" align="center" width="80">
<template v-slot="scope">
<el-tag v-if="scope.row.level === 'danger'" size="small" type="danger">紧急</el-tag>
<el-tag v-else-if="scope.row.level === 'warning'" size="small" type="warning">警告</el-tag>
<el-tag v-else size="small" type="info">提示</el-tag>
</template>
</el-table-column>
<el-table-column prop="title" label="标题" header-align="center" align="center" width="200" show-overflow-tooltip></el-table-column>
<el-table-column prop="content" label="内容" header-align="center" show-overflow-tooltip></el-table-column>
<el-table-column prop="sourceType" label="来源类型" header-align="center" align="center" width="110">
<template v-slot="scope">
<span v-if="scope.row.sourceType === 'manual'">手动发布</span>
<span v-else-if="scope.row.sourceType === 'import'">导入任务</span>
<span v-else-if="scope.row.sourceType === 'schedule'">定时任务</span>
<span v-else-if="scope.row.sourceType === 'datasource'">数据源监测</span>
<span v-else>{{ scope.row.sourceType }}</span>
</template>
</el-table-column>
<el-table-column prop="publishTime" label="发布时间" sortable="custom" header-align="center" align="center" width="170"></el-table-column>
<el-table-column prop="expireTime" label="过期时间" sortable="custom" header-align="center" align="center" width="170">
<template v-slot="scope">
<span v-if="scope.row.expireTime">{{ scope.row.expireTime }}</span>
<span v-else style="color: #999">--</span>
</template>
</el-table-column>
<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
<template v-slot="scope">
<el-button v-if="state.hasPermission('sys:alert:update')" type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
<el-button v-if="state.hasPermission('sys:alert:delete')" type="danger" link @click="state.deleteHandle(scope.row.id)">删除</el-button>
<el-button v-if="state.hasPermission('sys:alert:update')" type="warning" link @click="withdrawHandle(scope.row.id)">撤回</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
:current-page="state.page"
:page-sizes="[10, 20, 50, 100]"
:page-size="state.limit"
:total="state.total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="state.pageSizeChangeHandle"
@current-change="state.pageCurrentChangeHandle"
>
</el-pagination>
<!-- 弹窗, 新增 / 修改 -->
<add-or-update ref="addOrUpdateRef" @refreshDataList="state.getDataList"></add-or-update>
</div>
</template>
<script lang="ts" setup>
import useView from "@/hooks/useView";
import { reactive, ref, toRefs } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import AddOrUpdate from "./system-alert-add-or-update.vue";
const view = reactive({
getDataListURL: "/sys/alert/page",
getDataListIsPage: true,
deleteURL: "/sys/alert",
deleteIsBatch: true,
dataForm: {
level: "",
title: "",
sourceType: ""
}
});
const state = reactive({ ...useView(view), ...toRefs(view) });
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: string) => {
addOrUpdateRef.value.init(id);
};
const withdrawHandle = (id: string) => {
ElMessageBox.confirm("确定要撤回该通知吗?撤回后前端将不再展示。", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
baseService.put(`/sys/alert/${id}/withdraw`).then(() => {
ElMessage.success("撤回成功");
state.getDataList();
});
});
};
</script>