@zhangxij/dsh-positions 0.1.2 → 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/client.js CHANGED
@@ -1,9 +1,7 @@
1
1
  /**
2
2
  * 持仓成本台 · 浏览器端
3
3
  *
4
- * 与网页版持仓页一致:
5
- * 分组管理(整行) → 持仓表 → 展开/测算(同一张表里的行内测算)
6
- * 视觉上照搬网页版:白底、浅灰表头、测算行蓝底、行尾 保存/删除。
4
+ * v0.3:表头可管理(自定义列/排序/删除)、归档持仓查看、费率规则、分红。
7
5
  */
8
6
  window.__ModuleLoader__.load({
9
7
  id: '@zhangxij/dsh-positions',
@@ -14,62 +12,81 @@ window.__ModuleLoader__.load({
14
12
 
15
13
  const API = '/positions'
16
14
  const PANEL_ID = 'positions'
15
+ const DEFAULT_RULE = {
16
+ commissionRate: 0.00025,
17
+ minCommission: 5,
18
+ stampDutyRate: 0.0005,
19
+ transferFeeRate: 0.00001,
20
+ otherFixed: 0
21
+ }
17
22
 
18
23
  /* ------------------------------------------------------------ 计算 */
19
24
 
20
- function calcRecords(records, feeRate) {
21
- const rate = Number(feeRate) > 0 ? Number(feeRate) : 0.0003
25
+ function feeOf(rule, side, turnover) {
26
+ const r = rule || DEFAULT_RULE
27
+ const commission = Math.max(turnover * r.commissionRate, r.minCommission)
28
+ const stamp = side === '卖出' ? turnover * r.stampDutyRate : 0
29
+ const transfer = turnover * r.transferFeeRate
30
+ return commission + stamp + transfer + (r.otherFixed || 0)
31
+ }
32
+
33
+ function dividendTaxRate(records, date) {
34
+ const buys = (records || [])
35
+ .filter((r) => r.side === '买入' && String(r.date) <= String(date))
36
+ .sort((a, b) => String(a.date).localeCompare(String(b.date)))
37
+ if (!buys.length) return 0.2
38
+ const days = Math.floor((new Date(date).getTime() - new Date(buys[0].date).getTime()) / 86400000)
39
+ if (days <= 30) return 0.2
40
+ if (days <= 365) return 0.1
41
+ return 0
42
+ }
43
+
44
+ function calcRecords(records, rule) {
22
45
  let cumQty = 0
23
46
  let cumInvest = 0
24
- return (records || [])
47
+ const source = records || []
48
+ return source
25
49
  .slice()
26
50
  .sort((a, b) => String(a.date).localeCompare(String(b.date)))
27
51
  .map((r) => {
28
52
  const turnover = Number(r.price) * Number(r.qty)
29
- const fee = r.feeOverride !== undefined && r.feeOverride !== null ? Number(r.feeOverride) : turnover * rate
30
- const net = r.side === '买入' ? turnover + fee : turnover - fee
31
- if (r.side === '买入') {
32
- cumQty += Number(r.qty)
33
- cumInvest += net
34
- } else {
35
- cumQty -= Number(r.qty)
53
+ if (r.side === '分红') {
54
+ const taxRate = r.taxRate != null ? Number(r.taxRate) : dividendTaxRate(source, r.date)
55
+ const tax = turnover * taxRate
56
+ const net = turnover - tax
36
57
  cumInvest -= net
58
+ return {
59
+ date: r.date, side: '分红', price: Number(r.price), qty: Number(r.qty),
60
+ fee: tax, net, cumQty, cumInvest,
61
+ cost: cumQty > 0 ? cumInvest / cumQty : null, taxRate, feeFromImport: false
62
+ }
37
63
  }
64
+ const fee = r.feeOverride !== undefined && r.feeOverride !== null ? Number(r.feeOverride) : feeOf(rule, r.side, turnover)
65
+ const net = r.side === '买入' ? turnover + fee : turnover - fee
66
+ if (r.side === '买入') { cumQty += Number(r.qty); cumInvest += net }
67
+ else { cumQty -= Number(r.qty); cumInvest -= net }
38
68
  return {
39
- date: r.date,
40
- side: r.side,
41
- price: Number(r.price),
42
- qty: Number(r.qty),
43
- fee,
44
- net,
45
- cumQty,
46
- cumInvest,
69
+ date: r.date, side: r.side, price: Number(r.price), qty: Number(r.qty),
70
+ fee, net, cumQty, cumInvest,
47
71
  cost: cumQty > 0 ? cumInvest / cumQty : null,
48
72
  feeFromImport: r.feeOverride !== undefined
49
73
  }
50
74
  })
51
75
  }
52
76
 
53
- function previewCalc(base, row, feeRate) {
54
- const rate = Number(feeRate) > 0 ? Number(feeRate) : 0.0003
77
+ function previewCalc(base, row, rule) {
55
78
  const price = Number(row.price)
56
79
  const qty = Number(row.qty)
57
80
  if (!(price > 0) || !(qty > 0)) return { fee: '—', net: '—', cumQty: '—', cumInvest: '—', cost: '—', error: '' }
58
81
  const turnover = price * qty
59
- const fee = turnover * rate
82
+ const fee = feeOf(rule, row.side, turnover)
60
83
  const net = row.side === '卖出' ? turnover - fee : turnover + fee
61
- if (row.side === '卖出' && qty > base.cumQty) {
62
- return { fee: '—', net: '—', cumQty: '—', cumInvest: '—', cost: '超量', error: '超量' }
63
- }
84
+ if (row.side === '卖出' && qty > base.cumQty) return { fee: '—', net: '—', cumQty: '—', cumInvest: '—', cost: '超量', error: '超量' }
64
85
  const q = row.side === '买入' ? base.cumQty + qty : base.cumQty - qty
65
86
  const invest = row.side === '买入' ? base.cumInvest + net : base.cumInvest - net
66
87
  return {
67
- fee: fee.toFixed(2),
68
- net: net.toFixed(2),
69
- cumQty: q,
70
- cumInvest: invest.toFixed(2),
71
- cost: q > 0 ? (invest / q).toFixed(3) : '—',
72
- error: ''
88
+ fee: fee.toFixed(2), net: net.toFixed(2), cumQty: q, cumInvest: invest.toFixed(2),
89
+ cost: q > 0 ? (invest / q).toFixed(3) : '—', error: ''
73
90
  }
74
91
  }
75
92
 
@@ -87,6 +104,23 @@ window.__ModuleLoader__.load({
87
104
  )
88
105
  }
89
106
 
107
+ function cellValue(s, key) {
108
+ switch (key) {
109
+ case 'stock': return s.name
110
+ case 'date': return s.last ? s.last.date : '—'
111
+ case 'side': return s.last ? s.last.side : '—'
112
+ case 'price': return s.last ? s.last.price.toFixed(2) : '—'
113
+ case 'qty': return s.last ? s.last.qty : '—'
114
+ case 'fee': return s.last ? s.last.fee.toFixed(2) : '—'
115
+ case 'net': return s.last ? s.last.net.toFixed(2) : '—'
116
+ case 'cumQty': return s.cumQty
117
+ case 'cumInvest': return s.cumInvest.toFixed(2)
118
+ case 'cost': return s.last && s.last.cost !== null ? s.last.cost.toFixed(3) : '—'
119
+ case 'note': return s.note || ''
120
+ default: return (s.fields && s.fields[key]) || '—'
121
+ }
122
+ }
123
+
90
124
  /* -------------------------------------------------------------- CSS */
91
125
 
92
126
  const CSS = `
@@ -105,17 +139,20 @@ window.__ModuleLoader__.load({
105
139
  .pos-btn.primary:hover { background:#1d4ac0; color:#fff; }
106
140
  .pos-btn:disabled { opacity:.5; cursor:default; }
107
141
  .pos-card { background:#fff; border:1px solid #dde3ee; border-radius:12px; }
108
- .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; }
109
143
  .pos-input, .pos-select { height:30px; border-radius:8px; border:1px solid #dde3ee; background:#fff; color:#1f2937; padding:0 8px; font-size:12px; }
110
- .pos-input.num { width:100px; text-align:right; }
111
- .pos-filter { padding:10px 12px; margin-bottom:12px; }
144
+ .pos-input.num { width:84px; text-align:right; }
145
+ .pos-filters { display:flex; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
146
+ .pos-filter { flex:1 1 320px; padding:10px 12px; }
112
147
  .pos-filter-head { display:flex; align-items:center; justify-content:space-between; font-weight:600; font-size:13px; margin-bottom:8px; gap:8px; }
113
- .pos-chips { display:flex; gap:6px; flex-wrap:wrap; }
148
+ .pos-chips { display:flex; gap:6px; flex-wrap:wrap; align-items:center; }
114
149
  .pos-chip { display:inline-flex; align-items:center; gap:6px; height:26px; padding:0 10px; border-radius:999px;
115
150
  border:1px solid #dde3ee; background:#fff; font-size:12px; color:#344054; }
116
151
  .pos-chip .n { color:#667085; font-size:11px; }
152
+ .pos-chip.ok { background:#e8f7f0; border-color:#b7e4cf; color:#047857; }
117
153
  .pos-mini { font-size:12px; padding:0 10px; height:26px; border-radius:8px; cursor:pointer; border:1px solid #dde3ee; background:#fff; color:#1f2937; }
118
154
  .pos-mini:hover { border-color:#2457d6; color:#2457d6; }
155
+ .pos-mini:disabled { opacity:.4; cursor:default; }
119
156
  .pos-link { border:none; background:none; color:#2457d6; cursor:pointer; font-size:12px; padding:0 4px; }
120
157
  .pos-link:hover { text-decoration:underline; }
121
158
  .pos-link.danger { color:#b42318; }
@@ -132,6 +169,7 @@ window.__ModuleLoader__.load({
132
169
  .pos-down { color:#047857; }
133
170
  .pos-row { cursor:pointer; }
134
171
  .pos-row:hover td { background:#f8faff; }
172
+ .pos-row.archived td { color:#98a2b3; }
135
173
  .pos-detail td { background:#f8fafc; padding:0 !important; }
136
174
  .pos-detail-box { padding:14px 16px 18px; }
137
175
  .pos-list { width:100%; border-collapse:collapse; font-size:12px; background:#fff; border:1px solid #eef1f6; border-radius:10px; overflow:hidden; }
@@ -139,10 +177,9 @@ window.__ModuleLoader__.load({
139
177
  .pos-list th { background:#f8fafc; font-weight:600; color:#475467; }
140
178
  .pos-list tr:last-child td { border-bottom:none; }
141
179
  .pos-calc-tr td { background:#eef4ff; }
142
- .pos-calc-tr.pending td { background:#f8fafc; color:#667085; }
143
- .pos-calc-tr.error td { background:#feeceb; }
144
- .pos-calc-tr.saved td { background:#e8f7f0; }
145
- .pos-chip.ok { background:#e8f7f0; border-color:#b7e4cf; color:#047857; }
180
+ .pos-calc-tr.pending td { background:#f8fafc; color:#667085; }
181
+ .pos-calc-tr.error td { background:#feeceb; }
182
+ .pos-calc-tr.saved td { background:#e8f7f0; }
146
183
  .pos-cell-input { width:100%; min-width:70px; border:1px solid #dde3ee; border-radius:6px; background:#fff; color:#1f2937; padding:4px 6px; font-size:12px; }
147
184
  .pos-calc-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:10px; }
148
185
  .pos-note { font-size:11px; color:#98a2b3; margin:8px 0 0; }
@@ -159,6 +196,40 @@ window.__ModuleLoader__.load({
159
196
  .pos-grow:last-child { border-bottom:none; }
160
197
  .pos-grow .name { min-width:110px; font-weight:600; }
161
198
  .pos-grow .pos-input { width:120px; }
199
+ .pos-col-row { display:flex; align-items:center; gap:10px; padding:8px 0; border-bottom:1px solid #eef1f6; }
200
+ .pos-col-row:last-child { border-bottom:none; }
201
+ .pos-col-row .label { flex:1; font-weight:600; }
202
+ .pos-fee-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px 16px; }
203
+ .pos-fee-field { display:flex; flex-direction:column; gap:4px; }
204
+ .pos-fee-field label { font-size:11px; color:#667085; }
205
+ .pos-fee-field .unit { font-size:11px; color:#98a2b3; margin-left:4px; }
206
+ .pos-fee-preview { margin-top:6px; border:1px solid #dde3ee; border-radius:8px; padding:8px; background:#fbfcff; }
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
+
162
233
  `
163
234
 
164
235
  /* ------------------------------------------------------------ 图标 */
@@ -186,7 +257,7 @@ window.__ModuleLoader__.load({
186
257
  /* --------------------------------------------------- 历史 + 测算表 */
187
258
 
188
259
  function Ledger(props) {
189
- const { stock, feeRate, savedRows, onSave, onDeleteRecord } = props
260
+ const { stock, rule, savedRows, onSave, onDeleteRecord, customColumns, onSetField } = props
190
261
  const [rows, setRows] = useState(() => (savedRows || []).map((r) => Object.assign({}, r)))
191
262
  const [dirty, setDirty] = useState(false)
192
263
  const base = { cumQty: stock.cumQty, cumInvest: stock.cumInvest }
@@ -195,25 +266,29 @@ window.__ModuleLoader__.load({
195
266
  setRows((prev) => prev.map((row, idx) => (idx === i ? Object.assign({}, row, { [field]: value, saved: false }) : row)))
196
267
  setDirty(true)
197
268
  }
198
-
199
- const persist = async (next) => {
200
- setRows(next)
201
- setDirty(false)
202
- await onSave(next)
203
- }
204
-
269
+ const persist = async (next) => { setRows(next); setDirty(false); await onSave(next) }
205
270
  const saveRow = async (i) => {
206
271
  const row = rows[i]
207
272
  if (!(Number(row.price) > 0) || !(Number(row.qty) > 0)) return
208
273
  await persist(rows.map((r, idx) => (idx === i ? Object.assign({}, r, { saved: true }) : r)))
209
274
  }
210
-
211
275
  const saveAll = async () => {
212
- const next = rows.map((r) => (Number(r.price) > 0 && Number(r.qty) > 0 ? Object.assign({}, r, { saved: true }) : r))
213
- await persist(next)
276
+ await persist(rows.map((r) => (Number(r.price) > 0 && Number(r.qty) > 0 ? Object.assign({}, r, { saved: true }) : r)))
214
277
  }
215
278
 
216
279
  return h('div', null,
280
+ customColumns && customColumns.length
281
+ ? h('div', { className: 'pos-calc-row', style: { marginBottom: 10 } },
282
+ customColumns.map((col) => h('label', { key: col.key, style: { display: 'flex', gap: 6, alignItems: 'center', fontSize: 12 } },
283
+ h('span', { className: 'pos-muted' }, col.label),
284
+ h('input', {
285
+ className: 'pos-input', style: { width: 160 }, defaultValue: (stock.fields && stock.fields[col.key]) || '',
286
+ onBlur: (e) => onSetField && onSetField(stock.name, col.key, e.target.value)
287
+ })
288
+ ))
289
+ )
290
+ : null,
291
+
217
292
  h('div', { className: 'pos-muted', style: { fontSize: 12, marginBottom: 8 } }, '历史记录 + 测算'),
218
293
 
219
294
  h('table', { className: 'pos-list' },
@@ -233,25 +308,23 @@ window.__ModuleLoader__.load({
233
308
  h('td', null, r.cumInvest.toFixed(2)),
234
309
  h('td', null, r.cost === null ? '—' : r.cost.toFixed(3)),
235
310
  h('td', null,
236
- h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11 } }, '实际成交'),
311
+ h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11 } },
312
+ r.side === '分红' ? '分红 ' + Math.round((r.taxRate || 0) * 100) + '% 税' : '实际成交'),
237
313
  h('button', { className: 'pos-link danger', style: { marginLeft: 6 }, onClick: () => onDeleteRecord(stock.name, r) }, '删除')
238
314
  )
239
315
  )),
240
316
 
241
317
  rows.map((row, i) => {
242
- const p = previewCalc(base, row, feeRate)
318
+ const p = previewCalc(base, row, rule)
243
319
  const valid = Number(row.price) > 0 && Number(row.qty) > 0
244
320
  let cls = 'pos-calc-tr'
245
321
  if (row.saved) cls += ' saved'
246
322
  else if (!valid) cls += ' pending'
247
323
  else if (p.error) cls += ' error'
248
-
249
324
  return h('tr', { key: 'c' + i, className: cls },
250
325
  h('td', null, h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11, background: '#fff7e6', borderColor: '#f3d19e', color: '#b45309' } }, '测算 ' + (i + 1))),
251
- h('td', null, h('select', {
252
- className: 'pos-cell-input', value: row.side,
253
- onChange: (e) => update(i, 'side', e.target.value)
254
- }, h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出'))),
326
+ h('td', null, h('select', { className: 'pos-cell-input', value: row.side, onChange: (e) => update(i, 'side', e.target.value) },
327
+ h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出'))),
255
328
  h('td', null, h('input', { className: 'pos-cell-input', type: 'number', step: '0.01', placeholder: '价格', value: row.price, onChange: (e) => update(i, 'price', e.target.value) })),
256
329
  h('td', null, h('input', { className: 'pos-cell-input', type: 'number', step: '1', placeholder: '数量', value: row.qty, onChange: (e) => update(i, 'qty', e.target.value) })),
257
330
  h('td', null, p.fee),
@@ -297,21 +370,14 @@ window.__ModuleLoader__.load({
297
370
  ),
298
371
  stocks.map((s) => h('div', { key: s.name, className: 'pos-grow' },
299
372
  h('span', { className: 'name' }, s.name),
300
- h('input', {
301
- className: 'pos-input', list: 'pos-group-options', placeholder: '组名(可空)',
302
- value: draft[s.name].group,
303
- onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { group: e.target.value }) }))
304
- }),
373
+ h('input', { className: 'pos-input', list: 'pos-group-options', placeholder: '组名(可空)', value: draft[s.name].group,
374
+ onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { group: e.target.value }) })) }),
305
375
  h('span', { className: 'pos-muted' }, '现价'),
306
- h('input', {
307
- className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].price,
308
- onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { price: e.target.value }) }))
309
- }),
376
+ h('input', { className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].price,
377
+ onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { price: e.target.value }) })) }),
310
378
  h('span', { className: 'pos-muted' }, '当日盈亏'),
311
- h('input', {
312
- className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].dayPnl,
313
- onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { dayPnl: e.target.value }) }))
314
- })
379
+ h('input', { className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].dayPnl,
380
+ onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { dayPnl: e.target.value }) })) })
315
381
  )),
316
382
  h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
317
383
  h('button', { className: 'pos-btn', onClick: onClose }, '取消'),
@@ -320,6 +386,662 @@ window.__ModuleLoader__.load({
320
386
  )
321
387
  }
322
388
 
389
+ /* -------------------------------------------------------- 表头管理 */
390
+
391
+ function HeaderModal(props) {
392
+ const { state, onClose, onPatch } = props
393
+ const [label, setLabel] = useState('')
394
+
395
+ return h(Modal, { title: '表头管理', onClose, maxWidth: 640 },
396
+ h('p', { className: 'pos-sub', style: { marginTop: 0 } },
397
+ '可以新增自定义列(例如「股票代码」「备注」),调整顺序;内置列不能删除。'),
398
+ state.columns.map((col, index) => h('div', { key: col.key, className: 'pos-col-row' },
399
+ h('span', { className: 'label' }, col.label, col.builtin ? h('span', { className: 'pos-muted', style: { marginLeft: 6, fontSize: 11 } }, '内置') : h('span', { className: 'pos-muted', style: { marginLeft: 6, fontSize: 11 } }, '自定义')),
400
+ h('button', { className: 'pos-mini', disabled: index === 0, onClick: () => onPatch('moveColumn', { key: col.key, dir: -1 }) }, '↑'),
401
+ h('button', { className: 'pos-mini', disabled: index === state.columns.length - 1, onClick: () => onPatch('moveColumn', { key: col.key, dir: 1 }) }, '↓'),
402
+ col.builtin ? null : h('button', { className: 'pos-link danger', onClick: () => onPatch('deleteColumn', { key: col.key }) }, '删除')
403
+ )),
404
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } },
405
+ h('input', { className: 'pos-input', style: { flex: 1 }, placeholder: '新列名称,例如:股票代码', value: label, onChange: (e) => setLabel(e.target.value) }),
406
+ h('button', { className: 'pos-btn primary', onClick: async () => { if (!label.trim()) return; await onPatch('addColumn', { label: label.trim() }); setLabel('') } }, '添加列')
407
+ )
408
+ )
409
+ }
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
+
911
+ /* -------------------------------------------------------- 归档弹窗 */
912
+
913
+ function ArchiveModal(props) {
914
+ const { stocks, rule, state, onClose, onAct, onSetField, customColumns } = props
915
+ const [selected, setSelected] = useState(stocks[0] ? stocks[0].name : '')
916
+ const stock = stocks.find((s) => s.name === selected)
917
+
918
+ return h(Modal, { title: '归档持仓(数据保留,不参与统计)', onClose, maxWidth: 1000 },
919
+ stocks.length === 0
920
+ ? h('div', { className: 'pos-empty' }, '还没有归档的股票。')
921
+ : h('div', null,
922
+ h('div', { className: 'pos-chips', style: { marginBottom: 12 } },
923
+ stocks.map((s) => h('button', {
924
+ key: s.name,
925
+ className: 'pos-chip',
926
+ 'data-on': s.name === selected ? 'true' : 'false',
927
+ style: s.name === selected ? { borderColor: '#2457d6', color: '#2457d6' } : undefined,
928
+ onClick: () => setSelected(s.name)
929
+ }, s.name))
930
+ ),
931
+ stock
932
+ ? h('div', null,
933
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 } },
934
+ h('strong', null, stock.name),
935
+ h('span', { className: 'pos-muted' }, (stock.group || '未分组') + ' · ' + stock.records.length + ' 笔成交 · 成本 ' + (stock.last && stock.last.cost !== null ? stock.last.cost.toFixed(3) : '—')),
936
+ h('button', { className: 'pos-btn', style: { marginLeft: 'auto' }, onClick: () => onAct('unarchiveStock', { name: stock.name }) }, '恢复'),
937
+ h('button', { className: 'pos-btn', style: { color: '#b42318', borderColor: '#fecdca' }, onClick: () => { if (window.confirm('删除「' + stock.name + '」及其全部成交?')) onAct('deleteStock', { name: stock.name }) } }, '删除')
938
+ ),
939
+ h(Ledger, {
940
+ stock, rule,
941
+ savedRows: state.calc[stock.name],
942
+ onSave: (rows) => onAct('saveCalc', { name: stock.name, rows }),
943
+ onDeleteRecord: (name, row) => onAct('deleteRecord', { name, index: rawIndexOf(state, name, row), match: { date: row.date, side: row.side, price: row.price, qty: row.qty } }),
944
+ customColumns,
945
+ onSetField
946
+ })
947
+ )
948
+ : null
949
+ )
950
+ )
951
+ }
952
+
953
+ /* -------------------------------------------------------- 费率弹窗 */
954
+
955
+ const pct = (v, digits) => (Number(v) * 100).toFixed(digits)
956
+ const toDraft = (rule) => ({
957
+ id: rule.id, name: rule.name,
958
+ commission: pct(rule.commissionRate, 4), min: String(rule.minCommission),
959
+ stamp: pct(rule.stampDutyRate, 3), transfer: pct(rule.transferFeeRate, 4),
960
+ other: String(rule.otherFixed), note: rule.note || '', image: rule.image || ''
961
+ })
962
+
963
+ function FeeModal(props) {
964
+ const { state, onClose, onPatch } = props
965
+ const active = state.feeRules.find((r) => r.id === state.activeFeeRule) || state.feeRules[0]
966
+ const [draft, setDraft] = useState(() => toDraft(active))
967
+ const [saved, setSaved] = useState(false)
968
+ const set = (key, value) => { setDraft(Object.assign({}, draft, { [key]: value })); setSaved(false) }
969
+
970
+ const save = async () => {
971
+ await onPatch('saveFeeRule', {
972
+ rule: {
973
+ id: draft.id, name: draft.name.trim() || '未命名券商',
974
+ commissionRate: Number(draft.commission) / 100, minCommission: Number(draft.min),
975
+ stampDutyRate: Number(draft.stamp) / 100, transferFeeRate: Number(draft.transfer) / 100,
976
+ otherFixed: Number(draft.other), note: draft.note, image: draft.image
977
+ }
978
+ })
979
+ setSaved(true)
980
+ }
981
+ const createRule = async () => {
982
+ const rule = { id: 'rule-' + Date.now(), name: '新券商', commissionRate: 0.00025, minCommission: 5, stampDutyRate: 0.0005, transferFeeRate: 0.00001, otherFixed: 0, note: '', image: '' }
983
+ await onPatch('saveFeeRule', { rule })
984
+ await onPatch('setActiveFeeRule', { id: rule.id })
985
+ setDraft(toDraft(rule)); setSaved(false)
986
+ }
987
+ const removeRule = async () => {
988
+ if (state.feeRules.length <= 1) return
989
+ await onPatch('deleteFeeRule', { id: draft.id })
990
+ const next = state.feeRules.find((r) => r.id !== draft.id)
991
+ if (next) { setDraft(toDraft(next)); setSaved(false) }
992
+ }
993
+ const pickRule = async (id) => {
994
+ await onPatch('setActiveFeeRule', { id })
995
+ const rule = state.feeRules.find((r) => r.id === id)
996
+ if (rule) { setDraft(toDraft(rule)); setSaved(false) }
997
+ }
998
+ const upload = (file) => {
999
+ if (!file) return
1000
+ if (file.size > 300 * 1024) { window.alert('图片请小于 300KB,作为参考即可'); return }
1001
+ const reader = new FileReader()
1002
+ reader.onload = () => set('image', String(reader.result || ''))
1003
+ reader.readAsDataURL(file)
1004
+ }
1005
+ const field = (label, key, unit) => h('div', { className: 'pos-fee-field' },
1006
+ h('label', null, label, unit ? h('span', { className: 'unit' }, unit) : null),
1007
+ h('input', { className: 'pos-input', value: draft[key], onChange: (e) => set(key, e.target.value) })
1008
+ )
1009
+
1010
+ return h(Modal, { title: '费率规则', onClose, maxWidth: 720 },
1011
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12 } },
1012
+ h('span', { className: 'pos-muted' }, '当前使用:'),
1013
+ h('select', { className: 'pos-select', value: draft.id, onChange: (e) => pickRule(e.target.value) },
1014
+ state.feeRules.map((r) => h('option', { key: r.id, value: r.id }, r.name))),
1015
+ h('button', { className: 'pos-mini', onClick: createRule }, '+ 新建规则'),
1016
+ h('button', { className: 'pos-mini', onClick: removeRule, disabled: state.feeRules.length <= 1 }, '删除此规则')
1017
+ ),
1018
+ h('div', { className: 'pos-fee-grid' },
1019
+ field('规则名称', 'name'),
1020
+ field('佣金率', 'commission', '%'),
1021
+ field('最低佣金(元)', 'min'),
1022
+ field('印花税率(仅卖出)', 'stamp', '%'),
1023
+ field('过户费率', 'transfer', '%'),
1024
+ field('其他固定费用(元/笔)', 'other')
1025
+ ),
1026
+ h('div', { className: 'pos-fee-field', style: { marginTop: 10 } },
1027
+ h('label', null, '备注'),
1028
+ h('input', { className: 'pos-input', value: draft.note, onChange: (e) => set('note', e.target.value) })
1029
+ ),
1030
+ h('div', { style: { marginTop: 12 } },
1031
+ h('div', { className: 'pos-muted', style: { fontSize: 12, marginBottom: 6 } }, '券商费率截图(可选,仅作参考,数值请手填)'),
1032
+ h('input', { type: 'file', accept: 'image/*', onChange: (e) => upload(e.target.files && e.target.files[0]) }),
1033
+ draft.image ? h('div', { className: 'pos-fee-preview' }, h('img', { src: draft.image, alt: '券商费率截图' })) : null
1034
+ ),
1035
+ h('p', { className: 'pos-note' },
1036
+ '买入:佣金(不低于最低佣金)+ 过户费;卖出再加印花税;分红:按持股期自动估红利税(≤1 月 20%、≤1 年 10%、>1 年 0)。默认按东方财富标准。'),
1037
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
1038
+ saved ? h('span', { className: 'pos-chip ok', style: { height: 26 } }, '已保存') : null,
1039
+ h('button', { className: 'pos-btn', onClick: onClose }, '关闭'),
1040
+ h('button', { className: 'pos-btn primary', onClick: save }, '保存费率')
1041
+ )
1042
+ )
1043
+ }
1044
+
323
1045
  /* -------------------------------------------------------------- 页面 */
324
1046
 
325
1047
  function Page() {
@@ -328,8 +1050,14 @@ window.__ModuleLoader__.load({
328
1050
  const [expanded, setExpanded] = useState('')
329
1051
  const [calcFor, setCalcFor] = useState('')
330
1052
  const [groupOpen, setGroupOpen] = useState(false)
1053
+ const [feeOpen, setFeeOpen] = useState(false)
1054
+ const [headerOpen, setHeaderOpen] = useState(false)
1055
+ const [archiveOpen, setArchiveOpen] = useState(false)
331
1056
  const [busy, setBusy] = useState(false)
332
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)
333
1061
 
334
1062
  const load = () => {
335
1063
  fetch(API + '/state', { cache: 'no-store' })
@@ -344,6 +1072,35 @@ window.__ModuleLoader__.load({
344
1072
 
345
1073
  useEffect(() => { load() }, [])
346
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
+
347
1104
  const act = async (type, payload) => {
348
1105
  setBusy(true)
349
1106
  try {
@@ -363,35 +1120,33 @@ window.__ModuleLoader__.load({
363
1120
  }
364
1121
 
365
1122
  const state = data && data.state
366
- const feeRate = state ? state.feeRate : 0.0003
1123
+ const rule = state ? state.feeRules.find((r) => r.id === state.activeFeeRule) || state.feeRules[0] : DEFAULT_RULE
367
1124
 
368
1125
  const view = useMemo(() => {
369
1126
  if (!state) return null
370
1127
  const stocks = state.stocks.map((s) => {
371
- const records = calcRecords(s.records, feeRate)
1128
+ const records = calcRecords(s.records, rule)
372
1129
  const last = records.length ? records[records.length - 1] : null
373
1130
  const cumQty = last ? last.cumQty : 0
374
1131
  const cumInvest = last ? last.cumInvest : 0
375
1132
  const mv = Number(s.price || 0) * cumQty
376
1133
  return Object.assign({}, s, { records, cumQty, cumInvest, last, mv })
377
1134
  })
378
- const totalMv = stocks.reduce((sum, s) => sum + s.mv, 0)
1135
+ const visible = stocks.filter((s) => !s.archived)
1136
+ const totalMv = visible.reduce((sum, s) => sum + s.mv, 0)
379
1137
  const groups = []
380
1138
  const index = new Map()
381
- stocks.forEach((s) => {
1139
+ visible.forEach((s) => {
382
1140
  const name = s.group || '未分组'
383
- if (!index.has(name)) {
384
- index.set(name, { name, stocks: [], mv: 0, pnl: 0 })
385
- groups.push(index.get(name))
386
- }
1141
+ if (!index.has(name)) { index.set(name, { name, stocks: [], mv: 0, pnl: 0 }); groups.push(index.get(name)) }
387
1142
  const group = index.get(name)
388
1143
  group.stocks.push(s)
389
1144
  group.mv += s.mv
390
1145
  group.pnl += Number(s.dayPnl || 0)
391
1146
  })
392
1147
  groups.forEach((g) => { g.pos = totalMv > 0 ? (g.mv / totalMv) * 100 : null })
393
- return { stocks, groups, totalMv }
394
- }, [state, feeRate])
1148
+ return { stocks, visible, archived: stocks.filter((s) => s.archived), groups, totalMv, names: stocks }
1149
+ }, [state, rule])
395
1150
 
396
1151
  if (error && !data) {
397
1152
  return h('div', { className: 'pos-root' }, h('style', null, CSS),
@@ -401,19 +1156,16 @@ window.__ModuleLoader__.load({
401
1156
  return h('div', { className: 'pos-root' }, h('style', null, CSS), h('div', { className: 'pos-empty' }, '加载中…'))
402
1157
  }
403
1158
 
404
- const columns = 11
1159
+ const columns = state.columns
1160
+ const colSpan = columns.length + 1
1161
+ const customColumns = columns.filter((c) => !c.builtin)
405
1162
  const calcStock = calcFor ? view.stocks.find((s) => s.name === calcFor) : null
406
1163
 
407
1164
  const addTrade = async () => {
408
1165
  if (!form.name.trim() || !form.price || !form.qty) return
409
- await act('addTrade', {
410
- name: form.name.trim(),
411
- date: form.date || today(),
412
- side: form.side,
413
- price: form.price,
414
- qty: form.qty,
415
- feeOverride: form.fee === '' ? undefined : form.fee
416
- })
1166
+ const payload = { name: form.name.trim(), date: form.date || today(), side: form.side, price: form.price, qty: form.qty }
1167
+ if (form.side !== '分红' && form.fee !== '') payload.feeOverride = form.fee
1168
+ await act('addTrade', payload)
417
1169
  setForm(Object.assign({}, form, { price: '', qty: '', fee: '' }))
418
1170
  }
419
1171
 
@@ -429,14 +1181,30 @@ window.__ModuleLoader__.load({
429
1181
  setGroupOpen(false)
430
1182
  }
431
1183
 
1184
+ const removeStock = (name) => {
1185
+ if (!window.confirm('删除「' + name + '」及其全部成交记录?此操作不可恢复。')) return
1186
+ act('deleteStock', { name })
1187
+ }
1188
+
432
1189
  const ledgerProps = (s) => ({
433
1190
  stock: s,
434
- feeRate,
1191
+ rule,
435
1192
  savedRows: state.calc[s.name],
1193
+ customColumns,
1194
+ onSetField: (name, key, value) => act('setField', { name, key, value }),
436
1195
  onSave: (rows) => act('saveCalc', { name: s.name, rows }),
437
1196
  onDeleteRecord: (name, row) => act('deleteRecord', { name, index: rawIndexOf(state, name, row), match: { date: row.date, side: row.side, price: row.price, qty: row.qty } })
438
1197
  })
439
1198
 
1199
+ const opsCell = (s) => h('td', null,
1200
+ s.archived
1201
+ ? h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setArchiveOpen(true) } }, '查看')
1202
+ : h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setCalcFor(s.name) } }, '测算'),
1203
+ s.archived ? null : h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setExpanded(expanded === s.name ? '' : s.name) } }, expanded === s.name ? '收起' : '展开'),
1204
+ s.archived ? null : h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); act('archiveStock', { name: s.name }) } }, '归档'),
1205
+ h('button', { className: 'pos-link danger', onClick: (e) => { e.stopPropagation(); removeStock(s.name) } }, '删除')
1206
+ )
1207
+
440
1208
  return h('div', { className: 'pos-root' },
441
1209
  h('style', null, CSS),
442
1210
  h('div', { className: 'pos-wrap' },
@@ -447,6 +1215,7 @@ window.__ModuleLoader__.load({
447
1215
  h('p', { className: 'pos-sub' }, '只记你自己的持仓与成交,不含行情 · 数据目录 ' + (data.dataDir || ''))
448
1216
  ),
449
1217
  h('div', { className: 'pos-head-actions' },
1218
+ h('button', { className: 'pos-btn', onClick: () => setFeeOpen(true) }, '费率'),
450
1219
  h('button', { className: 'pos-btn', onClick: load, disabled: busy }, '刷新')
451
1220
  )
452
1221
  ),
@@ -457,43 +1226,57 @@ window.__ModuleLoader__.load({
457
1226
  h('span', { className: 'pos-muted' }, '记一笔'),
458
1227
  h('input', { className: 'pos-input', placeholder: '股票名称', value: form.name, list: 'pos-names',
459
1228
  onChange: (e) => setForm(Object.assign({}, form, { name: e.target.value })) }),
460
- h('datalist', { id: 'pos-names' }, state.stocks.map((s) => h('option', { key: s.name, value: s.name }))),
1229
+ h('datalist', { id: 'pos-names' }, view.names.map((s) => h('option', { key: s.name, value: s.name }))),
461
1230
  h('input', { className: 'pos-input', type: 'date', value: form.date,
462
1231
  onChange: (e) => setForm(Object.assign({}, form, { date: e.target.value })) }),
463
1232
  h('select', { className: 'pos-select', value: form.side,
464
1233
  onChange: (e) => setForm(Object.assign({}, form, { side: e.target.value })) },
465
- h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出')),
466
- h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '价格', value: form.price,
1234
+ h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出'), h('option', { value: '分红' }, '分红')),
1235
+ h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: form.side === '分红' ? '每股分红' : '价格', value: form.price,
467
1236
  onChange: (e) => setForm(Object.assign({}, form, { price: e.target.value })) }),
468
- h('input', { className: 'pos-input num', type: 'number', step: '1', placeholder: '数量', value: form.qty,
1237
+ h('input', { className: 'pos-input num', type: 'number', step: '1', placeholder: form.side === '分红' ? '股数' : '数量', value: form.qty,
469
1238
  onChange: (e) => setForm(Object.assign({}, form, { qty: e.target.value })) }),
470
- h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '费用(可空)', value: form.fee,
471
- onChange: (e) => setForm(Object.assign({}, form, { fee: e.target.value })) }),
472
- h('button', { className: 'pos-btn primary', onClick: addTrade, disabled: busy }, '写入历史')
1239
+ form.side === '分红'
1240
+ ? h('span', { className: 'pos-muted', style: { fontSize: 11 } }, '红利税按持股期自动估算')
1241
+ : h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '费用(可空)', value: form.fee,
1242
+ onChange: (e) => setForm(Object.assign({}, form, { fee: e.target.value })) }),
1243
+ h('button', { className: 'pos-btn primary', onClick: addTrade, disabled: busy }, '新增'),
1244
+ h('button', { className: 'pos-btn', onClick: () => { setEntrySeed(null); setEntryOpen(true) } }, '录入 (文件/截图)'),
473
1245
  ),
474
1246
 
475
- h('div', { className: 'pos-card pos-filter' },
476
- h('div', { className: 'pos-filter-head' },
477
- h('span', null, '分组管理'),
478
- h('button', { className: 'pos-mini', onClick: () => setGroupOpen(true) }, '编辑分组')
1247
+ h('div', { className: 'pos-filters' },
1248
+ h('div', { className: 'pos-card pos-filter' },
1249
+ h('div', { className: 'pos-filter-head' },
1250
+ h('span', null, '分组管理'),
1251
+ h('button', { className: 'pos-mini', onClick: () => setGroupOpen(true) }, '编辑分组')
1252
+ ),
1253
+ h('div', { className: 'pos-chips' },
1254
+ view.groups.map((g) => h('span', { key: g.name, className: 'pos-chip' },
1255
+ g.name, h('span', { className: 'n' }, String(g.stocks.length))))
1256
+ )
479
1257
  ),
480
- h('div', { className: 'pos-chips' },
481
- view.groups.map((g) => h('span', { key: g.name, className: 'pos-chip' },
482
- g.name, h('span', { className: 'n' }, String(g.stocks.length))))
1258
+ h('div', { className: 'pos-card pos-filter' },
1259
+ h('div', { className: 'pos-filter-head' },
1260
+ h('span', null, '表头管理'),
1261
+ h('button', { className: 'pos-mini', onClick: () => setHeaderOpen(true) }, '管理表头')
1262
+ ),
1263
+ h('div', { className: 'pos-chips' },
1264
+ columns.map((col) => h('span', { key: col.key, className: 'pos-chip' },
1265
+ col.label, col.builtin ? null : h('span', { className: 'n' }, '自定义')))
1266
+ )
483
1267
  )
484
1268
  ),
485
1269
 
486
1270
  h('div', { className: 'pos-table-wrap' },
487
1271
  h('table', { className: 'pos-table' },
488
1272
  h('thead', null, h('tr', null,
489
- h('th', null, '股票'), h('th', null, '日期'), h('th', null, '方向'), h('th', null, '价格'),
490
- h('th', null, '数量'), h('th', null, '费用'), h('th', null, '当次含费用投入'), h('th', null, '累计数量'),
491
- h('th', null, '累计投入'), h('th', null, '累计成本'), h('th', null, '操作')
1273
+ columns.map((col) => h('th', { key: col.key }, col.label)),
1274
+ h('th', null, '操作')
492
1275
  )),
493
1276
  h('tbody', null,
494
1277
  view.groups.map((group) => [
495
1278
  h('tr', { key: 'g-' + group.name, className: 'pos-group' },
496
- h('td', { colSpan: columns },
1279
+ h('td', { colSpan: colSpan },
497
1280
  h('div', { className: 'pos-group-inner' },
498
1281
  h('span', { className: 'pos-tag', style: { color: '#b42318', borderColor: '#fecdca' } }, group.name || '未分组'),
499
1282
  h('span', null, '市值 ' + money(group.mv)),
@@ -507,40 +1290,79 @@ window.__ModuleLoader__.load({
507
1290
  const isOpen = expanded === s.name
508
1291
  const rows = []
509
1292
  rows.push(h('tr', { key: 's-' + s.name, className: 'pos-row', onClick: () => setExpanded(isOpen ? '' : s.name) },
510
- h('td', null, s.name),
511
- h('td', null, s.last ? s.last.date : '—'),
512
- h('td', null, s.last ? s.last.side : '—'),
513
- h('td', null, s.last ? s.last.price.toFixed(2) : '—'),
514
- h('td', null, s.last ? s.last.qty : '—'),
515
- h('td', null, s.last ? s.last.fee.toFixed(2) : '—'),
516
- h('td', null, s.last ? s.last.net.toFixed(2) : '—'),
517
- h('td', null, s.cumQty),
518
- h('td', null, s.cumInvest.toFixed(2)),
519
- h('td', null, s.last && s.last.cost !== null ? s.last.cost.toFixed(3) : '—'),
520
- h('td', null,
521
- h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setCalcFor(s.name) } }, '测算'),
522
- h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setExpanded(isOpen ? '' : s.name) } }, isOpen ? '收起' : '展开')
523
- )
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
+ }),
1304
+ opsCell(s)
524
1305
  ))
525
- if (isOpen) {
1306
+ if (isOpen && !s.archived) {
526
1307
  rows.push(h('tr', { key: 'd-' + s.name, className: 'pos-detail' },
527
- h('td', { colSpan: columns }, h('div', { className: 'pos-detail-box' }, h(Ledger, ledgerProps(s))))
1308
+ h('td', { colSpan: colSpan }, h('div', { className: 'pos-detail-box' }, h(Ledger, ledgerProps(s))))
528
1309
  ))
529
1310
  }
530
1311
  return rows
531
1312
  })
532
- ])
1313
+ ]),
1314
+
1315
+ view.archived.length
1316
+ ? h('tr', { key: 'archived-head', className: 'pos-group' },
1317
+ h('td', { colSpan: colSpan },
1318
+ h('div', { className: 'pos-group-inner' },
1319
+ h('span', { className: 'pos-tag', style: { color: '#667085', borderColor: '#d0d5dd' } }, '已归档 ' + view.archived.length + ' 只'),
1320
+ h('button', { className: 'pos-mini', onClick: () => setArchiveOpen(true) }, '查看归档持仓')
1321
+ )))
1322
+ : null
533
1323
  )
534
1324
  )
535
1325
  ),
536
1326
 
537
- view.stocks.length === 0 ? h('div', { className: 'pos-empty' }, '还没有持仓,用上方的「记一笔」开始。') : null,
1327
+ view.visible.length === 0 ? h('div', { className: 'pos-empty' }, '还没有持仓,用上方的「记一笔」开始。') : null,
538
1328
 
539
1329
  h('p', { className: 'pos-note' },
540
- '费用默认按成交额 × ' + (feeRate * 100).toFixed(2) + '% 估算;成交记录里写了费用就优先用记录值(* 号标注)。')
1330
+ '费用按「费率」里的规则计算(默认东方财富:佣金万 2.5、最低 5 元;卖出印花税 0.05%;过户费 0.001%)。历史里写了费用就优先用记录值(* 号标注)。')
541
1331
  ),
542
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,
543
1354
  groupOpen ? h(GroupModal, { stocks: view.stocks, onClose: () => setGroupOpen(false), onSave: saveGroups }) : null,
1355
+ headerOpen ? h(HeaderModal, { state, onClose: () => setHeaderOpen(false), onPatch: act }) : null,
1356
+ feeOpen ? h(FeeModal, { state, onClose: () => setFeeOpen(false), onPatch: act }) : null,
1357
+ archiveOpen ? h(ArchiveModal, {
1358
+ stocks: view.archived,
1359
+ rule,
1360
+ state,
1361
+ customColumns,
1362
+ onSetField: (name, key, value) => act('setField', { name, key, value }),
1363
+ onClose: () => setArchiveOpen(false),
1364
+ onAct: act
1365
+ }) : null,
544
1366
 
545
1367
  calcStock ? h(Modal, { title: calcStock.name + ' · 历史记录与测算', onClose: () => setCalcFor('') },
546
1368
  h(Ledger, ledgerProps(calcStock))
@@ -550,7 +1372,7 @@ window.__ModuleLoader__.load({
550
1372
 
551
1373
  function apply(ctx) {
552
1374
  ctx.slots.inject('sidebar.panellist', () =>
553
- ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 8, label: () => '台账' }, Icon)
1375
+ ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 8, label: () => '持仓成本台' }, Icon)
554
1376
  )
555
1377
  ctx.slots.inject('main', () =>
556
1378
  ctx.slots.register({ name: 'main', key: PANEL_ID }, () => h(Page))