Compare commits

...

4 Commits

Author SHA1 Message Date
huangzd1997 cac901df34 refactor(phase-3): Publish 那枚私有 writeJson 并进底座,七支序列化出口收成一枚
Phase 3 收口清单里最后一项可选项。PublishTaskService 的私有
writeJson(Object, String) 与底座 AbstractFileTaskPipeline
writeJson(ObjectMapper, Object, String) 逐字同形(宽捕获 Exception、
抛 BusinessException(文案) 且不带 cause),四个调用点改成显式传 mapper,
本地同名件退场。文案四条一字未动,包括那句现网会说谎的「序列化上架任务失败」
系列与一条英文文案——文案是对外语义,改它=改线协议,不归本笔。

判据一格没花:用户授权的 RETHROW_FLOOR 380→379 实测不需要动。用该尺自述的
复现办法(上限压 0、下限抬 99999 各单跑本类一次)量到并档后整树
rethrow=383/total=1000,两格都在界内——380 这一格至今原样,未改基线、
未逐处记名。前例同 3D 第三笔:腾出的额度让「须授权」这项动作变成不必要。

底座 javadoc 两处指针同步更新(原来都写着 Publish「未并档」),并把
「归并 task 那三份会跌破下限」那句的前提数如实更正为 383/1000——
下一支若只归并其中一部分,先复现再判,别照抄旧结论。

门禁读数:mvn -o test-compile rc=0;定向 354 例/0 红/0 错/2 skipped
(Publish 全面+两支 golden+装配切片+CatchSilence/SourceScan/
SqlLayering/TaskStatusVocabulary/ArchitectureBoundary/TaskLifecycleDebt/
ResultFileJobHandler 家族/TaskResultFileJobWorker 家族;2 skip 是
SHUFU_SNAPSHOT_WRITE 未设时的写档器);publish 建单 35 段+回传 27 段
golden 在非写模式逐字节复现(git status -- src/test/resources 一字未动);
PublishTaskService 2132→2124(在册基线 2250,只许降这格满足)。
2026-10-22 10:53:45 +08:00
huangzd1997 e4471e08c3 refactor(oss): 摘两支零调用件+并档八格前缀守卫,可读性棘轮 973→958
红因:961→973 那 12 行来自 950f379d 的 download-endpoint 修复(真实增量,
不回退它)。本轮按 ops BACKLOG 口径把这一格真降回基线以下,不动
docs/readability-baseline.json、不 --write。

两条降法都刻意避开 catch 面,免得撞上 CatchSilence 的 RETHROW 下限:
1) 摘五棵树零调用件 uploadTaskScopePayload/uploadTaskParsedPayload
   (自 54ee3f304/7e1974a68 引入,正本通道早已是
   TransientPayloadStorageService.store("task-scope"|"task-parsed", …),
   测试也直接吃 uploadText+拼好的 key,两处方法名在 main/test/前端/ops
   全树零命中,无反射点名、无 XML/YML 绑定)。
2) 软件版本族四格与教程族守卫那八处逐字同形的 objectKey 前缀检查并成
   requirePrefixedObjectKey(objectKey, prefix, what)。异常类型与消息文本
   逐字不变(what + " objectKey must start with " + prefix 拼出的就是原来
   那两句),requireTutorialKey 保留为具名守卫转调公共件。

门禁读数:mvn -o test-compile rc=0;定向 120 例/0 红/0 错/0 skip
(OssStorageService/InternalAudio/DownloadUrlNonExpiring/SoftwareVersion
四支业务测试+CatchSilence/SourceScan/SqlLayering/TaskStatusVocabulary/
ArchitectureBoundary/TaskLifecycleDebt 六把守门尺,后两格证明本笔没动
catch 账与状态字面量账);ops 面 test_readability_ratchet 9 passed。
2026-10-22 10:39:36 +08:00
huangzd1997 d268ecdf6b feat(通知): task_failed 带 ref_json 定位锚点,明细可点直达任务详情
用户原话「都没体现哪个任务id/店铺/用户,咋排查」:通知表只有 title/content,
失败任务又按「用户×模块×自然日」聚合成一条,明细被 5 个 taskNo 预览 + 512 字截断吃掉。

- V162 给 biz_user_notification 加 ref_json(TEXT,可重跑迁移,存量不回填)
- 扫描器把桶内每个失败任务写成锚点(taskId/taskNo/moduleType/reason/updatedAt/
  deviceId),上限 20 条;品牌任务无 task_no 用 #<id> 兜底,保证至少一条可定位
- 详情接口回传 refs;同键刷新时锚点变化也更新,且不重新点亮已读
- 后台铃铛「展开明细」渲染成可点行,跳任务中心 ?taskNo= 自动开详情抽屉
- 新增判据 taskFailedAdminNotificationCarriesUidAndTaskNoAnchor:管理端正文必须含
  uid、每个桶的 ref_json 至少一条非空 taskNo
2026-10-22 10:28:12 +08:00
huangzd1997 78be0f02e2 chore(更新日志): 补 4.0.43–4.0.59 共 17 条,取数锚点改为 version.txt
chore(release): 版本号 x.y.z 的前缀停在 4.0.42,文件头写的划窗口径随之失效,
4.0.43 起再没补过条目(用户端始终停在 4.0.42)。改用 version.txt 每次变更提交
划窗口,按各窗口的 feat/fix 逐版补成用户能看懂的一句话;纯工程/尺子类不硬凑。
2026-10-22 10:28:07 +08:00
19 changed files with 529 additions and 83 deletions
@@ -13,6 +13,17 @@ export const ADMIN_NOTIFICATION_SEVERITY_LABELS: Readonly<Record<AdminNotificati
low: '低危',
}
/** 通知里的结构化定位锚点(当前只有 task_failed 使用:桶内每个失败任务一项)。 */
export interface AdminNotificationRef {
taskId: number | null
/** 任务号;品牌任务为 #<id>。任务详情接口按它查。 */
taskNo: string
moduleType?: string | null
reason?: string | null
updatedAt?: string | null
deviceId?: string | null
}
/** 单条通知(后台铃铛)。 */
export interface AdminNotificationItem {
id: number
@@ -22,6 +33,8 @@ export interface AdminNotificationItem {
severity?: string
title: string
content: string
/** 可点的定位锚点;旧后端/历史行没有这一列时为空。 */
refs?: AdminNotificationRef[] | null
read: boolean
readAt: string | null
createdAt: string | null
@@ -140,6 +140,18 @@
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
</div>
<div class="bell-item-content">{{ item.content }}</div>
<div v-if="item.refs && item.refs.length" class="bell-ref-list">
<button
v-for="ref in item.refs"
:key="`${item.id}-${ref.taskNo}`"
type="button"
class="bell-ref-link"
:title="ref.reason || `查看任务 ${ref.taskNo}`"
@click.stop="openTaskRef(item, ref)"
>
{{ ref.taskNo }}<span v-if="ref.reason" class="bell-ref-reason">:{{ ref.reason }}</span>
</button>
</div>
</li>
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-more">
另有 {{ detailTotal - details.length }} 条未列出,可缩小日期范围后查看
@@ -175,14 +187,17 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAdminSessionStore } from '@/stores/admin-session'
import type { AdminNotificationItem, AdminNotificationRef } from '@/api/notifications'
import {
NOTIFICATION_POLL_INTERVAL_MS,
formatDayLabel,
formatGroupCounts,
formatNotificationTime,
notificationGroupKey,
taskCenterRouteForRef,
} from '@/layout/notification-bell-model'
import { todayDateInput } from '@/utils/datetime'
import {
@@ -194,6 +209,7 @@ import {
} from '@/layout/notification-bell-panel'
const session = useAdminSessionStore()
const router = useRouter()
/**
* 面板的数据流(聚合组、明细、两个计数、防抖与取数)整块在 notification-bell-panel.ts。
@@ -231,6 +247,16 @@ const {
unreadCount,
} = useNotificationBellPanel({ uid: () => session.user?.id ?? 0, today: () => todayDateInput() })
/** 点锚点:先按原逻辑标已读,再跳任务中心(路由带 taskNo,页面进来自动开详情抽屉)。 */
function openTaskRef(item: AdminNotificationItem, ref: AdminNotificationRef): void {
const target = taskCenterRouteForRef(ref)
if (!target) {
return
}
void onItemClick(item)
void router.push(target)
}
const rootRef = ref<HTMLElement | null>(null)
const panelRef = ref<HTMLElement | null>(null)
const panelStyle = ref<Record<string, string>>({})
@@ -592,6 +618,12 @@ onUnmounted(() => {
word-break: break-all;
}
/* 定位锚点:任务号可点,直达任务详情。压低视觉权重,不与正文抢注意力。 */
.bell-ref-list { display: flex; flex-direction: column; gap: 2px; margin-top: 6px; }
.bell-ref-link { padding: 0; border: none; background: none; color: var(--admin-primary, #2f5d8b); font-family: inherit; font-size: 12px; line-height: 1.5; text-align: left; word-break: break-all; cursor: pointer; }
.bell-ref-link:hover { text-decoration: underline; }
.bell-ref-reason { color: #8a94a6; }
.bell-search {
display: flex;
flex-direction: column;
@@ -201,3 +201,22 @@ export function createSummaryFailureAlerter(feedback: BellFeedbackSink): {
},
}
}
/** 通知锚点的最小形状(与 AdminNotificationRef 对齐);不 import api 类型,保持本模块可被 node --test 直接跑。 */
export interface NotificationTaskRef {
taskNo?: string | null
}
/**
* 任务锚点 → 任务中心深链。taskNo 是任务详情接口的唯一入参,空值不给链接
* (宁可只显示文本,也不跳到一个必然查不到的任务上)。
*/
export function taskCenterRouteForRef(
ref: NotificationTaskRef | null | undefined,
): { path: string; query: { taskNo: string } } | null {
const taskNo = String(ref?.taskNo ?? '').trim()
if (!taskNo) {
return null
}
return { path: '/task-center/board', query: { taskNo } }
}
@@ -4,6 +4,7 @@
* 页签二「变体采集」= 麦象批量任务(variant-collection),数据口径与列不同故独立页签。
* 30s 轮询:页面隐藏暂停、回前台立即刷新、卸载清理;另有手动刷新。 */
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { userNotice } from '@/api/user-notice'
import { ElMessage } from 'element-plus'
import OldPagination from '@/components/OldPagination.vue'
@@ -51,6 +52,7 @@ const POLL_INTERVAL_MS = 30_000
/** 公司 tab 的唯一取值出口:非超管恒 null(store 里 companyIdForRequest 已经把它算成 null),
* 所以这里不需要再判一次角色——第二把尺子就是第二个口径。 */
const companyTab = useCompanyTabStore()
const route = useRoute()
type BoardTab = 'tasks' | 'variant'
const activeTab = ref<BoardTab>('tasks')
@@ -251,12 +253,12 @@ function changeVariantSize(size: number) {
// ---------------------------------------------------------------- 详情
async function openDetail(row: TaskCenterTaskRow) {
async function openDetailByTaskNo(taskNo: string, companyId: number | null = companyTab.requestCompanyId) {
detailVisible.value = true
detailLoading.value = true
detail.value = null
try {
detail.value = await fetchTaskCenterTaskDetail(row.taskNo, companyTab.requestCompanyId)
detail.value = await fetchTaskCenterTaskDetail(taskNo, companyId)
if (!detail.value) ElMessage.warning('任务不存在或无权查看')
} catch (error) {
showAdminFeedback(errorText(error, '任务详情加载失败'), 'error')
@@ -266,6 +268,10 @@ async function openDetail(row: TaskCenterTaskRow) {
}
}
async function openDetail(row: TaskCenterTaskRow) {
await openDetailByTaskNo(row.taskNo)
}
function accountOf(row: TaskCenterTaskRow): string {
return row.username || (row.userId != null ? `UID ${row.userId}` : '—')
}
@@ -291,6 +297,11 @@ function onVisibilityChange() {
onMounted(() => {
void refreshAll()
void loadInactiveTabTotal()
// 通知明细里的 taskNo 深链:进页直接开抽屉;不锁当前公司 tab(通知可能来自另一家,后端仍按数据权限收口)。
const linkedTaskNo = typeof route.query.taskNo === 'string' ? route.query.taskNo.trim() : ''
if (linkedTaskNo) {
void openDetailByTaskNo(linkedTaskNo, null)
}
document.addEventListener('visibilitychange', onVisibilityChange)
pollTimer = setInterval(() => {
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return
@@ -2,7 +2,7 @@
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
"totals": {
"files": 244,
"cases": 1727,
"cases": 1728,
"pins": 448,
"reads": 639
},
@@ -303,7 +303,7 @@
"reads": 2
},
"notification-bell.test.ts": {
"cases": 7,
"cases": 8,
"pins": 0,
"reads": 0
},
@@ -9,6 +9,7 @@ import {
hasNewNotification,
readLastNotifiedId,
writeLastNotifiedId,
taskCenterRouteForRef,
} from '../src/layout/notification-bell-model.ts'
function createStorage() {
@@ -110,3 +111,18 @@ test('test_组行计数文案:读完不再挂 0 未读', () => {
assert.equal(formatGroupCounts(12, 0), '12 条')
assert.equal(formatGroupCounts(1, null), '1 条')
})
test('test_任务锚点深链:按 taskNo 跳任务中心,空锚点不给链接', () => {
assert.deepEqual(taskCenterRouteForRef({ taskNo: 'DELETE_BRAND-101' }), {
path: '/task-center/board',
query: { taskNo: 'DELETE_BRAND-101' },
})
assert.deepEqual(taskCenterRouteForRef({ taskNo: ' #201 ' }), {
path: '/task-center/board',
query: { taskNo: '#201' },
})
assert.equal(taskCenterRouteForRef({ taskNo: '' }), null)
assert.equal(taskCenterRouteForRef({ taskNo: ' ' }), null)
assert.equal(taskCenterRouteForRef(null), null)
assert.equal(taskCenterRouteForRef(undefined), null)
})
@@ -196,9 +196,7 @@ public class OssStorageService {
* 服务端自己的读写走 internal-endpoint 那张 client,两者不能合用一张。
*/
public String presignSoftwareVersionUpload(String objectKey, int expirySeconds) {
if (objectKey == null || !objectKey.startsWith(SOFTWARE_VERSION_PREFIX)) {
throw new IllegalArgumentException("software version objectKey must start with " + SOFTWARE_VERSION_PREFIX);
}
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
try {
return presignClient().getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(Method.PUT)
@@ -213,9 +211,7 @@ public class OssStorageService {
/** 返回软件版本对象的字节数;对象不存在返回 -1(直传完成后由服务端核对大小是否超限)。 */
public long softwareVersionObjectSize(String objectKey) {
if (objectKey == null || !objectKey.startsWith(SOFTWARE_VERSION_PREFIX)) {
throw new IllegalArgumentException("software version objectKey must start with " + SOFTWARE_VERSION_PREFIX);
}
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
try {
var stat = buildClient().statObject(StatObjectArgs.builder()
.bucket(publicClientBucket())
@@ -234,9 +230,7 @@ public class OssStorageService {
/** 生成软件版本对象的公开下载 URL(与历史 file_url 同构:path-style client 桶)。 */
public String getSoftwareVersionDownloadUrl(String objectKey) {
if (objectKey == null || !objectKey.startsWith(SOFTWARE_VERSION_PREFIX)) {
throw new IllegalArgumentException("software version objectKey must start with " + SOFTWARE_VERSION_PREFIX);
}
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
return softwareVersionPublicUrl(objectKey);
}
@@ -254,9 +248,7 @@ public class OssStorageService {
/** 删除软件版本对象(client 桶);确认环节发现超限等异常时清理残留,避免公共桶悬挂大对象。 */
public void removeSoftwareVersionObject(String objectKey) {
if (objectKey == null || !objectKey.startsWith(SOFTWARE_VERSION_PREFIX)) {
throw new IllegalArgumentException("software version objectKey must start with " + SOFTWARE_VERSION_PREFIX);
}
requirePrefixedObjectKey(objectKey, SOFTWARE_VERSION_PREFIX, "software version");
try {
buildClient().removeObject(RemoveObjectArgs.builder()
.bucket(publicClientBucket())
@@ -324,8 +316,13 @@ public class OssStorageService {
}
private void requireTutorialKey(String objectKey) {
if (objectKey == null || !objectKey.startsWith(TUTORIAL_PREFIX)) {
throw new IllegalArgumentException("tutorial objectKey must start with " + TUTORIAL_PREFIX);
requirePrefixedObjectKey(objectKey, TUTORIAL_PREFIX, "tutorial");
}
/** objectKey 前缀守卫:软件版本族与教程族八格同款,只是前缀与文案里的名字不同。 */
private void requirePrefixedObjectKey(String objectKey, String prefix, String what) {
if (objectKey == null || !objectKey.startsWith(prefix)) {
throw new IllegalArgumentException(what + " objectKey must start with " + prefix);
}
}
@@ -484,18 +481,6 @@ public class OssStorageService {
}
}
public String uploadTaskScopePayload(String moduleType, Long taskId, String scopeHash, String content) {
String normalizedScopeHash = scopeHash == null || scopeHash.isBlank() ? UUID.randomUUID().toString() : scopeHash;
String objectKey = String.format("task-scope/%s/%s/%s.json", normalizeModuleType(moduleType), taskId, normalizedScopeHash);
return uploadText(objectKey, content);
}
public String uploadTaskParsedPayload(String moduleType, Long taskId, String scopeHash, String content) {
String normalizedScopeHash = scopeHash == null || scopeHash.isBlank() ? UUID.randomUUID().toString() : scopeHash;
String objectKey = String.format("task-parsed/%s/%s/%s.json", normalizeModuleType(moduleType), taskId, normalizedScopeHash);
return uploadText(objectKey, content);
}
public String readObjectAsString(String value) {
StorageLocation location = resolveStorageLocation(value);
if (location == null) {
@@ -23,6 +23,8 @@ public class UserNotificationEntity {
private String severity;
private String title;
private String content;
/** 结构化定位锚点 JSON(V162);null=该通知没有可点对象(存量行、服务级告警)。 */
private String refJson;
private String dedupeKey;
private LocalDateTime readAt;
private LocalDateTime createdAt;
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.notification.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/** 单条通知(桌面端与后台共用结构)。 */
@Data
@@ -19,6 +20,8 @@ public class NotificationItemVo {
private String severity;
private String title;
private String content;
/** 可点击的定位锚点(task_failed=桶内失败任务);null/空=该条没有可点对象。 */
private List<NotificationRefVo> refs;
/** 是否已读(前端展示用,等价于 readAt 非空) */
private Boolean read;
private LocalDateTime readAt;
@@ -0,0 +1,29 @@
package com.nanri.aiimage.modules.notification.model.vo;
import lombok.Data;
/**
* 通知的结构化定位锚点(ref_json 里的一项)。
*
* <p>当前只有 task_failed 使用:桶内每个失败任务一项。它是「点一下能跳到任务详情」
* 的唯一依据,正文里的自然语言只负责让人看懂,不承担定位职责。
*
* <p>字段全部按 JSON 原样回给前端;不认识的字段由反序列化层忽略——后续加锚点类型时
* 不至于让老 jar 读不出来。
*/
@Data
public class NotificationRefVo {
/** 失败任务主键(biz_file_task.id / brand_crawl_tasks.id)。 */
private Long taskId;
/** 任务号(品牌任务无 task_no 列,用 #&lt;id&gt; 兜底),任务详情接口按它查。 */
private String taskNo;
/** 模块类型原码(DELETE_BRAND / PRICE_TRACK / BRAND …)。 */
private String moduleType;
/** 该任务的失败原因(已压缩空白,最长 120 字)。 */
private String reason;
/** 任务进入失败终态的时间(yyyy-MM-dd HH:mm:ss)。 */
private String updatedAt;
/** 执行任务的客户端设备 id(历史任务为空)。 */
private String deviceId;
}
@@ -57,6 +57,15 @@ public class NotificationDispatchService {
*/
public int pushToAdmins(AdminAudience audience, String scene, String level, String title, String content,
String dedupeKeyBase, Long subjectUserId) {
return pushToAdmins(audience, scene, level, title, content, dedupeKeyBase, subjectUserId, null);
}
/**
* 同 {@link #pushToAdmins(AdminAudience, String, String, String, String, String, Long)},
* 额外带一份结构化定位锚点(任务失败桶的明细),供后台「展开明细」渲染成可点行。
*/
public int pushToAdmins(AdminAudience audience, String scene, String level, String title, String content,
String dedupeKeyBase, Long subjectUserId, String refJson) {
int pushed = 0;
int filtered = 0;
for (AdminUserEntity admin : audience.admins()) {
@@ -66,7 +75,7 @@ public class NotificationDispatchService {
}
String key = dedupeKeyBase + ":" + admin.getId();
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
scene, level, title, content, key, subjectUserId)) {
scene, level, title, content, key, subjectUserId, refJson)) {
pushed++;
}
}
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.notification.service;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.config.NotificationProperties;
@@ -51,8 +52,11 @@ public class NotificationScanScheduler {
private static final String BRAND_MODULE_TYPE = "BRAND";
private static final int MAX_TASK_NO_PREVIEW = 5;
/** 锚点条数上限:正文只放 5 个任务号,结构化锚点要能覆盖同桶多数失败,但不能让积压把行撑爆。 */
private static final int MAX_TASK_REF = 20;
private static final int REASON_MAX_LENGTH = 120;
private static final int PROBE_READ_TIMEOUT_MILLIS = 8_000;
private static final DateTimeFormatter REF_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 18960 的探针路径。根路径没有路由,恒 404 ⇒ 这一格只能读成「未验证」,
@@ -117,7 +121,8 @@ public class NotificationScanScheduler {
List<FailedTask> failed = new ArrayList<>();
List<FileTaskEntity> fileTasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.select(FileTaskEntity::getId, FileTaskEntity::getTaskNo, FileTaskEntity::getModuleType,
FileTaskEntity::getUserId, FileTaskEntity::getErrorMessage, FileTaskEntity::getUpdatedAt)
FileTaskEntity::getUserId, FileTaskEntity::getErrorMessage, FileTaskEntity::getUpdatedAt,
FileTaskEntity::getDeviceId)
.eq(FileTaskEntity::getStatus, STATUS_FAILED)
.gt(FileTaskEntity::getUpdatedAt, cutoff)
.orderByDesc(FileTaskEntity::getId)
@@ -127,7 +132,8 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), displayTaskNo(task.getTaskNo(), task.getId()),
task.getModuleType(), task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
task.getModuleType(), task.getUserId(), task.getErrorMessage(), task.getUpdatedAt(),
task.getDeviceId()));
}
List<BrandCrawlTaskEntity> brandTasks = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper<BrandCrawlTaskEntity>()
.select(BrandCrawlTaskEntity::getId, BrandCrawlTaskEntity::getUserId,
@@ -141,7 +147,7 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), "#" + task.getId(),
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage(), task.getUpdatedAt(), null));
}
if (failed.isEmpty()) {
log.info("[notification-scan] 近 {} 分钟无失败任务", properties.getTaskFailedWindowMinutes());
@@ -170,9 +176,10 @@ public class NotificationScanScheduler {
+ (preview.isEmpty() ? "" : "(" + preview + ")")
+ (reason.isEmpty() ? "" : ";最近失败原因:" + reason)
+ ",详情请查看对应工具页的「历史任务」。";
String refJson = refJsonOf(tasks);
if (notificationService.pushOrRefresh(key.userId(), NotificationService.AUDIENCE_USER,
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
label + "任务失败", userContent, dedupeKeyOf(key))) {
label + "任务失败", userContent, dedupeKeyOf(key), null, refJson)) {
userPushed++;
}
@@ -185,7 +192,7 @@ public class NotificationScanScheduler {
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
"用户任务失败:" + username, adminContent,
"task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.day(),
key.userId());
key.userId(), refJson);
}
log.info("[notification-scan] 任务失败扫描完成 窗口={}分钟 失败任务={} 聚合桶={} 用户通知={} 管理员通知={}",
properties.getTaskFailedWindowMinutes(), failed.size(), buckets.size(), userPushed, adminPushed);
@@ -390,14 +397,45 @@ public class NotificationScanScheduler {
private String latestReason(List<FailedTask> tasks) {
for (FailedTask task : tasks) {
if (task.errorMessage() != null && !task.errorMessage().isBlank()) {
String reason = task.errorMessage().trim().replaceAll("\\s+", " ");
return reason.length() <= REASON_MAX_LENGTH ? reason : reason.substring(0, REASON_MAX_LENGTH) + "…";
String reason = shortReason(task.errorMessage());
if (reason != null) {
return reason;
}
}
return "";
}
/**
* 桶内失败任务的结构化锚点(ref_json):每个任务一项,最多 {@link #MAX_TASK_REF} 条。
* 正文里的 taskNo 预览只有 5 个且会被 512 字截断,锚点是「点一下到任务详情」的唯一依据,
* 所以 taskNo 必须非空——fileTask 由 displayTaskNo 兜底,品牌任务用 #&lt;id&gt;。
*/
String refJsonOf(List<FailedTask> tasks) {
List<Map<String, Object>> refs = new ArrayList<>(Math.min(tasks.size(), MAX_TASK_REF));
for (FailedTask task : tasks) {
if (refs.size() >= MAX_TASK_REF) {
break;
}
Map<String, Object> ref = new LinkedHashMap<>();
ref.put("taskId", task.id());
ref.put("taskNo", task.taskNo());
ref.put("moduleType", task.moduleType());
ref.put("reason", shortReason(task.errorMessage()));
ref.put("updatedAt", task.updatedAt() == null ? null : task.updatedAt().format(REF_TIME_FORMAT));
ref.put("deviceId", task.deviceId());
refs.add(ref);
}
return JSONUtil.toJsonStr(refs);
}
private String shortReason(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
String reason = raw.trim().replaceAll("\\s+", " ");
return reason.length() <= REASON_MAX_LENGTH ? reason : reason.substring(0, REASON_MAX_LENGTH) + "…";
}
private String displayTaskNo(String taskNo, Long id) {
return taskNo == null || taskNo.isBlank() ? "#" + id : taskNo;
}
@@ -446,7 +484,7 @@ public class NotificationScanScheduler {
/** 统一视图的失败任务(两类表归一);updatedAt 即失败终态时间,决定落入哪一天的桶。 */
record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage,
LocalDateTime updatedAt) {
LocalDateTime updatedAt, String deviceId) {
}
/** 探测三态:ALIVE=业务可用;UNVERIFIED=服务回了话但证不了业务可用;DOWN=故障。 */
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.notification.service;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
@@ -10,6 +11,7 @@ import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationItemVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationRefVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -86,6 +88,8 @@ public class NotificationService {
private static final int TITLE_MAX_LENGTH = 128;
private static final int CONTENT_MAX_LENGTH = 512;
private static final int DEDUPE_KEY_MAX_LENGTH = 160;
/** ref_json 的安全上限:TEXT 能装 64KB,但一条通知的锚点超过这个量级说明聚合失控,整条丢弃。 */
private static final int REF_JSON_MAX_LENGTH = 4000;
/** 严重度排序表达式:与 {@link #severityRank} 同一口径,数据库侧分页必须同序。 */
private static final String SEVERITY_ORDER_SQL =
@@ -111,6 +115,18 @@ public class NotificationService {
*/
public boolean push(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId) {
return push(userId, audience, scene, level, title, content, dedupeKey, subjectUserId, null);
}
/**
* 推送一条通知(带结构化定位锚点)。
*
* @param refJson 可点的定位对象(JSON 数组字符串,见 {@link NotificationRefVo});null=没有。
* 超长时整条丢弃而不是截断:截断后的 JSON 前端解析不出来,比没有更糟。
*/
public boolean push(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId,
String refJson) {
if (userId == null || userId <= 0) {
log.warn("[notification] 推送被跳过:接收者无效 userId={} scene={}", userId, scene);
return false;
@@ -133,6 +149,7 @@ public class NotificationService {
row.setSeverity(severityOf(normalizedScene, normalizedLevel));
row.setTitle(truncate(title, TITLE_MAX_LENGTH));
row.setContent(truncate(content == null ? "" : content, CONTENT_MAX_LENGTH));
row.setRefJson(normalizeRefJson(refJson));
row.setDedupeKey(truncate(key, DEDUPE_KEY_MAX_LENGTH));
row.setCreatedAt(LocalDateTime.now());
try {
@@ -162,17 +179,25 @@ public class NotificationService {
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId) {
return pushOrRefresh(userId, audience, scene, level, title, content, dedupeKey, subjectUserId, null);
}
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId,
String refJson) {
String key = normalize(dedupeKey);
if (key.isEmpty()) {
return push(userId, audience, scene, level, title, content, key, subjectUserId);
return push(userId, audience, scene, level, title, content, key, subjectUserId, refJson);
}
UserNotificationEntity existing = selectByDedupeKey(key);
if (existing == null) {
return push(userId, audience, scene, level, title, content, key, subjectUserId);
return push(userId, audience, scene, level, title, content, key, subjectUserId, refJson);
}
String nextTitle = truncate(title, TITLE_MAX_LENGTH);
String nextContent = truncate(content == null ? "" : content, CONTENT_MAX_LENGTH);
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())) {
String nextRefJson = normalizeRefJson(refJson);
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())
&& java.util.Objects.equals(nextRefJson, existing.getRefJson())) {
return false;
}
String normalizedScene = normalize(scene).isEmpty() ? SCENE_SYSTEM : normalize(scene);
@@ -181,6 +206,7 @@ public class NotificationService {
.eq(UserNotificationEntity::getId, existing.getId())
.set(UserNotificationEntity::getTitle, nextTitle)
.set(UserNotificationEntity::getContent, nextContent)
.set(UserNotificationEntity::getRefJson, nextRefJson)
.set(UserNotificationEntity::getLevel, normalizedLevel)
.set(UserNotificationEntity::getSeverity, severityOf(normalizedScene, normalizedLevel)));
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
@@ -623,6 +649,7 @@ public class NotificationService {
vo.setSeverity(normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel()));
vo.setTitle(row.getTitle());
vo.setContent(row.getContent());
vo.setRefs(parseRefs(row.getRefJson()));
vo.setRead(row.getReadAt() != null);
vo.setReadAt(row.getReadAt());
vo.setCreatedAt(row.getCreatedAt());
@@ -637,4 +664,26 @@ public class NotificationService {
String normalized = value == null ? "" : value.trim();
return normalized.length() <= maxLength ? normalized : normalized.substring(0, maxLength);
}
/** 锚点落库前的唯一口径:空串归一成 NULL,超长整条丢弃(截断会产出不可解析的 JSON)。 */
private static String normalizeRefJson(String refJson) {
String value = normalize(refJson);
if (value.isEmpty()) {
return null;
}
if (value.length() > REF_JSON_MAX_LENGTH) {
log.warn("[notification] 定位锚点超长已丢弃 长度={} 上限={}", value.length(), REF_JSON_MAX_LENGTH);
return null;
}
return value;
}
/** 读取时解析锚点:ref_json 只由本服务写入(且超长整条丢弃),不存在解析失败的分支。 */
private List<NotificationRefVo> parseRefs(String refJson) {
String value = normalize(refJson);
if (value.isEmpty()) {
return null;
}
return JSONUtil.toList(value, NotificationRefVo.class);
}
}
@@ -959,8 +959,8 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
"PYTHON_QUEUE", request.getUserId(), deviceId, preparedFiles.size(), now);
task.setSuccessFileCount(0);
task.setFailedFileCount(failedFiles);
task.setRequestJson(writeJson(request, "序列化上架任务失败"));
task.setResultJson(writeJson(Map.of("ownerInstanceId", currentInstanceId()),
task.setRequestJson(writeJson(objectMapper, request, "序列化上架任务失败"));
task.setResultJson(writeJson(objectMapper, Map.of("ownerInstanceId", currentInstanceId()),
"Failed to save publish task instance owner"));
task.setErrorMessage(processableFiles > 0 ? null : "全部文件解析或店铺匹配失败");
task.setFinishedAt(processableFiles > 0 ? null : now);
@@ -1352,7 +1352,7 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
validateChunkTotal(scope == null ? null : scope.getChunkTotal(), chunkTotal);
List<PublishRowDto> rows = flattenRows(incoming);
String payloadJson = writeJson(rows, "序列化上架结果分片失败");
String payloadJson = writeJson(objectMapper, rows, "序列化上架结果分片失败");
String payloadHash = DigestUtil.sha256Hex(payloadJson);
TaskChunkEntity existing = findResultChunk(taskId, scopeHash, chunkIndex);
String storedPayload = null;
@@ -1622,7 +1622,7 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
Map<String, Object> state = new LinkedHashMap<>();
state.put("phase", completed ? "COMPLETE" : "RECEIVING");
state.put("receivedRows", Math.max(0, receivedRowCount));
return writeJson(state, "保存上架结果分片进度失败");
return writeJson(objectMapper, state, "保存上架结果分片进度失败");
}
private void updateReceivedProgress(Long taskId, PublishFileEntity file, int receivedRowCount) {
@@ -1998,14 +1998,6 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
return files.size() == 1 ? first : first + " 等 " + files.size() + " 个文件";
}
private String writeJson(Object value, String errorMessage) {
try {
return objectMapper.writeValueAsString(value);
} catch (Exception ex) {
throw new BusinessException(errorMessage);
}
}
private String formatTime(LocalDateTime value) {
return value == null ? null : value.format(TIME_FORMATTER);
}
@@ -45,13 +45,17 @@ import java.util.List;
* 只有文案不同,是最干净的公共件。Phase 2 当时落不了——{@code config/CatchSilenceRatchetTest}
* 的自述规则是「新增捕获块要么别加,要么同批减掉一处同形状」,而 Phase 2 禁止改七支
* ⇒ 减不掉只能不加(登记见蓝图 §5 Phase 2 那条);首迁这一笔删掉被迁支的本地同名件,
* 净增 ≤ 0 才成立。现成模板 {@code PublishTaskService} 的私有
* {@code writeJson(Object, String)} 就是带文案参数的形状(认方法名不认行号;那一格 3D 未并档)。
* 净增 ≤ 0 才成立。带文案参数的形状取自 {@code PublishTaskService} 那枚私有
* {@code writeJson(Object, String)}(认方法名不认行号);那一格已于 2026-10-22 并档,
* 本件至此是七支唯一的序列化出口。
* ⚠ task 模块内部那三份逐字同名件({@code TaskProgressSnapshotService:186}/
* {@code TaskResultItemService:405}/{@code TaskResultPayloadService:113})<b>本轮仍未归并</b>:
* 归并会把 RETHROW 那一格跌破下限(它是下限不是上限;首迁后落在 386,3B 并掉 ShopDataCrawl
* 那份私有同名件后按「逐条点名改基线」调到 385,出处写在 {@code CatchSilenceRatchetTest}),
* 再往下降就属于「调整门禁判据」动作,与 Phase 0 那格「三格守卫」同批做,不在迁移笔里顺手干。</li>
* 再往下降就属于「调整门禁判据」动作,与 Phase 0 那格「三格守卫」同批做,不在迁移笔里顺手干。
* ⚠ 那句「会跌破」的前提数在 2026-10-22 已变:当时 Publish 并档实测整树
* rethrow=383/total=1000(复现办法见 {@code CatchSilenceRatchetTest} 常量上方),
* 所以下一支若只归并 task 那三份中的部分,可能压根不需要动判据——先复现再判,别照抄这句。</li>
* <li><b>跑批</b>:服务端<b>没有属于这七支的可沉件</b>——机制早已收在
* {@link TaskFileJobService}(enqueue/claim/markSuccess/markFailed)+
* {@code TaskResultFileJobWorker}(取锁、重排、重试)+
@@ -319,8 +323,9 @@ public abstract class AbstractFileTaskPipeline<T> {
* <p>七支建单与状态回写时都要把对象转成 JSON,失败形状逐字相同:
* 抛 {@code BusinessException(<文案>)} 且<b>不带 cause</b>
* (ShopMatch{@code :510-512} 的文案是「task 不存在」、{@code :1301-1303} 是「序列化任务数据失败」,
* PriceTrack{@code :571-573} 与 Publish 的私有 {@code writeJson} 同款;Publish 那一格 3D 迁移
* <b>未</b>并档——它要动 {@code RETHROW_FLOOR},属门禁判据动作、须逐处记名授权)。
* PriceTrack{@code :571-573} 与 Publish 的私有 {@code writeJson} 同款;Publish 那一格已于
* 2026-10-22 并档(当时判「未并」的理由是它要动 {@code RETHROW_FLOOR},属门禁判据动作、
* 须逐处记名授权;实际并档后实测整树 rethrow 仍在上限内,那一格至今未被放宽)。
* 文案是各支自己的对外语义(其中「task 不存在」甚至是现网一句会说谎的文案——序列化失败跟任务存不存在
* 没关系,但 Python 侧按这句决定要不要重试,改它=改线协议),所以底座只收形状、文案由调用方给。
*
@@ -0,0 +1,51 @@
-- =============================================================
-- 迁移 V162__notification_ref_json
--
-- 1. 变更目的:给站内通知补「结构化定位锚点」列(2026-10-21 需求)。
-- 用户原话:「都没体现 哪个任务id 或者 店铺 或用户啥的关键信息 咋排查」。
-- 现状:biz_user_notification 只有 title(128)/content(512),task_failed 又按
-- 「用户 × 模块 × 自然日」聚合成一条,明细被 taskNoPreview(最多 5 个) + 最近
-- 一条原因(截 120) 压缩,且 content 再截 512 ⇒ 同桶其余任务连任务号都看不到。
-- 加这一列后,扫描器把桶内每个失败任务写成 JSON(taskId/taskNo/moduleType/
-- reason/updatedAt/deviceId),后台「展开明细」渲染成可点行、直达任务详情。
--
-- 2. 为什么不是把正文放宽:content 是给桌面用户看的自然语言,长度由 UI 决定;
-- 结构化定位信息要能被程序消费(跳转、对齐),混在一段文本里只能靠正则捞。
--
-- 3. 为什么用 TEXT 不用 JSON 类型:MySQL JSON 列在 JDBC 侧同样回字符串,
-- 但会给「老的 jar 不认识这一列」的回滚场景多绑一个数据库版本前提;
-- TEXT 与 V116 既有风格一致,可重跑、可直接 SHOW。
--
-- 4. 存量行:ref_json 保持 NULL(不回填)。历史 task_failed 通知的明细在聚合时
-- 就已丢弃,回填只能靠正则解析文案,正是本项目一直拒绝的做法。
--
-- 5. 锁表风险:低。TEXT NULL ADD COLUMN 在 MySQL 8 走 INSTANT(不重建表)。
-- 刻意不加索引:这一列只随明细行整体读出,从不做条件筛选。
--
-- 6. 验证 SQL(迁移后跑):
-- SHOW COLUMNS FROM `biz_user_notification` LIKE 'ref_json';
-- -> 期望 1 行:Type=text,Null=YES
-- SELECT id, scene, LEFT(ref_json, 120) FROM biz_user_notification
-- WHERE scene='task_failed' ORDER BY id DESC LIMIT 3;
-- -> 新产生的行应能看到 [{"taskId":...,"taskNo":"...
--
-- 7. 可重跑性:照 V146/V155/V157/V158/V161 惯例,加列前先查 information_schema;
-- 迁移中途失败时 flyway repair + 重启会从第一条语句重跑,裸 ADD COLUMN 会撞 1060。
--
-- 8. 回滚(人工补丁,写成注释以免被 Flyway 当迁移执行):
-- ALTER TABLE `biz_user_notification` DROP COLUMN `ref_json`;
-- 仅回滚 jar 不需要 DROP:旧 jar 的实体没有这一列,INSERT 不会写它。
-- =============================================================
SET @has_col := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_user_notification'
AND COLUMN_NAME = 'ref_json'
);
SET @ddl := IF(@has_col = 0,
'ALTER TABLE `biz_user_notification` ADD COLUMN `ref_json` TEXT NULL COMMENT ''结构化定位锚点 JSON(task_failed=桶内失败任务清单)'' AFTER `content`',
'SELECT ''biz_user_notification.ref_json already exists, skipped'' AS note');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -73,7 +73,7 @@ class NotificationDispatchServiceTest {
// 第 8 个参数是事件主体用户:管理员行必须带上它,聚合才有"按用户折"的键
org.mockito.Mockito.verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L));
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L), isNull());
}
@Test
@@ -97,13 +97,13 @@ class NotificationDispatchServiceTest {
assertThat(pushed).isEqualTo(2);
verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L));
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L), isNull());
verify(notificationService).pushOrRefresh(eq(2L), eq(NotificationService.AUDIENCE_ADMIN),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"), eq(20L));
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"), eq(20L), isNull());
// 非本组主管一条都不落
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), any());
anyString(), anyString(), anyString(), anyString(), any(), anyString());
}
/**
@@ -179,7 +179,7 @@ class NotificationDispatchServiceTest {
contains("任务部分结果缺失"), contains("12 个品牌查询失败"), eq("task_partial:3301"));
verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
eq(NotificationService.SCENE_TASK_PARTIAL), eq(NotificationService.LEVEL_WARNING),
contains("用户"), anyString(), eq("task_partial_admin:3301:1"), eq(20L));
contains("用户"), anyString(), eq("task_partial_admin:3301:1"), eq(20L), isNull());
}
@Test
@@ -216,6 +216,8 @@ class NotificationDispatchServiceTest {
anyString(), anyString(), anyString())).thenReturn(true);
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), any())).thenReturn(true);
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), any(), any())).thenReturn(true);
}
private AdminUserEntity admin(Long id, String username) {
@@ -68,18 +68,19 @@ class NotificationScanSchedulerTest {
when(dispatch.prepareAdminAudience()).thenReturn(
new NotificationDispatchService.AdminAudience(List.of(), Set.of(), Map.of()));
when(dispatch.displayNameOf(anyLong())).thenReturn("张三");
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(true);
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), any(), anyString())).thenReturn(true);
when(dispatch.pushToAdmins(any(NotificationDispatchService.AdminAudience.class), anyString(), anyString(),
anyString(), anyString(), anyString(), any())).thenReturn(1);
anyString(), anyString(), anyString(), any(), anyString())).thenReturn(1);
newScheduler().scanFailedTasks();
// 三个桶:用户7×跟价、用户7×品牌检测、用户8×货源查询
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> refCaptor = ArgumentCaptor.forClass(String.class);
verify(notificationService, times(3)).pushOrRefresh(anyLong(), eq(NotificationService.AUDIENCE_USER),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), contentCaptor.capture(), anyString());
anyString(), contentCaptor.capture(), anyString(), any(), refCaptor.capture());
List<String> contents = contentCaptor.getAllValues();
assertThat(contents).anySatisfy(text -> {
assertThat(text).contains("2 个跟价任务失败");
@@ -88,9 +89,57 @@ class NotificationScanSchedulerTest {
});
assertThat(contents).anySatisfy(text -> assertThat(text).contains("1 个货源查询任务失败"));
assertThat(contents).anySatisfy(text -> assertThat(text).contains("1 个品牌检测任务失败"));
assertThat(refCaptor.getAllValues()).hasSize(3).allSatisfy(json ->
assertThat(readRefs(json)).isNotEmpty());
verify(dispatch, times(3)).pushToAdmins(any(NotificationDispatchService.AdminAudience.class),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), anyString(), anyString(), anyLong());
anyString(), anyString(), anyString(), anyLong(), anyString());
}
/**
* 用户口径(2026-10-21):「通知里都没体现哪个任务 id / 店铺 / 用户,咋排查」。
* 管理端 task_failed 通知的可执行判据:正文必须带 uid,ref_json 必须至少有一条非空
* taskNo(品牌任务无 task_no 列,用 #&lt;id&gt; 兜底)。只断言标题字面量的测试对此完全无感。
*/
@Test
void taskFailedAdminNotificationCarriesUidAndTaskNoAnchor() {
when(fileTaskMapper.selectList(any())).thenReturn(List.of(
fileTask(101L, "DELETE_BRAND-101", "DELETE_BRAND", 1208L, "店铺打不开")));
BrandCrawlTaskEntity brandTask = new BrandCrawlTaskEntity();
brandTask.setId(201L);
brandTask.setUserId(1208L);
brandTask.setErrorMessage("品牌检测服务不可达");
when(brandCrawlTaskMapper.selectList(any())).thenReturn(List.of(brandTask));
stubAdminAudience();
newScheduler().scanFailedTasks();
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> refCaptor = ArgumentCaptor.forClass(String.class);
verify(dispatch, times(2)).pushToAdmins(any(NotificationDispatchService.AdminAudience.class),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), contentCaptor.capture(), anyString(), eq(1208L), refCaptor.capture());
assertThat(contentCaptor.getAllValues()).allSatisfy(text -> assertThat(text).contains("uid=1208"));
assertThat(refCaptor.getAllValues()).allSatisfy(json -> {
List<Map<String, Object>> refs = readRefs(json);
assertThat(refs).as("task_failed 通知必须带定位锚点").isNotEmpty();
assertThat(refs.get(0).get("taskNo")).as("锚点必须能定位任务").isNotNull();
});
assertThat(refCaptor.getAllValues()).anySatisfy(json -> assertThat(readRefs(json))
.anySatisfy(ref -> assertThat(ref.get("taskNo")).isEqualTo("DELETE_BRAND-101")));
assertThat(refCaptor.getAllValues()).anySatisfy(json -> assertThat(readRefs(json))
.anySatisfy(ref -> assertThat(ref.get("taskNo")).isEqualTo("#201")));
}
private static List<Map<String, Object>> readRefs(String json) {
try {
return new com.fasterxml.jackson.databind.ObjectMapper()
.readValue(json, new com.fasterxml.jackson.core.type.TypeReference<>() {
});
} catch (Exception ex) {
throw new AssertionError("ref_json 不是合法 JSON: " + json, ex);
}
}
@Test
@@ -101,9 +150,9 @@ class NotificationScanSchedulerTest {
newScheduler().scanFailedTasks();
verify(notificationService, org.mockito.Mockito.never()).pushOrRefresh(anyLong(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString());
anyString(), anyString(), anyString(), anyString(), any(), anyString());
verify(dispatch, org.mockito.Mockito.never()).pushToAdmins(any(), anyString(), anyString(),
anyString(), anyString(), anyString(), any());
anyString(), anyString(), anyString(), any(), anyString());
}
@Test
@@ -115,7 +164,7 @@ class NotificationScanSchedulerTest {
newScheduler().scanFailedTasks();
verify(notificationService, org.mockito.Mockito.never()).pushOrRefresh(anyLong(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString());
anyString(), anyString(), anyString(), anyString(), any(), anyString());
}
/**
@@ -136,13 +185,14 @@ class NotificationScanSchedulerTest {
ArgumentCaptor<String> userKey = ArgumentCaptor.forClass(String.class);
verify(notificationService, times(1)).pushOrRefresh(eq(7L), eq(NotificationService.AUDIENCE_USER),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), anyString(), userKey.capture());
anyString(), anyString(), userKey.capture(),
org.mockito.ArgumentMatchers.<Long>isNull(), anyString());
assertThat(userKey.getValue()).isEqualTo("task_failed:7:PRICE_TRACK:20261001");
ArgumentCaptor<String> adminKey = ArgumentCaptor.forClass(String.class);
verify(dispatch, times(1)).pushToAdmins(any(NotificationDispatchService.AdminAudience.class),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), anyString(), adminKey.capture(), eq(7L));
anyString(), anyString(), adminKey.capture(), eq(7L), anyString());
assertThat(adminKey.getValue()).isEqualTo("task_failed_admin:7:PRICE_TRACK:20261001");
}
@@ -159,7 +209,8 @@ class NotificationScanSchedulerTest {
ArgumentCaptor<String> userKey = ArgumentCaptor.forClass(String.class);
verify(notificationService, times(2)).pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), userKey.capture());
anyString(), anyString(), userKey.capture(),
org.mockito.ArgumentMatchers.<Long>isNull(), anyString());
assertThat(userKey.getAllValues()).containsExactlyInAnyOrder(
"task_failed:7:PRICE_TRACK:20261001", "task_failed:7:PRICE_TRACK:20261002");
}
@@ -473,10 +524,10 @@ class NotificationScanSchedulerTest {
when(dispatch.prepareAdminAudience()).thenReturn(
new NotificationDispatchService.AdminAudience(List.of(), Set.of(), Map.of()));
when(dispatch.displayNameOf(anyLong())).thenReturn("张三");
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(true);
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString())).thenReturn(true);
when(dispatch.pushToAdmins(any(NotificationDispatchService.AdminAudience.class), anyString(), anyString(),
anyString(), anyString(), anyString(), any())).thenReturn(1);
anyString(), anyString(), anyString(), any(), anyString())).thenReturn(1);
}
private FileTaskEntity fileTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage) {
+143 -4
View File
@@ -1,11 +1,11 @@
/**
* 桌面客户端更新日志(面向用户的通俗说明,桌面端更新面板展示)。
*
* 数据来源:app_client 仓库 git 历史——以各版本发版提交
* (chore(release): 版本号 x.y.z …)为界,取该窗口内的 feat/fix 提交,
* 自动整理成"用户能看懂的一句话"后追加到本文件(新版本放最前)。
* 数据来源:app_client 仓库 git 历史——以 `version.txt` 每次变更提交为界
* (4.0.43 起提交信息不再统一为 chore(release),锚点改用文件本身),
* 取该窗口内的 feat/fix 提交,自动整理成"用户能看懂的一句话"后追加到本文件(新版本放最前)。
* 取某版本区间的原始提交:
* git -C app_client log --oneline <上一版提交>..<本版提交>
* git -C app_client log --oneline <上一版 version.txt 提交>..<本版提交>
*
* 注意:version 必须与 web_config 发布记录 / /api/version/latest 的版本号
* 完全一致(不带 v 前缀),否则按本机版本筛选时匹配不到条目。
@@ -24,6 +24,145 @@ export interface ClientChangelogEntry {
/** 更新日志数据(新版本在前;发版时在数组最前追加一条) */
export const CLIENT_CHANGELOG: ClientChangelogEntry[] = [
{
version: '4.0.59',
date: '2026-10-21',
items: [
'任务多时不再丢失已领取的任务,减少无故失败',
'商品采集:搜索一直失败时如实报错,不再当成没搜到',
'品牌检测:翻页中途失败不再当作无冲突,避免漏检',
'相似ASIN:查不到结果时明确提示原因,不再静默无反应',
'审批:缺少筛选条件时如实报错,不再显示成功却没结果',
'手动停止采集时如实标记,不再显示为正常完成',
],
},
{
version: '4.0.58',
date: '2026-10-17',
items: [
'跟价:0 元商品自动补报价,不再一直改不动价格',
'巡店删除:草稿类商品需确认后才删,降低误删风险',
],
},
{
version: '4.0.57',
date: '2026-10-17',
items: [
'巡店删除:修复非在售商品可能被批量误删的严重问题',
'巡店删除、指定删除ASIN:适配新版「管理商品」页面',
'指定删除ASIN:修复页面被弹回首页、找不到商品',
],
},
{
version: '4.0.56',
date: '2026-10-17',
items: [
'跟价:全量模式可按勾选的多种商品状态分别执行',
'跟价:修复商品状态筛选失效、提示未收到有效数据',
'巡店删除:修复部分国家打不开商品页、被登录墙挡住',
],
},
{
version: '4.0.55',
date: '2026-10-16',
items: [
'恢复巡店删除与指定删除ASIN 功能',
'紫鸟浏览器统一使用新版,旧版不再支持',
],
},
{
version: '4.0.54',
date: '2026-10-15',
items: [
'全面切换到新版亚马逊后台界面,旧版界面不再支持',
],
},
{
version: '4.0.53',
date: '2026-10-14',
items: [
'上架:修复被误判为不兼容界面而直接失败的问题',
],
},
{
version: '4.0.52',
date: '2026-10-13',
items: [
'货源查询:未送达的结果保留 24 小时,不再提前丢弃',
],
},
{
version: '4.0.51',
date: '2026-10-13',
items: [
'紫鸟已手动打开时也能正常开店,不用先退出紫鸟',
'遇到亚马逊后台改版时明确提示,不再空转后报错',
],
},
{
version: '4.0.50',
date: '2026-10-11',
items: [
'任务进度显示更准确:各类任务都能看到总量和百分比',
'商品采集进度改为按国家统计,更贴近实际进度',
],
},
{
version: '4.0.49',
date: '2026-10-10',
items: [
'掉登录后自动识别并恢复,不用再关掉浏览器重开',
],
},
{
version: '4.0.48',
date: '2026-10-09',
items: [
'审批:掉登录后先自动恢复,不再空转后判失败',
'数字人启动失败的提示改为中文',
],
},
{
version: '4.0.47',
date: '2026-10-09',
items: [
'品牌检测:自动去掉查询词里多余的 Brand: 前缀',
],
},
{
version: '4.0.46',
date: '2026-10-08',
items: [
'任务结果回传更可靠,服务器未确认时会自动补发',
],
},
{
version: '4.0.45',
date: '2026-10-08',
items: [
'升级或退出客户端时不再打断正在跑的任务',
'结果没被服务器收下时不会显示为已完成',
'品牌检测遇到无法解析的商品会明确报错,不再反复重试',
'任务被拒绝或凭据异常时提示具体原因',
'金额留空不再导致整单采集失败',
],
},
{
version: '4.0.44',
date: '2026-10-03',
items: [
'更新前校验安装包完整性,防止下载到损坏或被替换的包',
'登录凭据改为连上服务器后领取,不再保存在安装包里',
],
},
{
version: '4.0.43',
date: '2026-10-03',
items: [
'开店失败时写明真实原因,不再统一提示未收到数据',
'任务很多时客户端不再卡住',
],
},
{
version: '4.0.42',
date: '2026-10-02',