@zhangxij/dsh-positions 0.3.0 → 0.3.1

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/README.md CHANGED
@@ -5,17 +5,27 @@
5
5
  大多数看盘软件告诉你「现在多少钱」,但不告诉你「买完这 200 股之后,我的成本、仓位、保本价会变成多少」。
6
6
  这个插件只做这一件事,顺便把持仓和成交流水记下来。
7
7
 
8
- > 不含行情、不联网、不荐股。所有数字都来自你自己录入的成交记录。
8
+ > 不含行情、不联网(截图识别需手动开启)、不荐股。所有数字都来自你自己录入的成交记录。
9
+
10
+ ## 最近更新(v0.3.1)
11
+
12
+ - **备注列**:每只股票可以写一句下一步计划(如「跌破 9.5 减半仓」),直接显示在表格里;
13
+ - **统一录入**:一个入口同时支持 **Ctrl+V 粘贴截图**、**拖入文件**、**选择文件(CSV / XLSX / TXT)** 和 **粘贴文本**;
14
+ - **按价格自动匹配**:没写股票名的成交,按价格匹配到已有持仓,匹配不上的在预览里手动选;
15
+ - **归档 / 删除**:归档保留数据、从统计里隐藏;删除才真正移除;
16
+ - **费率规则**:默认东方财富,可新建多家券商(佣金率、最低佣金、印花税、过户费、其他固定费用);
17
+ - **分红**:按「每股分红 × 股数」记账,红利税按持股期自动估算;
18
+ - **表头管理**:可新增自定义列(股票代码、备注等)、调整顺序,内置列不可删。
9
19
 
10
20
  ## 截图
11
21
 
12
22
  ![持仓总览](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/01-overview.jpg)
13
23
 
14
- ![展开后的历史记录与测算](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/02-calc.jpg)
24
+ ![录入:粘贴截图 / 拖文件 / 粘贴文本](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/02-entry.jpg)
15
25
 
16
- ![测算弹窗](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/03-modal.jpg)
26
+ ![费率规则](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/03-fees.jpg)
17
27
 
18
- ![分组弹窗](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/04-groups.jpg)
28
+ ![展开后的历史记录与测算](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/04-calc.jpg)
19
29
 
20
30
  ## 安装
21
31
 
package/client.js CHANGED
@@ -116,6 +116,7 @@ window.__ModuleLoader__.load({
116
116
  case 'cumQty': return s.cumQty
117
117
  case 'cumInvest': return s.cumInvest.toFixed(2)
118
118
  case 'cost': return s.last && s.last.cost !== null ? s.last.cost.toFixed(3) : '—'
119
+ case 'note': return s.note || ''
119
120
  default: return (s.fields && s.fields[key]) || '—'
120
121
  }
121
122
  }
@@ -138,9 +139,9 @@ window.__ModuleLoader__.load({
138
139
  .pos-btn.primary:hover { background:#1d4ac0; color:#fff; }
139
140
  .pos-btn:disabled { opacity:.5; cursor:default; }
140
141
  .pos-card { background:#fff; border:1px solid #dde3ee; border-radius:12px; }
141
- .pos-form { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding:10px 12px; margin-bottom:12px; }
142
+ .pos-form { display:flex; gap:8px; align-items:center; flex-wrap:nowrap; overflow-x:auto; padding:10px 12px; margin-bottom:12px; }
142
143
  .pos-input, .pos-select { height:30px; border-radius:8px; border:1px solid #dde3ee; background:#fff; color:#1f2937; padding:0 8px; font-size:12px; }
143
- .pos-input.num { width:100px; text-align:right; }
144
+ .pos-input.num { width:84px; text-align:right; }
144
145
  .pos-filters { display:flex; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
145
146
  .pos-filter { flex:1 1 320px; padding:10px 12px; }
146
147
  .pos-filter-head { display:flex; align-items:center; justify-content:space-between; font-weight:600; font-size:13px; margin-bottom:8px; gap:8px; }
@@ -204,6 +205,31 @@ window.__ModuleLoader__.load({
204
205
  .pos-fee-field .unit { font-size:11px; color:#98a2b3; margin-left:4px; }
205
206
  .pos-fee-preview { margin-top:6px; border:1px solid #dde3ee; border-radius:8px; padding:8px; background:#fbfcff; }
206
207
  .pos-fee-preview img { max-width:100%; max-height:180px; border-radius:6px; display:block; }
208
+ .pos-note-cell { max-width:190px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:#2457d6; cursor:pointer; }
209
+ .pos-note-cell:hover { text-decoration:underline; }
210
+ .pos-import-table { width:100%; border-collapse:collapse; font-size:12px; margin-top:10px; }
211
+ .pos-import-table th, .pos-import-table td { padding:6px 8px; text-align:left; border-bottom:1px solid #eef1f6; }
212
+ .pos-import-table th { background:#f8fafc; font-weight:600; color:#475467; }
213
+ .pos-import-table tr.unmatched td { background:#feeceb; }
214
+ .pos-import-select { height:28px; border-radius:6px; border:1px solid #dde3ee; background:#fff; font-size:12px; padding:0 6px; max-width:150px; }
215
+ .pos-drop { border:2px dashed #c7d2e5; border-radius:12px; padding:18px; text-align:center; color:#667085; font-size:12px;
216
+ background:#fbfcff; margin-bottom:10px; }
217
+ .pos-drop.hot { border-color:#2457d6; background:#f2f6ff; color:#2457d6; }
218
+ .pos-drop strong { color:#1f2937; font-size:13px; display:block; margin-bottom:4px; }
219
+ .pos-quick { display:flex; align-items:center; gap:10px; flex-wrap:wrap; padding:10px 12px; border:1px solid #b7e4cf;
220
+ background:#e8f7f0; border-radius:10px; margin-top:10px; font-size:12px; }
221
+ .pos-netrow { display:flex; align-items:center; gap:10px; padding:10px 12px; margin-bottom:10px;
222
+ border:1px solid #dde3ee; border-radius:10px; background:#fbfcff; font-size:12px; color:#344054; }
223
+ .pos-switch { position:relative; width:44px; height:24px; border-radius:999px; background:#d0d5dd;
224
+ cursor:pointer; transition:background .2s; flex:none; border:none; padding:0; }
225
+ .pos-switch.on { background:#2457d6; }
226
+ .pos-switch::after { content:''; position:absolute; top:3px; left:3px; width:18px; height:18px; border-radius:50%;
227
+ background:#fff; transition:transform .2s; box-shadow:0 1px 3px rgba(0,0,0,.25); }
228
+ .pos-switch.on::after { transform:translateX(20px); }
229
+ .pos-netrow .hint { color:#667085; }
230
+
231
+
232
+
207
233
  `
208
234
 
209
235
  /* ------------------------------------------------------------ 图标 */
@@ -382,6 +408,506 @@ window.__ModuleLoader__.load({
382
408
  )
383
409
  }
384
410
 
411
+ /* -------------------------------------------------------- 备注弹窗 */
412
+
413
+ function NoteModal(props) {
414
+ const { stock, onClose, onSave } = props
415
+ const [text, setText] = useState(stock.note || '')
416
+ return h(Modal, { title: '备注 · ' + stock.name, onClose, maxWidth: 560 },
417
+ h('p', { className: 'pos-sub', style: { marginTop: 0 } }, '写下接下来打算怎么操作这只股票,例如「跌破 9.5 减半仓」。备注会显示在持仓表这一行。'),
418
+ h('textarea', {
419
+ className: 'pos-input', style: { width: '100%', height: 120, padding: 8, lineHeight: 1.6 },
420
+ maxLength: 500, placeholder: '例如:等回踩 9.8 附近加仓 200 股', value: text,
421
+ onChange: (e) => setText(e.target.value)
422
+ }),
423
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 12 } },
424
+ h('button', { className: 'pos-btn', onClick: () => onSave('') }, '清除'),
425
+ h('button', { className: 'pos-btn', onClick: onClose }, '取消'),
426
+ h('button', { className: 'pos-btn primary', onClick: () => onSave(text.trim()) }, '保存备注')
427
+ )
428
+ )
429
+ }
430
+
431
+ /* -------------------------------------------------------- 导入弹窗 */
432
+
433
+ function normSide(value) {
434
+ const v = String(value || '').trim().toLowerCase()
435
+ if (v === '买入' || v === '买' || v === 'b' || v === 'buy') return '买入'
436
+ if (v === '卖出' || v === '卖' || v === 's' || v === 'sell') return '卖出'
437
+ if (v === '分红' || v === '红利' || v === 'dividend') return '分红'
438
+ return ''
439
+ }
440
+
441
+ function parseImport(text) {
442
+ const lines = String(text || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
443
+ if (!lines.length) return []
444
+ const isHeader = /日期|date|方向|side|价格|price/i.test(lines[0])
445
+ const head = lines[0].split(',').map((s) => s.trim().toLowerCase())
446
+ const pick = (...names) => head.findIndex((cell) => names.some((n) => cell === n || cell.includes(n)))
447
+ const idx = isHeader
448
+ ? {
449
+ date: pick('日期', 'date'), side: pick('方向', 'side', '买卖'),
450
+ price: pick('价格', 'price', '成交价'), qty: pick('数量', 'qty', '成交量', '股数'),
451
+ fee: pick('费用', 'fee', '手续费', '佣金'), name: pick('股票', '名称', 'name', 'stock')
452
+ }
453
+ : { date: 0, side: 1, price: 2, qty: 3, fee: 4, name: 5 }
454
+
455
+ return (isHeader ? lines.slice(1) : lines).map((line) => {
456
+ const cells = line.split(',').map((s) => s.trim())
457
+ const get = (i) => (i >= 0 && cells[i] !== undefined ? cells[i] : '')
458
+ return {
459
+ date: get(idx.date) || today(),
460
+ side: normSide(get(idx.side)),
461
+ price: get(idx.price),
462
+ qty: get(idx.qty),
463
+ fee: get(idx.fee),
464
+ name: get(idx.name)
465
+ }
466
+ }).filter((r) => r.side && Number(r.price) > 0 && Number(r.qty) > 0)
467
+ }
468
+
469
+ function matchByPrice(stocks, price) {
470
+ const p = Number(price)
471
+ if (!(p > 0)) return ''
472
+ const hits = stocks.filter((s) => {
473
+ if (Number(s.price) > 0 && Math.abs(Number(s.price) - p) / p < 0.005) return true
474
+ const last = s.records && s.records.length ? s.records[s.records.length - 1] : null
475
+ return last && Math.abs(Number(last.price) - p) / p < 0.005
476
+ })
477
+ return hits.length === 1 ? hits[0].name : ''
478
+ }
479
+
480
+ function ImportModal(props) {
481
+ const { stocks, onClose, onImport, initialText } = props
482
+ const [text, setText] = useState(initialText || '')
483
+ const [rows, setRows] = useState([])
484
+ const [note, setNote] = useState('')
485
+
486
+ const parse = (raw) => {
487
+ const parsed = parseImport(raw).map((r) => {
488
+ const explicit = r.name && stocks.some((s) => s.name === r.name)
489
+ const auto = !explicit && !r.name ? matchByPrice(stocks, r.price) : ''
490
+ return Object.assign({}, r, { name: explicit ? r.name : (r.name || auto), auto: !explicit && !!auto })
491
+ })
492
+ const autoCount = parsed.filter((r) => r.auto).length
493
+ setRows(parsed)
494
+ setNote(parsed.length
495
+ ? '解析到 ' + parsed.length + ' 条' + (autoCount ? ',其中 ' + autoCount + ' 条没写股票名,已按价格自动匹配(标「按价格匹配」)' : '') + ',请核对后再导入'
496
+ : '没有解析到有效行,格式示例:2026-11-20,买入,9.50,500,,贵州茅台')
497
+ }
498
+
499
+ useEffect(() => { if (initialText) parse(initialText) }, [])
500
+
501
+ const pickFile = (file) => {
502
+ if (!file) return
503
+ if (/\.xlsx$/i.test(file.name)) {
504
+ const reader = new FileReader()
505
+ reader.onload = async () => {
506
+ try {
507
+ const base64 = String(reader.result || '').split(',')[1] || ''
508
+ const res = await fetch(API + '/parse-xlsx', {
509
+ method: 'POST',
510
+ headers: { 'content-type': 'application/json' },
511
+ body: JSON.stringify({ data: base64 })
512
+ })
513
+ const json = await res.json()
514
+ if (!json.ok) throw new Error(json.error || '解析失败')
515
+ const raw = (json.lines || []).join('\n')
516
+ setText(raw)
517
+ parse(raw)
518
+ } catch (err) {
519
+ setNote('Excel 解析失败:' + String(err.message || err))
520
+ }
521
+ }
522
+ reader.readAsDataURL(file)
523
+ return
524
+ }
525
+ if (/\.xls$/i.test(file.name)) {
526
+ setNote('旧版 .xls 不支持,请在 Excel 里另存为 .xlsx 或 .csv')
527
+ return
528
+ }
529
+ const reader = new FileReader()
530
+ reader.onload = () => { const raw = String(reader.result || ''); setText(raw); parse(raw) }
531
+ reader.readAsText(file, 'utf-8')
532
+ }
533
+
534
+ const setRow = (i, name) => setRows((prev) => prev.map((r, idx) => (idx === i ? Object.assign({}, r, { name }) : r)))
535
+ const unmatched = rows.filter((r) => !r.name).length
536
+
537
+ return h(Modal, { title: '导入成交(CSV / 文本)', onClose, maxWidth: 900 },
538
+ h('p', { className: 'pos-sub', style: { marginTop: 0 } },
539
+ '每行格式:日期,方向,价格,数量,费用(可空),股票名称(可空)。' +
540
+ '没写股票名称时,会按价格匹配已有持仓(误差 0.5%);匹配不上或有多只候选时,请在下面手动选。'),
541
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8 } },
542
+ h('input', { type: 'file', accept: '.csv,.txt,.xlsx,text/csv,text/plain', onChange: (e) => pickFile(e.target.files && e.target.files[0]) }),
543
+ h('button', { className: 'pos-mini', onClick: () => parse(text) }, '解析预览')
544
+ ),
545
+ h('textarea', {
546
+ className: 'pos-input', style: { width: '100%', height: 110, padding: 8, lineHeight: 1.6 },
547
+ placeholder: '2026-11-20,买入,9.50,500,,\n2026-11-21,卖出,11.00,300,3.20,贵州茅台',
548
+ value: text, onChange: (e) => setText(e.target.value)
549
+ }),
550
+ note ? h('p', { className: 'pos-note' }, note) : null,
551
+ rows.length
552
+ ? h('table', { className: 'pos-import-table' },
553
+ h('thead', null, h('tr', null, ['日期', '方向', '价格', '数量', '费用', '匹配股票'].map((t, i) => h('th', { key: i }, t)))),
554
+ h('tbody', null, rows.map((r, i) => h('tr', { key: i, className: r.name ? '' : 'unmatched' },
555
+ h('td', null, r.date),
556
+ h('td', null, r.side),
557
+ h('td', null, r.price),
558
+ h('td', null, r.qty),
559
+ h('td', null, r.fee || '—'),
560
+ h('td', null, r.auto ? h('span', { className: 'pos-chip', style: { height: 20, fontSize: 10, marginRight: 4, background: '#fff7e6', borderColor: '#f3d19e', color: '#b45309' } }, '按价格匹配') : null,
561
+ h('select', { className: 'pos-import-select', value: r.name, onChange: (e) => setRow(i, e.target.value) },
562
+ h('option', { value: '' }, '— 请选择 —'),
563
+ stocks.map((s) => h('option', { key: s.name, value: s.name }, s.name))
564
+ ))
565
+ )))
566
+ )
567
+ : null,
568
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
569
+ unmatched ? h('span', { className: 'pos-error', style: { marginRight: 'auto' } }, '还有 ' + unmatched + ' 行未匹配') : null,
570
+ h('button', { className: 'pos-btn', onClick: onClose }, '取消'),
571
+ h('button', { className: 'pos-btn primary', disabled: !rows.length || unmatched > 0, onClick: () => onImport(rows) }, '确认导入')
572
+ )
573
+ )
574
+ }
575
+
576
+ /* -------------------------------------------------------- 图片识别 */
577
+
578
+ function ImageModal(props) {
579
+ const { state, onClose, onRecognized, onPatch } = props
580
+ const vision = state.vision || {}
581
+ const [draft, setDraft] = useState({ baseUrl: vision.baseUrl || '', apiKey: vision.apiKey || '', model: vision.model || '' })
582
+ const [busy, setBusy] = useState(false)
583
+ const [err, setErr] = useState('')
584
+ const [saved, setSaved] = useState(false)
585
+ const configured = !!(vision.apiKey && vision.baseUrl && vision.model)
586
+ const enabled = vision.enabled === true
587
+
588
+ const saveConfig = async () => {
589
+ await onPatch('setVision', draft)
590
+ setSaved(true)
591
+ }
592
+
593
+ const upload = (file) => {
594
+ if (!file) return
595
+ if (!configured) { setErr('请先保存 Base URL / API Key / 模型'); return }
596
+ if (file.size > 4 * 1024 * 1024) { setErr('图片请小于 4MB'); return }
597
+ const reader = new FileReader()
598
+ reader.onload = async () => {
599
+ setBusy(true); setErr('')
600
+ try {
601
+ const res = await fetch(API + '/recognize', {
602
+ method: 'POST',
603
+ headers: { 'content-type': 'application/json' },
604
+ body: JSON.stringify({ image: String(reader.result || '') })
605
+ })
606
+ const json = await res.json()
607
+ if (!json.ok) throw new Error(json.error || '识别失败')
608
+ const rows = Array.isArray(json.rows) ? json.rows : []
609
+ if (!rows.length) { setErr('没有从图片里识别出成交记录,换一张更清晰的试试'); return }
610
+ const lines = rows.map((r) => [r.date || '', r.side || '', r.price || '', r.qty || '', '', r.name || ''].join(','))
611
+ onRecognized(lines)
612
+ } catch (e) {
613
+ setErr(String(e.message || e))
614
+ } finally {
615
+ setBusy(false)
616
+ }
617
+ }
618
+ reader.readAsDataURL(file)
619
+ }
620
+
621
+ return h(Modal, { title: '上传图片识别(需要联网)', onClose, maxWidth: 620 },
622
+ h('p', { className: 'pos-sub', style: { marginTop: 0 } },
623
+ '识别时会把这张截图发送到你自己配置的视觉接口(走网络),不会上传到别处。第一次使用请先填好接口信息。'),
624
+ h('div', { className: 'pos-fee-grid' },
625
+ h('div', { className: 'pos-fee-field' },
626
+ h('label', null, 'Base URL'),
627
+ h('input', { className: 'pos-input', placeholder: 'https://api.openai.com/v1', value: draft.baseUrl, onChange: (e) => setDraft(Object.assign({}, draft, { baseUrl: e.target.value })) })
628
+ ),
629
+ h('div', { className: 'pos-fee-field' },
630
+ h('label', null, '模型'),
631
+ h('input', { className: 'pos-input', placeholder: 'gpt-4o-mini / qwen-vl-max', value: draft.model, onChange: (e) => setDraft(Object.assign({}, draft, { model: e.target.value })) })
632
+ ),
633
+ h('div', { className: 'pos-fee-field' },
634
+ h('label', null, 'API Key'),
635
+ h('input', { className: 'pos-input', type: 'password', placeholder: 'sk-…', value: draft.apiKey, onChange: (e) => setDraft(Object.assign({}, draft, { apiKey: e.target.value })) })
636
+ )
637
+ ),
638
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginTop: 12 } },
639
+ h('button', { className: 'pos-btn', onClick: saveConfig }, '保存配置'),
640
+ saved ? h('span', { className: 'pos-chip ok', style: { height: 26 } }, '已保存') : null,
641
+ configured ? h('span', { className: 'pos-chip ok', style: { height: 26 } }, '已配置') : h('span', { className: 'pos-chip warn', style: { height: 26 } }, '未配置')
642
+ ),
643
+ err ? h('p', { className: 'pos-error' }, err) : null,
644
+ h('div', { style: { marginTop: 12 } },
645
+ h('div', { className: 'pos-muted', style: { fontSize: 12, marginBottom: 6 } }, '选择截图(成交记录 / 对账单)'),
646
+ h('input', { type: 'file', accept: 'image/*', disabled: busy, onChange: (e) => upload(e.target.files && e.target.files[0]) })
647
+ ),
648
+ h('p', { className: 'pos-note' }, '图片会先转成文字行,再进入导入预览,你可以逐行核对、改股票、再确认导入。')
649
+ )
650
+ }
651
+
652
+ /* -------------------------------------------------------- 统一录入 */
653
+
654
+ function EntryPanel(props) {
655
+ const { stocks, state, seed, onClose, onImport, onPatch } = props
656
+ const [text, setText] = useState('')
657
+ const [rows, setRows] = useState([])
658
+ const [note, setNote] = useState('')
659
+ const [error, setError] = useState('')
660
+ const [busy, setBusy] = useState(false)
661
+ const [hot, setHot] = useState(false)
662
+ const [showVision, setShowVision] = useState(false)
663
+ const vision = state.vision || {}
664
+ const [vdraft, setVdraft] = useState({ baseUrl: vision.baseUrl || '', apiKey: vision.apiKey || '', model: vision.model || '' })
665
+ const configured = !!(vision.apiKey && vision.baseUrl && vision.model)
666
+ const enabled = vision.enabled === true
667
+
668
+ const parse = (raw) => {
669
+ const parsed = parseImport(raw).map((r) => {
670
+ const explicit = r.name && stocks.some((s) => s.name === r.name)
671
+ const auto = !explicit && !r.name ? matchByPrice(stocks, r.price) : ''
672
+ return Object.assign({}, r, { name: explicit ? r.name : (r.name || auto), auto: !explicit && !!auto })
673
+ })
674
+ const autoCount = parsed.filter((r) => r.auto).length
675
+ setRows(parsed)
676
+ setNote(parsed.length
677
+ ? '解析到 ' + parsed.length + ' 条' + (autoCount ? ',其中 ' + autoCount + ' 条没写股票名,已按价格自动匹配' : '') + ',请核对后再导入'
678
+ : '没有解析到有效行。格式:日期,方向,价格,数量,费用(可空),股票名称(可空)')
679
+ }
680
+
681
+ const fileToDataUrl = (file) => new Promise((resolvePromise, rejectPromise) => {
682
+ const reader = new FileReader()
683
+ reader.onload = () => resolvePromise(String(reader.result || ''))
684
+ reader.onerror = rejectPromise
685
+ reader.readAsDataURL(file)
686
+ })
687
+
688
+ const shrinkImage = (file) => new Promise((resolvePromise) => {
689
+ try {
690
+ const img = new Image()
691
+ const url = URL.createObjectURL(file)
692
+ img.onload = () => {
693
+ const max = 1800
694
+ const scale = Math.min(1, max / Math.max(img.width || 1, img.height || 1))
695
+ const canvas = document.createElement('canvas')
696
+ canvas.width = Math.max(1, Math.round((img.width || 1) * scale))
697
+ canvas.height = Math.max(1, Math.round((img.height || 1) * scale))
698
+ canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height)
699
+ URL.revokeObjectURL(url)
700
+ resolvePromise(canvas.toDataURL('image/jpeg', 0.9))
701
+ }
702
+ img.onerror = () => { URL.revokeObjectURL(url); resolvePromise(null) }
703
+ img.src = url
704
+ } catch {
705
+ resolvePromise(null)
706
+ }
707
+ })
708
+
709
+ const readText = (file) => new Promise((resolvePromise, rejectPromise) => {
710
+ const reader = new FileReader()
711
+ reader.onload = () => resolvePromise(String(reader.result || ''))
712
+ reader.onerror = rejectPromise
713
+ reader.readAsText(file, 'utf-8')
714
+ })
715
+
716
+ const recognize = async (file) => {
717
+ if (!enabled) {
718
+ setError('截图识别需要联网:请先打开上面的「联网识别截图」开关' + (configured ? '' : '(默认用当前 Harness 模型,识别失败可在下方指定接口)'))
719
+ return
720
+ }
721
+ setBusy(true); setError('')
722
+ try {
723
+ const dataUrl = (await shrinkImage(file)) || (await fileToDataUrl(file))
724
+ const res = await fetch(API + '/recognize', {
725
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ image: dataUrl })
726
+ })
727
+ const json = await res.json()
728
+ if (!json.ok) throw new Error(json.error || '识别失败')
729
+ const list = Array.isArray(json.rows) ? json.rows : []
730
+ if (!list.length) { setNote('没有从图片里识别出成交记录,换一张更清晰的截图试试'); return }
731
+ const raw = list.map((r) => [r.date || '', r.side || '', r.price || '', r.qty || '', '', r.name || ''].join(',')).join('\n')
732
+ setText(raw)
733
+ parse(raw)
734
+ setNote('图片识别出 ' + list.length + ' 行,已放进预览,请核对(识别可能有误差)')
735
+ } catch (err) {
736
+ setError(String(err.message || err))
737
+ } finally {
738
+ setBusy(false)
739
+ }
740
+ }
741
+
742
+ const readXlsx = async (file) => {
743
+ setBusy(true); setError('')
744
+ try {
745
+ const dataUrl = await fileToDataUrl(file)
746
+ const base64 = dataUrl.split(',')[1] || ''
747
+ const res = await fetch(API + '/parse-xlsx', {
748
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data: base64 })
749
+ })
750
+ const json = await res.json()
751
+ if (!json.ok) throw new Error(json.error || 'Excel 解析失败')
752
+ const raw = (json.lines || []).join('\n')
753
+ setText(raw)
754
+ parse(raw)
755
+ setNote('Excel 已转成文本预览(' + (json.lines || []).length + ' 行)')
756
+ } catch (err) {
757
+ setError(String(err.message || err))
758
+ } finally {
759
+ setBusy(false)
760
+ }
761
+ }
762
+
763
+ const ingest = async (file) => {
764
+ if (!file) return
765
+ setError('')
766
+ if (String(file.type || '').startsWith('image/')) return recognize(file)
767
+ if (/\.xlsx$/i.test(file.name)) return readXlsx(file)
768
+ if (/\.xls$/i.test(file.name)) { setError('旧版 .xls 不支持,请另存为 .xlsx 或 .csv'); return }
769
+ try {
770
+ const raw = await readText(file)
771
+ setText(raw)
772
+ parse(raw)
773
+ } catch (err) {
774
+ setError(String(err.message || err))
775
+ }
776
+ }
777
+
778
+ useEffect(() => {
779
+ if (!seed) return
780
+ if (seed.kind === 'text') { setText(seed.value); parse(seed.value) }
781
+ else if (seed.file) ingest(seed.file)
782
+ }, [])
783
+
784
+ useEffect(() => {
785
+ const onPaste = (e) => {
786
+ const items = Array.from((e.clipboardData && e.clipboardData.items) || [])
787
+ const img = items.find((i) => i.type && i.type.startsWith('image/'))
788
+ if (!img) return
789
+ e.preventDefault()
790
+ ingest(img.getAsFile())
791
+ }
792
+ window.addEventListener('paste', onPaste)
793
+ return () => window.removeEventListener('paste', onPaste)
794
+ }, [enabled, configured, stocks])
795
+
796
+ const setRow = (i, patch) => setRows((prev) => prev.map((r, idx) => (idx === i ? Object.assign({}, r, patch) : r)))
797
+ const unmatched = rows.filter((r) => !r.name).length
798
+
799
+ return h(Modal, { title: '录入成交', onClose, maxWidth: 900 },
800
+ h('div', { className: 'pos-netrow' },
801
+ h('button', {
802
+ className: 'pos-switch' + (enabled ? ' on' : ''),
803
+ title: enabled ? '点击关闭联网识别' : '点击开启联网识别',
804
+ onClick: async () => {
805
+ setError('')
806
+ await onPatch('setVision', Object.assign({}, vdraft, { enabled: !enabled }))
807
+ setNote(!enabled ? '已开启联网识别:截图会发送给当前 Harness 模型识别' : '已关闭联网识别')
808
+ }
809
+ }),
810
+ h('span', null, '联网识别截图'),
811
+ h('span', { className: 'hint' }, enabled ? '已开启:截图会发送给当前 Harness 模型' : '已关闭:截图不会离开本机'),
812
+ configured ? h('span', { className: 'pos-chip ok', style: { height: 22, fontSize: 11 } }, '自定义接口已配置') : null
813
+ ),
814
+
815
+ h('div', {
816
+ className: 'pos-drop' + (hot ? ' hot' : ''),
817
+ onDragOver: (e) => { e.preventDefault(); setHot(true) },
818
+ onDragLeave: () => setHot(false),
819
+ onDrop: (e) => { e.preventDefault(); setHot(false); ingest((e.dataTransfer.files || [])[0]) }
820
+ },
821
+ h('strong', null, '粘贴截图 / 拖入文件'),
822
+ h('div', null, '按 Ctrl+V 粘贴截图,或把截图、CSV、Excel 拖到这里'),
823
+ h('div', { style: { marginTop: 10 } },
824
+ h('input', { type: 'file', accept: 'image/*,.csv,.txt,.xlsx', onChange: (e) => ingest((e.target.files || [])[0]) })
825
+ )
826
+ ),
827
+
828
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 } },
829
+ h('span', { className: 'pos-muted', style: { fontSize: 12 } }, '或直接粘贴文本'),
830
+ h('button', { className: 'pos-mini', style: { marginLeft: 'auto' }, onClick: () => setShowVision(!showVision) }, configured ? '备用接口:已配置' : '备用接口(可选)'),
831
+ busy ? h('span', { className: 'pos-muted', style: { fontSize: 12 } }, '处理中…') : null
832
+ ),
833
+
834
+ showVision
835
+ ? h('div', { style: { border: '1px solid #dde3ee', borderRadius: 10, padding: 10, marginBottom: 10 } },
836
+ h('p', { className: 'pos-sub', style: { marginTop: 0 } },
837
+ '默认使用当前 Harness 模型识别截图;如果它不支持图片或识别失败,可以在这里指定一个支持图片的接口(可选)。'),
838
+ h('div', { className: 'pos-fee-grid' },
839
+ h('div', { className: 'pos-fee-field' },
840
+ h('label', null, 'Base URL'),
841
+ h('input', { className: 'pos-input', placeholder: 'https://api.openai.com/v1', value: vdraft.baseUrl, onChange: (e) => setVdraft(Object.assign({}, vdraft, { baseUrl: e.target.value })) })
842
+ ),
843
+ h('div', { className: 'pos-fee-field' },
844
+ h('label', null, '模型'),
845
+ h('input', { className: 'pos-input', placeholder: 'gpt-4o-mini / qwen-vl-max', value: vdraft.model, onChange: (e) => setVdraft(Object.assign({}, vdraft, { model: e.target.value })) })
846
+ ),
847
+ h('div', { className: 'pos-fee-field' },
848
+ h('label', null, 'API Key'),
849
+ h('input', { className: 'pos-input', type: 'password', placeholder: 'sk-…', value: vdraft.apiKey, onChange: (e) => setVdraft(Object.assign({}, vdraft, { apiKey: e.target.value })) })
850
+ )
851
+ ),
852
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
853
+ h('button', { className: 'pos-btn', onClick: async () => { await onPatch('setVision', vdraft); setNote('视觉接口已保存') } }, '保存接口')
854
+ )
855
+ )
856
+ : null,
857
+
858
+ h('textarea', {
859
+ className: 'pos-input', style: { width: '100%', height: 90, padding: 8, lineHeight: 1.6 },
860
+ placeholder: '2026-11-20,买入,9.50,500,,\n2026-11-21,卖出,11.00,300,3.20,贵州茅台',
861
+ value: text,
862
+ onChange: (e) => { setText(e.target.value); if (rows.length) setRows([]) }
863
+ }),
864
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
865
+ h('button', { className: 'pos-mini', onClick: () => parse(text) }, '解析文本')
866
+ ),
867
+
868
+ error ? h('p', { className: 'pos-error' }, error) : null,
869
+ note ? h('p', { className: 'pos-note' }, note) : null,
870
+
871
+ rows.length === 1
872
+ ? h('div', { className: 'pos-quick' },
873
+ h('span', null, '单条:'),
874
+ h('select', { className: 'pos-import-select', value: rows[0].name, onChange: (e) => setRow(0, { name: e.target.value }) },
875
+ h('option', { value: '' }, '— 选股票 —'),
876
+ stocks.map((s) => h('option', { key: s.name, value: s.name }, s.name))
877
+ ),
878
+ h('span', null, rows[0].side),
879
+ h('span', null, rows[0].price + ' × ' + rows[0].qty),
880
+ h('button', { className: 'pos-btn primary', disabled: !rows[0].name || busy, onClick: () => onImport(rows) }, '直接入账')
881
+ )
882
+ : null,
883
+
884
+ rows.length > 1
885
+ ? h('table', { className: 'pos-import-table' },
886
+ h('thead', null, h('tr', null, ['日期', '方向', '价格', '数量', '费用', '匹配股票', ''].map((t, i) => h('th', { key: i }, t)))),
887
+ h('tbody', null, rows.map((r, i) => h('tr', { key: i, className: r.name ? '' : 'unmatched' },
888
+ h('td', null, r.date),
889
+ h('td', null, r.side),
890
+ h('td', null, r.price),
891
+ h('td', null, r.qty),
892
+ h('td', null, r.fee || '—'),
893
+ h('td', null, r.auto ? h('span', { className: 'pos-chip', style: { height: 20, fontSize: 10, marginRight: 4, background: '#fff7e6', borderColor: '#f3d19e', color: '#b45309' } }, '按价格匹配') : null,
894
+ h('select', { className: 'pos-import-select', value: r.name, onChange: (e) => setRow(i, { name: e.target.value }) },
895
+ h('option', { value: '' }, '— 请选择 —'),
896
+ stocks.map((s) => h('option', { key: s.name, value: s.name }, s.name))
897
+ )),
898
+ h('td', null, h('button', { className: 'pos-link danger', onClick: () => setRows((prev) => prev.filter((_, idx) => idx !== i)) }, '删除'))
899
+ )))
900
+ )
901
+ : null,
902
+
903
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
904
+ unmatched ? h('span', { className: 'pos-error', style: { marginRight: 'auto' } }, '还有 ' + unmatched + ' 行未匹配') : null,
905
+ h('button', { className: 'pos-btn', onClick: onClose }, '取消'),
906
+ h('button', { className: 'pos-btn primary', disabled: !rows.length || unmatched > 0 || busy, onClick: () => onImport(rows) }, '确认导入')
907
+ )
908
+ )
909
+ }
910
+
385
911
  /* -------------------------------------------------------- 归档弹窗 */
386
912
 
387
913
  function ArchiveModal(props) {
@@ -529,6 +1055,9 @@ window.__ModuleLoader__.load({
529
1055
  const [archiveOpen, setArchiveOpen] = useState(false)
530
1056
  const [busy, setBusy] = useState(false)
531
1057
  const [form, setForm] = useState({ name: '', date: today(), side: '买入', price: '', qty: '', fee: '' })
1058
+ const [noteFor, setNoteFor] = useState('')
1059
+ const [entryOpen, setEntryOpen] = useState(false)
1060
+ const [entrySeed, setEntrySeed] = useState(null)
532
1061
 
533
1062
  const load = () => {
534
1063
  fetch(API + '/state', { cache: 'no-store' })
@@ -543,6 +1072,35 @@ window.__ModuleLoader__.load({
543
1072
 
544
1073
  useEffect(() => { load() }, [])
545
1074
 
1075
+ useEffect(() => {
1076
+ const onPaste = (e) => {
1077
+ if (entryOpen) return
1078
+ const items = Array.from((e.clipboardData && e.clipboardData.items) || [])
1079
+ const img = items.find((i) => i.type && i.type.startsWith('image/'))
1080
+ if (!img) return
1081
+ e.preventDefault()
1082
+ setEntrySeed({ file: img.getAsFile() })
1083
+ setEntryOpen(true)
1084
+ }
1085
+ const onDrop = (e) => {
1086
+ if (entryOpen) return
1087
+ const file = (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]) || null
1088
+ if (!file) return
1089
+ e.preventDefault()
1090
+ setEntrySeed({ file })
1091
+ setEntryOpen(true)
1092
+ }
1093
+ const onDragOver = (e) => { if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes('Files')) e.preventDefault() }
1094
+ window.addEventListener('paste', onPaste)
1095
+ window.addEventListener('drop', onDrop)
1096
+ window.addEventListener('dragover', onDragOver)
1097
+ return () => {
1098
+ window.removeEventListener('paste', onPaste)
1099
+ window.removeEventListener('drop', onDrop)
1100
+ window.removeEventListener('dragover', onDragOver)
1101
+ }
1102
+ }, [entryOpen])
1103
+
546
1104
  const act = async (type, payload) => {
547
1105
  setBusy(true)
548
1106
  try {
@@ -683,7 +1241,7 @@ window.__ModuleLoader__.load({
683
1241
  : h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '费用(可空)', value: form.fee,
684
1242
  onChange: (e) => setForm(Object.assign({}, form, { fee: e.target.value })) }),
685
1243
  h('button', { className: 'pos-btn primary', onClick: addTrade, disabled: busy }, '新增'),
686
- h('button', { className: 'pos-btn', onClick: () => setArchiveOpen(true) }, '查看归档持仓' + (view.archived.length ? '(' + view.archived.length + ')' : ''))
1244
+ h('button', { className: 'pos-btn', onClick: () => { setEntrySeed(null); setEntryOpen(true) } }, '录入 (文件/截图)'),
687
1245
  ),
688
1246
 
689
1247
  h('div', { className: 'pos-filters' },
@@ -732,7 +1290,17 @@ window.__ModuleLoader__.load({
732
1290
  const isOpen = expanded === s.name
733
1291
  const rows = []
734
1292
  rows.push(h('tr', { key: 's-' + s.name, className: 'pos-row', onClick: () => setExpanded(isOpen ? '' : s.name) },
735
- columns.map((col) => h('td', { key: col.key }, cellValue(s, col.key))),
1293
+ columns.map((col) => {
1294
+ if (col.key === 'note') {
1295
+ return h('td', {
1296
+ key: col.key,
1297
+ className: 'pos-note-cell',
1298
+ title: s.note || '点击添加备注',
1299
+ onClick: (e) => { e.stopPropagation(); setNoteFor(s.name) }
1300
+ }, s.note ? s.note : h('span', { className: 'pos-muted' }, '添加'))
1301
+ }
1302
+ return h('td', { key: col.key }, cellValue(s, col.key))
1303
+ }),
736
1304
  opsCell(s)
737
1305
  ))
738
1306
  if (isOpen && !s.archived) {
@@ -762,6 +1330,27 @@ window.__ModuleLoader__.load({
762
1330
  '费用按「费率」里的规则计算(默认东方财富:佣金万 2.5、最低 5 元;卖出印花税 0.05%;过户费 0.001%)。历史里写了费用就优先用记录值(* 号标注)。')
763
1331
  ),
764
1332
 
1333
+ noteFor ? h(NoteModal, {
1334
+ stock: view.stocks.find((s) => s.name === noteFor) || { name: noteFor, note: '' },
1335
+ onClose: () => setNoteFor(''),
1336
+ onSave: async (note) => { await act('setNote', { name: noteFor, note }); setNoteFor('') }
1337
+ }) : null,
1338
+ entryOpen ? h(EntryPanel, {
1339
+ stocks: view.stocks.filter((s) => !s.archived),
1340
+ state,
1341
+ seed: entrySeed,
1342
+ onClose: () => { setEntryOpen(false); setEntrySeed(null) },
1343
+ onPatch: act,
1344
+ onImport: async (rows) => {
1345
+ for (const r of rows) {
1346
+ const payload = { name: r.name, date: r.date, side: r.side, price: r.price, qty: r.qty }
1347
+ if (r.fee !== '' && r.side !== '分红') payload.feeOverride = r.fee
1348
+ await act('addTrade', payload)
1349
+ }
1350
+ setEntryOpen(false)
1351
+ setEntrySeed(null)
1352
+ }
1353
+ }) : null,
765
1354
  groupOpen ? h(GroupModal, { stocks: view.stocks, onClose: () => setGroupOpen(false), onSave: saveGroups }) : null,
766
1355
  headerOpen ? h(HeaderModal, { state, onClose: () => setHeaderOpen(false), onPatch: act }) : null,
767
1356
  feeOpen ? h(FeeModal, { state, onClose: () => setFeeOpen(false), onPatch: act }) : null,
Binary file
Binary file
Binary file
Binary file
package/index.js CHANGED
@@ -11,14 +11,15 @@
11
11
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
12
12
  import { homedir } from 'node:os'
13
13
  import { dirname, join, resolve } from 'node:path'
14
+ import { inflateRawSync } from 'node:zlib'
14
15
  import { fileURLToPath } from 'node:url'
15
16
  import seed from './seed.js'
16
17
 
17
18
  const ROUTE = '/positions'
18
- const MAX_BODY_BYTES = 256 * 1024
19
+ const MAX_BODY_BYTES = 8 * 1024 * 1024
19
20
  const HERE = dirname(fileURLToPath(import.meta.url))
20
21
 
21
- export const inject = ['webServer']
22
+ export const inject = ['webServer', 'llm', 'agentDefaultModel']
22
23
 
23
24
  /* ------------------------------------------------------------------ 数据目录 */
24
25
 
@@ -67,6 +68,7 @@ function normalizeStock(raw) {
67
68
  price: Math.max(0, num(raw.price)),
68
69
  dayPnl: num(raw.dayPnl),
69
70
  archived: raw.archived === true,
71
+ note: str(raw.note).slice(0, 500),
70
72
  fields: isObject(raw.fields)
71
73
  ? Object.keys(raw.fields).reduce((acc, k) => { acc[k] = str(raw.fields[k]).slice(0, 200); return acc }, {})
72
74
  : {},
@@ -125,12 +127,24 @@ function normalizeState(raw) {
125
127
  const activeFeeRule = rules.some((r) => r.id === state.activeFeeRule) ? state.activeFeeRule : rules[0].id
126
128
  let columns = Array.isArray(state.columns) ? state.columns.map(normalizeColumn).filter(Boolean) : []
127
129
  if (columns.length === 0) columns = DEFAULT_COLUMNS.map((c) => Object.assign({}, c))
130
+ if (!columns.some((c) => c.key === 'note')) {
131
+ const costIndex = columns.findIndex((c) => c.key === 'cost')
132
+ const noteColumn = { key: 'note', label: '备注', builtin: true }
133
+ if (costIndex >= 0) columns.splice(costIndex + 1, 0, noteColumn)
134
+ else columns.push(noteColumn)
135
+ }
128
136
  return {
129
137
  version: 1,
130
138
  columns,
131
139
  feeRules: rules,
132
140
  activeFeeRule,
133
141
  feeRate: num(state.feeRate) > 0 ? num(state.feeRate) : 0.0003,
142
+ vision: {
143
+ enabled: state.vision?.enabled === true,
144
+ baseUrl: str(state.vision?.baseUrl).slice(0, 300),
145
+ apiKey: str(state.vision?.apiKey).slice(0, 300),
146
+ model: str(state.vision?.model).slice(0, 100)
147
+ },
134
148
  tags: Array.isArray(state.tags) ? state.tags.map((t) => str(t).trim()).filter(Boolean) : seed.tags.slice(),
135
149
  activeTags: Array.isArray(state.activeTags) ? state.activeTags.map((t) => str(t).trim()).filter(Boolean) : [],
136
150
  calc: isObject(state.calc) ? state.calc : {},
@@ -138,6 +152,82 @@ function normalizeState(raw) {
138
152
  }
139
153
  }
140
154
 
155
+ /* ------------------------------------------------------------------ xlsx */
156
+
157
+ function unzipEntries(buf) {
158
+ let eocd = -1
159
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
160
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break }
161
+ }
162
+ if (eocd < 0) throw bad('不是有效的 xlsx 文件')
163
+ const count = buf.readUInt16LE(eocd + 10)
164
+ let off = buf.readUInt32LE(eocd + 16)
165
+ const files = {}
166
+ for (let i = 0; i < count; i++) {
167
+ if (off + 46 > buf.length || buf.readUInt32LE(off) !== 0x02014b50) break
168
+ const method = buf.readUInt16LE(off + 10)
169
+ const csize = buf.readUInt32LE(off + 20)
170
+ const nameLen = buf.readUInt16LE(off + 28)
171
+ const extraLen = buf.readUInt16LE(off + 30)
172
+ const commentLen = buf.readUInt16LE(off + 32)
173
+ const localOff = buf.readUInt32LE(off + 42)
174
+ const name = buf.toString('utf8', off + 46, off + 46 + nameLen)
175
+ const lNameLen = buf.readUInt16LE(localOff + 26)
176
+ const lExtraLen = buf.readUInt16LE(localOff + 28)
177
+ const dataStart = localOff + 30 + lNameLen + lExtraLen
178
+ const raw = buf.subarray(dataStart, dataStart + csize)
179
+ files[name] = method === 0 ? raw : inflateRawSync(raw)
180
+ off += 46 + nameLen + extraLen + commentLen
181
+ }
182
+ return files
183
+ }
184
+
185
+ function xmlText(xml) {
186
+ return String(xml)
187
+ .replace(/<\/?t[^>]*>/g, '')
188
+ .replace(/<[^>]+>/g, '')
189
+ .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'")
190
+ .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
191
+ }
192
+
193
+ function colIndex(ref) {
194
+ const letters = (String(ref).match(/^[A-Z]+/) || ['A'])[0]
195
+ let n = 0
196
+ for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64)
197
+ return n - 1
198
+ }
199
+
200
+ function parseXlsx(buf) {
201
+ const files = unzipEntries(buf)
202
+ const sheetName = Object.keys(files).find((n) => /^xl\/worksheets\/sheet1\.xml$/.test(n)) || Object.keys(files).find((n) => /^xl\/worksheets\/.*\.xml$/.test(n))
203
+ if (!sheetName) throw bad('xlsx 里找不到工作表')
204
+ const sharedXml = files['xl/sharedStrings.xml'] ? files['xl/sharedStrings.xml'].toString('utf8') : ''
205
+ const shared = []
206
+ for (const m of sharedXml.matchAll(/<si>([\s\S]*?)<\/si>/g)) shared.push(xmlText(m[1]))
207
+
208
+ const sheetXml = files[sheetName].toString('utf8')
209
+ const lines = []
210
+ for (const rowMatch of sheetXml.matchAll(/<row[^>]*>([\s\S]*?)<\/row>/g)) {
211
+ const cells = []
212
+ for (const c of rowMatch[1].matchAll(/<c\s+([^>]*?)(\/>|>([\s\S]*?)<\/c>)/g)) {
213
+ const attrs = c[1]
214
+ const body = c[3] || ''
215
+ const type = (attrs.match(/\bt="([^"]+)"/) || [])[1] || ''
216
+ const ref = (attrs.match(/\br="([^"]+)"/) || [])[1] || ''
217
+ const rawValue = (body.match(/<v>([\s\S]*?)<\/v>/) || [])[1]
218
+ let value = ''
219
+ if (type === 's') value = shared[Number(rawValue)] ?? ''
220
+ else if (type === 'inlineStr') value = xmlText((body.match(/<is>([\s\S]*?)<\/is>/) || [])[1] || '')
221
+ else if (rawValue !== undefined) value = xmlText(rawValue)
222
+ const index = ref ? colIndex(ref) : cells.length
223
+ cells[index] = String(value).trim()
224
+ }
225
+ const line = cells.map((v) => v ?? '').join(',').replace(/,+$/, '')
226
+ if (line.trim()) lines.push(line)
227
+ }
228
+ return lines
229
+ }
230
+
141
231
  /* -------------------------------------------------------------------- 动作 */
142
232
 
143
233
  function findStock(state, name) {
@@ -192,6 +282,23 @@ const actions = {
192
282
  return state
193
283
  },
194
284
 
285
+ setVision(state, payload) {
286
+ state.vision = {
287
+ enabled: payload?.enabled === true,
288
+ baseUrl: str(payload?.baseUrl).slice(0, 300),
289
+ apiKey: str(payload?.apiKey).slice(0, 300),
290
+ model: str(payload?.model).slice(0, 100)
291
+ }
292
+ return state
293
+ },
294
+
295
+ setNote(state, payload) {
296
+ const stock = findStock(state, str(payload?.name).trim())
297
+ if (!stock) throw bad('找不到这只股票')
298
+ stock.note = str(payload?.note).slice(0, 500)
299
+ return state
300
+ },
301
+
195
302
  setField(state, payload) {
196
303
  const stock = findStock(state, str(payload?.name).trim())
197
304
  const key = str(payload?.key).trim()
@@ -336,6 +443,51 @@ const actions = {
336
443
  }
337
444
  }
338
445
 
446
+ async function recognizeViaHarness(ctx, dataUrl, prompt) {
447
+ const llm = ctx.llm
448
+ if (!llm || typeof llm.stream !== 'function') return { ok: false, error: '当前 Harness 没有可用的模型服务' }
449
+ const sel = ctx.agentDefaultModel && typeof ctx.agentDefaultModel.currentSelection === 'function'
450
+ ? ctx.agentDefaultModel.currentSelection()
451
+ : null
452
+ if (!sel || !sel.provider || !sel.model) return { ok: false, error: '当前会话没有默认模型' }
453
+ const m = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]+)$/.exec(dataUrl)
454
+ if (!m) return { ok: false, error: '图片格式不对' }
455
+ const messages = [{
456
+ role: 'user',
457
+ source: { kind: 'user' },
458
+ content: [
459
+ { type: 'text', text: prompt },
460
+ { type: 'image', attachment: { mediaType: m[1], data: m[2] } }
461
+ ]
462
+ }]
463
+ const result = await llm.stream({
464
+ provider: sel.provider,
465
+ model: sel.model,
466
+ sessionId: 'dsh-positions',
467
+ temperature: 0,
468
+ messages
469
+ })
470
+ let text = ''
471
+ if (typeof result === 'string') text = result
472
+ else if (result && typeof result.text === 'string') text = result.text
473
+ else if (result && typeof result[Symbol.asyncIterator] === 'function') {
474
+ const seen = []
475
+ for await (const chunk of result) {
476
+ if (typeof chunk === 'string') text += chunk
477
+ else if (chunk) {
478
+ if (typeof chunk.text === 'string') text += chunk.text
479
+ else if (typeof chunk.delta === 'string' && String(chunk.type || '').includes('text')) text += chunk.delta
480
+ if (seen.length < 8) seen.push(String(chunk.type || (chunk.constructor && chunk.constructor.name) || '?'))
481
+ }
482
+ }
483
+ if (!text) text = 'DEBUG_CHUNKS:' + seen.join(',')
484
+ } else if (result && result.content) {
485
+ const parts = Array.isArray(result.content) ? result.content : [result.content]
486
+ text = parts.map((part) => (typeof part === 'string' ? part : (part && part.text) || '')).join('')
487
+ }
488
+ return { ok: true, text }
489
+ }
490
+
339
491
  function bad(message) {
340
492
  const error = new Error(message)
341
493
  error.status = 400
@@ -431,6 +583,104 @@ export function apply(ctx, config) {
431
583
  return
432
584
  }
433
585
 
586
+ if (req.method === 'POST' && suffix === '/parse-xlsx') {
587
+ const body = await readJson(req)
588
+ const data = str(body?.data)
589
+ if (!data) { send(res, 400, { ok: false, error: '缺少文件内容' }); return }
590
+ const buf = Buffer.from(data, 'base64')
591
+ if (buf.length > 8 * 1024 * 1024) { send(res, 413, { ok: false, error: '文件过大(上限 8MB)' }); return }
592
+ const lines = parseXlsx(buf)
593
+ send(res, 200, { ok: true, lines })
594
+ return
595
+ }
596
+
597
+ if (req.method === 'POST' && suffix === '/recognize') {
598
+ const body = await readJson(req)
599
+ const vision = state.vision || {}
600
+ if (vision.enabled !== true) {
601
+ send(res, 400, { ok: false, error: '截图识别需要联网,请先打开「联网识别」开关' })
602
+ return
603
+ }
604
+ const image = str(body?.image)
605
+ if (!image.startsWith('data:image/')) { send(res, 400, { ok: false, error: '图片格式不对' }); return }
606
+ if (image.length > 6 * 1024 * 1024) { send(res, 413, { ok: false, error: '图片过大(上限 6MB)' }); return }
607
+
608
+ const prompt = [
609
+ '你是股票成交记录提取器。从图片中提取所有成交记录,输出严格 JSON 数组,不要任何解释。',
610
+ '每项字段:date(YYYY-MM-DD)、side(买入/卖出/分红)、price(数字)、qty(数字)、name(股票名称,没有就空字符串)。',
611
+ '如果图片里没有日期,date 用今天。无法识别的行直接跳过。'
612
+ ].join('\n')
613
+
614
+ let rows = []
615
+ let source = 'harness'
616
+ let harnessError = ''
617
+ let harnessText = ''
618
+ try {
619
+ const viaHarness = await recognizeViaHarness(ctx, image, prompt)
620
+ if (viaHarness.ok) {
621
+ harnessText = String(viaHarness.text || '')
622
+ const match = harnessText.match(/\[[\s\S]*\]/)
623
+ if (match) {
624
+ try { rows = JSON.parse(match[0]) } catch { rows = [] }
625
+ }
626
+ if (!Array.isArray(rows)) rows = []
627
+ } else {
628
+ harnessError = viaHarness.error || 'Harness 模型不可用'
629
+ }
630
+ } catch (error) {
631
+ harnessError = error?.message || String(error)
632
+ }
633
+
634
+ if (rows.length === 0 && vision.apiKey && vision.baseUrl && vision.model) {
635
+ const endpoint = vision.baseUrl.replace(/\/+$/, '') + '/chat/completions'
636
+ const response = await fetch(endpoint, {
637
+ method: 'POST',
638
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + vision.apiKey },
639
+ body: JSON.stringify({
640
+ model: vision.model,
641
+ temperature: 0,
642
+ messages: [
643
+ { role: 'system', content: prompt },
644
+ { role: 'user', content: [
645
+ { type: 'text', text: '提取这些成交记录' },
646
+ { type: 'image_url', image_url: { url: image } }
647
+ ] }
648
+ ]
649
+ })
650
+ })
651
+ const text = await response.text()
652
+ if (response.ok) {
653
+ try {
654
+ const json = JSON.parse(text)
655
+ const content = json.choices?.[0]?.message?.content ?? ''
656
+ const match = String(content).match(/\[[\s\S]*\]/)
657
+ if (match) rows = JSON.parse(match[0])
658
+ if (!Array.isArray(rows)) rows = []
659
+ source = 'endpoint'
660
+ } catch {
661
+ send(res, 502, { ok: false, error: '接口返回的不是 JSON' })
662
+ return
663
+ }
664
+ } else {
665
+ send(res, 502, { ok: false, error: '视觉接口返回 ' + response.status + ':' + text.slice(0, 160) })
666
+ return
667
+ }
668
+ }
669
+
670
+ if (rows.length === 0) {
671
+ send(res, 200, {
672
+ ok: false,
673
+ error: harnessError
674
+ ? '识别失败:' + harnessError + '(可在「视觉接口设置」里指定一个支持图片的模型)'
675
+ : '没有识别出成交记录,换一张更清晰的截图试试',
676
+ raw: harnessText.slice(0, 400)
677
+ })
678
+ return
679
+ }
680
+ send(res, 200, { ok: true, source, rows: rows.slice(0, 200) })
681
+ return
682
+ }
683
+
434
684
  if (req.method === 'POST' && suffix === '/action') {
435
685
  const body = await readJson(req)
436
686
  const type = str(body?.type)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangxij/dsh-positions",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "持仓成本台:记持仓、记成交,测算买卖之后的成本、仓位与保本价。不含行情、不联网。",
5
5
  "private": false,
6
6
  "type": "module",
package/screenshots.json CHANGED
@@ -1,6 +1,6 @@
1
1
  [
2
2
  "docs/screenshots/01-overview.jpg",
3
- "docs/screenshots/02-calc.jpg",
4
- "docs/screenshots/03-modal.jpg",
5
- "docs/screenshots/04-groups.jpg"
3
+ "docs/screenshots/02-entry.jpg",
4
+ "docs/screenshots/03-fees.jpg",
5
+ "docs/screenshots/04-calc.jpg"
6
6
  ]
Binary file
Binary file
Binary file