dsh-ppt 0.24.2 → 0.26.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.
- package/CHANGELOG.md +16 -0
- package/README.en.md +13 -13
- package/README.md +13 -13
- package/docs/DATA.md +2 -2
- package/docs/REFERENCE.en.md +8 -8
- package/docs/REFERENCE.zh.md +8 -8
- package/docs/USAGE.en.md +11 -7
- package/docs/USAGE.md +11 -7
- package/docs/VALIDATION.md +4 -0
- package/docs/WORKBENCH.md +4 -4
- package/docs/assets/intro/workflow-en-dark.svg +1 -1
- package/docs/assets/intro/workflow-en-light.svg +1 -1
- package/docs/assets/intro/workflow-en-mobile-dark.svg +1 -1
- package/docs/assets/intro/workflow-en-mobile-light.svg +1 -1
- package/docs/assets/intro/workflow-zh-dark.svg +1 -1
- package/docs/assets/intro/workflow-zh-light.svg +1 -1
- package/docs/assets/intro/workflow-zh-mobile-dark.svg +1 -1
- package/docs/assets/intro/workflow-zh-mobile-light.svg +1 -1
- package/lib/client.js +3435 -467
- package/lib/ecosystem.d.ts +73 -0
- package/lib/ecosystem.js +1352 -0
- package/lib/execution.d.ts +6 -1
- package/lib/execution.js +69 -0
- package/lib/tools.js +77 -0
- package/lib/types.d.ts +57 -1
- package/lib/workbench-language.js +4 -0
- package/lib/workbench.d.ts +2 -0
- package/lib/workbench.js +331 -8
- package/package.json +1 -1
- package/skills/dsh-ppt/SKILL.md +3 -3
- package/skills/dsh-ppt/package.json +1 -1
- package/skills/dsh-ppt/references/advanced.md +10 -5
- package/skills/dsh-ppt/references/syntax.md +1 -0
- package/skills/dsh-ppt/scripts/build-deck.mjs +39 -8
- package/skills/dsh-ppt/scripts/deck-advanced.mjs +50 -13
- package/skills/dsh-ppt/scripts/deck-chrome.mjs +1706 -0
- package/skills/dsh-ppt/scripts/deck-core.mjs +116 -6
- package/skills/dsh-ppt/scripts/deck-delivery.mjs +636 -41
- package/skills/dsh-ppt/scripts/deck-diagrams.mjs +2842 -0
- package/skills/dsh-ppt/scripts/deck-director.mjs +49 -3
- package/skills/dsh-ppt/scripts/deck-layouts.mjs +482 -5270
- package/skills/dsh-ppt/scripts/deck-mermaid.mjs +2737 -0
- package/skills/dsh-ppt/scripts/deck-office.mjs +1541 -0
|
@@ -0,0 +1,1541 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deck-office.mjs —— 零新增依赖的 .xlsx / .csv / .tsv / .docx 直接吞吐解析器与数据视觉画像引擎。
|
|
3
|
+
*
|
|
4
|
+
* 能力边界:
|
|
5
|
+
* 1. 使用 Node 内置 `node:zlib` (`inflateRawSync`) 实现轻量 ZIP 中央目录读取器,零新增第三方依赖。
|
|
6
|
+
* 2. 解析 .xlsx(workbook.xml / sharedStrings.xml / styles.xml / sheet*.xml,支持共享字符串、内联串、数值与 Excel 日期序列号)
|
|
7
|
+
* 及 .csv / .tsv(按需懒加载已有依赖 csv-parse/sync)。
|
|
8
|
+
* 3. 确定性数据视觉画像(Data-to-Visual Profiler):
|
|
9
|
+
* - [Source, Target, Amount] 3 列流向表 -> sankey 桑基图页
|
|
10
|
+
* - Task + Start/End 或 Q1..Q4 / 月份排期列 -> gantt 甘特图页
|
|
11
|
+
* - 市场规模权重 + 竞品份额 % 列 -> marimekko 市场地图页
|
|
12
|
+
* - 基线/上期 .. +/- 变动 .. 期末/合计 -> waterfall 瀑布桥页
|
|
13
|
+
* - 双数值列量纲比 > 10x -> combo 双轴复合图页
|
|
14
|
+
* - 通用数值表 -> chart-split(highlight: 'max' + 自动 Top/Min/Avg 洞察卡)+ table 明细附录页
|
|
15
|
+
* 4. 解析 .docx Word 报告(document.xml / _rels / media/*):提取标题、H1/H2 及中文编号标题、加粗导语、
|
|
16
|
+
* Word 表格(<w:tbl>)、PNG/JPEG/WebP 嵌入图片、Mermaid 流程图/时序图与 $...$ 公式,
|
|
17
|
+
* 经智能导演 + smartLayout 生成 5–20 页高品味演示文稿。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { lstatSync, readFileSync } from 'node:fs'
|
|
21
|
+
import { createRequire } from 'node:module'
|
|
22
|
+
import { basename, extname, posix, resolve } from 'node:path'
|
|
23
|
+
import { inflateRawSync } from 'node:zlib'
|
|
24
|
+
import { promoteMarkdownSlides, inferThemeFromContent } from './deck-director.mjs'
|
|
25
|
+
|
|
26
|
+
const MAX_OFFICE_BYTES = 32 * 1024 * 1024
|
|
27
|
+
const MAX_ENTRY_BYTES = 32 * 1024 * 1024
|
|
28
|
+
const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
|
29
|
+
|
|
30
|
+
const require = createRequire(import.meta.url)
|
|
31
|
+
|
|
32
|
+
function fail(zh, en) {
|
|
33
|
+
throw new Error('dsh-ppt:' + zh + (en ? ' / ' + en : ''))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function abort(signal) {
|
|
37
|
+
signal?.throwIfAborted?.()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function decodeXml(str) {
|
|
41
|
+
return String(str ?? '')
|
|
42
|
+
.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => {
|
|
43
|
+
const code = Number.parseInt(hex, 16)
|
|
44
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : ''
|
|
45
|
+
})
|
|
46
|
+
.replace(/&#(\d+);/g, (_, dec) => {
|
|
47
|
+
const code = Number.parseInt(dec, 10)
|
|
48
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : ''
|
|
49
|
+
})
|
|
50
|
+
.replace(/</g, '<')
|
|
51
|
+
.replace(/>/g, '>')
|
|
52
|
+
.replace(/"/g, '"')
|
|
53
|
+
.replace(/'/g, "'")
|
|
54
|
+
.replace(/&/g, '&')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function cleanLine(value) {
|
|
58
|
+
return String(value ?? '').replace(/\s+/g, ' ').trim()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function csvParser() {
|
|
62
|
+
try {
|
|
63
|
+
return require('csv-parse/sync')
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error.code === 'MODULE_NOT_FOUND') {
|
|
66
|
+
fail('CSV/TSV 解析需安装技能目录依赖:npm install --ignore-scripts', 'CSV/TSV parsing requires skill dependencies: npm install --ignore-scripts')
|
|
67
|
+
}
|
|
68
|
+
throw error
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Zero-dep ZIP Central Directory Reader (node:zlib inflateRawSync)
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
function openZipArchive(bytes) {
|
|
77
|
+
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
|
|
78
|
+
if (buf.length < 22 || buf[0] !== 0x50 || buf[1] !== 0x4b) {
|
|
79
|
+
fail('无效的 Office 压缩包文件头(非标准 .xlsx / .docx ZIP)', 'Invalid Office ZIP archive header')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let eocdOffset = -1
|
|
83
|
+
const minScan = Math.max(0, buf.length - 65557)
|
|
84
|
+
for (let i = buf.length - 22; i >= minScan; i -= 1) {
|
|
85
|
+
if (buf[i] === 0x50 && buf[i + 1] === 0x4b && buf[i + 2] === 0x05 && buf[i + 3] === 0x06) {
|
|
86
|
+
eocdOffset = i
|
|
87
|
+
break
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (eocdOffset < 0) {
|
|
91
|
+
fail('Office 文件 ZIP 中央目录缺失或已损坏', 'Missing ZIP End of Central Directory')
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const totalEntries = buf.readUInt16LE(eocdOffset + 10)
|
|
95
|
+
const cdSize = buf.readUInt32LE(eocdOffset + 12)
|
|
96
|
+
const cdOffset = buf.readUInt32LE(eocdOffset + 16)
|
|
97
|
+
if (cdOffset + cdSize > buf.length) {
|
|
98
|
+
fail('Office 文件 ZIP 中央目录越界', 'ZIP Central Directory out of bounds')
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const entries = new Map()
|
|
102
|
+
const lowerMap = new Map()
|
|
103
|
+
let pos = cdOffset
|
|
104
|
+
for (let i = 0; i < totalEntries && pos + 46 <= buf.length; i += 1) {
|
|
105
|
+
if (buf.readUInt32LE(pos) !== 0x02014b50) break
|
|
106
|
+
const method = buf.readUInt16LE(pos + 10)
|
|
107
|
+
const compSize = buf.readUInt32LE(pos + 20)
|
|
108
|
+
const uncompSize = buf.readUInt32LE(pos + 24)
|
|
109
|
+
const nameLen = buf.readUInt16LE(pos + 28)
|
|
110
|
+
const extraLen = buf.readUInt16LE(pos + 30)
|
|
111
|
+
const commentLen = buf.readUInt16LE(pos + 32)
|
|
112
|
+
const localOffset = buf.readUInt32LE(pos + 42)
|
|
113
|
+
const rawName = buf.toString('utf8', pos + 46, pos + 46 + nameLen)
|
|
114
|
+
const normName = rawName.replace(/\\/g, '/').replace(/^\/+/, '')
|
|
115
|
+
if (!normName.includes('..') && uncompSize <= MAX_ENTRY_BYTES) {
|
|
116
|
+
const meta = { name: normName, method, compSize, uncompSize, localOffset }
|
|
117
|
+
entries.set(normName, meta)
|
|
118
|
+
lowerMap.set(normName.toLowerCase(), meta)
|
|
119
|
+
}
|
|
120
|
+
pos += 46 + nameLen + extraLen + commentLen
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const getMeta = (name) => {
|
|
124
|
+
const clean = String(name ?? '').replace(/\\/g, '/').replace(/^\/+/, '')
|
|
125
|
+
return entries.get(clean) || lowerMap.get(clean.toLowerCase()) || null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const readBuffer = (name) => {
|
|
129
|
+
const meta = getMeta(name)
|
|
130
|
+
if (!meta) return null
|
|
131
|
+
const lh = meta.localOffset
|
|
132
|
+
if (lh + 30 > buf.length || buf.readUInt32LE(lh) !== 0x04034b50) {
|
|
133
|
+
fail('Office ZIP 本地文件头损坏:' + meta.name, 'Corrupt ZIP local header: ' + meta.name)
|
|
134
|
+
}
|
|
135
|
+
const lfnLen = buf.readUInt16LE(lh + 26)
|
|
136
|
+
const lexLen = buf.readUInt16LE(lh + 28)
|
|
137
|
+
const dataStart = lh + 30 + lfnLen + lexLen
|
|
138
|
+
const dataEnd = dataStart + meta.compSize
|
|
139
|
+
if (dataEnd > buf.length) {
|
|
140
|
+
fail('Office ZIP 条目数据截断:' + meta.name, 'Truncated ZIP entry: ' + meta.name)
|
|
141
|
+
}
|
|
142
|
+
const slice = buf.subarray(dataStart, dataEnd)
|
|
143
|
+
if (meta.method === 0) return Buffer.from(slice)
|
|
144
|
+
if (meta.method === 8) {
|
|
145
|
+
try {
|
|
146
|
+
return inflateRawSync(slice, { maxOutputLength: MAX_ENTRY_BYTES })
|
|
147
|
+
} catch (err) {
|
|
148
|
+
fail('Office ZIP 解压失败(' + meta.name + '):' + err.message)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
fail('不支持的 Office ZIP 压缩方式:' + meta.method)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const readText = (name) => {
|
|
155
|
+
const b = readBuffer(name)
|
|
156
|
+
return b ? b.toString('utf8') : ''
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
has: (name) => Boolean(getMeta(name)),
|
|
161
|
+
list: (prefix = '') => {
|
|
162
|
+
const p = String(prefix).replace(/^\/+/, '').toLowerCase()
|
|
163
|
+
return [...entries.keys()].filter(k => !p || k.toLowerCase().startsWith(p))
|
|
164
|
+
},
|
|
165
|
+
readBuffer,
|
|
166
|
+
readText,
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function readOfficeInput(options = {}) {
|
|
171
|
+
let bytes
|
|
172
|
+
let sourceName = cleanLine(options.fileName || '')
|
|
173
|
+
let resolvedPath = ''
|
|
174
|
+
|
|
175
|
+
if (options.bytes !== undefined && options.bytes !== null) {
|
|
176
|
+
if (typeof options.bytes === 'string') {
|
|
177
|
+
const stripped = options.bytes.replace(/^data:[^;]+;base64,/, '').trim()
|
|
178
|
+
bytes = Buffer.from(stripped, 'base64')
|
|
179
|
+
} else if (Buffer.isBuffer(options.bytes) || options.bytes instanceof Uint8Array) {
|
|
180
|
+
bytes = Buffer.from(options.bytes)
|
|
181
|
+
} else {
|
|
182
|
+
fail('bytes 必须为 Buffer、Uint8Array 或 Base64 字符串')
|
|
183
|
+
}
|
|
184
|
+
if (!sourceName) sourceName = options.format ? `upload.${options.format}` : 'upload.xlsx'
|
|
185
|
+
} else {
|
|
186
|
+
const rawPath = String(options.filePath ?? options.path ?? '').trim()
|
|
187
|
+
if (!rawPath) fail('请提供有效的 .xlsx / .csv / .tsv / .docx 文件路径', 'Provide a valid .xlsx / .csv / .tsv / .docx filePath')
|
|
188
|
+
resolvedPath = resolve(String(options.cwd ?? '.'), rawPath)
|
|
189
|
+
let stat
|
|
190
|
+
try {
|
|
191
|
+
stat = lstatSync(resolvedPath)
|
|
192
|
+
} catch {
|
|
193
|
+
fail('找不到 Office 文件:' + resolvedPath, 'Office file not found: ' + resolvedPath)
|
|
194
|
+
}
|
|
195
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_OFFICE_BYTES) {
|
|
196
|
+
fail('Office 文件需为 32 MiB 内的普通文件:' + resolvedPath)
|
|
197
|
+
}
|
|
198
|
+
bytes = readFileSync(resolvedPath)
|
|
199
|
+
if (!sourceName) sourceName = basename(resolvedPath)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (bytes.length === 0 || bytes.length > MAX_OFFICE_BYTES) {
|
|
203
|
+
fail('Office 文件为空或超过 32 MiB 限制')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const rawExt = (
|
|
207
|
+
options.format ||
|
|
208
|
+
extname(sourceName).slice(1) ||
|
|
209
|
+
extname(resolvedPath).slice(1)
|
|
210
|
+
).toLowerCase().trim()
|
|
211
|
+
if (!['xlsx', 'csv', 'tsv', 'docx'].includes(rawExt)) {
|
|
212
|
+
fail('仅支持导入 .xlsx、.csv、.tsv 或 .docx 文件,当前格式:' + (rawExt || '未知'))
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return {
|
|
216
|
+
bytes,
|
|
217
|
+
format: rawExt,
|
|
218
|
+
fileName: (extname(sourceName) ? sourceName : basename(resolvedPath)) || `office.${rawExt}`,
|
|
219
|
+
resolvedPath: resolvedPath || sourceName,
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
// .xlsx Workbook Parser
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
function parseRelationshipsMap(relsXml) {
|
|
228
|
+
const map = new Map()
|
|
229
|
+
if (!relsXml) return map
|
|
230
|
+
for (const m of relsXml.matchAll(/<Relationship\b([^>]*)\/?>/g)) {
|
|
231
|
+
const attrs = m[1]
|
|
232
|
+
const id = /\bId=["']([^"']+)["']/.exec(attrs)?.[1]
|
|
233
|
+
const target = /\bTarget=["']([^"']+)["']/.exec(attrs)?.[1]
|
|
234
|
+
const mode = /\bTargetMode=["']([^"']+)["']/.exec(attrs)?.[1] || ''
|
|
235
|
+
if (id && target && mode.toLowerCase() !== 'external') {
|
|
236
|
+
map.set(id, target)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return map
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function resolveZipTarget(basePart, target) {
|
|
243
|
+
const clean = String(target ?? '').replace(/\\/g, '/').trim()
|
|
244
|
+
if (!clean) return ''
|
|
245
|
+
if (clean.startsWith('/')) return clean.replace(/^\/+/, '')
|
|
246
|
+
const dir = posix.dirname(basePart)
|
|
247
|
+
return posix.normalize(dir === '.' ? clean : posix.join(dir, clean)).replace(/^\/+/, '')
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function colRefToIndex(ref) {
|
|
251
|
+
const letters = /^([A-Za-z]+)/.exec(String(ref ?? ''))?.[1]
|
|
252
|
+
if (!letters) return -1
|
|
253
|
+
let idx = 0
|
|
254
|
+
for (const ch of letters.toUpperCase()) {
|
|
255
|
+
idx = idx * 26 + (ch.charCodeAt(0) - 64)
|
|
256
|
+
}
|
|
257
|
+
return idx - 1
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function parseSharedStrings(xml) {
|
|
261
|
+
if (!xml) return []
|
|
262
|
+
const out = []
|
|
263
|
+
for (const siMatch of xml.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>/g)) {
|
|
264
|
+
const inner = siMatch[1].replace(/<rPh\b[^>]*>[\s\S]*?<\/rPh>/g, '')
|
|
265
|
+
const parts = []
|
|
266
|
+
for (const tMatch of inner.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)) {
|
|
267
|
+
parts.push(decodeXml(tMatch[1]))
|
|
268
|
+
}
|
|
269
|
+
out.push(parts.join(''))
|
|
270
|
+
}
|
|
271
|
+
return out
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const BUILTIN_DATE_FMT_IDS = new Set([14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47])
|
|
275
|
+
|
|
276
|
+
function isDateFormatCode(code) {
|
|
277
|
+
if (!code) return false
|
|
278
|
+
const stripped = String(code).replace(/"[^"]*"/g, '').replace(/\[[^\]]*\]/g, '')
|
|
279
|
+
if (/[%#0?]/.test(stripped) && !/[ymd]/i.test(stripped)) return false
|
|
280
|
+
return /[ymdh]/i.test(stripped) && /[ymd]/i.test(stripped)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function parseDateStyleSet(stylesXml) {
|
|
284
|
+
const dateStyles = new Set()
|
|
285
|
+
if (!stylesXml) return dateStyles
|
|
286
|
+
const customDateFmts = new Set()
|
|
287
|
+
for (const m of stylesXml.matchAll(/<numFmt\b([^>]*)\/?>/g)) {
|
|
288
|
+
const attrs = m[1]
|
|
289
|
+
const id = Number(/\bnumFmtId=["'](\d+)["']/.exec(attrs)?.[1])
|
|
290
|
+
const code = /\bformatCode=["']([^"']*)["']/.exec(attrs)?.[1] || ''
|
|
291
|
+
if (Number.isFinite(id) && isDateFormatCode(decodeXml(code))) {
|
|
292
|
+
customDateFmts.add(id)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const cellXfsBlock = /<cellXfs\b[^>]*>([\s\S]*?)<\/cellXfs>/.exec(stylesXml)?.[1] || ''
|
|
296
|
+
let xfIndex = 0
|
|
297
|
+
for (const m of cellXfsBlock.matchAll(/<xf\b([^>]*)(?:\/>|>[\s\S]*?<\/xf>)/g)) {
|
|
298
|
+
const numFmtId = Number(/\bnumFmtId=["'](\d+)["']/.exec(m[1])?.[1])
|
|
299
|
+
const applyNumFmt = /\bapplyNumberFormat=["']([^"']+)["']/.exec(m[1])?.[1]
|
|
300
|
+
if ((applyNumFmt !== '0') && (BUILTIN_DATE_FMT_IDS.has(numFmtId) || customDateFmts.has(numFmtId))) {
|
|
301
|
+
dateStyles.add(xfIndex)
|
|
302
|
+
}
|
|
303
|
+
xfIndex += 1
|
|
304
|
+
}
|
|
305
|
+
return dateStyles
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function excelSerialToIsoDate(serial) {
|
|
309
|
+
if (!Number.isFinite(serial) || serial < 1 || serial > 2958465) return null
|
|
310
|
+
const wholeDays = Math.floor(serial)
|
|
311
|
+
// Excel 1900 leap-year bug adjustment: serial >= 60 is shifted by 1 day after Feb 28 1900
|
|
312
|
+
const adjusted = wholeDays > 59 ? wholeDays - 1 : wholeDays
|
|
313
|
+
const epochMs = Date.UTC(1899, 11, 31) + adjusted * 86400000
|
|
314
|
+
const d = new Date(epochMs)
|
|
315
|
+
if (Number.isNaN(d.getTime())) return null
|
|
316
|
+
const y = d.getUTCFullYear()
|
|
317
|
+
const m = String(d.getUTCMonth() + 1).padStart(2, '0')
|
|
318
|
+
const day = String(d.getUTCDate()).padStart(2, '0')
|
|
319
|
+
return `${y}-${m}-${day}`
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function parseWorksheetRows(sheetXml, sharedStrings, dateStyles) {
|
|
323
|
+
const rowList = []
|
|
324
|
+
let maxCols = 0
|
|
325
|
+
|
|
326
|
+
for (const rowMatch of sheetXml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
|
|
327
|
+
const rowInner = rowMatch[1]
|
|
328
|
+
const cells = []
|
|
329
|
+
let seqCol = 0
|
|
330
|
+
|
|
331
|
+
for (const cMatch of rowInner.matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
|
|
332
|
+
const attrs = cMatch[1]
|
|
333
|
+
const body = cMatch[2] || ''
|
|
334
|
+
const ref = /\br=["']([^"']+)["']/.exec(attrs)?.[1]
|
|
335
|
+
const colIdx = ref ? colRefToIndex(ref) : seqCol
|
|
336
|
+
const targetCol = colIdx >= 0 ? colIdx : seqCol
|
|
337
|
+
seqCol = targetCol + 1
|
|
338
|
+
|
|
339
|
+
const type = /\bt=["']([^"']+)["']/.exec(attrs)?.[1] || 'n'
|
|
340
|
+
const styleIdx = Number(/\bs=["'](\d+)["']/.exec(attrs)?.[1] ?? -1)
|
|
341
|
+
let value = ''
|
|
342
|
+
|
|
343
|
+
if (type === 'inlineStr') {
|
|
344
|
+
const isBlock = /<is\b[^>]*>([\s\S]*?)<\/is>/.exec(body)?.[1] || body
|
|
345
|
+
const parts = []
|
|
346
|
+
for (const tm of isBlock.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)) {
|
|
347
|
+
parts.push(decodeXml(tm[1]))
|
|
348
|
+
}
|
|
349
|
+
value = parts.join('')
|
|
350
|
+
} else {
|
|
351
|
+
const vRaw = /<v\b[^>]*>([\s\S]*?)<\/v>/.exec(body)?.[1]
|
|
352
|
+
if (vRaw !== undefined) {
|
|
353
|
+
const decoded = decodeXml(vRaw).trim()
|
|
354
|
+
if (type === 's') {
|
|
355
|
+
const idx = Number.parseInt(decoded, 10)
|
|
356
|
+
value = Number.isInteger(idx) && sharedStrings[idx] !== undefined ? sharedStrings[idx] : ''
|
|
357
|
+
} else if (type === 'b') {
|
|
358
|
+
value = decoded === '1' || decoded.toLowerCase() === 'true' ? 'TRUE' : 'FALSE'
|
|
359
|
+
} else if (type === 'str' || type === 'e') {
|
|
360
|
+
value = decoded
|
|
361
|
+
} else {
|
|
362
|
+
const num = Number(decoded)
|
|
363
|
+
if (Number.isFinite(num) && dateStyles.has(styleIdx)) {
|
|
364
|
+
value = excelSerialToIsoDate(num) || decoded
|
|
365
|
+
} else {
|
|
366
|
+
value = decoded
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const clean = cleanLine(value)
|
|
373
|
+
while (cells.length <= targetCol) cells.push('')
|
|
374
|
+
cells[targetCol] = clean
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (cells.some(c => c !== '')) {
|
|
378
|
+
maxCols = Math.max(maxCols, cells.length)
|
|
379
|
+
rowList.push(cells)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (rowList.length === 0 || maxCols === 0) return []
|
|
384
|
+
return rowList.map(r => {
|
|
385
|
+
const out = r.slice(0, maxCols)
|
|
386
|
+
while (out.length < maxCols) out.push('')
|
|
387
|
+
return out
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function parseXlsxArchive(bytes) {
|
|
392
|
+
const zip = openZipArchive(bytes)
|
|
393
|
+
const workbookXml = zip.readText('xl/workbook.xml')
|
|
394
|
+
const relsMap = parseRelationshipsMap(zip.readText('xl/_rels/workbook.xml.rels'))
|
|
395
|
+
const sharedStrings = parseSharedStrings(zip.readText('xl/sharedStrings.xml'))
|
|
396
|
+
const dateStyles = parseDateStyleSet(zip.readText('xl/styles.xml'))
|
|
397
|
+
|
|
398
|
+
const sheetSpecs = []
|
|
399
|
+
if (workbookXml) {
|
|
400
|
+
for (const m of workbookXml.matchAll(/<sheet\b([^>]*)\/?>/g)) {
|
|
401
|
+
const attrs = m[1]
|
|
402
|
+
const name = decodeXml(/\bname=["']([^"']+)["']/.exec(attrs)?.[1] || '')
|
|
403
|
+
const rid = /\b(?:r:)?id=["']([^"']+)["']/.exec(attrs)?.[1] || ''
|
|
404
|
+
const state = /\bstate=["']([^"']+)["']/.exec(attrs)?.[1] || ''
|
|
405
|
+
if (state === 'hidden' || state === 'veryHidden') continue
|
|
406
|
+
const target = relsMap.get(rid)
|
|
407
|
+
const partPath = target ? resolveZipTarget('xl/workbook.xml', target) : ''
|
|
408
|
+
if (partPath && zip.has(partPath)) {
|
|
409
|
+
sheetSpecs.push({ name: name || `Sheet ${sheetSpecs.length + 1}`, path: partPath })
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (sheetSpecs.length === 0) {
|
|
415
|
+
const fallbackPaths = zip.list('xl/worksheets/sheet')
|
|
416
|
+
.filter(p => /\.xml$/i.test(p))
|
|
417
|
+
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
|
|
418
|
+
fallbackPaths.forEach((p, idx) => sheetSpecs.push({ name: `Sheet ${idx + 1}`, path: p }))
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (sheetSpecs.length === 0) {
|
|
422
|
+
fail('Excel 工作簿中未找到有效工作表', 'No valid worksheets found in .xlsx workbook')
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const sheets = []
|
|
426
|
+
for (const spec of sheetSpecs) {
|
|
427
|
+
const xml = zip.readText(spec.path)
|
|
428
|
+
let rows = parseWorksheetRows(xml, sharedStrings, dateStyles)
|
|
429
|
+
let bannerTitle = ''
|
|
430
|
+
if (rows.length >= 3) {
|
|
431
|
+
const nonEmpty0 = rows[0].filter(Boolean)
|
|
432
|
+
const nonEmpty1 = rows[1].filter(Boolean)
|
|
433
|
+
if (nonEmpty0.length === 1 && nonEmpty1.length >= 2) {
|
|
434
|
+
bannerTitle = nonEmpty0[0]
|
|
435
|
+
rows = rows.slice(1)
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (rows.length >= 2) {
|
|
439
|
+
sheets.push({ name: spec.name, bannerTitle, rows })
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (sheets.length === 0) {
|
|
444
|
+
fail('Excel 工作簿中没有包含有效数据的表格工作表', 'No populated tables found in .xlsx workbook')
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
return { sheets }
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// ---------------------------------------------------------------------------
|
|
451
|
+
// .csv / .tsv Parser & Tabular Data-to-Visual Profiler
|
|
452
|
+
// ---------------------------------------------------------------------------
|
|
453
|
+
|
|
454
|
+
function parseDelimitedText(bytes, format) {
|
|
455
|
+
const text = bytes.toString('utf8')
|
|
456
|
+
const parsed = csvParser().parse(text, {
|
|
457
|
+
bom: true,
|
|
458
|
+
delimiter: format === 'tsv' ? '\t' : ',',
|
|
459
|
+
skip_empty_lines: true,
|
|
460
|
+
relax_column_count: true,
|
|
461
|
+
trim: true,
|
|
462
|
+
max_record_size: 200000,
|
|
463
|
+
})
|
|
464
|
+
const rows = parsed
|
|
465
|
+
.map(r => (Array.isArray(r) ? r.map(c => cleanLine(c)) : [cleanLine(r)]))
|
|
466
|
+
.filter(r => r.some(Boolean))
|
|
467
|
+
if (rows.length < 2) {
|
|
468
|
+
fail('CSV/TSV 文件至少需要包含表头与一行数据', 'CSV/TSV requires at least a header row and one data row')
|
|
469
|
+
}
|
|
470
|
+
const maxCols = Math.max(...rows.map(r => r.length))
|
|
471
|
+
const rect = rows.map(r => {
|
|
472
|
+
const copy = r.slice(0, maxCols)
|
|
473
|
+
while (copy.length < maxCols) copy.push('')
|
|
474
|
+
return copy
|
|
475
|
+
})
|
|
476
|
+
return rect
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function parseCellNumber(raw) {
|
|
480
|
+
const s = cleanLine(raw)
|
|
481
|
+
if (!s) return { ok: false, num: NaN, isPercent: false, unit: '', raw: '' }
|
|
482
|
+
const isPercent = /[%%]$/.test(s)
|
|
483
|
+
const currency = /^[¥$€£]/.exec(s)?.[0] || ''
|
|
484
|
+
const unitMatch = /([万亿千百kKmMbB]+|亿元|亿美元|万元|美元|元|人|次|家|个|件|ms|s|天|小时)$/.exec(s)
|
|
485
|
+
let unit = isPercent ? '%' : (unitMatch?.[1] || currency)
|
|
486
|
+
const cleaned = s
|
|
487
|
+
.replace(/^[¥$€£]\s*/, '')
|
|
488
|
+
.replace(/[%%]$/, '')
|
|
489
|
+
.replace(/(?:亿元|亿美元|万元|美元|元|[万亿千百kKmMbB]|人|次|家|个|件|ms|s|天|小时)$/i, '')
|
|
490
|
+
.replace(/,/g, '')
|
|
491
|
+
.trim()
|
|
492
|
+
if (!/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(cleaned)) {
|
|
493
|
+
return { ok: false, num: NaN, isPercent: false, unit: '', raw: s }
|
|
494
|
+
}
|
|
495
|
+
const num = Number(cleaned)
|
|
496
|
+
if (!Number.isFinite(num)) return { ok: false, num: NaN, isPercent: false, unit: '', raw: s }
|
|
497
|
+
return { ok: true, num, isPercent, unit, raw: s }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function formatNumCompact(num, unit = '') {
|
|
501
|
+
if (!Number.isFinite(num)) return String(num)
|
|
502
|
+
const abs = Math.abs(num)
|
|
503
|
+
let str
|
|
504
|
+
if (abs >= 1000) str = Math.round(num).toLocaleString('en-US')
|
|
505
|
+
else if (Number.isInteger(num)) str = String(num)
|
|
506
|
+
else str = Number(num.toFixed(2)).toString()
|
|
507
|
+
if (unit === '%' && !str.endsWith('%')) return str + '%'
|
|
508
|
+
if (['¥', '$', '€', '£'].includes(unit)) return unit + str
|
|
509
|
+
return unit ? `${str}${unit}` : str
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function profileColumns(rows) {
|
|
513
|
+
const headers = rows[0]
|
|
514
|
+
const data = rows.slice(1)
|
|
515
|
+
return headers.map((header, colIdx) => {
|
|
516
|
+
const vals = data.map(r => r[colIdx] ?? '')
|
|
517
|
+
const nonEmpty = vals.filter(v => v !== '')
|
|
518
|
+
const parsed = vals.map(parseCellNumber)
|
|
519
|
+
const numericHits = parsed.filter(p => p.ok)
|
|
520
|
+
const isNumeric = nonEmpty.length > 0 && (numericHits.length / nonEmpty.length) >= 0.65
|
|
521
|
+
const pctHits = numericHits.filter(p => p.isPercent).length
|
|
522
|
+
const unit = numericHits.find(p => p.unit)?.unit || ''
|
|
523
|
+
return {
|
|
524
|
+
index: colIdx,
|
|
525
|
+
header: header || `Col ${colIdx + 1}`,
|
|
526
|
+
values: vals,
|
|
527
|
+
parsed,
|
|
528
|
+
isNumeric,
|
|
529
|
+
isPercentCol: isNumeric && pctHits >= Math.max(1, numericHits.length * 0.6),
|
|
530
|
+
unit,
|
|
531
|
+
}
|
|
532
|
+
})
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function isSankeySheet(headers, dataRows, cols) {
|
|
536
|
+
if (cols.length < 3 || cols.length > 5 || dataRows.length < 2) return false
|
|
537
|
+
if (cols[0].isNumeric || cols[1].isNumeric || !cols[2].isNumeric) return false
|
|
538
|
+
const posCount = cols[2].parsed.filter(p => p.ok && p.num > 0).length
|
|
539
|
+
if (posCount < Math.max(2, dataRows.length * 0.7)) return false
|
|
540
|
+
const h0 = headers[0] || ''
|
|
541
|
+
const h1 = headers[1] || ''
|
|
542
|
+
const explicitFlowHeaders = /(?:source|from|origin|来源|起点|上游|流出方|一级)/i.test(h0) &&
|
|
543
|
+
/(?:target|to|dest|destination|去向|终点|下游|流入方|二级)/i.test(h1)
|
|
544
|
+
if (explicitFlowHeaders) return true
|
|
545
|
+
const srcSet = new Set(cols[0].values.filter(Boolean))
|
|
546
|
+
const dstSet = new Set(cols[1].values.filter(Boolean))
|
|
547
|
+
const hasChaining = [...srcSet].some(s => dstSet.has(s))
|
|
548
|
+
const hasFanOut = srcSet.size < dataRows.length
|
|
549
|
+
return hasChaining || (hasFanOut && cols.length === 3)
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const PERIOD_HEADER_RE = /^(?:Q[1-4](?:\s*\d{2,4})?|\d{2,4}Q[1-4]|M\d{1,2}|W\d{1,2}|[1-9]|1[0-2]月|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|\d{4}[-/]\d{1,2})$/i
|
|
553
|
+
const GANTT_ACTIVE_RE = /^(?:1|x|✓|✔|●|true|yes|active|done|wip|进行中|已完成|计划)$/i
|
|
554
|
+
|
|
555
|
+
function parseQuarterOrMonthIndex(val, colCount) {
|
|
556
|
+
const s = cleanLine(val)
|
|
557
|
+
const qm = /Q([1-4])/i.exec(s)
|
|
558
|
+
if (qm) return Number(qm[1]) - 1
|
|
559
|
+
const mm = /(?:^M|^第?)(\d{1,2})/i.exec(s)
|
|
560
|
+
if (mm) return Math.max(0, Math.min(colCount - 1, Number(mm[1]) - 1))
|
|
561
|
+
const n = Number(s)
|
|
562
|
+
if (Number.isFinite(n)) return Math.max(0, Math.min(colCount - 1, Math.round(n) - (n >= 1 ? 1 : 0)))
|
|
563
|
+
return 0
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function tryBuildGanttSlide(sheetName, headers, dataRows, cols, en) {
|
|
567
|
+
if (dataRows.length < 2) return null
|
|
568
|
+
const taskColIdx = Math.max(0, cols.findIndex(c => !c.isNumeric))
|
|
569
|
+
|
|
570
|
+
// Pattern A: Task + Start + End columns
|
|
571
|
+
const startIdx = headers.findIndex(h => /^(?:start|begin|from|开始|起始|启动)/i.test(h))
|
|
572
|
+
const endIdx = headers.findIndex(h => /^(?:end|finish|to|duration|span|结束|截止|周期|耗时|跨度|时长|工期)/i.test(h))
|
|
573
|
+
if (startIdx >= 0 && endIdx >= 0 && startIdx !== endIdx) {
|
|
574
|
+
const rawStarts = dataRows.map(r => r[startIdx])
|
|
575
|
+
const rawEnds = dataRows.map(r => r[endIdx])
|
|
576
|
+
const hasQuarters = [...rawStarts, ...rawEnds].some(v => /Q[1-4]/i.test(v)) || /季度|quarter/i.test(headers[startIdx] + ' ' + headers[endIdx])
|
|
577
|
+
const columns = hasQuarters ? ['Q1', 'Q2', 'Q3', 'Q4'] : ['M1', 'M2', 'M3', 'M4', 'M5', 'M6']
|
|
578
|
+
const items = dataRows.slice(0, 7).map((r, idx) => {
|
|
579
|
+
const title = r[taskColIdx] || `Task ${idx + 1}`
|
|
580
|
+
const rawStartNum = Number(parseCellNumber(r[startIdx]).num)
|
|
581
|
+
const isZeroBasedQuarter = hasQuarters && !/Q[1-4]/i.test(r[startIdx]) && Number.isFinite(rawStartNum) && rawStartNum >= 0 && rawStartNum < columns.length && rawStarts.some(v => Number(parseCellNumber(v).num) === 0)
|
|
582
|
+
const st = isZeroBasedQuarter
|
|
583
|
+
? Math.max(0, Math.min(columns.length - 1, Math.floor(rawStartNum)))
|
|
584
|
+
: parseQuarterOrMonthIndex(r[startIdx], columns.length)
|
|
585
|
+
const enRaw = cleanLine(r[endIdx])
|
|
586
|
+
const isDuration = /duration|span|耗时|周期|跨度|时长|工期/i.test(headers[endIdx])
|
|
587
|
+
const span = isDuration
|
|
588
|
+
? Math.max(1, Math.min(columns.length - st, Math.round(Number(parseCellNumber(enRaw).num) || 1)))
|
|
589
|
+
: Math.max(1, Math.min(columns.length - st, parseQuarterOrMonthIndex(enRaw, columns.length) - st + 1))
|
|
590
|
+
const isMilestone = /里程碑|milestone|上线|发布|launch/i.test(title)
|
|
591
|
+
return {
|
|
592
|
+
tag: `T${idx + 1}`,
|
|
593
|
+
title,
|
|
594
|
+
text: isDuration ? `${columns[st]}–${columns[Math.min(columns.length - 1, st + span - 1)]}` : `${r[startIdx]} → ${r[endIdx]}`,
|
|
595
|
+
start: st,
|
|
596
|
+
span: isMilestone && span <= 1 ? 0 : span,
|
|
597
|
+
...(isMilestone ? { milestone: true, status: 'warning' } : (idx === 0 ? { status: 'accent' } : {})),
|
|
598
|
+
}
|
|
599
|
+
})
|
|
600
|
+
return {
|
|
601
|
+
layout: 'gantt',
|
|
602
|
+
variant: hasQuarters ? 'quarters' : 'months',
|
|
603
|
+
kicker: sheetName,
|
|
604
|
+
title: en
|
|
605
|
+
? `${sheetName}: ${items.length}-workstream execution roadmap spans ${columns[0]}–${columns[columns.length - 1]}`
|
|
606
|
+
: `${sheetName}:${items.length} 项核心任务覆盖 ${columns[0]}–${columns[columns.length - 1]} 交付节奏`,
|
|
607
|
+
columns,
|
|
608
|
+
items,
|
|
609
|
+
takeaway: en
|
|
610
|
+
? `Roadmap coordinates ${items.length} parallel tasks across ${columns.length} phases.`
|
|
611
|
+
: `全周期统筹推进 ${items.length} 项关键任务,明确阶段里程碑与交付窗口。`,
|
|
612
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Pattern B: Task + Period columns (Q1..Q4 / M1..M6 / Months)
|
|
617
|
+
const periodCols = cols.filter((c, i) => i !== taskColIdx && PERIOD_HEADER_RE.test(c.header))
|
|
618
|
+
if (periodCols.length >= 3) {
|
|
619
|
+
const usedPeriods = periodCols.slice(0, 8)
|
|
620
|
+
const columns = usedPeriods.map(c => c.header)
|
|
621
|
+
const activeHits = dataRows.reduce((cnt, r) => cnt + usedPeriods.filter(pc => GANTT_ACTIVE_RE.test(cleanLine(r[pc.index]))).length, 0)
|
|
622
|
+
if (activeHits >= dataRows.length) {
|
|
623
|
+
const items = dataRows.slice(0, 7).map((r, idx) => {
|
|
624
|
+
const flags = usedPeriods.map(pc => GANTT_ACTIVE_RE.test(cleanLine(r[pc.index])))
|
|
625
|
+
const first = flags.indexOf(true)
|
|
626
|
+
const last = flags.lastIndexOf(true)
|
|
627
|
+
const start = first >= 0 ? first : idx % columns.length
|
|
628
|
+
const span = first >= 0 ? Math.max(1, last - first + 1) : 1
|
|
629
|
+
const title = r[taskColIdx] || `Task ${idx + 1}`
|
|
630
|
+
return {
|
|
631
|
+
tag: `T${idx + 1}`,
|
|
632
|
+
title,
|
|
633
|
+
text: `${columns[start]}–${columns[Math.min(columns.length - 1, start + span - 1)]}`,
|
|
634
|
+
start,
|
|
635
|
+
span,
|
|
636
|
+
...(idx === 0 ? { status: 'accent' } : {}),
|
|
637
|
+
}
|
|
638
|
+
})
|
|
639
|
+
const variant = columns.every(c => /^Q[1-4]/i.test(c)) ? 'quarters' : columns.every(c => /^W\d/i.test(c)) ? 'weeks' : 'months'
|
|
640
|
+
return {
|
|
641
|
+
layout: 'gantt',
|
|
642
|
+
variant,
|
|
643
|
+
kicker: sheetName,
|
|
644
|
+
title: en
|
|
645
|
+
? `${sheetName}: Schedule spans ${columns[0]} through ${columns[columns.length - 1]} across ${items.length} tasks`
|
|
646
|
+
: `${sheetName}:${items.length} 项任务排期横跨 ${columns[0]} 至 ${columns[columns.length - 1]}`,
|
|
647
|
+
columns,
|
|
648
|
+
items,
|
|
649
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
return null
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function tryBuildMarimekkoSlide(sheetName, headers, dataRows, cols, en) {
|
|
658
|
+
if (cols.length < 3 || dataRows.length < 2) return null
|
|
659
|
+
|
|
660
|
+
// Pattern A: Long format -> [Segment, Size/Weight, Share1%, Share2%, ...]
|
|
661
|
+
const sizeCol = cols[1]
|
|
662
|
+
const shareCols = cols.slice(2).filter(c => c.isNumeric)
|
|
663
|
+
const shareLooksPct = shareCols.length >= 2 && shareCols.some(c => c.isPercentCol || /份额|占比|share|pct|%/i.test(c.header))
|
|
664
|
+
const sizeHeaderMatch = /规模|容量|体量|权重|总额|size|weight|tam|market|volume/i.test(sizeCol.header)
|
|
665
|
+
if (!cols[0].isNumeric && sizeCol.isNumeric && !sizeCol.isPercentCol && (shareLooksPct || sizeHeaderMatch)) {
|
|
666
|
+
const segRows = dataRows.slice(0, 6)
|
|
667
|
+
const headerOut = [headers[0] || 'Segment', ...segRows.map((r, idx) => {
|
|
668
|
+
const segName = r[0] || `Seg ${idx + 1}`
|
|
669
|
+
const sz = r[1] || ''
|
|
670
|
+
return `${segName} (${sz})`
|
|
671
|
+
})]
|
|
672
|
+
const competitorRows = shareCols.slice(0, 6).map(sc => [
|
|
673
|
+
sc.header.replace(/[%%()()]/g, '').trim() || sc.header,
|
|
674
|
+
...segRows.map(r => {
|
|
675
|
+
const p = sc.parsed[dataRows.indexOf(r)]
|
|
676
|
+
if (!p?.ok) return '0%'
|
|
677
|
+
const val = p.isPercent ? p.num : (p.num <= 1 ? p.num * 100 : p.num)
|
|
678
|
+
return `${Number(val.toFixed(1))}%`
|
|
679
|
+
}),
|
|
680
|
+
])
|
|
681
|
+
const totalSize = segRows.reduce((sum, r) => sum + (parseCellNumber(r[1]).num || 0), 0)
|
|
682
|
+
const topSeg = segRows.reduce((best, r) => (parseCellNumber(r[1]).num > parseCellNumber(best[1]).num ? r : best), segRows[0])
|
|
683
|
+
return {
|
|
684
|
+
layout: 'marimekko',
|
|
685
|
+
kicker: sheetName,
|
|
686
|
+
title: en
|
|
687
|
+
? `${sheetName}: ${topSeg[0]} leads ${formatNumCompact(totalSize, sizeCol.unit)} addressable landscape`
|
|
688
|
+
: `${sheetName}:${topSeg[0]} 领跑 ${formatNumCompact(totalSize, sizeCol.unit)} 细分市场格局`,
|
|
689
|
+
rows: [headerOut, ...competitorRows],
|
|
690
|
+
takeaway: en
|
|
691
|
+
? `Largest segment is ${topSeg[0]} (${topSeg[1]}); ${competitorRows.length} competitors mapped across ${segRows.length} segments.`
|
|
692
|
+
: `最大细分赛道为「${topSeg[0]}」(${topSeg[1]}),覆盖 ${competitorRows.length} 家竞争方份额分布。`,
|
|
693
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// Pattern B: Wide Marimekko -> headers carry weights or row 1 is Weight/Size + % rows
|
|
698
|
+
const pctRowCount = dataRows.filter(r => r.slice(1).some(c => /[%%]/.test(c))).length
|
|
699
|
+
const hasWeightHeader = headers.slice(1).some(h => /\(\s*\d/.test(h) || /(\s*\d/.test(h))
|
|
700
|
+
const hasWeightRow = dataRows.length >= 2 && /规模|容量|体量|权重|size|weight|tam/i.test(dataRows[0][0] || '')
|
|
701
|
+
if (pctRowCount >= 2 && (hasWeightHeader || hasWeightRow)) {
|
|
702
|
+
return {
|
|
703
|
+
layout: 'marimekko',
|
|
704
|
+
kicker: sheetName,
|
|
705
|
+
title: en ? `${sheetName}: Segment sizing & competitive share Marimekko` : `${sheetName}:细分市场规模与份额 Marimekko 格局`,
|
|
706
|
+
rows: [headers, ...dataRows].slice(0, 8),
|
|
707
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
return null
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function tryBuildWaterfallSlide(sheetName, headers, dataRows, cols, en) {
|
|
715
|
+
if (cols.length < 2 || cols.length > 3 || dataRows.length < 3 || dataRows.length > 12) return null
|
|
716
|
+
if (cols[0].isNumeric || !cols[1].isNumeric) return null
|
|
717
|
+
const cats = dataRows.map(r => r[0] || '')
|
|
718
|
+
const nums = cols[1].parsed.map(p => (p.ok ? p.num : 0))
|
|
719
|
+
const firstLabel = cats[0] || ''
|
|
720
|
+
const lastLabel = cats[cats.length - 1] || ''
|
|
721
|
+
const hasBridgeEnds = /(?:基线|期初|上期|起始|初始|base|start|begin|opening|q[1-4]\s*base)/i.test(firstLabel) ||
|
|
722
|
+
/(?:期末|合计|总计|净额|最终|end|total|final|net|closing)/i.test(lastLabel)
|
|
723
|
+
const hasMixedSigns = nums.slice(1, -1).some(v => v < 0) && nums.slice(1, -1).some(v => v > 0)
|
|
724
|
+
if (!hasBridgeEnds && !hasMixedSigns) return null
|
|
725
|
+
|
|
726
|
+
const totalIndices = [0]
|
|
727
|
+
if (/(?:期末|合计|总计|净额|最终|end|total|final|net|closing)/i.test(lastLabel)) {
|
|
728
|
+
totalIndices.push(cats.length - 1)
|
|
729
|
+
}
|
|
730
|
+
const unit = cols[1].unit
|
|
731
|
+
const startVal = nums[0]
|
|
732
|
+
const endVal = totalIndices.includes(cats.length - 1) ? nums[nums.length - 1] : nums.reduce((a, b) => a + b, 0)
|
|
733
|
+
const midSteps = cats.slice(1, totalIndices.includes(cats.length - 1) ? -1 : undefined).map((c, idx) => ({ name: c, val: nums[idx + 1] }))
|
|
734
|
+
const topDriver = midSteps.reduce((b, cur) => (cur.val > b.val ? cur : b), midSteps[0] || { name: '-', val: 0 })
|
|
735
|
+
const topDrag = midSteps.reduce((b, cur) => (cur.val < b.val ? cur : b), midSteps[0] || { name: '-', val: 0 })
|
|
736
|
+
|
|
737
|
+
return {
|
|
738
|
+
layout: 'chart-split',
|
|
739
|
+
variant: 'chart-left',
|
|
740
|
+
kicker: sheetName,
|
|
741
|
+
title: en
|
|
742
|
+
? `${sheetName}: Net bridge moves from ${formatNumCompact(startVal, unit)} to ${formatNumCompact(endVal, unit)}`
|
|
743
|
+
: `${sheetName}:核心指标由 ${formatNumCompact(startVal, unit)} 桥接至 ${formatNumCompact(endVal, unit)}`,
|
|
744
|
+
chart: {
|
|
745
|
+
kind: 'waterfall',
|
|
746
|
+
categories: cats,
|
|
747
|
+
series: [{ name: headers[1] || 'Bridge', values: nums }],
|
|
748
|
+
totalIndices,
|
|
749
|
+
unit,
|
|
750
|
+
showValues: true,
|
|
751
|
+
},
|
|
752
|
+
items: [
|
|
753
|
+
{ tag: en ? 'TOP DRIVER' : '最大正向拉动', title: topDriver.name, text: `${topDriver.val >= 0 ? '+' : ''}${formatNumCompact(topDriver.val, unit)}` },
|
|
754
|
+
...(topDrag.val < 0 ? [{ tag: en ? 'TOP DRAG' : '主要负向拖累', title: topDrag.name, text: formatNumCompact(topDrag.val, unit) }] : []),
|
|
755
|
+
{ tag: en ? 'NET CHANGE' : '净变动幅度', title: `${endVal >= startVal ? '+' : ''}${formatNumCompact(endVal - startVal, unit)}`, text: startVal !== 0 ? `${(((endVal - startVal) / Math.abs(startVal)) * 100).toFixed(1)}%` : '' },
|
|
756
|
+
],
|
|
757
|
+
takeaway: en
|
|
758
|
+
? `Primary upside comes from ${topDriver.name} (${topDriver.val >= 0 ? '+' : ''}${formatNumCompact(topDriver.val, unit)}).`
|
|
759
|
+
: `核心增量来自「${topDriver.name}」(${topDriver.val >= 0 ? '+' : ''}${formatNumCompact(topDriver.val, unit)})。`,
|
|
760
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function buildNumericSheetSlides(sheet, en) {
|
|
765
|
+
const { name: sheetName, bannerTitle, rows } = sheet
|
|
766
|
+
const headers = rows[0]
|
|
767
|
+
const dataRows = rows.slice(1)
|
|
768
|
+
const cols = profileColumns(rows)
|
|
769
|
+
const out = []
|
|
770
|
+
|
|
771
|
+
// 1) Sankey
|
|
772
|
+
if (isSankeySheet(headers, dataRows, cols)) {
|
|
773
|
+
const unit = cols[2].unit
|
|
774
|
+
const items = dataRows.slice(0, 12).map((r, idx) => {
|
|
775
|
+
const p = cols[2].parsed[idx]
|
|
776
|
+
const valStr = p.ok ? formatNumCompact(p.num, p.unit || unit) : cleanLine(r[2])
|
|
777
|
+
return {
|
|
778
|
+
tag: r[0],
|
|
779
|
+
title: r[1],
|
|
780
|
+
value: valStr,
|
|
781
|
+
...(r[3] ? { delta: r[3] } : {}),
|
|
782
|
+
}
|
|
783
|
+
})
|
|
784
|
+
const targetNames = new Set(dataRows.map(r => cleanLine(r[1])).filter(Boolean))
|
|
785
|
+
const rootOutSum = dataRows.reduce((s, r, idx) => {
|
|
786
|
+
const src = cleanLine(r[0])
|
|
787
|
+
const p = cols[2].parsed[idx]
|
|
788
|
+
return (!targetNames.has(src) && p?.ok) ? s + p.num : s
|
|
789
|
+
}, 0)
|
|
790
|
+
const allOutSum = cols[2].parsed.reduce((s, p) => s + (p.ok ? p.num : 0), 0)
|
|
791
|
+
const totalFlow = rootOutSum > 0 ? rootOutSum : allOutSum
|
|
792
|
+
const maxRowIdx = cols[2].parsed.reduce((bi, p, idx, arr) => (p.ok && p.num > (arr[bi]?.num ?? -Infinity) ? idx : bi), 0)
|
|
793
|
+
const maxRow = dataRows[maxRowIdx] || dataRows[0]
|
|
794
|
+
out.push({
|
|
795
|
+
layout: 'sankey',
|
|
796
|
+
kicker: sheetName,
|
|
797
|
+
title: en
|
|
798
|
+
? `${sheetName}: ${maxRow[0]} → ${maxRow[1]} leads ${formatNumCompact(totalFlow, unit)} total flow`
|
|
799
|
+
: `${sheetName}:「${maxRow[0]} → ${maxRow[1]}」主导 ${formatNumCompact(totalFlow, unit)} 核心流向`,
|
|
800
|
+
items,
|
|
801
|
+
takeaway: en
|
|
802
|
+
? `Top flow path is ${maxRow[0]} → ${maxRow[1]} (${maxRow[2]}).`
|
|
803
|
+
: `最大流量路径为「${maxRow[0]} → ${maxRow[1]}」(${maxRow[2]})。`,
|
|
804
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
805
|
+
})
|
|
806
|
+
return { slides: out, kpiSummary: { label: sheetName, value: formatNumCompact(totalFlow, unit), note: `${maxRow[0]} → ${maxRow[1]}` } }
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// 2) Gantt
|
|
810
|
+
const ganttSlide = tryBuildGanttSlide(sheetName, headers, dataRows, cols, en)
|
|
811
|
+
if (ganttSlide) {
|
|
812
|
+
out.push(ganttSlide)
|
|
813
|
+
return { slides: out, kpiSummary: { label: sheetName, value: String(ganttSlide.items.length), unit: en ? 'tasks' : '项任务', note: ganttSlide.columns.join('·') } }
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// 3) Marimekko
|
|
817
|
+
const mekkoSlide = tryBuildMarimekkoSlide(sheetName, headers, dataRows, cols, en)
|
|
818
|
+
if (mekkoSlide) {
|
|
819
|
+
out.push(mekkoSlide)
|
|
820
|
+
return { slides: out, kpiSummary: null }
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// 4) Waterfall
|
|
824
|
+
const waterfallSlide = tryBuildWaterfallSlide(sheetName, headers, dataRows, cols, en)
|
|
825
|
+
if (waterfallSlide) {
|
|
826
|
+
out.push(waterfallSlide)
|
|
827
|
+
const lastVal = cols[1].parsed[cols[1].parsed.length - 1]?.num ?? 0
|
|
828
|
+
return { slides: out, kpiSummary: { label: sheetName, value: formatNumCompact(lastVal, cols[1].unit), note: waterfallSlide.takeaway } }
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// 5) Numeric chart-split (Combo >10x scale ratio OR general column/bar/line) + Table appendix
|
|
832
|
+
const catCol = cols.find(c => !c.isNumeric) || cols[0]
|
|
833
|
+
const numCols = cols.filter(c => c.isNumeric && c.index !== catCol.index)
|
|
834
|
+
|
|
835
|
+
if (numCols.length >= 1) {
|
|
836
|
+
const chartRows = dataRows.slice(0, 12)
|
|
837
|
+
const categories = chartRows.map((r, idx) => r[catCol.index] || `#${idx + 1}`)
|
|
838
|
+
const primary = numCols[0]
|
|
839
|
+
const primaryVals = chartRows.map((_, idx) => (primary.parsed[idx]?.ok ? primary.parsed[idx].num : 0))
|
|
840
|
+
|
|
841
|
+
// Check 2+ numeric series with >10x scale ratio -> Combo dual-axis chart-split
|
|
842
|
+
let chartSpec
|
|
843
|
+
let kpiDelta = ''
|
|
844
|
+
if (numCols.length >= 2) {
|
|
845
|
+
const s0 = numCols[0]
|
|
846
|
+
const s1 = numCols[1]
|
|
847
|
+
const v0 = chartRows.map((_, idx) => (s0.parsed[idx]?.ok ? s0.parsed[idx].num : 0))
|
|
848
|
+
const v1 = chartRows.map((_, idx) => (s1.parsed[idx]?.ok ? s1.parsed[idx].num : 0))
|
|
849
|
+
const max0 = Math.max(1e-9, ...v0.map(Math.abs))
|
|
850
|
+
const max1 = Math.max(1e-9, ...v1.map(Math.abs))
|
|
851
|
+
const ratio = Math.max(max0 / max1, max1 / max0)
|
|
852
|
+
if (ratio > 10 || s0.isPercentCol !== s1.isPercentCol) {
|
|
853
|
+
const primaryIdx = max0 >= max1 ? 0 : 1
|
|
854
|
+
const majorCol = numCols[primaryIdx]
|
|
855
|
+
const minorCol = numCols[1 - primaryIdx]
|
|
856
|
+
const majorVals = primaryIdx === 0 ? v0 : v1
|
|
857
|
+
const minorVals = primaryIdx === 0 ? v1 : v0
|
|
858
|
+
chartSpec = {
|
|
859
|
+
kind: 'combo',
|
|
860
|
+
categories,
|
|
861
|
+
series: [
|
|
862
|
+
{ name: majorCol.header, values: majorVals, chartKind: 'column' },
|
|
863
|
+
{ name: minorCol.header, values: minorVals, chartKind: 'line', secondaryAxis: true },
|
|
864
|
+
],
|
|
865
|
+
unit: majorCol.unit,
|
|
866
|
+
showValues: categories.length <= 8,
|
|
867
|
+
}
|
|
868
|
+
const minorLast = minorVals[minorVals.length - 1]
|
|
869
|
+
kpiDelta = `${minorCol.header}: ${formatNumCompact(minorLast, minorCol.unit)}`
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (!chartSpec) {
|
|
874
|
+
const usedCols = numCols.slice(0, 3)
|
|
875
|
+
const isTime = categories.length >= 4 && categories.every(c => /^(?:20\d{2}|Q[1-4]|M\d{1,2}|\d{4}[-/]\d{1,2}|\d{1,2}月|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i.test(c))
|
|
876
|
+
const longLabels = categories.length > 7 || categories.some(c => c.length > 10)
|
|
877
|
+
const kind = isTime ? 'line' : (longLabels ? 'bar' : 'column')
|
|
878
|
+
chartSpec = {
|
|
879
|
+
kind,
|
|
880
|
+
categories,
|
|
881
|
+
series: usedCols.map(nc => ({
|
|
882
|
+
name: nc.header,
|
|
883
|
+
values: chartRows.map((_, idx) => (nc.parsed[idx]?.ok ? nc.parsed[idx].num : 0)),
|
|
884
|
+
})),
|
|
885
|
+
...(usedCols.length === 1 ? { highlight: 'max' } : {}),
|
|
886
|
+
unit: primary.unit,
|
|
887
|
+
showValues: categories.length <= 8 && usedCols.length <= 2,
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// Compute Top / Min / Average insight cards on primary series
|
|
892
|
+
const mainSeries = chartSpec.series[0]
|
|
893
|
+
const mainVals = mainSeries.values
|
|
894
|
+
const maxIdx = mainVals.reduce((bi, v, i, a) => (v > a[bi] ? i : bi), 0)
|
|
895
|
+
const minIdx = mainVals.reduce((bi, v, i, a) => (v < a[bi] ? i : bi), 0)
|
|
896
|
+
const sum = mainVals.reduce((a, b) => a + b, 0)
|
|
897
|
+
const avg = sum / Math.max(1, mainVals.length)
|
|
898
|
+
const firstVal = mainVals[0]
|
|
899
|
+
const lastVal = mainVals[mainVals.length - 1]
|
|
900
|
+
const growthPct = mainVals.length >= 2 && firstVal !== 0
|
|
901
|
+
? ((lastVal - firstVal) / Math.abs(firstVal)) * 100
|
|
902
|
+
: null
|
|
903
|
+
|
|
904
|
+
if (!kpiDelta && growthPct !== null && Number.isFinite(growthPct)) {
|
|
905
|
+
kpiDelta = `${growthPct >= 0 ? '+' : ''}${growthPct.toFixed(1)}%`
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const pUnit = primary.unit || chartSpec.unit || ''
|
|
909
|
+
const titlePrefix = bannerTitle || sheetName
|
|
910
|
+
out.push({
|
|
911
|
+
layout: 'chart-split',
|
|
912
|
+
variant: 'chart-left',
|
|
913
|
+
kicker: sheetName,
|
|
914
|
+
title: en
|
|
915
|
+
? `${titlePrefix}: ${categories[maxIdx]} peaks at ${formatNumCompact(mainVals[maxIdx], pUnit)} (avg ${formatNumCompact(avg, pUnit)})`
|
|
916
|
+
: `${titlePrefix}:「${categories[maxIdx]}」以 ${formatNumCompact(mainVals[maxIdx], pUnit)} 领跑(均值 ${formatNumCompact(avg, pUnit)})`,
|
|
917
|
+
chart: chartSpec,
|
|
918
|
+
items: [
|
|
919
|
+
{ tag: en ? 'PEAK' : '最高峰值', title: categories[maxIdx], text: `${mainSeries.name}: **${formatNumCompact(mainVals[maxIdx], pUnit)}**` },
|
|
920
|
+
{ tag: en ? 'LOWEST' : '最低谷值', title: categories[minIdx], text: `${mainSeries.name}: ${formatNumCompact(mainVals[minIdx], pUnit)}` },
|
|
921
|
+
{ tag: en ? 'AVERAGE' : '均值基准', title: formatNumCompact(avg, pUnit), text: growthPct !== null ? `${en ? 'Period change' : '首末变动'} ${growthPct >= 0 ? '+' : ''}${growthPct.toFixed(1)}%` : `${mainVals.length} ${en ? 'items' : '项统计'}` },
|
|
922
|
+
],
|
|
923
|
+
takeaway: en
|
|
924
|
+
? `${categories[maxIdx]} outperforms ${categories[minIdx]} by ${formatNumCompact(mainVals[maxIdx] - mainVals[minIdx], pUnit)}.`
|
|
925
|
+
: `最高项「${categories[maxIdx]}」高出最低项「${categories[minIdx]}」达 ${formatNumCompact(mainVals[maxIdx] - mainVals[minIdx], pUnit)}。`,
|
|
926
|
+
source: en ? `Source: Sheet "${sheetName}" (${dataRows.length} rows)` : `数据来源:工作表「${sheetName}」(共 ${dataRows.length} 行)`,
|
|
927
|
+
})
|
|
928
|
+
|
|
929
|
+
// Append full data table appendix (capped at 14 rows = max 2 paginated slides)
|
|
930
|
+
const tableColsCount = Math.min(6, headers.length)
|
|
931
|
+
const tableRows = [headers.slice(0, tableColsCount), ...dataRows.slice(0, 14).map(r => r.slice(0, tableColsCount))]
|
|
932
|
+
out.push({
|
|
933
|
+
layout: 'table',
|
|
934
|
+
tableStyle: 'consulting',
|
|
935
|
+
kicker: en ? `${sheetName} · Appendix` : `${sheetName} · 数据明细`,
|
|
936
|
+
title: en ? `${sheetName}: Complete metric breakdown (${dataRows.length} records)` : `${sheetName}:完整结构化明细数据(共 ${dataRows.length} 条)`,
|
|
937
|
+
rows: tableRows,
|
|
938
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
939
|
+
})
|
|
940
|
+
|
|
941
|
+
const topTotal = primary.isPercentCol ? avg : sum
|
|
942
|
+
return {
|
|
943
|
+
slides: out,
|
|
944
|
+
kpiSummary: {
|
|
945
|
+
label: `${sheetName} · ${mainSeries.name}`,
|
|
946
|
+
value: formatNumCompact(topTotal, pUnit),
|
|
947
|
+
delta: kpiDelta,
|
|
948
|
+
note: `${en ? 'Peak' : '峰值'}: ${categories[maxIdx]} (${formatNumCompact(mainVals[maxIdx], pUnit)})`,
|
|
949
|
+
},
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Fallback for purely textual tables
|
|
954
|
+
const tableRows = [headers.slice(0, 6), ...dataRows.slice(0, 14).map(r => r.slice(0, 6))]
|
|
955
|
+
out.push({
|
|
956
|
+
layout: 'table',
|
|
957
|
+
tableStyle: 'consulting',
|
|
958
|
+
kicker: sheetName,
|
|
959
|
+
title: en ? `${sheetName}: Structured summary (${dataRows.length} entries)` : `${sheetName}:结构化台账总览(共 ${dataRows.length} 条)`,
|
|
960
|
+
rows: tableRows,
|
|
961
|
+
source: en ? `Source: Sheet "${sheetName}"` : `数据来源:工作表「${sheetName}」`,
|
|
962
|
+
})
|
|
963
|
+
return { slides: out, kpiSummary: null }
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function profileTabularWorkbook(sheets, fileName, en) {
|
|
967
|
+
const baseTitle = cleanLine(fileName.replace(/\.[^.]+$/, '')) || (en ? 'Data Executive Report' : '数据洞察专项汇报')
|
|
968
|
+
const sheetNames = sheets.map(s => s.name)
|
|
969
|
+
const totalRows = sheets.reduce((s, sh) => s + Math.max(0, sh.rows.length - 1), 0)
|
|
970
|
+
|
|
971
|
+
const bodySlides = []
|
|
972
|
+
const kpiItems = []
|
|
973
|
+
|
|
974
|
+
for (const sheet of sheets) {
|
|
975
|
+
const profiled = buildNumericSheetSlides(sheet, en)
|
|
976
|
+
bodySlides.push(...profiled.slides)
|
|
977
|
+
if (profiled.kpiSummary && kpiItems.length < 4) {
|
|
978
|
+
kpiItems.push(profiled.kpiSummary)
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
if (kpiItems.length < 2) {
|
|
983
|
+
kpiItems.unshift(
|
|
984
|
+
{ label: en ? 'Sheets Analyzed' : '分析工作表数', value: String(sheets.length), unit: en ? 'sheets' : '张', note: sheetNames.slice(0, 3).join(' · ') },
|
|
985
|
+
{ label: en ? 'Data Records' : '总计数据记录', value: String(totalRows), unit: en ? 'rows' : '行', note: fileName },
|
|
986
|
+
)
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
const cover = {
|
|
990
|
+
layout: 'cover',
|
|
991
|
+
kicker: en ? 'OFFICE DATA INTELLIGENCE' : 'Excel / CSV 智能数据战报',
|
|
992
|
+
title: baseTitle,
|
|
993
|
+
subtitle: en
|
|
994
|
+
? `${sheets.length} sheet(s) · ${totalRows} data records automatically profiled`
|
|
995
|
+
: `自动解析 ${sheets.length} 张工作表 · 共 ${totalRows} 条业务数据记录`,
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
const execKpi = {
|
|
999
|
+
layout: 'kpi',
|
|
1000
|
+
variant: 'grid',
|
|
1001
|
+
kicker: en ? '01 · Executive Summary' : '01 · 核心指标总览',
|
|
1002
|
+
title: en
|
|
1003
|
+
? `Key highlights across ${sheets.length} dataset(s) and ${totalRows} records`
|
|
1004
|
+
: `核心业务指标汇总(覆盖 ${sheets.length} 张表 / ${totalRows} 条记录)`,
|
|
1005
|
+
items: kpiItems.slice(0, 4).map(k => ({
|
|
1006
|
+
tag: k.label,
|
|
1007
|
+
title: k.label,
|
|
1008
|
+
value: k.value,
|
|
1009
|
+
...(k.unit ? { unit: k.unit } : {}),
|
|
1010
|
+
...(k.delta ? { delta: k.delta, status: k.delta.startsWith('-') ? 'negative' : 'positive' } : {}),
|
|
1011
|
+
...(k.note ? { text: k.note } : {}),
|
|
1012
|
+
})),
|
|
1013
|
+
source: en ? `Source: ${fileName}` : `数据来源:${fileName}`,
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
const closing = {
|
|
1017
|
+
layout: 'closing',
|
|
1018
|
+
variant: 'cta-cards',
|
|
1019
|
+
kicker: en ? 'NEXT ACTIONS' : '下一步行动建议',
|
|
1020
|
+
title: en ? 'Review key anomalies and lock next-cycle targets' : '复核核心峰值异动,明确下阶段行动项',
|
|
1021
|
+
subtitle: en ? `Generated directly from ${fileName}` : `基于 ${fileName} 原始数据自动生成`,
|
|
1022
|
+
items: [
|
|
1023
|
+
{ tag: '01', title: en ? 'Verify Peak Drivers' : '复盘峰值动因', text: en ? 'Replicate top-performing segment mechanics' : '提炼领跑分项成功经验并横向复制' },
|
|
1024
|
+
{ tag: '02', title: en ? 'Address Bottlenecks' : '跟进短板整改', text: en ? 'Inspect trailing rows in appendix tables' : '结合明细附录排查落后项与风险点' },
|
|
1025
|
+
],
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const slides = [cover, execKpi, ...bodySlides, closing]
|
|
1029
|
+
return {
|
|
1030
|
+
title: baseTitle,
|
|
1031
|
+
language: en ? 'en' : 'zh',
|
|
1032
|
+
slides,
|
|
1033
|
+
stats: {
|
|
1034
|
+
sourceFormat: extname(fileName).slice(1).toLowerCase() || 'xlsx',
|
|
1035
|
+
sheetCount: sheets.length,
|
|
1036
|
+
totalRows,
|
|
1037
|
+
slideCount: slides.length,
|
|
1038
|
+
},
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// ---------------------------------------------------------------------------
|
|
1043
|
+
// .docx Word Report Parser
|
|
1044
|
+
// ---------------------------------------------------------------------------
|
|
1045
|
+
|
|
1046
|
+
function detectImageMime(bytes) {
|
|
1047
|
+
if (!bytes || bytes.length < 12) return null
|
|
1048
|
+
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png'
|
|
1049
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'
|
|
1050
|
+
if (bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'
|
|
1051
|
+
return null
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
function extractParagraphRunsMarkdown(pXml) {
|
|
1055
|
+
const runs = []
|
|
1056
|
+
for (const rMatch of pXml.matchAll(/<w:r\b[^>]*>([\s\S]*?)<\/w:r>/g)) {
|
|
1057
|
+
const rInner = rMatch[1]
|
|
1058
|
+
const rPr = /<w:rPr\b[^>]*>([\s\S]*?)<\/w:rPr>/.exec(rInner)?.[1] || ''
|
|
1059
|
+
const isBold = /<w:b\b(?![^>]*w:val=["'](?:0|false)["'])[^>]*\/?>/.test(rPr)
|
|
1060
|
+
const parts = []
|
|
1061
|
+
for (const tok of rInner.matchAll(/<w:t\b[^>]*>([\s\S]*?)<\/w:t>|<w:tab\b[^>]*\/?>|<w:br\b[^>]*\/?>/g)) {
|
|
1062
|
+
if (tok[0].startsWith('<w:tab')) parts.push(' ')
|
|
1063
|
+
else if (tok[0].startsWith('<w:br')) parts.push('\n')
|
|
1064
|
+
else parts.push(decodeXml(tok[1]))
|
|
1065
|
+
}
|
|
1066
|
+
const text = parts.join('')
|
|
1067
|
+
if (text) runs.push({ text, bold: isBold })
|
|
1068
|
+
}
|
|
1069
|
+
const merged = []
|
|
1070
|
+
for (const r of runs) {
|
|
1071
|
+
const last = merged[merged.length - 1]
|
|
1072
|
+
if (last && last.bold === r.bold) last.text += r.text
|
|
1073
|
+
else merged.push({ ...r })
|
|
1074
|
+
}
|
|
1075
|
+
const plain = merged.map(r => r.text).join('').replace(/[ \t]+/g, ' ').trim()
|
|
1076
|
+
if (!plain) return { plain: '', markdown: '', isAllBold: false }
|
|
1077
|
+
const hasBold = merged.some(r => r.bold && r.text.trim())
|
|
1078
|
+
const hasNonBold = merged.some(r => !r.bold && r.text.trim())
|
|
1079
|
+
if (!hasBold || !hasNonBold) {
|
|
1080
|
+
return { plain, markdown: plain, isAllBold: hasBold && !hasNonBold }
|
|
1081
|
+
}
|
|
1082
|
+
const md = merged.map(seg => {
|
|
1083
|
+
if (!seg.bold) return seg.text
|
|
1084
|
+
const m = /^(\s*)([\s\S]*?)(\s*)$/.exec(seg.text)
|
|
1085
|
+
return m && m[2] ? `${m[1]}**${m[2]}**${m[3]}` : seg.text
|
|
1086
|
+
}).join('').replace(/\*\*\s*\*\*/g, '').replace(/[ \t]+/g, ' ').trim()
|
|
1087
|
+
return { plain, markdown: md, isAllBold: false }
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
function splitBodyTopLevelBlocks(bodyXml) {
|
|
1091
|
+
const blocks = []
|
|
1092
|
+
let i = 0
|
|
1093
|
+
while (i < bodyXml.length) {
|
|
1094
|
+
const nextP = bodyXml.indexOf('<w:p', i)
|
|
1095
|
+
const nextTbl = bodyXml.indexOf('<w:tbl', i)
|
|
1096
|
+
if (nextP < 0 && nextTbl < 0) break
|
|
1097
|
+
const isTbl = nextTbl >= 0 && (nextP < 0 || nextTbl < nextP)
|
|
1098
|
+
const start = isTbl ? nextTbl : nextP
|
|
1099
|
+
const tag = isTbl ? 'w:tbl' : 'w:p'
|
|
1100
|
+
// Verify tag boundary
|
|
1101
|
+
const afterTag = bodyXml[start + tag.length + 1]
|
|
1102
|
+
if (afterTag !== '>' && afterTag !== ' ' && afterTag !== '/') {
|
|
1103
|
+
i = start + tag.length + 1
|
|
1104
|
+
continue
|
|
1105
|
+
}
|
|
1106
|
+
if (bodyXml[start + tag.length + 1] === '/' && bodyXml[start + tag.length + 2] === '>') {
|
|
1107
|
+
i = start + tag.length + 3
|
|
1108
|
+
continue
|
|
1109
|
+
}
|
|
1110
|
+
// Depth-aware close tag search for nested tables/paragraphs
|
|
1111
|
+
let depth = 0
|
|
1112
|
+
let cursor = start
|
|
1113
|
+
let end = -1
|
|
1114
|
+
const openRe = new RegExp(`<${tag}(?:\\s[^>]*)?>|<\\/${tag}>`, 'g')
|
|
1115
|
+
openRe.lastIndex = start
|
|
1116
|
+
let m
|
|
1117
|
+
while ((m = openRe.exec(bodyXml)) !== null) {
|
|
1118
|
+
if (m[0].startsWith(`</${tag}`)) {
|
|
1119
|
+
depth -= 1
|
|
1120
|
+
if (depth === 0) {
|
|
1121
|
+
end = openRe.lastIndex
|
|
1122
|
+
break
|
|
1123
|
+
}
|
|
1124
|
+
} else if (!m[0].endsWith('/>')) {
|
|
1125
|
+
depth += 1
|
|
1126
|
+
}
|
|
1127
|
+
cursor = openRe.lastIndex
|
|
1128
|
+
}
|
|
1129
|
+
if (end < 0) break
|
|
1130
|
+
blocks.push({ kind: isTbl ? 'tbl' : 'p', xml: bodyXml.slice(start, end) })
|
|
1131
|
+
i = end
|
|
1132
|
+
}
|
|
1133
|
+
return blocks
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
function parseDocxTable(tblXml) {
|
|
1137
|
+
const rows = []
|
|
1138
|
+
for (const trMatch of tblXml.matchAll(/<w:tr\b[^>]*>([\s\S]*?)<\/w:tr>/g)) {
|
|
1139
|
+
const row = []
|
|
1140
|
+
for (const tcMatch of trMatch[1].matchAll(/<w:tc\b[^>]*>([\s\S]*?)<\/w:tc>/g)) {
|
|
1141
|
+
const cellParas = []
|
|
1142
|
+
for (const pMatch of tcMatch[1].matchAll(/<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g)) {
|
|
1143
|
+
const { markdown } = extractParagraphRunsMarkdown(pMatch[0])
|
|
1144
|
+
if (markdown) cellParas.push(markdown)
|
|
1145
|
+
}
|
|
1146
|
+
row.push(cleanLine(cellParas.join(' ')))
|
|
1147
|
+
}
|
|
1148
|
+
if (row.some(Boolean)) rows.push(row)
|
|
1149
|
+
}
|
|
1150
|
+
if (rows.length < 2) return null
|
|
1151
|
+
const maxCols = Math.min(6, Math.max(...rows.map(r => r.length)))
|
|
1152
|
+
return rows.map(r => {
|
|
1153
|
+
const out = r.slice(0, maxCols)
|
|
1154
|
+
while (out.length < maxCols) out.push('')
|
|
1155
|
+
return out
|
|
1156
|
+
})
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
function parseDocxArchive(bytes, fileName) {
|
|
1160
|
+
const zip = openZipArchive(bytes)
|
|
1161
|
+
const docXml = zip.readText('word/document.xml')
|
|
1162
|
+
if (!docXml) {
|
|
1163
|
+
fail('Word 文档缺失 word/document.xml', 'Invalid .docx: missing word/document.xml')
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const relsMap = parseRelationshipsMap(zip.readText('word/_rels/document.xml.rels'))
|
|
1167
|
+
const mediaDataUris = new Map()
|
|
1168
|
+
for (const [rid, target] of relsMap.entries()) {
|
|
1169
|
+
const part = resolveZipTarget('word/document.xml', target)
|
|
1170
|
+
if (!part) continue
|
|
1171
|
+
const imgBytes = zip.readBuffer(part)
|
|
1172
|
+
if (!imgBytes || imgBytes.length > MAX_IMAGE_BYTES) continue
|
|
1173
|
+
const mime = detectImageMime(imgBytes)
|
|
1174
|
+
if (mime) {
|
|
1175
|
+
mediaDataUris.set(rid, {
|
|
1176
|
+
dataUri: `data:${mime};base64,${imgBytes.toString('base64')}`,
|
|
1177
|
+
name: basename(part),
|
|
1178
|
+
})
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
const bodyXml = /<w:body\b[^>]*>([\s\S]*?)<\/w:body>/.exec(docXml)?.[1] || docXml
|
|
1183
|
+
const blocks = splitBodyTopLevelBlocks(bodyXml)
|
|
1184
|
+
|
|
1185
|
+
let docTitle = ''
|
|
1186
|
+
let docSubtitle = ''
|
|
1187
|
+
const items = []
|
|
1188
|
+
let inMermaidFence = false
|
|
1189
|
+
let mermaidBuf = []
|
|
1190
|
+
|
|
1191
|
+
for (const blk of blocks) {
|
|
1192
|
+
if (blk.kind === 'tbl') {
|
|
1193
|
+
const rows = parseDocxTable(blk.xml)
|
|
1194
|
+
if (rows) items.push({ kind: 'table', rows })
|
|
1195
|
+
continue
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const pXml = blk.xml
|
|
1199
|
+
const pStyle = /<w:pStyle\b[^>]*w:val=["']([^"']+)["']/.exec(pXml)?.[1] || ''
|
|
1200
|
+
const hasListNum = /<w:numPr\b/.test(pXml) || /List/i.test(pStyle)
|
|
1201
|
+
const { plain, markdown, isAllBold } = extractParagraphRunsMarkdown(pXml)
|
|
1202
|
+
|
|
1203
|
+
const embedIds = []
|
|
1204
|
+
for (const em of pXml.matchAll(/(?:r:embed|r:id)=["']([^"']+)["']/g)) {
|
|
1205
|
+
if (mediaDataUris.has(em[1])) embedIds.push(mediaDataUris.get(em[1]))
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
if (inMermaidFence) {
|
|
1209
|
+
if (/^```/.test(plain)) {
|
|
1210
|
+
const code = mermaidBuf.join('\n').trim()
|
|
1211
|
+
if (code) items.push({ kind: 'mermaid', code })
|
|
1212
|
+
inMermaidFence = false
|
|
1213
|
+
mermaidBuf = []
|
|
1214
|
+
} else if (plain) {
|
|
1215
|
+
mermaidBuf.push(plain)
|
|
1216
|
+
}
|
|
1217
|
+
continue
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
if (/^```mermaid\b/i.test(plain)) {
|
|
1221
|
+
const rest = plain.replace(/^```mermaid\b/i, '').trim()
|
|
1222
|
+
if (rest.endsWith('```')) {
|
|
1223
|
+
const code = rest.slice(0, -3).trim()
|
|
1224
|
+
if (code) items.push({ kind: 'mermaid', code })
|
|
1225
|
+
} else {
|
|
1226
|
+
inMermaidFence = true
|
|
1227
|
+
mermaidBuf = rest ? [rest] : []
|
|
1228
|
+
}
|
|
1229
|
+
continue
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
if (/^(?:Title|标题)$/i.test(pStyle) && plain) {
|
|
1233
|
+
if (!docTitle) docTitle = plain
|
|
1234
|
+
continue
|
|
1235
|
+
}
|
|
1236
|
+
if (/^(?:Subtitle|副标题)$/i.test(pStyle) && plain) {
|
|
1237
|
+
if (!docSubtitle) docSubtitle = plain
|
|
1238
|
+
continue
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
const isH1 = /^(?:Heading\s*1|1|标题\s*1)$/i.test(pStyle) ||
|
|
1242
|
+
(/^[一二三四五六七八九十]+、\S+/.test(plain) && plain.length <= 42) ||
|
|
1243
|
+
(/^第[一二三四五六七八九十\d]+[章节部分]\s*\S+/.test(plain) && plain.length <= 42)
|
|
1244
|
+
const isH2 = /^(?:Heading\s*[23]|[23]|标题\s*[23])$/i.test(pStyle) ||
|
|
1245
|
+
(/^([一二三四五六七八九十]+)\S+/.test(plain) && plain.length <= 44) ||
|
|
1246
|
+
(/^\d+(?:\.\d+)?[.、]\s+\S+/.test(plain) && plain.length <= 44 && (isAllBold || !hasListNum))
|
|
1247
|
+
|
|
1248
|
+
if (isH1 && plain) {
|
|
1249
|
+
if (!docTitle && items.length === 0) {
|
|
1250
|
+
docTitle = plain
|
|
1251
|
+
} else {
|
|
1252
|
+
items.push({ kind: 'h1', text: plain })
|
|
1253
|
+
}
|
|
1254
|
+
} else if (isH2 && plain) {
|
|
1255
|
+
items.push({ kind: 'h2', text: plain })
|
|
1256
|
+
} else if (plain) {
|
|
1257
|
+
// Check standalone display formula $$...$$ or $...$
|
|
1258
|
+
const dispFormula = /^\$\$([\s\S]+)\$\$$/.exec(plain) || /^\$([^$]+)\$$/.exec(plain)
|
|
1259
|
+
if (dispFormula) {
|
|
1260
|
+
items.push({ kind: 'formula', formula: dispFormula[1].trim() })
|
|
1261
|
+
} else if (/^(?:flowchart|graph)\s+(?:TD|TB|LR|RL)\b|^sequenceDiagram\b/i.test(plain) && /(?:-->|-.->|->>|-->>)/.test(plain)) {
|
|
1262
|
+
items.push({ kind: 'mermaid', code: plain })
|
|
1263
|
+
} else {
|
|
1264
|
+
items.push({ kind: 'para', plain, markdown, isBullet: hasListNum })
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
for (const img of embedIds) {
|
|
1269
|
+
items.push({ kind: 'image', src: img.dataUri, alt: img.name })
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
if (inMermaidFence && mermaidBuf.length) {
|
|
1274
|
+
items.push({ kind: 'mermaid', code: mermaidBuf.join('\n').trim() })
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
const fallbackTitle = cleanLine(fileName.replace(/\.[^.]+$/, '')) || 'Word Report'
|
|
1278
|
+
const title = docTitle || fallbackTitle
|
|
1279
|
+
const sampleText = [title, docSubtitle, ...items.map(it => it.text || it.plain || '')].join(' ')
|
|
1280
|
+
const en = (sampleText.match(/[\u3400-\u9fff]/g) || []).length < 6
|
|
1281
|
+
|
|
1282
|
+
// Convert linear document items into cohesive structured slides (5-20 slides)
|
|
1283
|
+
const sections = []
|
|
1284
|
+
let cur = null
|
|
1285
|
+
const ensureSection = (heading, level = 2) => {
|
|
1286
|
+
if (!cur) {
|
|
1287
|
+
cur = { title: heading || title, level, bullets: [], tables: [], images: [], mermaids: [], formulas: [] }
|
|
1288
|
+
}
|
|
1289
|
+
return cur
|
|
1290
|
+
}
|
|
1291
|
+
const flushSection = () => {
|
|
1292
|
+
if (cur && (cur.bullets.length || cur.tables.length || cur.images.length || cur.mermaids.length || cur.formulas.length || cur.title !== title)) {
|
|
1293
|
+
sections.push(cur)
|
|
1294
|
+
}
|
|
1295
|
+
cur = null
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
for (const it of items) {
|
|
1299
|
+
if (it.kind === 'h1' || it.kind === 'h2') {
|
|
1300
|
+
flushSection()
|
|
1301
|
+
cur = { title: it.text, level: it.kind === 'h1' ? 1 : 2, bullets: [], tables: [], images: [], mermaids: [], formulas: [] }
|
|
1302
|
+
} else if (it.kind === 'para') {
|
|
1303
|
+
ensureSection(title)
|
|
1304
|
+
// Extract inline $...$ formula if embedded in paragraph
|
|
1305
|
+
const inlineF = /\$([^$\n]{2,120})\$/.exec(it.plain)
|
|
1306
|
+
if (inlineF && !cur.formulas.length) cur.formulas.push(inlineF[1].trim())
|
|
1307
|
+
cur.bullets.push(it.markdown)
|
|
1308
|
+
} else if (it.kind === 'table') {
|
|
1309
|
+
ensureSection(title)
|
|
1310
|
+
cur.tables.push(it.rows)
|
|
1311
|
+
} else if (it.kind === 'image') {
|
|
1312
|
+
ensureSection(title)
|
|
1313
|
+
cur.images.push({ src: it.src, alt: it.alt })
|
|
1314
|
+
} else if (it.kind === 'mermaid') {
|
|
1315
|
+
ensureSection(title)
|
|
1316
|
+
cur.mermaids.push(it.code)
|
|
1317
|
+
} else if (it.kind === 'formula') {
|
|
1318
|
+
ensureSection(title)
|
|
1319
|
+
cur.formulas.push(it.formula)
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
flushSection()
|
|
1323
|
+
|
|
1324
|
+
const slides = []
|
|
1325
|
+
slides.push({
|
|
1326
|
+
layout: 'cover',
|
|
1327
|
+
kicker: en ? 'WORD DOCUMENT BRIEF' : 'Word 报告智能成稿',
|
|
1328
|
+
title,
|
|
1329
|
+
subtitle: docSubtitle || (en ? `Synthesized from ${fileName}` : `由 ${fileName} 自动提炼并排版成稿`),
|
|
1330
|
+
})
|
|
1331
|
+
|
|
1332
|
+
if (sections.length >= 4) {
|
|
1333
|
+
slides.push({
|
|
1334
|
+
layout: 'agenda',
|
|
1335
|
+
variant: 'cards',
|
|
1336
|
+
kicker: en ? 'AGENDA' : '报告目录',
|
|
1337
|
+
title: en ? 'Report structure and key chapters' : '汇报核心章节与论证脉络',
|
|
1338
|
+
bullets: sections.slice(0, 6).map(s => s.title),
|
|
1339
|
+
})
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
let sectionNum = 0
|
|
1343
|
+
for (const sec of sections) {
|
|
1344
|
+
if (slides.length >= 19) break
|
|
1345
|
+
sectionNum += 1
|
|
1346
|
+
const kicker = `${String(sectionNum).padStart(2, '0')} · ${sec.title.slice(0, 18)}`
|
|
1347
|
+
|
|
1348
|
+
// Formulas -> callout(formula)
|
|
1349
|
+
if (sec.formulas.length > 0 && slides.length < 19) {
|
|
1350
|
+
slides.push({
|
|
1351
|
+
layout: 'callout',
|
|
1352
|
+
variant: 'formula',
|
|
1353
|
+
kicker,
|
|
1354
|
+
title: sec.title,
|
|
1355
|
+
formula: sec.formulas[0],
|
|
1356
|
+
bullets: sec.bullets.slice(0, 3),
|
|
1357
|
+
})
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// Mermaid blocks -> layout: 'mermaid'
|
|
1361
|
+
for (const code of sec.mermaids) {
|
|
1362
|
+
if (slides.length >= 19) break
|
|
1363
|
+
slides.push({
|
|
1364
|
+
layout: 'mermaid',
|
|
1365
|
+
kicker,
|
|
1366
|
+
title: sec.title,
|
|
1367
|
+
mermaid: code,
|
|
1368
|
+
})
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
// Embedded images -> image-right with paired bullets
|
|
1372
|
+
if (sec.images.length > 0 && slides.length < 19) {
|
|
1373
|
+
slides.push({
|
|
1374
|
+
layout: 'image-right',
|
|
1375
|
+
variant: 'framed',
|
|
1376
|
+
kicker,
|
|
1377
|
+
title: sec.title,
|
|
1378
|
+
image: { src: sec.images[0].src, alt: sec.images[0].alt || sec.title, fit: 'contain' },
|
|
1379
|
+
bullets: sec.bullets.slice(0, 4),
|
|
1380
|
+
})
|
|
1381
|
+
} else if (sec.bullets.length > 0 && sec.formulas.length === 0) {
|
|
1382
|
+
// Chunk bullets cleanly (<= 5 per slide)
|
|
1383
|
+
for (let i = 0; i < sec.bullets.length && slides.length < 19; i += 5) {
|
|
1384
|
+
const chunk = sec.bullets.slice(i, i + 5)
|
|
1385
|
+
slides.push({
|
|
1386
|
+
layout: 'bullets',
|
|
1387
|
+
kicker,
|
|
1388
|
+
title: i === 0 ? sec.title : `${sec.title} (${Math.floor(i / 5) + 1})`,
|
|
1389
|
+
bullets: chunk,
|
|
1390
|
+
})
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// Tables -> table slide
|
|
1395
|
+
for (const tbl of sec.tables) {
|
|
1396
|
+
if (slides.length >= 19) break
|
|
1397
|
+
slides.push({
|
|
1398
|
+
layout: 'table',
|
|
1399
|
+
tableStyle: 'consulting',
|
|
1400
|
+
kicker,
|
|
1401
|
+
title: sec.title,
|
|
1402
|
+
rows: tbl.slice(0, 8),
|
|
1403
|
+
})
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
// Ensure at least 5 slides for cohesive deck rhythm if document was short
|
|
1408
|
+
if (slides.length < 4 && sections.length === 0) {
|
|
1409
|
+
slides.push({
|
|
1410
|
+
layout: 'statement',
|
|
1411
|
+
kicker: '01',
|
|
1412
|
+
title,
|
|
1413
|
+
subtitle: docSubtitle || fileName,
|
|
1414
|
+
})
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
slides.push({
|
|
1418
|
+
layout: 'closing',
|
|
1419
|
+
variant: 'cta-cards',
|
|
1420
|
+
kicker: en ? 'NEXT STEPS' : '总结与后续行动',
|
|
1421
|
+
title: en ? 'Key conclusions and recommended next actions' : '核心结论确认与下一步推进计划',
|
|
1422
|
+
subtitle: en ? `Source document: ${fileName}` : `原始文档:${fileName}`,
|
|
1423
|
+
items: sections.slice(0, 3).map((s, idx) => ({
|
|
1424
|
+
tag: `0${idx + 1}`,
|
|
1425
|
+
title: s.title,
|
|
1426
|
+
text: s.bullets[0] ? cleanLine(s.bullets[0].replace(/\*\*/g, '')).slice(0, 60) : '',
|
|
1427
|
+
})),
|
|
1428
|
+
})
|
|
1429
|
+
|
|
1430
|
+
const promoted = promoteMarkdownSlides(slides, { explicitSmartLayout: true })
|
|
1431
|
+
return {
|
|
1432
|
+
title,
|
|
1433
|
+
language: en ? 'en' : 'zh',
|
|
1434
|
+
slides: promoted,
|
|
1435
|
+
stats: {
|
|
1436
|
+
sourceFormat: 'docx',
|
|
1437
|
+
sectionCount: sections.length,
|
|
1438
|
+
tableCount: items.filter(i => i.kind === 'table').length,
|
|
1439
|
+
imageCount: mediaDataUris.size,
|
|
1440
|
+
mermaidCount: items.filter(i => i.kind === 'mermaid').length,
|
|
1441
|
+
slideCount: promoted.length,
|
|
1442
|
+
},
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// ---------------------------------------------------------------------------
|
|
1447
|
+
// Public API: extractOfficeSource & importOfficeDeck
|
|
1448
|
+
// ---------------------------------------------------------------------------
|
|
1449
|
+
|
|
1450
|
+
/**
|
|
1451
|
+
* Extract structured slides & metadata from `.xlsx`, `.csv`, `.tsv`, or `.docx`.
|
|
1452
|
+
* Zero external new dependencies (uses Node zlib inflateRawSync + lazy csv-parse).
|
|
1453
|
+
*/
|
|
1454
|
+
export async function extractOfficeSource(options = {}) {
|
|
1455
|
+
abort(options.signal)
|
|
1456
|
+
const input = readOfficeInput(options)
|
|
1457
|
+
const enHint = options.lang === 'en'
|
|
1458
|
+
|
|
1459
|
+
if (input.format === 'xlsx') {
|
|
1460
|
+
const { sheets } = parseXlsxArchive(input.bytes)
|
|
1461
|
+
const sample = sheets.flatMap(s => s.rows.slice(0, 5).flat()).join(' ')
|
|
1462
|
+
const en = options.lang ? enHint : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
|
|
1463
|
+
const profiled = profileTabularWorkbook(sheets, input.fileName, en)
|
|
1464
|
+
return {
|
|
1465
|
+
ok: true,
|
|
1466
|
+
importedFrom: input.resolvedPath,
|
|
1467
|
+
...profiled,
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
if (input.format === 'csv' || input.format === 'tsv') {
|
|
1472
|
+
const rows = parseDelimitedText(input.bytes, input.format)
|
|
1473
|
+
const sample = rows.slice(0, 6).flat().join(' ')
|
|
1474
|
+
const en = options.lang ? enHint : (sample.match(/[\u3400-\u9fff]/g) || []).length < 4
|
|
1475
|
+
const sheetTitle = cleanLine(input.fileName.replace(/\.[^.]+$/, '')) || (en ? 'Dataset' : '数据表')
|
|
1476
|
+
const profiled = profileTabularWorkbook([{ name: sheetTitle, bannerTitle: '', rows }], input.fileName, en)
|
|
1477
|
+
return {
|
|
1478
|
+
ok: true,
|
|
1479
|
+
importedFrom: input.resolvedPath,
|
|
1480
|
+
...profiled,
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
const parsedDocx = parseDocxArchive(input.bytes, input.fileName)
|
|
1485
|
+
return {
|
|
1486
|
+
ok: true,
|
|
1487
|
+
importedFrom: input.resolvedPath,
|
|
1488
|
+
...parsedDocx,
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* Import an Office document (.xlsx / .csv / .tsv / .docx) directly into a full dsh-ppt deck
|
|
1494
|
+
* (HTML slideshow + 100% native editable PPTX + JSON project + optional handout/one-pager).
|
|
1495
|
+
*/
|
|
1496
|
+
export async function importOfficeDeck(options = {}) {
|
|
1497
|
+
abort(options.signal)
|
|
1498
|
+
const extracted = await extractOfficeSource(options)
|
|
1499
|
+
const { buildDeckAsync } = await import('./deck-advanced.mjs')
|
|
1500
|
+
|
|
1501
|
+
const requestedTheme = typeof options.theme === 'string' && options.theme.trim() ? options.theme.trim() : 'auto'
|
|
1502
|
+
const persona = typeof options.persona === 'string' && options.persona.trim() ? options.persona.trim() : 'auto'
|
|
1503
|
+
const title = (typeof options.title === 'string' && options.title.trim()) || extracted.title
|
|
1504
|
+
const lang = options.lang || extracted.language || 'zh'
|
|
1505
|
+
const inferred = requestedTheme === 'auto'
|
|
1506
|
+
? inferThemeFromContent({ title, slides: extracted.slides, persona }).theme
|
|
1507
|
+
: requestedTheme
|
|
1508
|
+
|
|
1509
|
+
const baseFileName = options.fileName ||
|
|
1510
|
+
cleanLine(basename(extracted.importedFrom || title).replace(/\.[^.]+$/, '')) ||
|
|
1511
|
+
title
|
|
1512
|
+
|
|
1513
|
+
const brand = options.chromeStyle
|
|
1514
|
+
? { ...(options.brand && typeof options.brand === 'object' ? options.brand : {}), chromeStyle: options.chromeStyle }
|
|
1515
|
+
: options.brand
|
|
1516
|
+
|
|
1517
|
+
const built = await buildDeckAsync({
|
|
1518
|
+
title,
|
|
1519
|
+
slides: extracted.slides,
|
|
1520
|
+
theme: inferred,
|
|
1521
|
+
persona,
|
|
1522
|
+
lang,
|
|
1523
|
+
motion: options.motion,
|
|
1524
|
+
brand,
|
|
1525
|
+
outputDir: options.outputDir || options.outDir || '.',
|
|
1526
|
+
fileName: baseFileName,
|
|
1527
|
+
overwrite: options.overwrite === true,
|
|
1528
|
+
smartLayout: false,
|
|
1529
|
+
handout: options.handout === true,
|
|
1530
|
+
onePager: options.onePager === true,
|
|
1531
|
+
...(options.targetMinutes !== undefined ? { targetMinutes: options.targetMinutes } : {}),
|
|
1532
|
+
cwd: options.cwd,
|
|
1533
|
+
signal: options.signal,
|
|
1534
|
+
})
|
|
1535
|
+
|
|
1536
|
+
return {
|
|
1537
|
+
...built,
|
|
1538
|
+
importedFrom: extracted.importedFrom,
|
|
1539
|
+
officeStats: extracted.stats,
|
|
1540
|
+
}
|
|
1541
|
+
}
|