dsh-ustc-campus 0.2.14 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ import { readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+
3
+ function unlink(file) {
4
+ try { unlinkSync(file); }
5
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
6
+ }
7
+
8
+ // One owner per file. Writes and invalidation are synchronous so no old-account
9
+ // rename can race an unlink. Network readers carry the generation they started in.
10
+ export function createSnapshotCache(file, { now = Date.now, limit = 64, retryMs = 60_000 } = {}) {
11
+ const temporary = file && `${file}.tmp`;
12
+ const entries = new Map();
13
+ const pending = new Map();
14
+ const failures = new Map();
15
+ let generation = 0;
16
+ if (file) {
17
+ try { unlink(temporary); } catch { /* retry on write or explicit clear */ }
18
+ try {
19
+ const stored = JSON.parse(readFileSync(file, 'utf8'));
20
+ if (stored.version === 1 && Array.isArray(stored.entries)) {
21
+ for (const [key, entry] of stored.entries.slice(-limit)) {
22
+ if (typeof key === 'string' && Number.isFinite(entry?.at) && entry.value != null) entries.set(key, entry);
23
+ }
24
+ }
25
+ } catch { /* missing or unreadable cache: refill from the source */ }
26
+ }
27
+
28
+ function persist() {
29
+ if (!file) return;
30
+ try {
31
+ writeFileSync(temporary, JSON.stringify({ version: 1, entries: [...entries] }), { flag: 'wx', mode: 0o600 });
32
+ renameSync(temporary, file);
33
+ } catch {
34
+ try { unlink(temporary); } catch { /* explicit clear will retry */ }
35
+ }
36
+ }
37
+
38
+ function setBounded(map, key, value) {
39
+ map.delete(key);
40
+ if (map.size >= limit) map.delete(map.keys().next().value);
41
+ map.set(key, value);
42
+ }
43
+
44
+ function refresh(key, load, { maxAge = 0, force = false, accept = () => true, backoff = () => true } = {}) {
45
+ const running = pending.get(key);
46
+ if (running) return running;
47
+ const cached = entries.get(key);
48
+ const time = now();
49
+ if (!force && (time - (cached?.at ?? -Infinity) < maxAge || time - (failures.get(key) ?? -Infinity) < retryMs)) {
50
+ if (cached) return Promise.resolve(cached.value);
51
+ if (failures.has(key)) return Promise.resolve(undefined);
52
+ }
53
+ const epoch = generation;
54
+ const task = Promise.resolve().then(() => epoch === generation ? load() : undefined).then(value => {
55
+ if (epoch !== generation) return undefined;
56
+ if (accept(value)) {
57
+ setBounded(entries, key, { at: now(), value });
58
+ failures.delete(key);
59
+ persist();
60
+ } else if (backoff(value)) {
61
+ setBounded(failures, key, now());
62
+ }
63
+ return value;
64
+ }, error => {
65
+ if (epoch !== generation) return undefined;
66
+ if (backoff(error)) setBounded(failures, key, now());
67
+ throw error;
68
+ }).finally(() => {
69
+ if (pending.get(key) === task) pending.delete(key);
70
+ });
71
+ pending.set(key, task);
72
+ return task;
73
+ }
74
+
75
+ function cancelPending() {
76
+ generation++;
77
+ pending.clear();
78
+ }
79
+ function clearFailures() {
80
+ failures.clear();
81
+ }
82
+ function clear() {
83
+ cancelPending();
84
+ entries.clear();
85
+ failures.clear();
86
+ if (!file) return;
87
+ try { unlink(file); }
88
+ finally { unlink(temporary); }
89
+ }
90
+
91
+ return { get: key => entries.get(key), syncing: key => pending.has(key), refresh, clear, clearFailures, cancelPending,
92
+ due(key, maxAge) {
93
+ const time = now();
94
+ return !pending.has(key) && time - (entries.get(key)?.at ?? -Infinity) >= maxAge
95
+ && time - (failures.get(key) ?? -Infinity) >= retryMs;
96
+ }
97
+ };
98
+ }
package/src/state.mjs CHANGED
@@ -2,16 +2,19 @@ import { mkdirSync, readFileSync, renameSync, writeFileSync, unlinkSync } from '
2
2
  import { join } from 'node:path';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
4
  import { DAY, shDate, localMidnight, parseCalendar, calendarEntries } from './calendar.mjs';
5
- import { createFeed } from './feed.mjs';
5
+ import { createFeed, FEED_SOURCES } from './feed.mjs';
6
+ import { createCustomFeeds, CustomFeedError } from './custom-feeds.mjs';
7
+ import { createRecommender } from './recommender.mjs';
6
8
  import { createMaterials } from './materials.mjs';
7
9
  import { createLocalItems, LocalItemError } from './local-items.mjs';
8
10
  import { sanitizeText } from './public-fetch.mjs';
9
11
 
10
12
  export const MAX_ICS = 1024 * 1024;
11
13
  const MAX_SCHOOL_ENTRIES = 2000;
14
+ const FEED_SNAPSHOT_LIMIT = 12;
15
+ const NO_EXTRA_ITEMS = [];
12
16
  const localKinds = new Set(['course', 'exam']);
13
- const nonActivitySources = new Set(['news']);
14
- const readLabels = { schedule: '课表', saved: '收藏', items: '日程' };
17
+ const readLabels = { schedule: '课表', saved: '收藏', items: '日程', recommender: '推荐偏好', 'custom-feeds': '自定义订阅' };
15
18
  export class CampusInputError extends Error {}
16
19
  function clockMinutes(value) {
17
20
  if (typeof value !== 'string') return null;
@@ -39,11 +42,27 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
39
42
  catch (error) { try { unlinkSync(temp); } catch { /* retain primary error */ } throw error; }
40
43
  };
41
44
  const feed = createFeed({ read, write, now, fetch });
45
+ const customFeeds = createCustomFeeds({ read, write, now, fetch });
46
+ let feedbackVersion = 0;
47
+ const recommender = createRecommender({ read, now, write(key, value) {
48
+ feedbackVersion++;
49
+ write(key, value);
50
+ } });
51
+ const lastExtraItemsById = new Map();
42
52
  const materials = createMaterials({ read, write, now, fetch });
43
53
  const localItems = createLocalItems({ read, write, now });
44
54
  let schedule = read('schedule') ?? {};
45
55
  let saved = read('saved') ?? {};
46
56
  let recommendationAgenda;
57
+ const feedSnapshots = new Map();
58
+ let snapshotsVersion;
59
+ let indexedExtras;
60
+
61
+ function clearExtraFeedData() {
62
+ lastExtraItemsById.clear();
63
+ indexedExtras = undefined;
64
+ feedSnapshots.clear();
65
+ }
47
66
  const range = (from, through) => {
48
67
  let start, last;
49
68
  try { start = localMidnight(from); last = localMidnight(through); }
@@ -181,18 +200,87 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
181
200
  recommendationAgenda = undefined;
182
201
  return { label: removed.label };
183
202
  }
203
+ function findAnyFeedItem(lookupId) {
204
+ return feed.getItemById(lookupId) ?? customFeeds.getItemById(lookupId) ?? lastExtraItemsById.get(lookupId) ?? null;
205
+ }
206
+ function findAnySourceMeta(srcId) {
207
+ if (FEED_SOURCES[srcId]) return FEED_SOURCES[srcId];
208
+ if (srcId === 'youth-enrolling') {
209
+ return { id: 'youth-enrolling', label: '青春科大 · 报名中二课', category: 'activity', kind: 'event' };
210
+ }
211
+ return customFeeds.getSourceMeta(srcId) ?? null;
212
+ }
184
213
  function queryFeed(options = {}) {
185
- const from = shDate(now());
186
- if (options.sort === 'recommended' && recommendationAgenda?.from !== from) {
214
+ const nowMs = now();
215
+ const from = shDate(nowMs);
216
+ const recommended = options.sort === 'recommended' || options.sort === 'recommend';
217
+ if (recommended && recommendationAgenda?.from !== from) {
187
218
  recommendationAgenda = agenda({ from, through: shDate(localMidnight(from) + 30 * DAY) });
188
219
  }
189
- const coverage = options.sort === 'recommended' ? recommendationAgenda : null;
190
- const interests = Array.isArray(options.interests) ? options.interests.slice(0, 12).map(x => String(x).slice(0, 64)) : [];
191
- const result = feed.query({ source: options.source, keyword: options.keyword, sort: options.sort, interests,
192
- agenda: coverage?.entries, agendaCoverage: coverage ? {
220
+ const coverage = recommended ? recommendationAgenda : null;
221
+ const hostExtraItems = Array.isArray(options.extraItems) ? options.extraItems : NO_EXTRA_ITEMS;
222
+ if (hostExtraItems !== indexedExtras) {
223
+ clearExtraFeedData();
224
+ indexedExtras = hostExtraItems;
225
+ for (const item of hostExtraItems) if (item?.id) lastExtraItemsById.set(item.id, item);
226
+ }
227
+ const version = `${feed.revision()}/${customFeeds.revision()}/${feedbackVersion}/${Math.floor(nowMs / 60_000)}`;
228
+ if (snapshotsVersion !== version) {
229
+ snapshotsVersion = version;
230
+ feedSnapshots.clear();
231
+ }
232
+ const key = JSON.stringify([options.source, options.category, options.intent, options.keyword, recommended,
233
+ options.interests, options.courseTitles]);
234
+ let snapshot = feedSnapshots.get(key);
235
+ if (!snapshot || snapshot.coverage !== coverage || snapshot.extraSources !== options.extraSources || snapshot.saved !== saved) {
236
+ snapshot = { coverage, extraSources: options.extraSources, saved, result: computeFeed(options, coverage, hostExtraItems) };
237
+ feedSnapshots.delete(key);
238
+ if (feedSnapshots.size >= FEED_SNAPSHOT_LIMIT) feedSnapshots.delete(feedSnapshots.keys().next().value);
239
+ feedSnapshots.set(key, snapshot);
240
+ }
241
+ const { items, sources } = snapshot.result;
242
+ const total = items.length;
243
+ const paginated = options.page != null || options.pageSize != null;
244
+ const rawSize = options.pageSize == null ? 20 : Number(options.pageSize);
245
+ const pageSize = paginated ? Math.min(100, Math.max(1, Number.isNaN(rawSize) ? 20 : Math.trunc(rawSize))) : Math.max(1, total);
246
+ const totalPages = Math.ceil(total / pageSize);
247
+ const page = paginated ? Math.max(1, Math.min(totalPages, Math.trunc(Number(options.page) || 1))) : 1;
248
+ const visible = paginated ? items.slice((page - 1) * pageSize, page * pageSize) : items;
249
+ return { sources, total, page, pageSize, totalPages, hasMore: page < totalPages,
250
+ items: visible.map(item => ({ ...item, saved: Object.hasOwn(saved, item.id) })) };
251
+ }
252
+
253
+ function computeFeed(options, coverage, hostExtraItems) {
254
+ const importedTitles = (coverage?.entries ?? [])
255
+ .filter(entry => entry.kind === 'course' || entry.kind === 'exam')
256
+ .map(entry => entry.title)
257
+ .filter(Boolean);
258
+ const hostCourseTitles = Array.isArray(options.courseTitles)
259
+ ? options.courseTitles.slice(0, 40).map(x => sanitizeText(String(x ?? ''), 120)).filter(Boolean)
260
+ : [];
261
+ const courseTitles = [...new Set([...hostCourseTitles, ...importedTitles])].slice(0, 40);
262
+ const savedTitles = Object.values(saved).map(item => item.title).filter(Boolean).slice(0, 20);
263
+ const extraItems = [...customFeeds.getItems(), ...hostExtraItems];
264
+ const extraSources = [
265
+ ...customFeeds.getSourceStatuses(),
266
+ ...(Array.isArray(options.extraSources) ? options.extraSources : [])
267
+ ];
268
+ return feed.query({
269
+ source: options.source,
270
+ category: options.category,
271
+ intent: options.intent,
272
+ keyword: options.keyword,
273
+ sort: options.sort,
274
+ interests: Array.isArray(options.interests) ? options.interests.slice(0, 12).map(x => String(x).slice(0, 64)) : [],
275
+ extraItems,
276
+ extraSources,
277
+ recommender,
278
+ userContext: { courseTitles, savedTitles },
279
+ agenda: coverage?.entries,
280
+ agendaCoverage: coverage ? {
193
281
  ...range(coverage.from, coverage.through), complete: coverage.imported.length > 0 && !coverage.truncated && !coverage.warnings.length,
194
- } : undefined });
195
- return { ...result, items: result.items.map(item => ({ ...item, saved: Object.hasOwn(saved, item.id) })) };
282
+ } : undefined
283
+ });
196
284
  }
197
285
  function saveEvent({ id, action = 'save' } = {}) {
198
286
  if (typeof id !== 'string' || !id || id.length > 200 || !['save', 'remove'].includes(action)) throw new CampusInputError('无效的活动 ID 或操作');
@@ -204,23 +292,65 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
204
292
  return { status: 'removed', event };
205
293
  }
206
294
  if (Object.hasOwn(saved, id)) return { status: 'already_saved', event: saved[id] };
207
- const item = feed.query().items.find(item => item.id === id);
295
+ const extraItems = [...customFeeds.getItems(), ...lastExtraItemsById.values()];
296
+ const item = feed.query({ extraItems }).items.find(entry => entry.id === id);
208
297
  if (!item) throw new CampusInputError('找不到该活动;请先查询资讯');
209
298
  // Only an official activity with a proven clock time can become an agenda
210
299
  // event. News publications and date-only rows are never auto-saved.
211
- if (nonActivitySources.has(item.source)) throw new CampusInputError('新闻不是活动,不能保存为日程');
300
+ const itemKind = FEED_SOURCES[item.source]?.kind;
301
+ if (itemKind && itemKind !== 'event') {
302
+ throw new CampusInputError(itemKind === 'notice' ? '通知不是活动,不能保存为日程' : '新闻不是活动,不能保存为日程');
303
+ }
304
+ if (!itemKind && item.intent !== 'activity') {
305
+ throw new CampusInputError('通知或资讯不是活动,不能保存为日程');
306
+ }
212
307
  if (!Number.isFinite(item.start) || typeof item.date !== 'string') {
213
308
  throw new CampusInputError('只有官方活动列表中时间明确的场次可保存;仅有日期或时间未注明的信息不会保存');
214
309
  }
215
310
  localMidnight(item.date);
216
- const event = { id, kind: 'event', source: item.source === 'lug' ? '科大 LUG' : '官方活动', activitySource: item.source,
311
+ const event = { id, kind: 'event', source: item.source === 'lug' ? '科大 LUG' : item.source === 'youth-enrolling' ? '青春科大 · 第二课堂' : '官方活动', activitySource: item.source,
217
312
  title: item.title, date: item.date, time: item.time ?? null, start: item.start, end: item.end ?? item.start,
218
313
  location: item.location ?? '', url: item.url ?? null };
219
314
  const next = { ...saved, [id]: event };
220
315
  write('saved', next); saved = next;
221
316
  recommendationAgenda = undefined;
317
+ recommender.recordFeedback(
318
+ { action: 'save', itemId: id, item },
319
+ { getItem: findAnyFeedItem, getSourceMeta: findAnySourceMeta }
320
+ );
222
321
  return { status: 'saved', event, note: '仅保存到本地日程,未报名' };
223
322
  }
323
+ function recordFeedFeedback(data = {}) {
324
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
325
+ throw new CampusInputError('反馈参数无效');
326
+ }
327
+ return recommender.recordFeedback(data, {
328
+ getItem: findAnyFeedItem,
329
+ getSourceMeta: findAnySourceMeta
330
+ });
331
+ }
332
+ function feedProfile() {
333
+ return recommender.getProfile();
334
+ }
335
+ function listCustomFeeds() {
336
+ return customFeeds.list();
337
+ }
338
+ function addCustomFeed(data) {
339
+ try {
340
+ return customFeeds.add(data);
341
+ } catch (error) {
342
+ if (error instanceof CustomFeedError) throw new CampusInputError(error.message);
343
+ throw error;
344
+ }
345
+ }
346
+ function removeCustomFeed(data) {
347
+ try {
348
+ return customFeeds.remove(data);
349
+ } catch (error) {
350
+ if (error instanceof CustomFeedError) throw new CampusInputError(error.message);
351
+ throw error;
352
+ }
353
+ }
224
354
  function mutateItem(data, trusted = {}) {
225
355
  try {
226
356
  const trustedEntries = trusted && typeof trusted === 'object' ? trusted.schoolEntries : undefined;
@@ -245,6 +375,12 @@ export function openCampus(dir, { now = Date.now, fetch = globalThis.fetch } = {
245
375
  }
246
376
  }
247
377
  return { agenda, importCalendar, forgetCalendar, queryFeed, saveEvent, mutateItem, findItems,
248
- refresh: options => feed.refresh(options), lookup: query => materials.lookup(query),
249
- close() { feed.close(); materials.close(); } };
378
+ recordFeedFeedback, feedProfile, listCustomFeeds, addCustomFeed, removeCustomFeed,
379
+ validateAgendaRange: range, clearExtraFeedData,
380
+ refresh: async options => {
381
+ const [feedResult] = await Promise.all([feed.refresh(options), customFeeds.refresh(options)]);
382
+ return feedResult;
383
+ },
384
+ lookup: query => materials.lookup(query),
385
+ close() { feed.close(); customFeeds.close(); materials.close(); } };
250
386
  }
@@ -33,8 +33,8 @@ import {
33
33
 
34
34
  const PLAN_TTL_MS = 15 * 60_000;
35
35
  const MAX_PLANS = 32;
36
- const DEFAULT_VERIFY_ATTEMPTS = 3;
37
- const DEFAULT_VERIFY_DELAY_MS = 800;
36
+ const DEFAULT_VERIFY_ATTEMPTS = 2;
37
+ const DEFAULT_VERIFY_DELAY_MS = 300;
38
38
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
39
39
 
40
40
  function canonicalJson(value) {
@@ -64,36 +64,32 @@ function sleep(ms, signal) {
64
64
  });
65
65
  }
66
66
 
67
- async function findInOwnList(context, token, itemId, opts) {
68
- const maxPages = 10;
69
- const pageSize = 100;
70
- for (let pageNo = 1; pageNo <= maxPages; pageNo += 1) {
71
- const res = await youthQuery(
72
- context,
73
- token,
74
- 'item/scParticipateItem/list',
75
- { queryCatelog: 0, pageNo, pageSize },
76
- opts
77
- );
78
- if (res.kind !== 'ok') return { kind: res.kind };
79
- const records = Array.isArray(res.value.records) ? res.value.records : null;
80
- if (!records) return { kind: 'failure' };
81
- const hit = records.find((row) => cleanId(row?.id ?? row?.itemId) === itemId);
82
- if (hit) return { kind: 'ok', found: true, record: hit };
83
- const total = Number(res.value.total);
84
- if (!Number.isFinite(total) || pageNo * pageSize >= total || records.length === 0) {
85
- return { kind: 'ok', found: false, record: null };
86
- }
87
- }
88
- return { kind: 'failure' };
67
+ async function findInOwnList(context, token, itemId, title, opts) {
68
+ const res = await youthQuery(context, token, 'item/scParticipateItem/list', {
69
+ queryCatelog: 0, pageNo: 1, pageSize: 100, ...(title ? { itemName: title } : {})
70
+ }, opts);
71
+ if (res.kind !== 'ok') return res;
72
+ if (!Array.isArray(res.value.records)) return { kind: 'failure' };
73
+ const record = res.value.records.find(row => cleanId(row?.id ?? row?.itemId) === itemId);
74
+ return { kind: 'ok', record: record ?? null };
89
75
  }
90
76
 
91
- async function readItemState(context, token, itemId, opts) {
92
- const detailRes = await youthQuery(context, token, 'item/scItem/queryById', { id: itemId }, opts);
93
- if (detailRes.kind !== 'ok') return { kind: detailRes.kind };
94
- const ownRes = await findInOwnList(context, token, itemId, opts);
95
- if (ownRes.kind !== 'ok') return { kind: ownRes.kind };
96
- return { kind: 'ok', detail: detailRes.value, ownFound: ownRes.found, ownRecord: ownRes.record };
77
+ async function readItemState(context, token, itemId, opts, { target, title, checkCancelPolicy } = {}) {
78
+ const result = await youthQuery(context, token, 'item/scItem/queryById', { id: itemId }, opts);
79
+ const detail = result.kind === 'ok' && cleanId(result.value.id ?? result.value.itemId) === itemId ? result.value : null;
80
+ const reg = registration(detail);
81
+ if (target !== undefined && reg === target) return { kind: 'verified' };
82
+ if (target === undefined && !detail) return { kind: result.kind === 'ok' ? 'failure' : result.kind };
83
+ if (target === undefined && reg !== null && (!checkCancelPolicy || !reg || detail.cancelSign != null)) {
84
+ return { kind: 'ok', detail, ownFound: reg, ownRecord: reg ? detail : null };
85
+ }
86
+ // Absence from a filtered or truncated list does not prove cancellation.
87
+ if (target === false) return { kind: 'uncertain' };
88
+ const own = await findInOwnList(context, token, itemId, title || cleanText(detail?.itemName ?? detail?.title, 100), opts);
89
+ const found = Boolean(own.record && registration(own.record) !== false);
90
+ if (target === true) return { kind: found ? 'verified' : 'uncertain' };
91
+ if (own.kind !== 'ok') return { kind: own.kind };
92
+ return { kind: 'ok', detail, ownFound: reg === true || found, ownRecord: own.record };
97
93
  }
98
94
 
99
95
  function summarizePlanContent(action, itemId, detail) {
@@ -148,6 +144,7 @@ export function createYouthActions({
148
144
  }
149
145
 
150
146
  const plans = new Map();
147
+ let generation = 0;
151
148
  const clockMs = () => (typeof now === 'function' ? Number(now()) : Date.now());
152
149
 
153
150
  function pruneExpired() {
@@ -234,6 +231,7 @@ export function createYouthActions({
234
231
 
235
232
  async function prepareEnroll({ itemId } = {}) {
236
233
  pruneExpired();
234
+ const epoch = generation;
237
235
  const id = cleanId(itemId);
238
236
  if (!id) {
239
237
  return { state: 'invalid', message: '请提供有效的二课活动 ID。', untrustedContent: true };
@@ -249,6 +247,7 @@ export function createYouthActions({
249
247
  if (!check.ok) return { kind: 'blocked', check };
250
248
  return { kind: 'ok', context, detail: stateRes.detail };
251
249
  });
250
+ if (epoch !== generation) return { state: 'not_connected', requestSent: false, message: '学校账号已切换,请重新准备。' };
252
251
 
253
252
  if (res.kind === 'not_connected') {
254
253
  return { state: 'not_connected', message: '该功能需要登录学校账号,请在左侧「校园」页右上角登录后再试。', untrustedContent: true };
@@ -292,6 +291,7 @@ export function createYouthActions({
292
291
 
293
292
  async function prepareCancel({ itemId } = {}) {
294
293
  pruneExpired();
294
+ const epoch = generation;
295
295
  const id = cleanId(itemId);
296
296
  if (!id) {
297
297
  return { state: 'invalid', message: '请提供有效的二课活动 ID。', untrustedContent: true };
@@ -301,7 +301,7 @@ export function createYouthActions({
301
301
  const opts = { now, requestTimeoutMs };
302
302
  const session = await obtainYouthSession(context, opts);
303
303
  if (session.kind !== 'token') return { kind: session.kind };
304
- const stateRes = await readItemState(context, session.token, id, opts);
304
+ const stateRes = await readItemState(context, session.token, id, opts, { checkCancelPolicy: true });
305
305
  if (stateRes.kind !== 'ok') return { kind: stateRes.kind };
306
306
  const reg = registration(stateRes.detail);
307
307
  if (!stateRes.ownFound && reg !== true) {
@@ -313,6 +313,7 @@ export function createYouthActions({
313
313
  }
314
314
  return { kind: 'ok', context, detail: stateRes.detail };
315
315
  });
316
+ if (epoch !== generation) return { state: 'not_connected', requestSent: false, message: '学校账号已切换,请重新准备。' };
316
317
 
317
318
  if (res.kind === 'not_connected') {
318
319
  return { state: 'not_connected', message: '该功能需要登录学校账号,请在左侧「校园」页右上角登录后再试。', untrustedContent: true };
@@ -351,21 +352,15 @@ export function createYouthActions({
351
352
  return view(plan);
352
353
  }
353
354
 
354
- async function verifyOutcome(context, token, action, itemId, opts, signal) {
355
- const attempts = Math.max(1, verifyAttempts);
355
+ async function verifyOutcome(context, token, content, opts, signal) {
356
+ const attempts = Math.min(2, Math.max(1, verifyAttempts));
356
357
  for (let i = 0; i < attempts; i += 1) {
357
358
  if (i > 0) await sleep(verifyDelayMs, signal);
358
359
  if (signal?.aborted) break;
359
- const check = await readItemState(context, token, itemId, opts);
360
- if (check.kind === 'ok') {
361
- const reg = registration(check.detail);
362
- if (action === 'enroll' && (check.ownFound || reg === true)) {
363
- return { kind: 'verified' };
364
- }
365
- if (action === 'cancel' && !check.ownFound && reg === false) {
366
- return { kind: 'verified' };
367
- }
368
- }
360
+ const check = await readItemState(context, token, content.itemId,
361
+ { ...opts, timeout: Math.min(requestTimeoutMs, 2_500) },
362
+ { target: content.action === 'enroll', title: content.title });
363
+ if (check.kind === 'verified') return check;
369
364
  }
370
365
  return { kind: 'uncertain' };
371
366
  }
@@ -418,7 +413,8 @@ export function createYouthActions({
418
413
  const session = await obtainYouthSession(context, opts);
419
414
  if (session.kind !== 'token') return { kind: session.kind };
420
415
 
421
- const preflight = await readItemState(context, session.token, plan.content.itemId, opts);
416
+ const preflight = await readItemState(context, session.token, plan.content.itemId, opts,
417
+ { checkCancelPolicy: plan.content.action === 'cancel' });
422
418
  if (preflight.kind !== 'ok') return { kind: preflight.kind };
423
419
 
424
420
  if (plan.content.action === 'enroll') {
@@ -431,7 +427,7 @@ export function createYouthActions({
431
427
  if (!preflight.ownFound && reg !== true) {
432
428
  return { kind: 'state_changed', reason: 'not_enrolled', message: '该活动已不在本人报名列表中,未重复取消。' };
433
429
  }
434
- const policy = deriveCancelPolicy(preflight.detail);
430
+ const policy = deriveCancelPolicy(preflight.detail, { enrolledRow: preflight.ownRecord });
435
431
  if (!policy.cancelAllowed) {
436
432
  return { kind: 'state_changed', reason: 'not_cancellable', message: policy.cancelRuleNote };
437
433
  }
@@ -441,6 +437,7 @@ export function createYouthActions({
441
437
  ? `item/scItemRegistration/enter/${encodeURIComponent(plan.content.itemId)}`
442
438
  : `item/scItemRegistration/cancellRegistration/${encodeURIComponent(plan.content.itemId)}`;
443
439
 
440
+ if (signal?.aborted || plans.get(planId) !== plan) return { kind: 'state_changed', message: '确认已失效,没有提交。' };
444
441
  plan.state = 'executing';
445
442
  plan.requestSent = true;
446
443
  const post = await youthPost(context, session.token, endpoint, {}, opts);
@@ -454,16 +451,18 @@ export function createYouthActions({
454
451
  return { kind: 'uncertain', accepted: null, message: '暂未收到平台明确回执,请用 youth_action_status 查询最新状态。' };
455
452
  }
456
453
 
457
- const verified = await verifyOutcome(context, session.token, plan.content.action, plan.content.itemId, opts, signal);
454
+ const verified = await verifyOutcome(context, session.token, plan.content, opts, signal);
458
455
  if (verified.kind === 'verified') {
459
456
  return { kind: 'verified', serverMessage: post.message };
460
457
  }
461
458
  return {
462
459
  kind: 'uncertain',
463
460
  accepted: true,
464
- message: '请求已受理,活动列表尚未刷新,请稍后用 youth_action_status 查询。'
461
+ message: '请求已受理,尚未在官方记录中核实,请稍后用 youth_action_status 查询。'
465
462
  };
466
463
  });
464
+ if (plans.get(planId) !== plan) return { state: 'expired', planId, requestSent: plan.requestSent,
465
+ message: '学校账号已切换,无法继续核对此计划。' };
467
466
 
468
467
  if (execRes.kind === 'not_connected') {
469
468
  if (!plan.requestSent) {
@@ -524,17 +523,11 @@ export function createYouthActions({
524
523
  const opts = { now, requestTimeoutMs };
525
524
  const session = await obtainYouthSession(context, opts);
526
525
  if (session.kind !== 'token') return { kind: session.kind };
527
- const check = await readItemState(context, session.token, plan.content.itemId, opts);
528
- if (check.kind !== 'ok') return { kind: check.kind };
529
- const reg = registration(check.detail);
530
- if (plan.content.action === 'enroll' && (check.ownFound || reg === true)) {
531
- return { kind: 'verified' };
532
- }
533
- if (plan.content.action === 'cancel' && !check.ownFound && reg === false) {
534
- return { kind: 'verified' };
535
- }
536
- return { kind: 'still_uncertain' };
526
+ if (context !== plan.owner) return { kind: 'still_uncertain' };
527
+ return readItemState(context, session.token, plan.content.itemId, opts,
528
+ { target: plan.content.action === 'enroll', title: plan.content.title });
537
529
  });
530
+ if (plans.get(planId) !== plan) return { state: 'not_found', planId, message: '找不到此二课操作计划,或计划已过期。' };
538
531
 
539
532
  if (res.kind === 'verified') {
540
533
  plan.state = 'verified';
@@ -550,6 +543,7 @@ export function createYouthActions({
550
543
  prepareEnroll,
551
544
  prepareCancel,
552
545
  confirm,
553
- status
546
+ status,
547
+ clear() { generation++; plans.clear(); }
554
548
  });
555
549
  }