smart-field-extractor.js
26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
/**
* 智能字段提取器
*
* @description 从保险产品文档中智能提取配置字段,支持中英文、繁简体
* @module scripts/smart-field-extractor
* @author Claude Code
* @created 2026-02-14
*/
/**
* 保险缴费年期匹配模式
*
* @description 用于识别各种格式的缴费年期选项
* @constant {Object}
*/
const PAYMENT_PERIOD_PATTERNS = {
// 一次性缴费关键词
singlePayment: ['整付', '趸交', '躉繳', 'lump sum', 'single'],
// 数字+年格式(3年、5年、10年等)
yearlyPattern: /^(\d+)\s*年$/,
// 至X岁格式
untilAgePattern: /^至?\s*(\d+)\s*岁$/,
// 列表项格式(- 3年、• 5年等)
listItemPattern: /^[-•·]\s*(.+)$/
}
/**
* 检查是否为有效的缴费年期选项
*
* @param {string} text - 待检查文本
* @returns {boolean} 是否为有效缴费年期
*/
const isValidPaymentPeriod = (text) => {
const trimmed = text.trim()
// 排除无效关键字
if (trimmed.includes('投保') || trimmed.includes('年龄') || trimmed.includes('年齡')) {
return false
}
// 1. 匹配 "X年" 格式
if (PAYMENT_PERIOD_PATTERNS.yearlyPattern.test(trimmed)) {
return true
}
// 2. 匹配 "至X岁" 格式
if (PAYMENT_PERIOD_PATTERNS.untilAgePattern.test(trimmed)) {
return true
}
// 3. 匹配一次性缴费关键词
if (PAYMENT_PERIOD_PATTERNS.singlePayment.some(kw =>
trimmed.toLowerCase() === kw.toLowerCase()
)) {
return true
}
// 4. 匹配列表项格式(提取内容后递归检查)
const listItemMatch = trimmed.match(PAYMENT_PERIOD_PATTERNS.listItemPattern)
if (listItemMatch) {
return isValidPaymentPeriod(listItemMatch[1])
}
// 5. 通用匹配:包含"年"或"岁"或"交"的短文本(2-10字符)
if (trimmed.length >= 2 && trimmed.length <= 10) {
if (/年|岁|交|付/.test(trimmed)) {
return true
}
}
return false
}
/**
* 标准化缴费年期选项
*
* @param {string} text - 原始文本
* @returns {string} 标准化后的文本
*/
const normalizePaymentPeriod = (text) => {
const trimmed = text.trim()
// 标准化一次性缴费
if (PAYMENT_PERIOD_PATTERNS.singlePayment.some(kw =>
trimmed.toLowerCase() === kw.toLowerCase()
)) {
return '整付'
}
// 标准化 "X年" 格式
const yearlyMatch = trimmed.match(PAYMENT_PERIOD_PATTERNS.yearlyPattern)
if (yearlyMatch) {
return `${yearlyMatch[1]}年`
}
// 标准化 "至X岁" 格式
const ageMatch = trimmed.match(PAYMENT_PERIOD_PATTERNS.untilAgePattern)
if (ageMatch) {
return `至${ageMatch[1]}岁`
}
// 处理列表项格式
const listItemMatch = trimmed.match(PAYMENT_PERIOD_PATTERNS.listItemPattern)
if (listItemMatch) {
return normalizePaymentPeriod(listItemMatch[1])
}
return trimmed
}
/**
* 字段提取规则配置
*
* @description 定义每个字段的匹配规则、优先级和默认值
*/
const FIELD_RULES = {
// 产品名称
product_name: {
priority: 1,
patterns: [
/产品名称[::]\s*([^\n]+)/,
/计划书名称[::]\s*([^\n]+)/,
/Product\s+Name[::]\s*([^\n]+)/i,
/^#\s+(.+)$/m, // Markdown 标题
// 新增:识别包含"计划"的标题行(如 "LV3 长宁終身壽險計劃3")
// 格式:产品代码 + 中文产品名(包含"計劃/计划")
/^[A-Z]{2,4}\d?\s*[-::]?\s*([^\n]*(?:計劃|计划)[^\n]*)/m,
// 纯产品名称(包含"計劃/计划")- 通常为计划书名称
/^([^\n]{2,30}?(?:計劃|计划)[^\n]*)/m
],
fallback: null, // 必填,无默认值
required: true,
postProcess: (value) => {
// 处理正则匹配结果(数组)
if (Array.isArray(value) && value.length > 1) {
let name = value[1] || value[0] || ''
// 移除产品代码前缀
name = name.replace(/^[A-Z]{2,4}\d?\s*[-::]?\s*/, '')
// 移除后缀说明(如 "- 性別, 年齡, 出生年月日")
name = name.split(/[-—::]/)[0].trim()
return name || null
}
return value
}
},
// 产品类型(保险类别)
product_type: {
priority: 2,
patterns: [
// 从内容推断
{
type: 'content_match',
rules: [
// 储蓄型产品(新增"储蓄产品"关键字)
{ keywords: ['储蓄产品', '储蓄型', '储蓄', 'saving', '传承', '家传', '红利', '提取'], value: 'savings' },
// 重疾型产品
{ keywords: ['重疾', 'critical', '守护', '严重疾病'], value: 'critical-illness' },
// 人寿型产品
{ keywords: ['人寿', 'life', '创富', '身故保障', '壽險', '壽险'], value: 'life-insurance' }
]
},
// 新增:从标题行推断(如 "LV3 长宁終身壽險計劃3" 中的"壽險")
{
type: 'title_match',
rules: [
{ pattern: /終身壽險|終身寿险|壽險計劃|寿险计划/, value: 'life-insurance' },
{ pattern: /儲蓄計劃|储蓄计划|儲蓄產品|储蓄产品/, value: 'savings' },
{ pattern: /重疾|嚴重疾病/, value: 'critical-illness' }
]
}
],
fallback: 'savings',
required: true
},
// 币种
currency: {
priority: 3,
patterns: [
// 统计货币符号出现次数
{
type: 'count_match',
rules: [
{ pattern: /\$/g, value: 'USD' },
{ pattern: /HK\$/g, value: 'HKD' },
{ pattern: /¥|人民币/g, value: 'CNY' },
{ pattern: /€/g, value: 'EUR' }
]
},
/币种[::]\s*(USD|CNY|HKD|EUR)/i,
/Currency[::]\s*(USD|CNY|HKD|EUR)/i
],
fallback: 'USD',
required: true
},
// 缴费年期
payment_periods: {
priority: 4,
patterns: [
// 匹配 "年繳保費繳費年期" 或 "缴费年期" 后面的列表
// 策略:使用通用匹配函数识别各种格式的缴费年期选项
{
type: 'smart_list_extract',
startPattern: /(?:年繳保費)?繳費年期[::\s]*\n/,
endKeywords: ['提取', '保險期間', '保险期间', '投保年龄', '投保年齡', '選是', '選項', 'GC宏', 'FA宏', 'LV2'],
itemFilter: (line) => isValidPaymentPeriod(line)
}
],
fallback: ['整付', '3年', '5年'],
required: true,
postProcess: (values) => {
// 过滤并标准化
const normalized = values
.map(v => normalizePaymentPeriod(v))
.filter(v => v && isValidPaymentPeriod(v))
// 去重、排序(整付放最前,其他按数字排序)
return [...new Set(normalized)].sort((a, b) => {
if (a === '整付') return -1
if (b === '整付') return 1
// 提取数字进行排序
const numA = parseInt(a.match(/\d+/)?.[0] || '999')
const numB = parseInt(b.match(/\d+/)?.[0] || '999')
return numA - numB
})
}
},
// 年龄范围
age_range: {
priority: 5,
patterns: [
// 匹配 "0-75岁" 格式
{
type: 'range_extract',
pattern: /(\d+)\s*[-~至]\s*(\d+)\s*岁?/
},
// 匹配 "投保年龄:0-75岁" 格式
/投保年龄[::]\s*(\d+)\s*[-~至]\s*(\d+)\s*岁?/,
/年龄范围[::]\s*(\d+)\s*[-~至]\s*(\d+)\s*岁?/
],
fallback: { min: 0, max: 75 },
required: true,
postProcess: (match) => {
if (match && typeof match === 'object' && match.min !== undefined) {
return match
}
if (Array.isArray(match) && match.length >= 2) {
return { min: parseInt(match[1]), max: parseInt(match[2]) }
}
return null
}
},
// 保险期间
insurance_period: {
priority: 6,
patterns: [
/保險期間[::]\s*([^\n]+)/,
/保险期间[::]\s*([^\n]+)/,
/Insurance\s+Period[::]\s*([^\n]+)/i,
/保障期间[::]\s*([^\n]+)/
],
fallback: '终身',
required: true,
postProcess: (value) => {
// 处理正则匹配结果(数组)或直接字符串
let str = value
if (Array.isArray(value)) {
str = value[1] || value[0] || ''
}
if (!str || typeof str !== 'string') return '终身'
const normalized = str.trim()
// 标准化常见表述
if (normalized.includes('终身') || normalized.includes('終身') || normalized.toLowerCase().includes('whole life')) {
return '终身'
}
return normalized
}
},
// 提取方式(仅储蓄类)
withdrawal_modes: {
priority: 7,
patterns: [
{
type: 'list_extract',
pattern: /提取选项[::]\s*([^\n]+)/,
itemPattern: /指定提取金额|最高固定提取金额/g
},
/提取方式[::]\s*([^\n]+)/
],
fallback: ['年龄指定金额', '最高固定金额'],
required: false,
productType: ['savings'],
postProcess: (values) => {
// 处理正则匹配结果(数组,第一个元素是完整匹配,第二个是捕获组)
if (Array.isArray(values) && values.length > 1 && typeof values[1] === 'string') {
values = values[1]
}
if (typeof values === 'string') {
// 从单行文本中提取
const modes = []
if (values.includes('指定提取金额')) modes.push('指定提取金额')
if (values.includes('最高固定提取金额')) modes.push('最高固定提取金额')
return modes.length > 0 ? modes : ['年龄指定金额', '最高固定金额']
}
return Array.isArray(values) ? values : ['年龄指定金额', '最高固定金额']
}
},
// 提取期(仅储蓄类)
withdrawal_periods: {
priority: 8,
patterns: [
{
type: 'list_extract',
pattern: /提取期[((]年[))][::]\s*([\s\S]*?)(?=\n\n|\n\n|$)/,
itemPattern: /^\s*[-•·]\s*(\d+\s*年)|^\s*(\d+)\s*年\s*$/gm
}
],
fallback: ['1年', '3年', '5年', '10年'],
required: false,
productType: ['savings'],
postProcess: (values) => {
const normalized = values.map(v => {
const match = v.match(/(\d+)\s*年/)
return match ? `${match[1]}年` : v.trim()
})
return [...new Set(normalized)].sort((a, b) => parseInt(a) - parseInt(b))
}
}
}
/**
* 从文本中提取字段值
*
* @param {string} content - 文档内容
* @param {string} fieldName - 字段名称
* @returns {{value: any, matched: boolean, pattern: string|null}} 提取结果
*/
function extractField(content, fieldName) {
const rule = FIELD_RULES[fieldName]
if (!rule) {
return { value: null, matched: false, pattern: null }
}
// 尝试每个匹配模式
for (const pattern of rule.patterns) {
let match = null
let patternDesc = ''
if (typeof pattern === 'object' && pattern.type) {
// 复杂匹配模式
switch (pattern.type) {
case 'content_match':
match = matchByContent(content, pattern.rules)
patternDesc = `content_match(${pattern.rules.length} rules)`
break
case 'title_match':
match = matchByTitle(content, pattern.rules)
patternDesc = `title_match(${pattern.rules.length} rules)`
break
case 'count_match':
match = matchByCount(content, pattern.rules)
patternDesc = `count_match(${pattern.rules.length} rules)`
break
case 'list_extract':
match = extractList(content, pattern.pattern, pattern.itemPattern)
patternDesc = `list_extract`
break
case 'smart_list_extract':
match = smartExtractList(
content,
pattern.startPattern,
pattern.endKeywords,
pattern.itemFilter
)
patternDesc = `smart_list_extract`
break
case 'range_extract':
match = extractRange(content, pattern.pattern)
patternDesc = `range_extract`
break
case 'options_extract':
match = extractOptionsFields(content, pattern.keyword)
patternDesc = `options_extract(${pattern.keyword})`
break
}
} else if (pattern instanceof RegExp) {
// 正则表达式匹配
match = content.match(pattern)
patternDesc = pattern.toString()
}
// 如果匹配成功
if (match) {
let value = match
// 应用后处理
if (rule.postProcess) {
value = rule.postProcess(match)
} else if (Array.isArray(match) && match.length > 1) {
// 正则匹配结果,取第一个捕获组
value = match[1]
}
return {
value,
matched: true,
pattern: patternDesc
}
}
}
// 没有匹配,返回默认值
return {
value: rule.fallback,
matched: false,
pattern: null
}
}
/**
* 通过关键词匹配内容
*/
function matchByContent(content, rules) {
const contentLower = content.toLowerCase()
for (const rule of rules) {
const hasKeyword = rule.keywords.some(keyword => {
return contentLower.includes(keyword.toLowerCase())
})
if (hasKeyword) {
return rule.value
}
}
return null
}
/**
* 通过标题模式匹配
*
* @description 从文档标题或产品名称行中匹配产品类型
* @param {string} content - 文档内容
* @param {Array} rules - 匹配规则数组
* @returns {string|null} 匹配的值
*/
function matchByTitle(content, rules) {
// 提取可能的产品标题行(通常在文档开头)
const lines = content.split('\n').slice(0, 20) // 只检查前20行
const titleLines = lines.filter(line => {
const trimmed = line.trim()
// 标题行通常包含产品代码、产品名称等
return trimmed.length > 5 && trimmed.length < 100 &&
(/[A-Z]{2,4}\d?/.test(trimmed) ||
/計劃|计划|保障|保险|壽險|壽险/.test(trimmed))
})
// 合并标题行进行匹配
const titleText = titleLines.join('\n')
for (const rule of rules) {
if (rule.pattern && rule.pattern.test(titleText)) {
return rule.value
}
}
return null
}
/**
* 从"选项"段落提取字段
*
* @description 识别 "XXX選項:" 或 "XXX选项:" 格式的段落,提取其中的字段列表
* 示例:
* - "基本人壽保障選項:" 之后的性别、年龄等字段
* - "提取選項:" 之后的提取方式
* @param {string} content - 文档内容
* @param {string} optionKeyword - 选项关键词(如 "基本人壽保障選項")
* @returns {Array<{name: string, description: string}>|null} 提取的字段列表
*/
function extractOptionsFields(content, optionKeyword) {
// 匹配 "XXX選項:" 或 "XXX选项:" 格式
const pattern = new RegExp(`${optionKeyword}[::\\s]*\\n([\\s\\S]*?)(?=\\n\\n|\\n[A-Z]|\\n\\d+\\.\\s|$)`, 'gm')
const match = content.match(pattern)
if (!match) return null
const optionContent = match[0]
const fields = []
// 按行分割,提取字段名和描述
const lines = optionContent.split('\n').slice(1) // 跳过标题行
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
// 常见字段格式:
// 1. "性別" - 纯字段名
// 2. "年齡 (1-75岁)" - 字段名 + 范围说明
// 3. "- 出生年月日" - 列表格式
// 4. "提取金额: 指定金额" - 字段名 + 描述
// 提取字段名(去除列表符号和说明)
const fieldMatch = trimmed.match(/^(?:[-•·]\s*)?([^::((]+)/)
if (fieldMatch) {
const fieldName = fieldMatch[1].trim()
if (fieldName && fieldName.length > 0 && fieldName.length < 20) {
fields.push({
name: fieldName,
description: trimmed // 保留完整描述
})
}
}
}
return fields.length > 0 ? fields : null
}
/**
* 查找所有"选项"段落
*
* @description 扫描文档中所有包含"選項"或"选项"的段落标题
* @param {string} content - 文档内容
* @returns {Array<{keyword: string, startIndex: number, fields: Array}>} 选项段落列表
*/
function findAllOptionSections(content) {
const sections = []
// 匹配所有 "XXX選項:" 或 "XXX选项:" 格式
const pattern = /([^\n]*(?:選項|选项|選是)[::]?)/gm
let match
while ((match = pattern.exec(content)) !== null) {
const keyword = match[1].trim()
const startIndex = match.index
// 提取该选项下的字段
const fields = extractOptionsFields(content, keyword.replace(/[::]/g, ''))
if (fields && fields.length > 0) {
sections.push({
keyword,
startIndex,
fields
})
}
}
return sections
}
/**
* 通过统计匹配内容
*/
function matchByCount(content, rules) {
let maxCount = 0
let maxValue = null
for (const rule of rules) {
const matches = content.match(rule.pattern)
const count = matches ? matches.length : 0
if (count > maxCount) {
maxCount = count
maxValue = rule.value
}
}
return maxValue
}
/**
* 提取列表项
*/
function extractList(content, pattern, itemPattern) {
const sectionMatch = content.match(pattern)
if (!sectionMatch) return null
const section = sectionMatch[1]
const items = []
// 将 itemPattern 转换为正则表达式
const regex = typeof itemPattern === 'string' ? new RegExp(itemPattern, 'gm') : itemPattern
// 使用 exec 循环提取所有匹配项
let match
while ((match = regex.exec(section)) !== null) {
// 提取第一个非空捕获组
let item = null
// 尝试所有捕获组,找到第一个非空的
for (let i = 1; i < match.length; i++) {
if (match[i] && match[i].trim()) {
item = match[i].trim()
break
}
}
// 如果没有捕获组,使用整个匹配
if (!item && match[0] && match[0].trim()) {
item = match[0].trim()
}
if (item) {
items.push(item)
}
}
// 如果正则匹配失败,尝试按行分割
if (items.length === 0) {
const lines = section.split('\n')
for (const line of lines) {
const trimmed = line.trim()
// 过滤掉空行和短文本
if (trimmed && trimmed.length > 0 && trimmed.length < 50) {
items.push(trimmed)
}
}
}
return items.length > 0 ? items : null
}
/**
* 提取范围值
*/
function extractRange(content, pattern) {
const match = content.match(pattern)
if (!match) return null
return {
min: parseInt(match[1]),
max: parseInt(match[2])
}
}
/**
* 智能提取列表项
*
* @description 从文档中智能提取列表,支持不规则格式和多行内容
* @param {string} content - 文档内容
* @param {RegExp} startPattern - 列表起始模式
* @param {string[]} endKeywords - 结束关键词列表
* @param {Function} itemFilter - 列表项过滤函数
* @returns {string[]|null} 提取的列表项数组
*/
function smartExtractList(content, startPattern, endKeywords, itemFilter) {
// 1. 找到起始位置
const startMatch = content.match(startPattern)
if (!startMatch) return null
// 获取起始位置后的内容
const startIndex = startMatch.index + startMatch[0].length
const remainingContent = content.slice(startIndex)
// 2. 按行分割并逐行扫描
const lines = remainingContent.split('\n')
const items = []
for (const line of lines) {
const trimmedLine = line.trim()
// 3. 检查是否遇到结束关键词
if (endKeywords.some(keyword => trimmedLine.includes(keyword))) {
break
}
// 4. 使用 itemFilter 过滤有效项
if (itemFilter && typeof itemFilter === 'function') {
if (itemFilter(trimmedLine)) {
items.push(trimmedLine)
}
} else {
// 默认过滤:非空行且长度合理
if (trimmedLine && trimmedLine.length > 0 && trimmedLine.length < 100) {
items.push(trimmedLine)
}
}
}
return items.length > 0 ? items : null
}
/**
* 生成字段建议值
*
* @param {string} fieldName - 字段名称
* @param {string} content - 文档内容
* @returns {Array<string>} 建议值列表
*/
function generateSuggestions(fieldName, content) {
const suggestions = {
product_name: ['从文档标题提取', '从第一行提取', '手动输入产品全称'],
product_type: ['savings - 储蓄型产品', 'critical-illness - 重疾型产品', 'life-insurance - 人寿型产品'],
currency: ['USD - 美元', 'CNY - 人民币', 'HKD - 港币', 'EUR - 欧元'],
payment_periods: ['整付', '3年', '5年', '10年', '15年', '20年'],
age_range: ['0-75岁(常见范围)', '0-70岁', '1-65岁'],
insurance_period: ['终身', '至100岁', '20年', '30年'],
withdrawal_modes: ['指定提取金额', '最高固定提取金额'],
withdrawal_periods: ['1年', '3年', '5年', '10年', '15年', '20年']
}
return suggestions[fieldName] || ['请手动输入']
}
/**
* 生成人工审核报告
*
* @param {Object} result - 提取结果
* @returns {string} Markdown 格式的审核报告
*/
export function generateAuditReport(result) {
const { config, unmatched, warnings, matchDetails } = result
let report = `## 📊 字段提取报告\n\n`
// 匹配统计
const matchedCount = matchDetails.filter(m => m.matched).length
const totalCount = matchDetails.length
report += `### 匹配统计\n\n`
report += `- ✅ 成功匹配: ${matchedCount}/${totalCount} 字段\n`
report += `- ⚠️ 使用默认值: ${warnings.length} 字段\n`
report += `- ❌ 未匹配(需人工补充): ${unmatched.length} 字段\n\n`
// 匹配详情表格
report += `### 匹配详情\n\n`
report += `| 字段 | 状态 | 提取方式 | 值 |\n`
report += `|------|------|----------|----|\n`
for (const detail of matchDetails) {
const status = detail.matched ? '✅' : (FIELD_RULES[detail.field]?.required ? '⚠️' : 'ℹ️')
const method = detail.matched ? detail.pattern : '默认值'
const valuePreview = JSON.stringify(detail.value).substring(0, 50)
report += `| ${detail.field} | ${status} | ${method} | ${valuePreview} |\n`
}
// 警告信息
if (warnings.length > 0) {
report += `\n### ⚠️ 警告信息\n\n`
for (const warning of warnings) {
report += `- **${warning.field}**: ${warning.message}\n`
}
}
// 未匹配字段(需要人工补充)
if (unmatched.length > 0) {
report += `\n### ❌ 未匹配字段(需要人工补充)\n\n`
for (const item of unmatched) {
report += `#### ${item.field}\n\n`
report += `- **原因**: ${item.reason}\n`
report += `- **建议值**:\n`
for (const suggestion of item.suggestions) {
report += ` - ${suggestion}\n`
}
report += `\n`
}
}
return report
}
/**
* 智能提取所有字段(支持多产品)
*
* @description 从单个产品内容片段中提取字段,优先使用传入的产品名称
* @param {string} content - 产品内容片段
* @param {string} fileName - 文件名
* @param {Object} options - 额外选项
* @param {string} options.productCode - 产品代码(如 GS、GC、FA)
* @param {string} options.productName - 产品名称(从分割器获取)
* @returns {{config: Object, unmatched: Array, warnings: Array, matchDetails: Array}} 提取结果
*/
export function smartExtractFieldsForProduct(content, fileName, options = {}) {
const { productCode, productName } = options
const config = {}
const unmatched = []
const warnings = []
const matchDetails = []
// 按优先级提取字段
const sortedFields = Object.entries(FIELD_RULES).sort((a, b) => a[1].priority - b[1].priority)
for (const [fieldName, rule] of sortedFields) {
// 跳过 product_name,后面特殊处理
if (fieldName === 'product_name') continue
const result = extractField(content, fieldName)
// 记录匹配详情
matchDetails.push({
field: fieldName,
matched: result.matched,
pattern: result.pattern,
value: result.value
})
// 如果匹配成功或字段有默认值
if (result.value !== null) {
config[fieldName] = result.value
// 如果使用了默认值,记录警告
if (!result.matched && rule.required) {
warnings.push({
field: fieldName,
message: `未找到字段 "${fieldName}",使用默认值: ${JSON.stringify(rule.fallback)}`,
severity: 'warning'
})
}
} else if (rule.required) {
// 必填字段未匹配
unmatched.push({
field: fieldName,
reason: '未找到匹配内容',
suggestions: generateSuggestions(fieldName, content)
})
}
}
// ========== 产品名称特殊处理 ==========
// 优先级: 传入的产品名称 > 从内容提取 > 文件名
if (productName) {
// 使用分割器传入的产品名称
config.product_name = productName
matchDetails.unshift({
field: 'product_name',
matched: true,
pattern: 'product_splitter',
value: productName
})
} else {
// 尝试从内容提取
const nameResult = extractField(content, 'product_name')
if (nameResult.matched && nameResult.value) {
config.product_name = nameResult.value
matchDetails.unshift({
field: 'product_name',
matched: true,
pattern: nameResult.pattern,
value: nameResult.value
})
} else {
// 使用文件名
const baseName = fileName.replace(/\.[^/.]+$/, '')
config.product_name = baseName
warnings.push({
field: 'product_name',
message: `未找到产品名称,使用文件名: "${baseName}"`,
severity: 'info'
})
matchDetails.unshift({
field: 'product_name',
matched: false,
pattern: 'filename_fallback',
value: baseName
})
}
}
// 如果有产品代码,添加到配置中
if (productCode) {
config.product_code = productCode
}
// 根据产品类型过滤字段
if (config.product_type !== 'savings') {
delete config.withdrawal_modes
delete config.withdrawal_periods
}
return {
config,
unmatched,
warnings,
matchDetails
}
}
/**
* 智能提取所有字段(原始函数,保持兼容)
*
* @param {string} content - 文档内容
* @param {string} fileName - 文件名(用于推断产品名称)
* @returns {{config: Object, unmatched: Array, warnings: Array}} 提取结果
*/
export function smartExtractFields(content, fileName) {
return smartExtractFieldsForProduct(content, fileName, {})
}
export { FIELD_RULES }