verce-vue-test 0.0.115 → 0.0.116

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "verce-vue-test",
3
- "version": "0.0.115",
3
+ "version": "0.0.116",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "scripts": {
@@ -1,153 +1,657 @@
1
1
  import baseHttpClient from '@/utils/baseHttpClient'
2
2
 
3
- export type AnnouncementRecord = {
4
- annouId: string
5
- orgNo: string | null
6
- annouTitle: string
7
- annouSts: string
8
- topFlag: string
9
- createUserId: string | null
10
- updateUserId: string | null
11
- createTm: string
12
- updateTm: string
13
- annouLimitFlag: string
14
- annouConte: string
15
- effDt: string | null
16
- expireDt: string | null
3
+ export interface Article {
4
+ id: string
5
+ title: string
6
+ content: string
7
+ author: string
8
+ createdAt: string
9
+ updatedAt: string
10
+ }
11
+
12
+ export interface ArticlePayload {
13
+ title: string
14
+ content: string
17
15
  }
18
16
 
19
- export type AnnouncementDetailRecord = AnnouncementRecord & {
17
+ export interface AnnouncementPayload {
18
+ annouTitle: string
19
+ annouConte: string
20
+ annouId: string
21
+ annouZrFteLag: string
22
+ annouSts: string
23
+ department: string
24
+ efDt: string
25
+ expireDt: string
20
26
  orgList: unknown[]
27
+ orgNo: string
21
28
  roleList: unknown[]
29
+ topFlag: string
22
30
  userList: unknown[]
23
31
  }
24
32
 
25
- type AnnouncementPageData = {
26
- total: number
27
- list: AnnouncementRecord[]
28
- pageNum: number
29
- pageSize: number
30
- size: number
31
- pages: number
32
- }
33
-
34
- type AnnouncementResponse = {
35
- code: string
33
+ type ApiResponse<T> = {
34
+ code: number | string
36
35
  message: string
37
- data: AnnouncementPageData
36
+ data: T
38
37
  }
39
38
 
40
- type AnnouncementDetailResponse = {
41
- code: string
42
- message: string
43
- data: Partial<AnnouncementDetailRecord>
39
+ type RawRecord = Record<string, unknown>
40
+
41
+ const LIST_URL = '/uaa/announcement/get/restricted'
42
+ const DETAIL_URL = '/uaa/announcement/get/id'
43
+ const ADD_URL = '/uaa/announcement/add'
44
+ const UPDATE_URL = '/uaa/announcement/update'
45
+
46
+ const MAX_TITLE_LENGTH = 40
47
+ const MAX_IMAGE_COUNT = 3
48
+ const MAX_IMAGE_SIZE = 5 * 1024 * 1024
49
+ const MAX_ARTICLE_HTML_SIZE = 20 * 1024 * 1024
50
+
51
+ const DEFAULT_ANNOUNCEMENT_FIELDS = {
52
+ annouZrFteLag: '0',
53
+ annouSts: '0',
54
+ department: '100011',
55
+ efDt: '2026-07-01 00:00:00',
56
+ expireDt: '2026-07-31 00:00:00',
57
+ orgList: [],
58
+ orgNo: '25001',
59
+ roleList: [],
60
+ topFlag: '0',
61
+ userList: [],
62
+ } satisfies Omit<AnnouncementPayload, 'annouTitle' | 'annouConte' | 'annouId'>
63
+
64
+ const ALLOWED_TAGS = new Set([
65
+ 'A',
66
+ 'B',
67
+ 'BLOCKQUOTE',
68
+ 'BR',
69
+ 'CODE',
70
+ 'DIV',
71
+ 'EM',
72
+ 'H2',
73
+ 'H3',
74
+ 'I',
75
+ 'IMG',
76
+ 'LI',
77
+ 'OL',
78
+ 'P',
79
+ 'PRE',
80
+ 'S',
81
+ 'SPAN',
82
+ 'STRONG',
83
+ 'U',
84
+ 'UL',
85
+ ])
86
+
87
+ const ALLOWED_IMAGE_MIME_TYPES = new Set([
88
+ 'image/png',
89
+ 'image/jpeg',
90
+ 'image/webp',
91
+ ])
92
+
93
+ const BASE64_IMAGE_SIGNATURES = [
94
+ { mime: 'image/png', pattern: /^iVBORw0KGgo/ },
95
+ { mime: 'image/jpeg', pattern: /^\/9j\// },
96
+ { mime: 'image/webp', pattern: /^UklGR/ },
97
+ ]
98
+
99
+ /** 查询公告完整列表;该接口不接收分页、搜索或状态参数。 */
100
+ export async function queryArticles(signal?: AbortSignal) {
101
+ const response = await baseHttpClient.get<ApiResponse<unknown>>(LIST_URL, { signal })
102
+ const data = unwrapResponse(response, '公告查询失败')
103
+
104
+ return extractRecords(data).map((record) => mapAnnouncementRecord(record))
44
105
  }
45
106
 
46
- export type AnnouncementPageResult = {
47
- total: number
48
- list: AnnouncementRecord[]
49
- currentPage: number
50
- pageSize: number
107
+ /** 根据 annouId 查询公告详情。 */
108
+ export async function getArticleDetail(annouId: string, signal?: AbortSignal) {
109
+ const normalizedId = normalizeAnnouncementId(annouId)
110
+ const query = new URLSearchParams({ annouId: normalizedId })
111
+ const response = await baseHttpClient.get<ApiResponse<unknown>>(
112
+ `${DETAIL_URL}?${query.toString()}`,
113
+ { signal },
114
+ )
115
+ const data = unwrapResponse(response, '公告详情查询失败')
116
+
117
+ return mapAnnouncementRecord(extractDetailRecord(data), normalizedId)
51
118
  }
52
119
 
53
- function toPositiveInteger(value: unknown, field: string) {
54
- const number = Number(value)
55
- if (!Number.isInteger(number) || number < 1) {
56
- throw new Error(`公告接口返回的 ${field} 无效`)
120
+ /** 新增公告;annouId 固定为空字符串,其余范围字段使用当前契约固定值。 */
121
+ export async function createArticle(payload: ArticlePayload, signal?: AbortSignal) {
122
+ const normalizedPayload = normalizeArticlePayload(payload)
123
+ const requestBody = buildAnnouncementPayload(normalizedPayload)
124
+ const response = await baseHttpClient.post<ApiResponse<unknown>>(ADD_URL, requestBody, { signal })
125
+ const data = unwrapResponse(response, '公告新增失败')
126
+ const record = {
127
+ ...requestBody,
128
+ ...extractDetailRecord(data),
57
129
  }
58
- return number
59
- }
60
130
 
61
- function normalizeRecord(source: Partial<AnnouncementRecord>): AnnouncementRecord {
62
- const annouId = String(source.annouId ?? '').trim()
63
- if (!annouId) throw new Error('公告接口返回的 annouId 为空')
131
+ return mapAnnouncementRecord(record, readString(record, ['annouId', 'id']))
132
+ }
64
133
 
65
- return {
66
- annouId,
67
- orgNo: source.orgNo == null ? null : String(source.orgNo),
68
- annouTitle: String(source.annouTitle ?? ''),
69
- annouSts: String(source.annouSts ?? ''),
70
- topFlag: String(source.topFlag ?? '0'),
71
- createUserId: source.createUserId == null ? null : String(source.createUserId),
72
- updateUserId: source.updateUserId == null ? null : String(source.updateUserId),
73
- createTm: String(source.createTm ?? ''),
74
- updateTm: String(source.updateTm ?? ''),
75
- annouLimitFlag: String(source.annouLimitFlag ?? '0'),
76
- annouConte: String(source.annouConte ?? ''),
77
- effDt: source.effDt == null ? null : String(source.effDt),
78
- expireDt: source.expireDt == null ? null : String(source.expireDt),
79
- }
80
- }
81
-
82
- /** 查询公告管理列表,分页字段严格使用接口规定的 currentPage/pageSize。 */
83
- export async function queryAnnouncements(
84
- currentPage: number,
85
- pageSize: number,
134
+ /** 修改公告;请求体与新增一致,仅 annouId 改为当前公告 ID。 */
135
+ export async function updateArticle(
136
+ annouId: string,
137
+ payload: ArticlePayload,
86
138
  signal?: AbortSignal,
87
- ): Promise<AnnouncementPageResult> {
88
- const query = new URLSearchParams({
89
- currentPage: String(currentPage),
90
- pageSize: String(pageSize),
91
- })
92
- const response = await baseHttpClient.get<AnnouncementResponse>(
93
- `/uaa/announcement/get?${query.toString()}`,
139
+ ) {
140
+ const normalizedId = normalizeAnnouncementId(annouId)
141
+ const normalizedPayload = normalizeArticlePayload(payload)
142
+ const requestBody = buildAnnouncementPayload(normalizedPayload, normalizedId)
143
+ const response = await baseHttpClient.post<ApiResponse<unknown>>(
144
+ UPDATE_URL,
145
+ requestBody,
94
146
  { signal },
95
147
  )
148
+ const data = unwrapResponse(response, '公告修改失败')
149
+ const record = {
150
+ ...requestBody,
151
+ ...extractDetailRecord(data),
152
+ }
153
+
154
+ return mapAnnouncementRecord(record, normalizedId)
155
+ }
156
+
157
+ export function formatArticleDate(value: string) {
158
+ const date = new Date(value)
96
159
 
97
- if (response.code !== '0000') {
98
- throw new Error(response.message || '公告查询失败')
160
+ if (Number.isNaN(date.getTime())) {
161
+ return ''
99
162
  }
100
- if (!response.data || !Array.isArray(response.data.list)) {
101
- throw new Error('公告接口返回结构不正确')
163
+
164
+ return new Intl.DateTimeFormat('zh-CN', {
165
+ year: 'numeric',
166
+ month: '2-digit',
167
+ day: '2-digit',
168
+ hour: '2-digit',
169
+ minute: '2-digit',
170
+ }).format(date)
171
+ }
172
+
173
+ export function extractTextFromHtml(html: string) {
174
+ if (!html.trim()) {
175
+ return ''
102
176
  }
103
177
 
104
- const total = Number(response.data.total)
105
- if (!Number.isInteger(total) || total < 0) {
106
- throw new Error('公告接口返回的 total 无效')
178
+ const doc = new DOMParser().parseFromString(html, 'text/html')
179
+
180
+ return doc.body.textContent?.replace(/\s+/g, ' ').trim() || ''
181
+ }
182
+
183
+ /** 对提交前及接口返回的正文统一执行 HTML 白名单清洗。 */
184
+ export function sanitizeArticleHtml(html: string) {
185
+ if (!html.trim()) {
186
+ return ''
107
187
  }
108
188
 
109
- return {
110
- total,
111
- list: response.data.list.map(normalizeRecord),
112
- currentPage: toPositiveInteger(response.data.pageNum || currentPage, 'pageNum'),
113
- pageSize: toPositiveInteger(response.data.pageSize || pageSize, 'pageSize'),
189
+ const doc = new DOMParser().parseFromString(`<article>${html}</article>`, 'text/html')
190
+ const root = doc.body.firstElementChild
191
+
192
+ if (!root) {
193
+ return ''
114
194
  }
195
+
196
+ sanitizeChildren(root, doc)
197
+
198
+ return root.innerHTML.trim()
115
199
  }
116
200
 
117
- /** 根据 annouId 查询公告详情。 */
118
- export async function queryAnnouncementDetail(
119
- annouId: string,
120
- signal?: AbortSignal,
121
- ): Promise<AnnouncementDetailRecord> {
122
- const normalizedId = String(annouId ?? '').trim()
123
- if (!normalizedId) {
201
+ function normalizeAnnouncementId(value: string) {
202
+ const annouId = String(value ?? '').trim()
203
+
204
+ if (!annouId) {
124
205
  throw new Error('公告 annouId 不能为空')
125
206
  }
126
207
 
127
- const query = new URLSearchParams({ annouId: normalizedId })
128
- const response = await baseHttpClient.get<AnnouncementDetailResponse>(
129
- `/uaa/announcement/get/id?${query.toString()}`,
130
- { signal },
131
- )
208
+ return annouId
209
+ }
210
+
211
+ function normalizeArticlePayload(payload: ArticlePayload): ArticlePayload {
212
+ const title = String(payload.title ?? '').trim()
213
+ const content = sanitizeArticleHtml(String(payload.content ?? ''))
132
214
 
133
- if (response.code !== '0000') {
134
- throw new Error(response.message || '公告详情查询失败')
215
+ if (!title) {
216
+ throw new Error('公告标题不能为空')
135
217
  }
136
- if (!response.data || typeof response.data !== 'object' || Array.isArray(response.data)) {
137
- throw new Error('公告详情接口返回结构不正确')
218
+
219
+ if (title.length > MAX_TITLE_LENGTH) {
220
+ throw new Error(`公告标题不能超过 ${MAX_TITLE_LENGTH} 个字符`)
138
221
  }
139
222
 
140
- const listFields = ['orgList', 'roleList', 'userList'] as const
141
- for (const field of listFields) {
142
- if (response.data[field] !== undefined && !Array.isArray(response.data[field])) {
143
- throw new Error(`公告详情接口返回的 ${field} 无效`)
223
+ if (!extractTextFromHtml(content) && countArticleImages(content) === 0) {
224
+ throw new Error('公告正文不能为空')
225
+ }
226
+
227
+ validateArticleContent(content)
228
+
229
+ return { title, content }
230
+ }
231
+
232
+ function validateArticleContent(html: string) {
233
+ if (getUtf8Size(html) > MAX_ARTICLE_HTML_SIZE) {
234
+ throw new Error('公告正文总大小不能超过 20MB')
235
+ }
236
+
237
+ const doc = new DOMParser().parseFromString(html, 'text/html')
238
+ const images = Array.from(doc.querySelectorAll('img[src]'))
239
+
240
+ if (images.length > MAX_IMAGE_COUNT) {
241
+ throw new Error(`每篇公告最多插入 ${MAX_IMAGE_COUNT} 张图片`)
242
+ }
243
+
244
+ images.forEach((image) => {
245
+ const source = image.getAttribute('src') || ''
246
+ const match = source.match(/^data:image\/[a-z0-9.+-]+;base64,([\s\S]+)$/i)
247
+
248
+ if (match && getBase64ByteSize(match[1] || '') > MAX_IMAGE_SIZE) {
249
+ throw new Error('单张图片不能超过 5MB')
250
+ }
251
+ })
252
+ }
253
+
254
+ function buildAnnouncementPayload(payload: ArticlePayload, annouId = ''): AnnouncementPayload {
255
+ return {
256
+ annouTitle: payload.title,
257
+ annouConte: payload.content,
258
+ annouId,
259
+ ...DEFAULT_ANNOUNCEMENT_FIELDS,
260
+ }
261
+ }
262
+
263
+ function unwrapResponse(response: ApiResponse<unknown>, fallbackMessage: string) {
264
+ if (!isRecord(response)) {
265
+ throw new Error('公告接口返回结构不正确')
266
+ }
267
+
268
+ if (!isSuccessCode(response.code)) {
269
+ throw new Error(readResponseMessage(response) || fallbackMessage)
270
+ }
271
+
272
+ return response.data
273
+ }
274
+
275
+ function isSuccessCode(code: unknown) {
276
+ return code === 0 || code === '0' || code === '0000'
277
+ }
278
+
279
+ function readResponseMessage(response: RawRecord) {
280
+ return typeof response.message === 'string' ? response.message.trim() : ''
281
+ }
282
+
283
+ function extractRecords(data: unknown): RawRecord[] {
284
+ const candidates = [
285
+ data,
286
+ getValue(data, ['list']),
287
+ getValue(data, ['records']),
288
+ getValue(data, ['rows']),
289
+ getValue(data, ['resultList']),
290
+ getValue(data, ['content']),
291
+ getValue(data, ['body', 'list']),
292
+ getValue(data, ['body', 'records']),
293
+ getValue(data, ['body', 'rows']),
294
+ getValue(data, ['body', 'resultList']),
295
+ ]
296
+
297
+ for (const candidate of candidates) {
298
+ if (Array.isArray(candidate)) {
299
+ return candidate.filter(isRecord)
144
300
  }
145
301
  }
146
302
 
303
+ return []
304
+ }
305
+
306
+ function extractDetailRecord(data: unknown): RawRecord {
307
+ const records = extractRecords(data)
308
+
309
+ if (records.length > 0) {
310
+ return records[0]!
311
+ }
312
+
313
+ return isRecord(data) ? data : {}
314
+ }
315
+
316
+ function mapAnnouncementRecord(record: RawRecord, fallbackId = ''): Article {
317
+ const now = new Date().toISOString()
318
+ const id =
319
+ readString(record, ['annouId', 'announcementId', 'articleId', 'id', 'uuid']) || fallbackId
320
+ const title = readString(record, [
321
+ 'annouTitle',
322
+ 'announTitle',
323
+ 'announcementTitle',
324
+ 'title',
325
+ 'name',
326
+ 'subject',
327
+ ])
328
+ const content = readString(record, [
329
+ 'annouConte',
330
+ 'announContent',
331
+ 'announcementContent',
332
+ 'articleContent',
333
+ 'contentHtml',
334
+ 'htmlContent',
335
+ 'content',
336
+ ])
337
+ const createdAt =
338
+ readString(record, ['createTime', 'createdAt', 'publishTime', 'pubTime', 'gmtCreate']) || now
339
+ const updatedAt =
340
+ readString(record, ['updateTime', 'updatedAt', 'modifyTime', 'gmtModified']) || createdAt
341
+
147
342
  return {
148
- ...normalizeRecord(response.data),
149
- orgList: response.data.orgList ?? [],
150
- roleList: response.data.roleList ?? [],
151
- userList: response.data.userList ?? [],
343
+ id,
344
+ title: title || '未命名公告',
345
+ content: sanitizeArticleHtml(content),
346
+ author:
347
+ readString(record, ['author', 'publisherName', 'pubUserName', 'creatorName', 'createBy']) ||
348
+ '管理员',
349
+ createdAt: normalizeDate(createdAt),
350
+ updatedAt: normalizeDate(updatedAt),
351
+ }
352
+ }
353
+
354
+ function readString(record: RawRecord, keys: string[]) {
355
+ for (const key of keys) {
356
+ const value = record[key]
357
+
358
+ if (typeof value === 'string' && value.trim()) {
359
+ return value.trim()
360
+ }
361
+
362
+ if (typeof value === 'number') {
363
+ return String(value)
364
+ }
365
+ }
366
+
367
+ return ''
368
+ }
369
+
370
+ function getValue(value: unknown, path: string[]) {
371
+ return path.reduce<unknown>((current, key) => {
372
+ if (!isRecord(current)) {
373
+ return undefined
374
+ }
375
+
376
+ return current[key]
377
+ }, value)
378
+ }
379
+
380
+ function normalizeDate(value: string) {
381
+ if (/^\d{4}-\d{2}-\d{2}/.test(value)) {
382
+ return value
383
+ }
384
+
385
+ if (/^\d{14}$/.test(value)) {
386
+ return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}T${value.slice(8, 10)}:${value.slice(10, 12)}:${value.slice(12, 14)}`
387
+ }
388
+
389
+ if (/^\d{8}$/.test(value)) {
390
+ return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}T00:00:00`
391
+ }
392
+
393
+ return value
394
+ }
395
+
396
+ function isRecord(value: unknown): value is RawRecord {
397
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
398
+ }
399
+
400
+ function getUtf8Size(value: string) {
401
+ return new Blob([value]).size
402
+ }
403
+
404
+ function countArticleImages(html: string) {
405
+ if (!html.trim()) {
406
+ return 0
407
+ }
408
+
409
+ return new DOMParser().parseFromString(html, 'text/html').querySelectorAll('img[src]').length
410
+ }
411
+
412
+ function getBase64ByteSize(value: string) {
413
+ const base64 = normalizeBase64Payload(value)
414
+ const paddingLength = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0
415
+
416
+ return Math.max(0, Math.floor((base64.length * 3) / 4) - paddingLength)
417
+ }
418
+
419
+ function sanitizeChildren(parent: ParentNode, doc: Document) {
420
+ Array.from(parent.childNodes).forEach((child) => {
421
+ if (child.nodeType === Node.COMMENT_NODE) {
422
+ child.remove()
423
+ return
424
+ }
425
+
426
+ if (child.nodeType !== Node.ELEMENT_NODE) {
427
+ return
428
+ }
429
+
430
+ const element = child as HTMLElement
431
+
432
+ if (!ALLOWED_TAGS.has(element.tagName)) {
433
+ const fragment = doc.createDocumentFragment()
434
+
435
+ while (element.firstChild) {
436
+ fragment.appendChild(element.firstChild)
437
+ }
438
+
439
+ element.replaceWith(fragment)
440
+ sanitizeChildren(parent, doc)
441
+ return
442
+ }
443
+
444
+ sanitizeAttributes(element)
445
+ sanitizeChildren(element, doc)
446
+ })
447
+ }
448
+
449
+ function sanitizeAttributes(element: HTMLElement) {
450
+ Array.from(element.attributes).forEach((attribute) => {
451
+ const name = attribute.name.toLowerCase()
452
+
453
+ if (element.tagName === 'IMG') {
454
+ sanitizeImageAttribute(element, attribute)
455
+ return
456
+ }
457
+
458
+ if (element.tagName === 'A' && name === 'href') {
459
+ if (!isSafeHref(attribute.value)) {
460
+ element.removeAttribute(attribute.name)
461
+ return
462
+ }
463
+
464
+ element.setAttribute('target', '_blank')
465
+ element.setAttribute('rel', 'noopener noreferrer')
466
+ return
467
+ }
468
+
469
+ if (element.tagName === 'A' && (name === 'target' || name === 'rel')) {
470
+ return
471
+ }
472
+
473
+ if (element.tagName === 'CODE' && name === 'class') {
474
+ const languageClass = normalizeCodeLanguageClass(attribute.value)
475
+
476
+ if (languageClass) {
477
+ element.setAttribute('class', languageClass)
478
+ return
479
+ }
480
+ }
481
+
482
+ if (element.tagName === 'CODE' && name === 'data-language') {
483
+ const language = normalizeCodeLanguage(attribute.value)
484
+
485
+ if (language) {
486
+ element.setAttribute('data-language', language)
487
+ return
488
+ }
489
+ }
490
+
491
+ element.removeAttribute(attribute.name)
492
+ })
493
+
494
+ if (element.tagName === 'IMG') {
495
+ finalizeImageElement(element)
496
+ }
497
+ }
498
+
499
+ function sanitizeImageAttribute(element: HTMLElement, attribute: Attr) {
500
+ const name = attribute.name.toLowerCase()
501
+
502
+ if (name === 'src') {
503
+ const src = normalizeImageSource(attribute.value)
504
+
505
+ if (src) {
506
+ element.setAttribute('src', src)
507
+ return
508
+ }
509
+ }
510
+
511
+ if (name === 'alt' || name === 'title') {
512
+ element.setAttribute(name, attribute.value.trim().slice(0, 120))
513
+ return
514
+ }
515
+
516
+ if (name === 'width' || name === 'height') {
517
+ const dimension = normalizeImageDimension(attribute.value)
518
+
519
+ if (dimension) {
520
+ element.setAttribute(name, dimension)
521
+ return
522
+ }
523
+ }
524
+
525
+ element.removeAttribute(attribute.name)
526
+ }
527
+
528
+ function finalizeImageElement(element: HTMLElement) {
529
+ if (!element.getAttribute('src')) {
530
+ element.remove()
531
+ return
532
+ }
533
+
534
+ if (!element.hasAttribute('alt')) {
535
+ element.setAttribute('alt', '')
536
+ }
537
+
538
+ element.setAttribute('loading', 'lazy')
539
+ element.setAttribute('decoding', 'async')
540
+ }
541
+
542
+ function normalizeImageSource(value: string) {
543
+ const source = value.trim()
544
+
545
+ if (!source) {
546
+ return ''
547
+ }
548
+
549
+ const dataImageSource = normalizeDataImageSource(source)
550
+
551
+ if (dataImageSource) {
552
+ return dataImageSource
553
+ }
554
+
555
+ const bareBase64Source = normalizeBareBase64ImageSource(source)
556
+
557
+ if (bareBase64Source) {
558
+ return bareBase64Source
559
+ }
560
+
561
+ try {
562
+ const url = new URL(source, window.location.origin)
563
+
564
+ return ['http:', 'https:'].includes(url.protocol) ? source : ''
565
+ } catch {
566
+ return ''
567
+ }
568
+ }
569
+
570
+ function normalizeDataImageSource(value: string) {
571
+ const match = value.match(/^data:(image\/[a-z0-9.+-]+);base64,([\s\S]+)$/i)
572
+
573
+ if (!match) {
574
+ return ''
575
+ }
576
+
577
+ const mime = normalizeImageMimeType(match[1] || '')
578
+ const base64 = normalizeBase64Payload(match[2] || '')
579
+
580
+ if (!mime || !isBase64Payload(base64)) {
581
+ return ''
582
+ }
583
+
584
+ return `data:${mime};base64,${base64}`
585
+ }
586
+
587
+ function normalizeBareBase64ImageSource(value: string) {
588
+ const base64 = normalizeBase64Payload(value)
589
+ const mime = getBase64ImageMimeType(base64)
590
+
591
+ if (!mime || !isBase64Payload(base64)) {
592
+ return ''
593
+ }
594
+
595
+ return `data:${mime};base64,${base64}`
596
+ }
597
+
598
+ function normalizeImageMimeType(value: string) {
599
+ const mime = value.trim().toLowerCase().replace(/^image\/jpg$/, 'image/jpeg')
600
+
601
+ return ALLOWED_IMAGE_MIME_TYPES.has(mime) ? mime : ''
602
+ }
603
+
604
+ function normalizeBase64Payload(value: string) {
605
+ return value.replace(/\s+/g, '')
606
+ }
607
+
608
+ function isBase64Payload(value: string) {
609
+ return Boolean(value) && value.length % 4 !== 1 && /^[A-Za-z0-9+/]+={0,2}$/.test(value)
610
+ }
611
+
612
+ function getBase64ImageMimeType(value: string) {
613
+ return BASE64_IMAGE_SIGNATURES.find(({ pattern }) => pattern.test(value))?.mime || ''
614
+ }
615
+
616
+ function normalizeImageDimension(value: string) {
617
+ const dimension = Number.parseInt(value, 10)
618
+
619
+ if (!Number.isFinite(dimension) || dimension <= 0 || dimension > 4096) {
620
+ return ''
621
+ }
622
+
623
+ return String(dimension)
624
+ }
625
+
626
+ function normalizeCodeLanguageClass(value: string) {
627
+ const language = value
628
+ .split(/\s+/)
629
+ .find((className) => className.startsWith('language-'))
630
+ ?.replace(/^language-/, '')
631
+
632
+ if (!language) {
633
+ return ''
634
+ }
635
+
636
+ return `language-${normalizeCodeLanguage(language)}`
637
+ }
638
+
639
+ function normalizeCodeLanguage(value: string) {
640
+ return value.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 24)
641
+ }
642
+
643
+ function isSafeHref(value: string) {
644
+ const href = value.trim()
645
+
646
+ if (href.startsWith('#')) {
647
+ return true
648
+ }
649
+
650
+ try {
651
+ const url = new URL(href, window.location.origin)
652
+
653
+ return ['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol)
654
+ } catch {
655
+ return false
152
656
  }
153
657
  }
@@ -26,6 +26,7 @@ export type TamResponse<T> = {
26
26
  }
27
27
 
28
28
  type ErrorResponse = {
29
+ message?: string
29
30
  error?: {
30
31
  message?: string
31
32
  }
@@ -96,7 +97,7 @@ function resolveUrl(path: string) {
96
97
  function getErrorMessage(payload: unknown, fallback: string) {
97
98
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return fallback
98
99
  const response = payload as ErrorResponse
99
- return response.head?.retMsg || response.error?.message || fallback
100
+ return response.head?.retMsg || response.error?.message || response.message || fallback
100
101
  }
101
102
 
102
103
  async function request<T>(
@@ -1,33 +1,24 @@
1
- import baseHttpClient from '@/utils/baseHttpClient'
2
- import { queryAnnouncementDetail, queryAnnouncements } from '@/api/announcement'
1
+ import {
2
+ createArticle,
3
+ getArticleDetail,
4
+ queryArticles,
5
+ updateArticle,
6
+ } from '@/api/announcement'
3
7
 
4
- import type {
5
- NoticeDetail,
6
- NoticeListQuery,
7
- NoticeListResponse,
8
- NoticePayload,
9
- } from './types'
8
+ import type { NoticePayload } from './types'
10
9
 
11
- export async function getNoticeList(query: NoticeListQuery): Promise<NoticeListResponse> {
12
- const response = await queryAnnouncements(query.currentPage, query.pageSize)
13
- return {
14
- resultList: response.list,
15
- totalCount: response.total,
16
- }
10
+ export function getNoticeList() {
11
+ return queryArticles()
17
12
  }
18
13
 
19
14
  export function getNoticeDetail(id: number | string) {
20
- return queryAnnouncementDetail(String(id))
15
+ return getArticleDetail(String(id))
21
16
  }
22
17
 
23
18
  export function createNotice(payload: NoticePayload) {
24
- return baseHttpClient.post<NoticeDetail>('/notices', payload)
19
+ return createArticle(payload)
25
20
  }
26
21
 
27
22
  export function updateNotice(id: number | string, payload: NoticePayload) {
28
- return baseHttpClient.put<NoticeDetail>(`/notices/${id}`, payload)
29
- }
30
-
31
- export function deleteNotice(id: number | string) {
32
- return baseHttpClient.delete<{ success: boolean; message: string }>(`/notices/${id}`)
23
+ return updateArticle(String(id), payload)
33
24
  }
@@ -23,39 +23,14 @@ const pageTitle = computed(() => (isEdit.value ? '编辑公告' : '新增公告'
23
23
 
24
24
  const form = reactive({
25
25
  title: '',
26
- publishTime: createDefaultPublishTime(),
27
- pinned: false,
28
26
  contentHtml: '',
29
27
  })
30
28
 
31
29
  const rules: FormRules = {
32
30
  title: [
33
31
  { required: true, message: '请输入公告标题', trigger: 'blur' },
34
- { max: 300, message: '公告标题不能超过 300 个字符', trigger: 'blur' },
32
+ { max: 40, message: '公告标题不能超过 40 个字符', trigger: 'blur' },
35
33
  ],
36
- publishTime: [
37
- { required: true, message: '请选择发布时间', trigger: 'change' },
38
- ],
39
- }
40
-
41
- function pad(value: number) {
42
- return String(value).padStart(2, '0')
43
- }
44
-
45
- function createDefaultPublishTime() {
46
- const now = new Date()
47
- return [
48
- now.getFullYear(),
49
- '-',
50
- pad(now.getMonth() + 1),
51
- '-',
52
- pad(now.getDate()),
53
- ' ',
54
- pad(now.getHours()),
55
- ':',
56
- pad(now.getMinutes()),
57
- ':00',
58
- ].join('')
59
34
  }
60
35
 
61
36
  function hasContent(html: string) {
@@ -69,10 +44,8 @@ async function loadDetail() {
69
44
  pageLoading.value = true
70
45
  try {
71
46
  const detail = await getNoticeDetail(noticeId.value)
72
- form.title = detail.annouTitle
73
- form.publishTime = detail.createTm || createDefaultPublishTime()
74
- form.pinned = detail.topFlag === '1'
75
- form.contentHtml = detail.annouConte
47
+ form.title = detail.title
48
+ form.contentHtml = detail.content
76
49
  } catch (error) {
77
50
  ElMessage.error(error instanceof Error ? error.message : '公告详情加载失败')
78
51
  } finally {
@@ -98,10 +71,7 @@ async function handleSubmit() {
98
71
  try {
99
72
  const payload = {
100
73
  title: form.title.trim(),
101
- date: form.publishTime.slice(0, 10),
102
- publishTime: form.publishTime,
103
- pinned: form.pinned,
104
- contentHtml: form.contentHtml,
74
+ content: form.contentHtml,
105
75
  }
106
76
 
107
77
  if (noticeId.value) {
@@ -153,7 +123,7 @@ onMounted(loadDetail)
153
123
  <span class="card-step">01</span>
154
124
  <div>
155
125
  <strong>基本信息</strong>
156
- <small>设置公告标题与展示规则</small>
126
+ <small>公告标题最多输入 40 个字符</small>
157
127
  </div>
158
128
  </div>
159
129
  </template>
@@ -162,32 +132,12 @@ onMounted(loadDetail)
162
132
  <el-form-item label="公告标题" prop="title" class="title-field">
163
133
  <el-input
164
134
  v-model="form.title"
165
- maxlength="300"
135
+ maxlength="40"
166
136
  show-word-limit
167
137
  clearable
168
138
  placeholder="请输入公告标题"
169
139
  />
170
140
  </el-form-item>
171
- <el-form-item label="发布时间" prop="publishTime">
172
- <el-date-picker
173
- v-model="form.publishTime"
174
- type="datetime"
175
- value-format="YYYY-MM-DD HH:mm:ss"
176
- placeholder="请选择发布时间"
177
- style="width: 100%"
178
- />
179
- </el-form-item>
180
- <el-form-item label="置顶设置">
181
- <div class="pinned-setting">
182
- <el-switch
183
- v-model="form.pinned"
184
- inline-prompt
185
- active-text="是"
186
- inactive-text="否"
187
- />
188
- <span>{{ form.pinned ? '该公告将在列表顶部优先展示' : '按发布时间参与列表排序' }}</span>
189
- </div>
190
- </el-form-item>
191
141
  </div>
192
142
  </el-card>
193
143
 
@@ -340,22 +290,11 @@ onMounted(loadDetail)
340
290
  }
341
291
 
342
292
  .basic-form-grid {
343
- display: grid;
344
- grid-template-columns: minmax(0, 1fr) 260px;
345
- column-gap: 24px;
293
+ max-width: 760px;
346
294
  }
347
295
 
348
296
  .title-field {
349
- grid-column: 1 / -1;
350
- }
351
-
352
- .pinned-setting {
353
- display: flex;
354
- align-items: center;
355
- gap: 12px;
356
- min-height: 32px;
357
- color: #8491a5;
358
- font-size: 13px;
297
+ width: 100%;
359
298
  }
360
299
 
361
300
  .content-card :deep(.el-card__body) {
@@ -391,13 +330,5 @@ onMounted(loadDetail)
391
330
  padding: 16px 16px 92px;
392
331
  }
393
332
 
394
- .basic-form-grid {
395
- grid-template-columns: 1fr;
396
- }
397
-
398
- .title-field {
399
- grid-column: auto;
400
- }
401
-
402
333
  }
403
334
  </style>
@@ -1,32 +1,52 @@
1
1
  <script setup lang="ts">
2
- import { onMounted, reactive, ref } from 'vue'
2
+ import { computed, onMounted, reactive, ref, watch } from 'vue'
3
3
  import { useRouter } from 'vue-router'
4
- import { Delete, EditPen, Plus, Refresh } from '@element-plus/icons-vue'
5
- import { ElMessage, ElMessageBox } from 'element-plus'
4
+ import { EditPen, Plus, Refresh, Search } from '@element-plus/icons-vue'
5
+ import { ElMessage } from 'element-plus'
6
6
 
7
- import { deleteNotice, getNoticeList } from './api'
7
+ import { extractTextFromHtml, formatArticleDate } from '@/api/announcement'
8
+ import { getNoticeList } from './api'
8
9
  import type { NoticeListItem } from './types'
9
10
 
10
11
  const router = useRouter()
11
12
  const loading = ref(false)
12
- const deletingId = ref<string>()
13
+ const keyword = ref('')
13
14
  const tableData = ref<NoticeListItem[]>([])
14
- const total = ref(0)
15
15
 
16
16
  const pagination = reactive({
17
17
  currentPage: 1,
18
18
  pageSize: 10,
19
19
  })
20
20
 
21
+ const filteredTableData = computed(() => {
22
+ const searchText = keyword.value.trim().toLocaleLowerCase('zh-CN')
23
+
24
+ if (!searchText) {
25
+ return tableData.value
26
+ }
27
+
28
+ return tableData.value.filter((item) => {
29
+ const contentText = extractTextFromHtml(item.content)
30
+ const searchableText = `${item.title} ${item.author} ${contentText}`
31
+
32
+ return searchableText.toLocaleLowerCase('zh-CN').includes(searchText)
33
+ })
34
+ })
35
+
36
+ const total = computed(() => filteredTableData.value.length)
37
+ const pagedTableData = computed(() => {
38
+ const start = (pagination.currentPage - 1) * pagination.pageSize
39
+
40
+ return filteredTableData.value.slice(start, start + pagination.pageSize)
41
+ })
42
+ const emptyText = computed(() => (keyword.value.trim() ? '未找到匹配公告' : '暂无公告数据'))
43
+
21
44
  async function loadList() {
22
45
  loading.value = true
23
46
  try {
24
- const response = await getNoticeList({
25
- currentPage: pagination.currentPage,
26
- pageSize: pagination.pageSize,
27
- })
28
- tableData.value = response.resultList
29
- total.value = response.totalCount
47
+ tableData.value = await getNoticeList()
48
+ const pageCount = Math.max(1, Math.ceil(total.value / pagination.pageSize))
49
+ pagination.currentPage = Math.min(pagination.currentPage, pageCount)
30
50
  } catch (error) {
31
51
  ElMessage.error(error instanceof Error ? error.message : '公告列表加载失败')
32
52
  } finally {
@@ -41,43 +61,18 @@ function handleCreate() {
41
61
  function handleEdit(row: NoticeListItem) {
42
62
  void router.push({
43
63
  name: 'noticeManagementEdit',
44
- params: { id: row.annouId },
64
+ params: { id: row.id },
45
65
  })
46
66
  }
47
67
 
48
- async function handleDelete(row: NoticeListItem) {
49
- try {
50
- await ElMessageBox.confirm(
51
- `删除后无法恢复,确认删除公告“${row.annouTitle}”吗?`,
52
- '删除公告',
53
- {
54
- confirmButtonText: '确认删除',
55
- cancelButtonText: '取消',
56
- type: 'warning',
57
- },
58
- )
59
- deletingId.value = row.annouId
60
- await deleteNotice(row.annouId)
61
- ElMessage.success('公告删除成功')
62
-
63
- if (tableData.value.length === 1 && pagination.currentPage > 1) {
64
- pagination.currentPage -= 1
65
- }
66
- await loadList()
67
- } catch (error) {
68
- if (error !== 'cancel' && error !== 'close') {
69
- ElMessage.error(error instanceof Error ? error.message : '公告删除失败')
70
- }
71
- } finally {
72
- deletingId.value = undefined
73
- }
74
- }
75
-
76
68
  function handlePageSizeChange() {
77
69
  pagination.currentPage = 1
78
- void loadList()
79
70
  }
80
71
 
72
+ watch(keyword, () => {
73
+ pagination.currentPage = 1
74
+ })
75
+
81
76
  onMounted(loadList)
82
77
  </script>
83
78
 
@@ -87,7 +82,7 @@ onMounted(loadList)
87
82
  <div>
88
83
  <p class="heading-eyebrow">CONTENT CENTER</p>
89
84
  <h1>公告管理</h1>
90
- <p class="heading-description">统一维护平台通知内容、发布时间与置顶状态</p>
85
+ <p class="heading-description">统一维护公告标题、正文内容与发布信息</p>
91
86
  </div>
92
87
  <el-button type="primary" :icon="Plus" @click="handleCreate">新增公告</el-button>
93
88
  </section>
@@ -97,57 +92,52 @@ onMounted(loadList)
97
92
  <div class="table-card__header">
98
93
  <div>
99
94
  <span class="table-card__title">公告列表</span>
100
- <span class="table-card__count">共 {{ total }} 条</span>
95
+ <span class="table-card__count">共 {{ tableData.length }} 条</span>
96
+ </div>
97
+ <div class="table-card__actions">
98
+ <el-input
99
+ v-model="keyword"
100
+ class="notice-search"
101
+ :prefix-icon="Search"
102
+ clearable
103
+ placeholder="搜索标题、正文或作者"
104
+ />
105
+ <el-button :icon="Refresh" :loading="loading" @click="loadList">刷新</el-button>
101
106
  </div>
102
- <el-button :icon="Refresh" :loading="loading" @click="loadList">刷新</el-button>
103
107
  </div>
104
108
  </template>
105
109
 
106
110
  <el-table
107
111
  v-loading="loading"
108
- :data="tableData"
109
- row-key="annouId"
112
+ :data="pagedTableData"
113
+ row-key="id"
110
114
  class="notice-table"
111
- empty-text="暂无公告数据"
115
+ :empty-text="emptyText"
112
116
  >
113
117
  <el-table-column type="index" label="序号" width="72" align="center">
114
118
  <template #default="{ $index }">
115
119
  {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
116
120
  </template>
117
121
  </el-table-column>
118
- <el-table-column prop="annouTitle" label="公告标题" min-width="360" show-overflow-tooltip>
122
+ <el-table-column prop="title" label="公告标题" min-width="360" show-overflow-tooltip>
119
123
  <template #default="{ row }">
120
- <div class="notice-title-cell">
121
- <span v-if="row.topFlag === '1'" class="pinned-mark">置顶</span>
122
- <span class="notice-title-text">{{ row.annouTitle }}</span>
123
- </div>
124
+ <span class="notice-title-text">{{ row.title }}</span>
124
125
  </template>
125
126
  </el-table-column>
126
- <el-table-column prop="annouSts" label="公告状态" width="110" align="center">
127
+ <el-table-column prop="author" label="发布人" width="150" show-overflow-tooltip />
128
+ <el-table-column label="创建时间" width="190">
127
129
  <template #default="{ row }">
128
- <el-tag :type="row.annouSts === '0' ? 'success' : 'info'" effect="light">
129
- {{ row.annouSts }}
130
- </el-tag>
130
+ {{ formatArticleDate(row.createdAt) || '—' }}
131
131
  </template>
132
132
  </el-table-column>
133
- <el-table-column label="发布时间" width="180">
133
+ <el-table-column label="更新时间" width="190">
134
134
  <template #default="{ row }">
135
- {{ row.createTm || '—' }}
135
+ {{ formatArticleDate(row.updatedAt) || '—' }}
136
136
  </template>
137
137
  </el-table-column>
138
- <el-table-column prop="createUserId" label="创建人" width="140" show-overflow-tooltip />
139
- <el-table-column label="操作" width="168" fixed="right" align="center">
138
+ <el-table-column label="操作" width="96" fixed="right" align="center">
140
139
  <template #default="{ row }">
141
140
  <el-button link type="primary" :icon="EditPen" @click="handleEdit(row)">编辑</el-button>
142
- <el-button
143
- link
144
- type="danger"
145
- :icon="Delete"
146
- :loading="deletingId === row.annouId"
147
- @click="handleDelete(row)"
148
- >
149
- 删除
150
- </el-button>
151
141
  </template>
152
142
  </el-table-column>
153
143
  </el-table>
@@ -160,7 +150,6 @@ onMounted(loadList)
160
150
  :total="total"
161
151
  background
162
152
  layout="total, sizes, prev, pager, next, jumper"
163
- @current-change="loadList"
164
153
  @size-change="handlePageSizeChange"
165
154
  />
166
155
  </div>
@@ -223,10 +212,23 @@ onMounted(loadList)
223
212
  padding: 0 20px 18px;
224
213
  }
225
214
 
226
- .table-card__header {
215
+ .table-card__header,
216
+ .table-card__actions {
227
217
  display: flex;
228
218
  align-items: center;
219
+ }
220
+
221
+ .table-card__header {
229
222
  justify-content: space-between;
223
+ gap: 16px;
224
+ }
225
+
226
+ .table-card__actions {
227
+ gap: 10px;
228
+ }
229
+
230
+ .notice-search {
231
+ width: 260px;
230
232
  }
231
233
 
232
234
  .table-card__title {
@@ -241,34 +243,12 @@ onMounted(loadList)
241
243
  font-size: 13px;
242
244
  }
243
245
 
244
- .table-card__hint {
245
- color: #a0a9b8;
246
- font-size: 12px;
247
- }
248
-
249
246
  .notice-table {
250
247
  --el-table-header-bg-color: #f8fafc;
251
248
  --el-table-header-text-color: #667085;
252
249
  --el-table-row-hover-bg-color: #f6f9fe;
253
250
  }
254
251
 
255
- .notice-title-cell {
256
- display: flex;
257
- align-items: center;
258
- min-width: 0;
259
- gap: 10px;
260
- }
261
-
262
- .pinned-mark {
263
- flex: 0 0 auto;
264
- padding: 2px 7px;
265
- border-radius: 4px;
266
- color: #e5484d;
267
- background: #fff0f0;
268
- font-size: 12px;
269
- line-height: 20px;
270
- }
271
-
272
252
  .notice-title-text {
273
253
  overflow: hidden;
274
254
  color: #273247;
@@ -292,8 +272,14 @@ onMounted(loadList)
292
272
  align-items: flex-end;
293
273
  }
294
274
 
295
- .table-card__hint {
296
- display: none;
275
+ .table-card__header {
276
+ align-items: flex-start;
277
+ flex-direction: column;
278
+ }
279
+
280
+ .table-card__actions,
281
+ .notice-search {
282
+ width: 100%;
297
283
  }
298
284
  }
299
285
  </style>
@@ -1,43 +1,4 @@
1
- export type NoticeListItem = {
2
- annouId: string
3
- orgNo: string | null
4
- annouTitle: string
5
- annouSts: string
6
- topFlag: string
7
- createUserId: string | null
8
- updateUserId: string | null
9
- createTm: string
10
- updateTm: string
11
- annouLimitFlag: string
12
- annouConte: string
13
- effDt: string | null
14
- expireDt: string | null
15
- }
1
+ import type { Article, ArticlePayload } from '@/api/announcement'
16
2
 
17
- export type NoticeDetail = {
18
- id: number | string
19
- title: string
20
- date: string
21
- publishTime: string
22
- views: number
23
- pinned: boolean
24
- contentHtml: string
25
- }
26
-
27
- export type NoticeListQuery = {
28
- currentPage: number
29
- pageSize: number
30
- }
31
-
32
- export type NoticeListResponse = {
33
- resultList: NoticeListItem[]
34
- totalCount: number
35
- }
36
-
37
- export type NoticePayload = {
38
- title: string
39
- date: string
40
- publishTime: string
41
- pinned: boolean
42
- contentHtml: string
43
- }
3
+ export type NoticeListItem = Article
4
+ export type NoticePayload = ArticlePayload