@zhangxij/dsh-positions 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +20 -12
  2. package/client.js +361 -128
  3. package/index.js +137 -1
  4. package/package.json +1 -1
  5. package/seed.js +14 -0
package/README.md CHANGED
@@ -9,13 +9,13 @@
9
9
 
10
10
  ## 截图
11
11
 
12
- ![持仓总览](docs/screenshots/01-overview.jpg)
12
+ ![持仓总览](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/01-overview.jpg)
13
13
 
14
- ![展开后的历史记录与测算](docs/screenshots/02-calc.jpg)
14
+ ![展开后的历史记录与测算](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/02-calc.jpg)
15
15
 
16
- ![测算弹窗](docs/screenshots/03-modal.jpg)
16
+ ![测算弹窗](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/03-modal.jpg)
17
17
 
18
- ![分组弹窗](docs/screenshots/04-groups.jpg)
18
+ ![分组弹窗](https://unpkg.com/@zhangxij/dsh-positions@latest/docs/screenshots/04-groups.jpg)
19
19
 
20
20
  ## 安装
21
21
 
@@ -35,11 +35,18 @@ dsh plugin --profile web add file:D:\path\to\dsh-positions
35
35
 
36
36
  ## 怎么用
37
37
 
38
- 1. **记一笔**:顶部一行填股票、日期、买卖、价格、数量(费用可留空,会按费率估算),点「写入历史」。
39
- 2. **理论评价**:勾选维度后,表格右侧会多出对应列(当前显示「待规则」,规则留到后续版本)。
40
- 3. **分组**:展开某只股票,在详情里改「分组」,表格会按分组聚合出汇总行。
41
- 4. **测算**:展开股票 → 测算区填方向/价格/数量 → 立刻看到费用、累计数量、新成本;可以加多组一起比较,点「保存测算」会记住。
42
- 5. **现价/当日盈亏**:展开后填,用于计算市值与仓位占比。这是你自己填的数字,不是行情。
38
+ 1. **记一笔**:顶部填股票、日期、方向(买入 / 卖出 / **分红**)、价格、数量,点「新增」。
39
+ - 分红填「每股分红 × 股数」,红利税按持股期自动估算(≤1 月 20%、≤12 月 10%、>1 年 0),净额冲减成本;
40
+ - 费用留空就按「费率」规则算,写了就优先用你写的(* 号标注)。
41
+ 2. **费率**:右上角「费率」——默认东方财富(佣金万 2.5、最低 5 元;卖出印花税 0.05%;过户费 0.001%)。
42
+ 可新建 / 切换 / 删除多家券商规则,也可以上传费率截图作参考(数值仍需手填)。
43
+ 3. **分组**:展开股票,在「编辑分组」里改组名、现价、当日盈亏;表格按分组聚合汇总行。
44
+ 4. **表头**:分组管理右边的「表头管理」——可新增自定义列(如股票代码、备注)、↑↓ 调顺序、删除自定义列;
45
+ 内置列不能删。自定义列的值在股票展开详情顶部填写。
46
+ 5. **测算**:展开或点「测算」→ 填方向/价格/数量 → 立刻看到费用、累计数量、新成本;可加多组比较,支持保存。
47
+ 6. **归档 / 删除**:
48
+ - 「归档」= 从表格与统计里消失,数据保留;点「查看归档持仓」可查看完整记录并恢复;
49
+ - 「删除」= 连同全部成交一起删除,不可恢复。
43
50
 
44
51
  ## 数据在哪
45
52
 
@@ -50,9 +57,10 @@ dsh plugin --profile web add file:D:\path\to\dsh-positions
50
57
  3. 仓库内 `data/`(仅开发目录存在时使用)
51
58
  4. `%LOCALAPPDATA%\dsh-positions`(Windows)/ `~/.local/share/dsh-positions`(其他系统)
52
59
 
53
- 文件只有一个:`state.json`,每次修改立即落盘。**不会写进 `node_modules`。**
60
+ 文件只有一个:`state.json`,每次修改立即落盘,里面包含持仓/成交、分组、费率规则、表头定义与自定义列的值。
61
+ **不会写进 `node_modules`。**
54
62
 
55
- 首次启动会写入 5 只示例股票,保证装完不是空白页;示例可以直接删。
63
+ 首次启动会写入 5 只示例股票和一条东方财富费率,保证装完不是空白页;示例可以直接删。
56
64
 
57
65
  ## 隐私与权限
58
66
 
@@ -64,7 +72,7 @@ dsh plugin --profile web add file:D:\path\to\dsh-positions
64
72
  ## 已知限制
65
73
 
66
74
  - 没有行情,所以「市值 / 当日盈亏」要你自己填现价与盈亏。
67
- - 理论评价目前只有标签位,规则判定要到后续版本。
75
+ - 券商费率截图只作参考,不自动 OCR 识别(数值请手填)。
68
76
  - 单机单用户,没有账号体系(数据在你自己电脑上)。
69
77
  - 无导出功能(后续加 JSON/CSV 导出)。
70
78
 
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,22 @@ 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
+ default: return (s.fields && s.fields[key]) || '—'
120
+ }
121
+ }
122
+
90
123
  /* -------------------------------------------------------------- CSS */
91
124
 
92
125
  const CSS = `
@@ -108,14 +141,17 @@ window.__ModuleLoader__.load({
108
141
  .pos-form { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding:10px 12px; margin-bottom:12px; }
109
142
  .pos-input, .pos-select { height:30px; border-radius:8px; border:1px solid #dde3ee; background:#fff; color:#1f2937; padding:0 8px; font-size:12px; }
110
143
  .pos-input.num { width:100px; text-align:right; }
111
- .pos-filter { padding:10px 12px; margin-bottom:12px; }
144
+ .pos-filters { display:flex; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
145
+ .pos-filter { flex:1 1 320px; padding:10px 12px; }
112
146
  .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; }
147
+ .pos-chips { display:flex; gap:6px; flex-wrap:wrap; align-items:center; }
114
148
  .pos-chip { display:inline-flex; align-items:center; gap:6px; height:26px; padding:0 10px; border-radius:999px;
115
149
  border:1px solid #dde3ee; background:#fff; font-size:12px; color:#344054; }
116
150
  .pos-chip .n { color:#667085; font-size:11px; }
151
+ .pos-chip.ok { background:#e8f7f0; border-color:#b7e4cf; color:#047857; }
117
152
  .pos-mini { font-size:12px; padding:0 10px; height:26px; border-radius:8px; cursor:pointer; border:1px solid #dde3ee; background:#fff; color:#1f2937; }
118
153
  .pos-mini:hover { border-color:#2457d6; color:#2457d6; }
154
+ .pos-mini:disabled { opacity:.4; cursor:default; }
119
155
  .pos-link { border:none; background:none; color:#2457d6; cursor:pointer; font-size:12px; padding:0 4px; }
120
156
  .pos-link:hover { text-decoration:underline; }
121
157
  .pos-link.danger { color:#b42318; }
@@ -132,6 +168,7 @@ window.__ModuleLoader__.load({
132
168
  .pos-down { color:#047857; }
133
169
  .pos-row { cursor:pointer; }
134
170
  .pos-row:hover td { background:#f8faff; }
171
+ .pos-row.archived td { color:#98a2b3; }
135
172
  .pos-detail td { background:#f8fafc; padding:0 !important; }
136
173
  .pos-detail-box { padding:14px 16px 18px; }
137
174
  .pos-list { width:100%; border-collapse:collapse; font-size:12px; background:#fff; border:1px solid #eef1f6; border-radius:10px; overflow:hidden; }
@@ -139,10 +176,9 @@ window.__ModuleLoader__.load({
139
176
  .pos-list th { background:#f8fafc; font-weight:600; color:#475467; }
140
177
  .pos-list tr:last-child td { border-bottom:none; }
141
178
  .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; }
179
+ .pos-calc-tr.pending td { background:#f8fafc; color:#667085; }
180
+ .pos-calc-tr.error td { background:#feeceb; }
181
+ .pos-calc-tr.saved td { background:#e8f7f0; }
146
182
  .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
183
  .pos-calc-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:10px; }
148
184
  .pos-note { font-size:11px; color:#98a2b3; margin:8px 0 0; }
@@ -159,6 +195,15 @@ window.__ModuleLoader__.load({
159
195
  .pos-grow:last-child { border-bottom:none; }
160
196
  .pos-grow .name { min-width:110px; font-weight:600; }
161
197
  .pos-grow .pos-input { width:120px; }
198
+ .pos-col-row { display:flex; align-items:center; gap:10px; padding:8px 0; border-bottom:1px solid #eef1f6; }
199
+ .pos-col-row:last-child { border-bottom:none; }
200
+ .pos-col-row .label { flex:1; font-weight:600; }
201
+ .pos-fee-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px 16px; }
202
+ .pos-fee-field { display:flex; flex-direction:column; gap:4px; }
203
+ .pos-fee-field label { font-size:11px; color:#667085; }
204
+ .pos-fee-field .unit { font-size:11px; color:#98a2b3; margin-left:4px; }
205
+ .pos-fee-preview { margin-top:6px; border:1px solid #dde3ee; border-radius:8px; padding:8px; background:#fbfcff; }
206
+ .pos-fee-preview img { max-width:100%; max-height:180px; border-radius:6px; display:block; }
162
207
  `
163
208
 
164
209
  /* ------------------------------------------------------------ 图标 */
@@ -186,7 +231,7 @@ window.__ModuleLoader__.load({
186
231
  /* --------------------------------------------------- 历史 + 测算表 */
187
232
 
188
233
  function Ledger(props) {
189
- const { stock, feeRate, savedRows, onSave, onDeleteRecord } = props
234
+ const { stock, rule, savedRows, onSave, onDeleteRecord, customColumns, onSetField } = props
190
235
  const [rows, setRows] = useState(() => (savedRows || []).map((r) => Object.assign({}, r)))
191
236
  const [dirty, setDirty] = useState(false)
192
237
  const base = { cumQty: stock.cumQty, cumInvest: stock.cumInvest }
@@ -195,25 +240,29 @@ window.__ModuleLoader__.load({
195
240
  setRows((prev) => prev.map((row, idx) => (idx === i ? Object.assign({}, row, { [field]: value, saved: false }) : row)))
196
241
  setDirty(true)
197
242
  }
198
-
199
- const persist = async (next) => {
200
- setRows(next)
201
- setDirty(false)
202
- await onSave(next)
203
- }
204
-
243
+ const persist = async (next) => { setRows(next); setDirty(false); await onSave(next) }
205
244
  const saveRow = async (i) => {
206
245
  const row = rows[i]
207
246
  if (!(Number(row.price) > 0) || !(Number(row.qty) > 0)) return
208
247
  await persist(rows.map((r, idx) => (idx === i ? Object.assign({}, r, { saved: true }) : r)))
209
248
  }
210
-
211
249
  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)
250
+ await persist(rows.map((r) => (Number(r.price) > 0 && Number(r.qty) > 0 ? Object.assign({}, r, { saved: true }) : r)))
214
251
  }
215
252
 
216
253
  return h('div', null,
254
+ customColumns && customColumns.length
255
+ ? h('div', { className: 'pos-calc-row', style: { marginBottom: 10 } },
256
+ customColumns.map((col) => h('label', { key: col.key, style: { display: 'flex', gap: 6, alignItems: 'center', fontSize: 12 } },
257
+ h('span', { className: 'pos-muted' }, col.label),
258
+ h('input', {
259
+ className: 'pos-input', style: { width: 160 }, defaultValue: (stock.fields && stock.fields[col.key]) || '',
260
+ onBlur: (e) => onSetField && onSetField(stock.name, col.key, e.target.value)
261
+ })
262
+ ))
263
+ )
264
+ : null,
265
+
217
266
  h('div', { className: 'pos-muted', style: { fontSize: 12, marginBottom: 8 } }, '历史记录 + 测算'),
218
267
 
219
268
  h('table', { className: 'pos-list' },
@@ -233,25 +282,23 @@ window.__ModuleLoader__.load({
233
282
  h('td', null, r.cumInvest.toFixed(2)),
234
283
  h('td', null, r.cost === null ? '—' : r.cost.toFixed(3)),
235
284
  h('td', null,
236
- h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11 } }, '实际成交'),
285
+ h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11 } },
286
+ r.side === '分红' ? '分红 ' + Math.round((r.taxRate || 0) * 100) + '% 税' : '实际成交'),
237
287
  h('button', { className: 'pos-link danger', style: { marginLeft: 6 }, onClick: () => onDeleteRecord(stock.name, r) }, '删除')
238
288
  )
239
289
  )),
240
290
 
241
291
  rows.map((row, i) => {
242
- const p = previewCalc(base, row, feeRate)
292
+ const p = previewCalc(base, row, rule)
243
293
  const valid = Number(row.price) > 0 && Number(row.qty) > 0
244
294
  let cls = 'pos-calc-tr'
245
295
  if (row.saved) cls += ' saved'
246
296
  else if (!valid) cls += ' pending'
247
297
  else if (p.error) cls += ' error'
248
-
249
298
  return h('tr', { key: 'c' + i, className: cls },
250
299
  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: '卖出' }, '卖出'))),
300
+ h('td', null, h('select', { className: 'pos-cell-input', value: row.side, onChange: (e) => update(i, 'side', e.target.value) },
301
+ h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出'))),
255
302
  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
303
  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
304
  h('td', null, p.fee),
@@ -297,21 +344,14 @@ window.__ModuleLoader__.load({
297
344
  ),
298
345
  stocks.map((s) => h('div', { key: s.name, className: 'pos-grow' },
299
346
  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
- }),
347
+ h('input', { className: 'pos-input', list: 'pos-group-options', placeholder: '组名(可空)', value: draft[s.name].group,
348
+ onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { group: e.target.value }) })) }),
305
349
  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
- }),
350
+ h('input', { className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].price,
351
+ onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { price: e.target.value }) })) }),
310
352
  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
- })
353
+ h('input', { className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].dayPnl,
354
+ onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { dayPnl: e.target.value }) })) })
315
355
  )),
316
356
  h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
317
357
  h('button', { className: 'pos-btn', onClick: onClose }, '取消'),
@@ -320,6 +360,162 @@ window.__ModuleLoader__.load({
320
360
  )
321
361
  }
322
362
 
363
+ /* -------------------------------------------------------- 表头管理 */
364
+
365
+ function HeaderModal(props) {
366
+ const { state, onClose, onPatch } = props
367
+ const [label, setLabel] = useState('')
368
+
369
+ return h(Modal, { title: '表头管理', onClose, maxWidth: 640 },
370
+ h('p', { className: 'pos-sub', style: { marginTop: 0 } },
371
+ '可以新增自定义列(例如「股票代码」「备注」),调整顺序;内置列不能删除。'),
372
+ state.columns.map((col, index) => h('div', { key: col.key, className: 'pos-col-row' },
373
+ 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 } }, '自定义')),
374
+ h('button', { className: 'pos-mini', disabled: index === 0, onClick: () => onPatch('moveColumn', { key: col.key, dir: -1 }) }, '↑'),
375
+ h('button', { className: 'pos-mini', disabled: index === state.columns.length - 1, onClick: () => onPatch('moveColumn', { key: col.key, dir: 1 }) }, '↓'),
376
+ col.builtin ? null : h('button', { className: 'pos-link danger', onClick: () => onPatch('deleteColumn', { key: col.key }) }, '删除')
377
+ )),
378
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } },
379
+ h('input', { className: 'pos-input', style: { flex: 1 }, placeholder: '新列名称,例如:股票代码', value: label, onChange: (e) => setLabel(e.target.value) }),
380
+ h('button', { className: 'pos-btn primary', onClick: async () => { if (!label.trim()) return; await onPatch('addColumn', { label: label.trim() }); setLabel('') } }, '添加列')
381
+ )
382
+ )
383
+ }
384
+
385
+ /* -------------------------------------------------------- 归档弹窗 */
386
+
387
+ function ArchiveModal(props) {
388
+ const { stocks, rule, state, onClose, onAct, onSetField, customColumns } = props
389
+ const [selected, setSelected] = useState(stocks[0] ? stocks[0].name : '')
390
+ const stock = stocks.find((s) => s.name === selected)
391
+
392
+ return h(Modal, { title: '归档持仓(数据保留,不参与统计)', onClose, maxWidth: 1000 },
393
+ stocks.length === 0
394
+ ? h('div', { className: 'pos-empty' }, '还没有归档的股票。')
395
+ : h('div', null,
396
+ h('div', { className: 'pos-chips', style: { marginBottom: 12 } },
397
+ stocks.map((s) => h('button', {
398
+ key: s.name,
399
+ className: 'pos-chip',
400
+ 'data-on': s.name === selected ? 'true' : 'false',
401
+ style: s.name === selected ? { borderColor: '#2457d6', color: '#2457d6' } : undefined,
402
+ onClick: () => setSelected(s.name)
403
+ }, s.name))
404
+ ),
405
+ stock
406
+ ? h('div', null,
407
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 } },
408
+ h('strong', null, stock.name),
409
+ h('span', { className: 'pos-muted' }, (stock.group || '未分组') + ' · ' + stock.records.length + ' 笔成交 · 成本 ' + (stock.last && stock.last.cost !== null ? stock.last.cost.toFixed(3) : '—')),
410
+ h('button', { className: 'pos-btn', style: { marginLeft: 'auto' }, onClick: () => onAct('unarchiveStock', { name: stock.name }) }, '恢复'),
411
+ h('button', { className: 'pos-btn', style: { color: '#b42318', borderColor: '#fecdca' }, onClick: () => { if (window.confirm('删除「' + stock.name + '」及其全部成交?')) onAct('deleteStock', { name: stock.name }) } }, '删除')
412
+ ),
413
+ h(Ledger, {
414
+ stock, rule,
415
+ savedRows: state.calc[stock.name],
416
+ onSave: (rows) => onAct('saveCalc', { name: stock.name, rows }),
417
+ onDeleteRecord: (name, row) => onAct('deleteRecord', { name, index: rawIndexOf(state, name, row), match: { date: row.date, side: row.side, price: row.price, qty: row.qty } }),
418
+ customColumns,
419
+ onSetField
420
+ })
421
+ )
422
+ : null
423
+ )
424
+ )
425
+ }
426
+
427
+ /* -------------------------------------------------------- 费率弹窗 */
428
+
429
+ const pct = (v, digits) => (Number(v) * 100).toFixed(digits)
430
+ const toDraft = (rule) => ({
431
+ id: rule.id, name: rule.name,
432
+ commission: pct(rule.commissionRate, 4), min: String(rule.minCommission),
433
+ stamp: pct(rule.stampDutyRate, 3), transfer: pct(rule.transferFeeRate, 4),
434
+ other: String(rule.otherFixed), note: rule.note || '', image: rule.image || ''
435
+ })
436
+
437
+ function FeeModal(props) {
438
+ const { state, onClose, onPatch } = props
439
+ const active = state.feeRules.find((r) => r.id === state.activeFeeRule) || state.feeRules[0]
440
+ const [draft, setDraft] = useState(() => toDraft(active))
441
+ const [saved, setSaved] = useState(false)
442
+ const set = (key, value) => { setDraft(Object.assign({}, draft, { [key]: value })); setSaved(false) }
443
+
444
+ const save = async () => {
445
+ await onPatch('saveFeeRule', {
446
+ rule: {
447
+ id: draft.id, name: draft.name.trim() || '未命名券商',
448
+ commissionRate: Number(draft.commission) / 100, minCommission: Number(draft.min),
449
+ stampDutyRate: Number(draft.stamp) / 100, transferFeeRate: Number(draft.transfer) / 100,
450
+ otherFixed: Number(draft.other), note: draft.note, image: draft.image
451
+ }
452
+ })
453
+ setSaved(true)
454
+ }
455
+ const createRule = async () => {
456
+ const rule = { id: 'rule-' + Date.now(), name: '新券商', commissionRate: 0.00025, minCommission: 5, stampDutyRate: 0.0005, transferFeeRate: 0.00001, otherFixed: 0, note: '', image: '' }
457
+ await onPatch('saveFeeRule', { rule })
458
+ await onPatch('setActiveFeeRule', { id: rule.id })
459
+ setDraft(toDraft(rule)); setSaved(false)
460
+ }
461
+ const removeRule = async () => {
462
+ if (state.feeRules.length <= 1) return
463
+ await onPatch('deleteFeeRule', { id: draft.id })
464
+ const next = state.feeRules.find((r) => r.id !== draft.id)
465
+ if (next) { setDraft(toDraft(next)); setSaved(false) }
466
+ }
467
+ const pickRule = async (id) => {
468
+ await onPatch('setActiveFeeRule', { id })
469
+ const rule = state.feeRules.find((r) => r.id === id)
470
+ if (rule) { setDraft(toDraft(rule)); setSaved(false) }
471
+ }
472
+ const upload = (file) => {
473
+ if (!file) return
474
+ if (file.size > 300 * 1024) { window.alert('图片请小于 300KB,作为参考即可'); return }
475
+ const reader = new FileReader()
476
+ reader.onload = () => set('image', String(reader.result || ''))
477
+ reader.readAsDataURL(file)
478
+ }
479
+ const field = (label, key, unit) => h('div', { className: 'pos-fee-field' },
480
+ h('label', null, label, unit ? h('span', { className: 'unit' }, unit) : null),
481
+ h('input', { className: 'pos-input', value: draft[key], onChange: (e) => set(key, e.target.value) })
482
+ )
483
+
484
+ return h(Modal, { title: '费率规则', onClose, maxWidth: 720 },
485
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12 } },
486
+ h('span', { className: 'pos-muted' }, '当前使用:'),
487
+ h('select', { className: 'pos-select', value: draft.id, onChange: (e) => pickRule(e.target.value) },
488
+ state.feeRules.map((r) => h('option', { key: r.id, value: r.id }, r.name))),
489
+ h('button', { className: 'pos-mini', onClick: createRule }, '+ 新建规则'),
490
+ h('button', { className: 'pos-mini', onClick: removeRule, disabled: state.feeRules.length <= 1 }, '删除此规则')
491
+ ),
492
+ h('div', { className: 'pos-fee-grid' },
493
+ field('规则名称', 'name'),
494
+ field('佣金率', 'commission', '%'),
495
+ field('最低佣金(元)', 'min'),
496
+ field('印花税率(仅卖出)', 'stamp', '%'),
497
+ field('过户费率', 'transfer', '%'),
498
+ field('其他固定费用(元/笔)', 'other')
499
+ ),
500
+ h('div', { className: 'pos-fee-field', style: { marginTop: 10 } },
501
+ h('label', null, '备注'),
502
+ h('input', { className: 'pos-input', value: draft.note, onChange: (e) => set('note', e.target.value) })
503
+ ),
504
+ h('div', { style: { marginTop: 12 } },
505
+ h('div', { className: 'pos-muted', style: { fontSize: 12, marginBottom: 6 } }, '券商费率截图(可选,仅作参考,数值请手填)'),
506
+ h('input', { type: 'file', accept: 'image/*', onChange: (e) => upload(e.target.files && e.target.files[0]) }),
507
+ draft.image ? h('div', { className: 'pos-fee-preview' }, h('img', { src: draft.image, alt: '券商费率截图' })) : null
508
+ ),
509
+ h('p', { className: 'pos-note' },
510
+ '买入:佣金(不低于最低佣金)+ 过户费;卖出再加印花税;分红:按持股期自动估红利税(≤1 月 20%、≤1 年 10%、>1 年 0)。默认按东方财富标准。'),
511
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
512
+ saved ? h('span', { className: 'pos-chip ok', style: { height: 26 } }, '已保存') : null,
513
+ h('button', { className: 'pos-btn', onClick: onClose }, '关闭'),
514
+ h('button', { className: 'pos-btn primary', onClick: save }, '保存费率')
515
+ )
516
+ )
517
+ }
518
+
323
519
  /* -------------------------------------------------------------- 页面 */
324
520
 
325
521
  function Page() {
@@ -328,6 +524,9 @@ window.__ModuleLoader__.load({
328
524
  const [expanded, setExpanded] = useState('')
329
525
  const [calcFor, setCalcFor] = useState('')
330
526
  const [groupOpen, setGroupOpen] = useState(false)
527
+ const [feeOpen, setFeeOpen] = useState(false)
528
+ const [headerOpen, setHeaderOpen] = useState(false)
529
+ const [archiveOpen, setArchiveOpen] = useState(false)
331
530
  const [busy, setBusy] = useState(false)
332
531
  const [form, setForm] = useState({ name: '', date: today(), side: '买入', price: '', qty: '', fee: '' })
333
532
 
@@ -363,35 +562,33 @@ window.__ModuleLoader__.load({
363
562
  }
364
563
 
365
564
  const state = data && data.state
366
- const feeRate = state ? state.feeRate : 0.0003
565
+ const rule = state ? state.feeRules.find((r) => r.id === state.activeFeeRule) || state.feeRules[0] : DEFAULT_RULE
367
566
 
368
567
  const view = useMemo(() => {
369
568
  if (!state) return null
370
569
  const stocks = state.stocks.map((s) => {
371
- const records = calcRecords(s.records, feeRate)
570
+ const records = calcRecords(s.records, rule)
372
571
  const last = records.length ? records[records.length - 1] : null
373
572
  const cumQty = last ? last.cumQty : 0
374
573
  const cumInvest = last ? last.cumInvest : 0
375
574
  const mv = Number(s.price || 0) * cumQty
376
575
  return Object.assign({}, s, { records, cumQty, cumInvest, last, mv })
377
576
  })
378
- const totalMv = stocks.reduce((sum, s) => sum + s.mv, 0)
577
+ const visible = stocks.filter((s) => !s.archived)
578
+ const totalMv = visible.reduce((sum, s) => sum + s.mv, 0)
379
579
  const groups = []
380
580
  const index = new Map()
381
- stocks.forEach((s) => {
581
+ visible.forEach((s) => {
382
582
  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
- }
583
+ if (!index.has(name)) { index.set(name, { name, stocks: [], mv: 0, pnl: 0 }); groups.push(index.get(name)) }
387
584
  const group = index.get(name)
388
585
  group.stocks.push(s)
389
586
  group.mv += s.mv
390
587
  group.pnl += Number(s.dayPnl || 0)
391
588
  })
392
589
  groups.forEach((g) => { g.pos = totalMv > 0 ? (g.mv / totalMv) * 100 : null })
393
- return { stocks, groups, totalMv }
394
- }, [state, feeRate])
590
+ return { stocks, visible, archived: stocks.filter((s) => s.archived), groups, totalMv, names: stocks }
591
+ }, [state, rule])
395
592
 
396
593
  if (error && !data) {
397
594
  return h('div', { className: 'pos-root' }, h('style', null, CSS),
@@ -401,19 +598,16 @@ window.__ModuleLoader__.load({
401
598
  return h('div', { className: 'pos-root' }, h('style', null, CSS), h('div', { className: 'pos-empty' }, '加载中…'))
402
599
  }
403
600
 
404
- const columns = 11
601
+ const columns = state.columns
602
+ const colSpan = columns.length + 1
603
+ const customColumns = columns.filter((c) => !c.builtin)
405
604
  const calcStock = calcFor ? view.stocks.find((s) => s.name === calcFor) : null
406
605
 
407
606
  const addTrade = async () => {
408
607
  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
- })
608
+ const payload = { name: form.name.trim(), date: form.date || today(), side: form.side, price: form.price, qty: form.qty }
609
+ if (form.side !== '分红' && form.fee !== '') payload.feeOverride = form.fee
610
+ await act('addTrade', payload)
417
611
  setForm(Object.assign({}, form, { price: '', qty: '', fee: '' }))
418
612
  }
419
613
 
@@ -429,14 +623,30 @@ window.__ModuleLoader__.load({
429
623
  setGroupOpen(false)
430
624
  }
431
625
 
626
+ const removeStock = (name) => {
627
+ if (!window.confirm('删除「' + name + '」及其全部成交记录?此操作不可恢复。')) return
628
+ act('deleteStock', { name })
629
+ }
630
+
432
631
  const ledgerProps = (s) => ({
433
632
  stock: s,
434
- feeRate,
633
+ rule,
435
634
  savedRows: state.calc[s.name],
635
+ customColumns,
636
+ onSetField: (name, key, value) => act('setField', { name, key, value }),
436
637
  onSave: (rows) => act('saveCalc', { name: s.name, rows }),
437
638
  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
639
  })
439
640
 
641
+ const opsCell = (s) => h('td', null,
642
+ s.archived
643
+ ? h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setArchiveOpen(true) } }, '查看')
644
+ : h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setCalcFor(s.name) } }, '测算'),
645
+ s.archived ? null : h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setExpanded(expanded === s.name ? '' : s.name) } }, expanded === s.name ? '收起' : '展开'),
646
+ s.archived ? null : h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); act('archiveStock', { name: s.name }) } }, '归档'),
647
+ h('button', { className: 'pos-link danger', onClick: (e) => { e.stopPropagation(); removeStock(s.name) } }, '删除')
648
+ )
649
+
440
650
  return h('div', { className: 'pos-root' },
441
651
  h('style', null, CSS),
442
652
  h('div', { className: 'pos-wrap' },
@@ -447,6 +657,7 @@ window.__ModuleLoader__.load({
447
657
  h('p', { className: 'pos-sub' }, '只记你自己的持仓与成交,不含行情 · 数据目录 ' + (data.dataDir || ''))
448
658
  ),
449
659
  h('div', { className: 'pos-head-actions' },
660
+ h('button', { className: 'pos-btn', onClick: () => setFeeOpen(true) }, '费率'),
450
661
  h('button', { className: 'pos-btn', onClick: load, disabled: busy }, '刷新')
451
662
  )
452
663
  ),
@@ -457,43 +668,57 @@ window.__ModuleLoader__.load({
457
668
  h('span', { className: 'pos-muted' }, '记一笔'),
458
669
  h('input', { className: 'pos-input', placeholder: '股票名称', value: form.name, list: 'pos-names',
459
670
  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 }))),
671
+ h('datalist', { id: 'pos-names' }, view.names.map((s) => h('option', { key: s.name, value: s.name }))),
461
672
  h('input', { className: 'pos-input', type: 'date', value: form.date,
462
673
  onChange: (e) => setForm(Object.assign({}, form, { date: e.target.value })) }),
463
674
  h('select', { className: 'pos-select', value: form.side,
464
675
  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,
676
+ h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出'), h('option', { value: '分红' }, '分红')),
677
+ h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: form.side === '分红' ? '每股分红' : '价格', value: form.price,
467
678
  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,
679
+ h('input', { className: 'pos-input num', type: 'number', step: '1', placeholder: form.side === '分红' ? '股数' : '数量', value: form.qty,
469
680
  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 }, '写入历史')
681
+ form.side === '分红'
682
+ ? h('span', { className: 'pos-muted', style: { fontSize: 11 } }, '红利税按持股期自动估算')
683
+ : h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '费用(可空)', value: form.fee,
684
+ onChange: (e) => setForm(Object.assign({}, form, { fee: e.target.value })) }),
685
+ 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 + ')' : ''))
473
687
  ),
474
688
 
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) }, '编辑分组')
689
+ h('div', { className: 'pos-filters' },
690
+ h('div', { className: 'pos-card pos-filter' },
691
+ h('div', { className: 'pos-filter-head' },
692
+ h('span', null, '分组管理'),
693
+ h('button', { className: 'pos-mini', onClick: () => setGroupOpen(true) }, '编辑分组')
694
+ ),
695
+ h('div', { className: 'pos-chips' },
696
+ view.groups.map((g) => h('span', { key: g.name, className: 'pos-chip' },
697
+ g.name, h('span', { className: 'n' }, String(g.stocks.length))))
698
+ )
479
699
  ),
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))))
700
+ h('div', { className: 'pos-card pos-filter' },
701
+ h('div', { className: 'pos-filter-head' },
702
+ h('span', null, '表头管理'),
703
+ h('button', { className: 'pos-mini', onClick: () => setHeaderOpen(true) }, '管理表头')
704
+ ),
705
+ h('div', { className: 'pos-chips' },
706
+ columns.map((col) => h('span', { key: col.key, className: 'pos-chip' },
707
+ col.label, col.builtin ? null : h('span', { className: 'n' }, '自定义')))
708
+ )
483
709
  )
484
710
  ),
485
711
 
486
712
  h('div', { className: 'pos-table-wrap' },
487
713
  h('table', { className: 'pos-table' },
488
714
  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, '操作')
715
+ columns.map((col) => h('th', { key: col.key }, col.label)),
716
+ h('th', null, '操作')
492
717
  )),
493
718
  h('tbody', null,
494
719
  view.groups.map((group) => [
495
720
  h('tr', { key: 'g-' + group.name, className: 'pos-group' },
496
- h('td', { colSpan: columns },
721
+ h('td', { colSpan: colSpan },
497
722
  h('div', { className: 'pos-group-inner' },
498
723
  h('span', { className: 'pos-tag', style: { color: '#b42318', borderColor: '#fecdca' } }, group.name || '未分组'),
499
724
  h('span', null, '市值 ' + money(group.mv)),
@@ -507,40 +732,48 @@ window.__ModuleLoader__.load({
507
732
  const isOpen = expanded === s.name
508
733
  const rows = []
509
734
  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
- )
735
+ columns.map((col) => h('td', { key: col.key }, cellValue(s, col.key))),
736
+ opsCell(s)
524
737
  ))
525
- if (isOpen) {
738
+ if (isOpen && !s.archived) {
526
739
  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))))
740
+ h('td', { colSpan: colSpan }, h('div', { className: 'pos-detail-box' }, h(Ledger, ledgerProps(s))))
528
741
  ))
529
742
  }
530
743
  return rows
531
744
  })
532
- ])
745
+ ]),
746
+
747
+ view.archived.length
748
+ ? h('tr', { key: 'archived-head', className: 'pos-group' },
749
+ h('td', { colSpan: colSpan },
750
+ h('div', { className: 'pos-group-inner' },
751
+ h('span', { className: 'pos-tag', style: { color: '#667085', borderColor: '#d0d5dd' } }, '已归档 ' + view.archived.length + ' 只'),
752
+ h('button', { className: 'pos-mini', onClick: () => setArchiveOpen(true) }, '查看归档持仓')
753
+ )))
754
+ : null
533
755
  )
534
756
  )
535
757
  ),
536
758
 
537
- view.stocks.length === 0 ? h('div', { className: 'pos-empty' }, '还没有持仓,用上方的「记一笔」开始。') : null,
759
+ view.visible.length === 0 ? h('div', { className: 'pos-empty' }, '还没有持仓,用上方的「记一笔」开始。') : null,
538
760
 
539
761
  h('p', { className: 'pos-note' },
540
- '费用默认按成交额 × ' + (feeRate * 100).toFixed(2) + '% 估算;成交记录里写了费用就优先用记录值(* 号标注)。')
762
+ '费用按「费率」里的规则计算(默认东方财富:佣金万 2.5、最低 5 元;卖出印花税 0.05%;过户费 0.001%)。历史里写了费用就优先用记录值(* 号标注)。')
541
763
  ),
542
764
 
543
765
  groupOpen ? h(GroupModal, { stocks: view.stocks, onClose: () => setGroupOpen(false), onSave: saveGroups }) : null,
766
+ headerOpen ? h(HeaderModal, { state, onClose: () => setHeaderOpen(false), onPatch: act }) : null,
767
+ feeOpen ? h(FeeModal, { state, onClose: () => setFeeOpen(false), onPatch: act }) : null,
768
+ archiveOpen ? h(ArchiveModal, {
769
+ stocks: view.archived,
770
+ rule,
771
+ state,
772
+ customColumns,
773
+ onSetField: (name, key, value) => act('setField', { name, key, value }),
774
+ onClose: () => setArchiveOpen(false),
775
+ onAct: act
776
+ }) : null,
544
777
 
545
778
  calcStock ? h(Modal, { title: calcStock.name + ' · 历史记录与测算', onClose: () => setCalcFor('') },
546
779
  h(Ledger, ledgerProps(calcStock))
@@ -550,7 +783,7 @@ window.__ModuleLoader__.load({
550
783
 
551
784
  function apply(ctx) {
552
785
  ctx.slots.inject('sidebar.panellist', () =>
553
- ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 8, label: () => '台账' }, Icon)
786
+ ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 8, label: () => '持仓成本台' }, Icon)
554
787
  )
555
788
  ctx.slots.inject('main', () =>
556
789
  ctx.slots.register({ name: 'main', key: PANEL_ID }, () => h(Page))
package/index.js CHANGED
@@ -47,7 +47,7 @@ function normalizeRecord(raw) {
47
47
  if (!isObject(raw)) return null
48
48
  const date = str(raw.date)
49
49
  if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null
50
- const side = raw.side === '卖出' ? '卖出' : raw.side === '买入' ? '买入' : null
50
+ const side = raw.side === '卖出' ? '卖出' : raw.side === '买入' ? '买入' : raw.side === '分红' ? '分红' : null
51
51
  const price = num(raw.price)
52
52
  const qty = num(raw.qty)
53
53
  if (!side || price <= 0 || qty <= 0) return null
@@ -66,15 +66,70 @@ function normalizeStock(raw) {
66
66
  group: str(raw.group).trim(),
67
67
  price: Math.max(0, num(raw.price)),
68
68
  dayPnl: num(raw.dayPnl),
69
+ archived: raw.archived === true,
70
+ fields: isObject(raw.fields)
71
+ ? Object.keys(raw.fields).reduce((acc, k) => { acc[k] = str(raw.fields[k]).slice(0, 200); return acc }, {})
72
+ : {},
69
73
  records: Array.isArray(raw.records) ? raw.records.map(normalizeRecord).filter(Boolean) : []
70
74
  }
71
75
  }
72
76
 
77
+ const DEFAULT_COLUMNS = [
78
+ { key: 'stock', label: '股票', builtin: true },
79
+ { key: 'date', label: '日期', builtin: true },
80
+ { key: 'side', label: '方向', builtin: true },
81
+ { key: 'price', label: '价格', builtin: true },
82
+ { key: 'qty', label: '数量', builtin: true },
83
+ { key: 'fee', label: '费用', builtin: true },
84
+ { key: 'net', label: '当次含费用投入', builtin: true },
85
+ { key: 'cumQty', label: '累计数量', builtin: true },
86
+ { key: 'cumInvest', label: '累计投入', builtin: true },
87
+ { key: 'cost', label: '累计成本', builtin: true }
88
+ ]
89
+
90
+ function normalizeColumn(raw) {
91
+ if (!isObject(raw)) return null
92
+ const key = str(raw.key).trim()
93
+ const label = str(raw.label).trim()
94
+ if (!key || !label) return null
95
+ return { key, label: label.slice(0, 20), builtin: raw.builtin === true }
96
+ }
97
+
98
+ function clampRate(value, fallback) {
99
+ const n = num(value, fallback)
100
+ return n >= 0 && n <= 0.05 ? n : fallback
101
+ }
102
+
103
+ function normalizeRule(raw) {
104
+ if (!isObject(raw)) return null
105
+ const name = str(raw.name).trim()
106
+ if (!name) return null
107
+ return {
108
+ id: str(raw.id).trim() || 'rule-' + name,
109
+ name,
110
+ commissionRate: clampRate(raw.commissionRate, 0.00025),
111
+ minCommission: Math.max(0, num(raw.minCommission, 5)),
112
+ stampDutyRate: clampRate(raw.stampDutyRate, 0.0005),
113
+ transferFeeRate: clampRate(raw.transferFeeRate, 0.00001),
114
+ otherFixed: Math.max(0, num(raw.otherFixed, 0)),
115
+ note: str(raw.note).slice(0, 200),
116
+ image: str(raw.image).slice(0, 400000)
117
+ }
118
+ }
119
+
73
120
  function normalizeState(raw) {
74
121
  const state = isObject(raw) ? raw : {}
75
122
  const stocks = Array.isArray(state.stocks) ? state.stocks.map(normalizeStock).filter(Boolean) : []
123
+ let rules = Array.isArray(state.feeRules) ? state.feeRules.map(normalizeRule).filter(Boolean) : []
124
+ if (rules.length === 0) rules = seed.feeRules.map(normalizeRule).filter(Boolean)
125
+ const activeFeeRule = rules.some((r) => r.id === state.activeFeeRule) ? state.activeFeeRule : rules[0].id
126
+ let columns = Array.isArray(state.columns) ? state.columns.map(normalizeColumn).filter(Boolean) : []
127
+ if (columns.length === 0) columns = DEFAULT_COLUMNS.map((c) => Object.assign({}, c))
76
128
  return {
77
129
  version: 1,
130
+ columns,
131
+ feeRules: rules,
132
+ activeFeeRule,
78
133
  feeRate: num(state.feeRate) > 0 ? num(state.feeRate) : 0.0003,
79
134
  tags: Array.isArray(state.tags) ? state.tags.map((t) => str(t).trim()).filter(Boolean) : seed.tags.slice(),
80
135
  activeTags: Array.isArray(state.activeTags) ? state.activeTags.map((t) => str(t).trim()).filter(Boolean) : [],
@@ -105,6 +160,87 @@ const actions = {
105
160
  return state
106
161
  },
107
162
 
163
+ addColumn(state, payload) {
164
+ const label = str(payload?.label).trim()
165
+ if (!label) throw bad('列名不能为空')
166
+ if (state.columns.filter((c) => !c.builtin).length >= 10) throw bad('自定义列最多 10 个')
167
+ state.columns.push({ key: 'c' + Date.now(), label: label.slice(0, 20), builtin: false })
168
+ return state
169
+ },
170
+
171
+ deleteColumn(state, payload) {
172
+ const key = str(payload?.key).trim()
173
+ const column = state.columns.find((c) => c.key === key)
174
+ if (!column) throw bad('找不到这列')
175
+ if (column.builtin) throw bad('内置列不能删除')
176
+ state.columns = state.columns.filter((c) => c.key !== key)
177
+ state.stocks.forEach((s) => { if (s.fields) delete s.fields[key] })
178
+ return state
179
+ },
180
+
181
+ moveColumn(state, payload) {
182
+ const key = str(payload?.key).trim()
183
+ const dir = num(payload?.dir, 0) > 0 ? 1 : -1
184
+ const index = state.columns.findIndex((c) => c.key === key)
185
+ const next = index + dir
186
+ if (index < 0 || next < 0 || next >= state.columns.length) return state
187
+ const list = state.columns.slice()
188
+ const tmp = list[index]
189
+ list[index] = list[next]
190
+ list[next] = tmp
191
+ state.columns = list
192
+ return state
193
+ },
194
+
195
+ setField(state, payload) {
196
+ const stock = findStock(state, str(payload?.name).trim())
197
+ const key = str(payload?.key).trim()
198
+ if (!stock) throw bad('找不到这只股票')
199
+ if (!state.columns.some((c) => c.key === key && !c.builtin)) throw bad('找不到这列')
200
+ stock.fields = stock.fields || {}
201
+ stock.fields[key] = str(payload?.value).slice(0, 200)
202
+ return state
203
+ },
204
+
205
+ archiveStock(state, payload) {
206
+ const stock = findStock(state, str(payload?.name).trim())
207
+ if (!stock) throw bad('找不到这只股票')
208
+ stock.archived = true
209
+ return state
210
+ },
211
+
212
+ unarchiveStock(state, payload) {
213
+ const stock = findStock(state, str(payload?.name).trim())
214
+ if (!stock) throw bad('找不到这只股票')
215
+ stock.archived = false
216
+ return state
217
+ },
218
+
219
+ saveFeeRule(state, payload) {
220
+ const rule = normalizeRule(payload?.rule)
221
+ if (!rule) throw bad('费率规则不完整')
222
+ const index = state.feeRules.findIndex((r) => r.id === rule.id)
223
+ if (index >= 0) state.feeRules[index] = rule
224
+ else state.feeRules.push(rule)
225
+ if (!state.feeRules.some((r) => r.id === state.activeFeeRule)) state.activeFeeRule = rule.id
226
+ return state
227
+ },
228
+
229
+ deleteFeeRule(state, payload) {
230
+ const id = str(payload?.id).trim()
231
+ if (state.feeRules.length <= 1) throw bad('至少保留一条费率规则')
232
+ state.feeRules = state.feeRules.filter((r) => r.id !== id)
233
+ if (!state.feeRules.some((r) => r.id === state.activeFeeRule)) state.activeFeeRule = state.feeRules[0].id
234
+ return state
235
+ },
236
+
237
+ setActiveFeeRule(state, payload) {
238
+ const id = str(payload?.id).trim()
239
+ if (!state.feeRules.some((r) => r.id === id)) throw bad('找不到这条费率规则')
240
+ state.activeFeeRule = id
241
+ return state
242
+ },
243
+
108
244
  deleteStock(state, payload) {
109
245
  const name = str(payload?.name).trim()
110
246
  state.stocks = state.stocks.filter((s) => s.name !== name)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhangxij/dsh-positions",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "持仓成本台:记持仓、记成交,测算买卖之后的成本、仓位与保本价。不含行情、不联网。",
5
5
  "private": false,
6
6
  "type": "module",
package/seed.js CHANGED
@@ -6,6 +6,20 @@ export default {
6
6
  version: 1,
7
7
  updatedAt: '2027-03-15',
8
8
  feeRate: 0.0003,
9
+ feeRules: [
10
+ {
11
+ id: 'eastmoney',
12
+ name: '东方财富(默认)',
13
+ commissionRate: 0.00025,
14
+ minCommission: 5,
15
+ stampDutyRate: 0.0005,
16
+ transferFeeRate: 0.00001,
17
+ otherFixed: 0,
18
+ note: '佣金万 2.5、最低 5 元;卖出印花税 0.05%;过户费 0.001%。可在「费率」里按你的券商改。',
19
+ image: ''
20
+ }
21
+ ],
22
+ activeFeeRule: 'eastmoney',
9
23
  tags: ['量比/换手/振幅', '偏态', '趋势4项', '股东数', '全球流动性'],
10
24
  activeTags: [],
11
25
  calc: {},