dsh-cost-meter 1.9.74 → 1.9.76

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.
@@ -1,4 +1,9 @@
1
- /** 千问 / 阿里云资金账户可用金(issue #98)。凭据仅用于服务端 ACS3 签名。 */
1
+ /**
2
+ * 千问 / 阿里云资金账户可用金(issue #98)。凭据仅用于服务端 ACS3 签名。
3
+ *
4
+ * 资金账户 AvailableAmount 与符合条件的券余额分别查询。
5
+ * QueryCashCoupons 返回的 Balance 是剩余金额,券仍受实际订单抵扣规则约束。
6
+ */
2
7
  import { createHash, createHmac, randomUUID } from 'node:crypto'
3
8
  import { credentialRef } from '@deepseek-ai/dsh-credentials'
4
9
  import { fetchWithRetry } from './net.js'
@@ -11,28 +16,69 @@ export const ALIYUN_BALANCE_CREDENTIAL_VARS = [
11
16
  'ALIBABA_CLOUD_ACCESS_KEY_SECRET',
12
17
  'ALIBABA_CLOUD_SECURITY_TOKEN',
13
18
  ]
19
+ /** 资金账户可用金接口的 BSS 版本。 */
20
+ const BSS_VERSION_FUND_ACCOUNT = '2023-09-30'
21
+ /**
22
+ * 代金券接口的 BSS 版本。
23
+ * 注意:QueryCashCoupons 只存在于老版本 BSS(2017-12-14),在 2023-09-30 下不存在;
24
+ * 两个接口共用同一个 endpoint 与同一套 ACS3 签名,仅 Action/Version 不同。
25
+ */
26
+ const BSS_VERSION_CASH_COUPON = '2017-12-14'
27
+ const CASH_COUPON_ACTION = 'QueryCashCoupons'
28
+ const CASH_COUPON_PAGE_SIZE = 100
29
+ const CASH_COUPON_MAX_PAGES = 10
30
+ /** 券状态里算「还能用」的取值(服务端大小写不统一,统一转小写比较)。 */
31
+ const AVAILABLE_COUPON_STATUS = new Set(['available', 'availabletouse', 'effective'])
14
32
  const MAX_BYTES = 262144
15
33
  const hash = value => createHash('sha256').update(value).digest('hex')
16
34
 
17
- export function signAliyunBalanceRequest(accessKeyId, accessKeySecret, securityToken = '', { now = new Date(), nonce = randomUUID() } = {}) {
35
+ /** ACS3 要求的 RFC3986 编码(encodeURIComponent 额外放过 !'()*~,此处收紧)。 */
36
+ const rfc3986 = value => encodeURIComponent(String(value))
37
+ .replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
38
+ .replace(/%7E/g, '~')
39
+
40
+ /** 规范查询串:按参数名排序,与真正发出去的 query 必须逐字节一致。 */
41
+ const canonicalQuery = params => Object.keys(params).sort()
42
+ .map(key => `${rfc3986(key)}=${rfc3986(params[key])}`).join('&')
43
+
44
+ /**
45
+ * ACS3-HMAC-SHA256 签名(通用形态)。
46
+ *
47
+ * 业务参数走 query(`paramLocation: 'query'`),请求体恒空,因此
48
+ * x-acs-content-sha256 恒为 sha256('')。canonical 的 query 段必须与 URL 完全一致,
49
+ * 所以这里把拼好的 query 一并返回,调用方不得再自行拼接。
50
+ */
51
+ function signAliyunRequest({
52
+ accessKeyId, accessKeySecret, securityToken = '', action, version,
53
+ params = {}, now = new Date(), nonce = randomUUID(),
54
+ }) {
55
+ const query = canonicalQuery(params)
18
56
  const headers = {
19
57
  'content-type': 'application/x-www-form-urlencoded',
20
58
  host: 'business.aliyuncs.com',
21
- 'x-acs-action': 'GetFundAccountAvailableAmount',
59
+ 'x-acs-action': action,
22
60
  'x-acs-content-sha256': hash(''),
23
61
  'x-acs-date': now.toISOString().replace(/\.\d{3}Z$/, 'Z'),
24
62
  'x-acs-signature-nonce': nonce,
25
- 'x-acs-version': '2023-09-30',
63
+ 'x-acs-version': version,
26
64
  }
27
65
  if (securityToken) headers['x-acs-security-token'] = securityToken
28
66
  const keys = Object.keys(headers).sort()
29
67
  const signedHeaders = keys.join(';')
30
68
  const canonicalHeaders = keys.map(key => `${key}:${headers[key].trim()}\n`).join('')
31
- const canonical = ['POST', '/', '', canonicalHeaders, signedHeaders, hash('')].join('\n')
69
+ const canonical = ['POST', '/', query, canonicalHeaders, signedHeaders, hash('')].join('\n')
32
70
  const signature = createHmac('sha256', accessKeySecret).update(`ACS3-HMAC-SHA256\n${hash(canonical)}`).digest('hex')
33
71
  headers.Authorization = `ACS3-HMAC-SHA256 Credential=${accessKeyId},SignedHeaders=${signedHeaders},Signature=${signature}`
34
72
  headers.Accept = 'application/json'
35
- return { method: 'POST', headers, body: '', redirect: 'manual' }
73
+ return { method: 'POST', headers, body: '', redirect: 'manual', query }
74
+ }
75
+
76
+ /** 资金账户可用金请求(签名口径与 v1.9.x 完全一致:Action/Version 固定,无业务参数)。 */
77
+ export function signAliyunBalanceRequest(accessKeyId, accessKeySecret, securityToken = '', { now = new Date(), nonce = randomUUID() } = {}) {
78
+ return signAliyunRequest({
79
+ accessKeyId, accessKeySecret, securityToken, now, nonce,
80
+ action: 'GetFundAccountAvailableAmount', version: BSS_VERSION_FUND_ACCOUNT, params: {},
81
+ })
36
82
  }
37
83
 
38
84
  const messages = {
@@ -45,6 +91,17 @@ const messages = {
45
91
  payload: '阿里云余额响应无效或过大,请稍后重试',
46
92
  amount: '阿里云余额响应缺少有效的 AvailableAmount,未将其视为零余额',
47
93
  currency: '阿里云余额响应缺少受支持的币种(CNY / USD / EUR)',
94
+ couponPermission: '代金券查询被拒,请检查 RAM 权限 bss:DescribeCoupons',
95
+ couponHttp: '代金券接口返回 HTTP {status}',
96
+ couponNetwork: '代金券接口网络请求失败,请稍后重试',
97
+ couponRedirect: '代金券接口发生重定向,已拒绝转发凭据',
98
+ couponPayload: '代金券响应无效或过大,请稍后重试',
99
+ couponFailed: '代金券查询失败:{message}',
100
+ couponNone: '没有可计入的代金券',
101
+ couponPartial: '代金券信息不完整,金额仅含已确认的代金券',
102
+ couponLine: '资金账户 {cash} + 代金券 {coupon}({count} 张,最近 {date} 到期)',
103
+ couponNoDate: '资金账户 {cash} + 代金券 {coupon}({count} 张)',
104
+ cashOnly: '资金账户 {cash}({reason})',
48
105
  },
49
106
  en: {
50
107
  missing: 'Configure Alibaba Cloud RAM AccessKey ID and AccessKey Secret (not a Qianwen model API key)',
@@ -55,20 +112,128 @@ const messages = {
55
112
  payload: 'Alibaba Cloud balance response is invalid or too large; please retry later',
56
113
  amount: 'Alibaba Cloud balance response has no valid AvailableAmount; it was not treated as zero',
57
114
  currency: 'Alibaba Cloud balance response has no supported currency (CNY / USD / EUR)',
115
+ couponPermission: 'cash coupon query denied; check RAM permission bss:DescribeCoupons',
116
+ couponHttp: 'cash coupon endpoint returned HTTP {status}',
117
+ couponNetwork: 'cash coupon endpoint network request failed; please retry later',
118
+ couponRedirect: 'cash coupon endpoint redirect refused to protect credentials',
119
+ couponPayload: 'cash coupon response is invalid or too large; please retry later',
120
+ couponFailed: 'cash coupon query failed: {message}',
121
+ couponNone: 'no eligible cash coupons',
122
+ couponPartial: 'coupon data is incomplete; only confirmed coupons are included',
123
+ couponLine: 'fund account {cash} + coupons {coupon} ({count} coupon(s), nearest expiry {date})',
124
+ couponNoDate: 'fund account {cash} + coupons {coupon} ({count} coupon(s))',
125
+ cashOnly: 'fund account {cash} ({reason})',
58
126
  },
59
127
  }
60
128
  const failure = (locale, key, status = '') => new Error(messages[locale === 'en' ? 'en' : 'zh'][key].replace('{status}', String(status)))
129
+ const text = (locale, key, vars = {}) => messages[locale === 'en' ? 'en' : 'zh'][key]
130
+ .replace(/\{(\w+)\}/g, (whole, name) => (vars[name] === undefined ? whole : String(vars[name])))
61
131
 
62
132
  export function parseAliyunBalance(data, locale = 'zh') {
63
133
  const raw = data?.AvailableAmount
64
- const text = typeof raw === 'string' ? raw.trim() : ''
65
- const amount = typeof raw === 'number' ? raw : /^[+-]?\d+(\.\d+)?$/.test(text) ? Number(text) : NaN
134
+ const textAmount = typeof raw === 'string' ? raw.trim() : ''
135
+ const amount = typeof raw === 'number' ? raw : /^[+-]?\d+(\.\d+)?$/.test(textAmount) ? Number(textAmount) : NaN
66
136
  if (!Number.isFinite(amount)) throw failure(locale, 'amount')
67
137
  if (!['CNY', 'USD', 'EUR'].includes(data?.Currency)) throw failure(locale, 'currency')
68
138
  // AvailableAmount 是可用金,包含信控/未结清款等因素;不能把它当成现金余额或消费额。
69
139
  return { remaining: amount, unit: data.Currency, maxBudget: null, spend: null }
70
140
  }
71
141
 
142
+ // ── 代金券(QueryCashCoupons) ─────────────────────────────────────────────
143
+
144
+ /** Data 可能是数组、Data.CashCoupon 数组,也可能再多包一层(与 dsh-aliyun-balance 同口径)。 */
145
+ export function cashCouponList(data) {
146
+ if (!data || typeof data !== 'object') return []
147
+ const body = data.Data ?? data.data
148
+ const candidates = [
149
+ body,
150
+ body && body.CashCoupon,
151
+ data.CashCoupon,
152
+ body && body.CashCoupon && body.CashCoupon.CashCoupon,
153
+ body && body.CashCouponList,
154
+ body && body.CashCoupons,
155
+ ]
156
+ for (const candidate of candidates) if (Array.isArray(candidate)) return candidate
157
+ return []
158
+ }
159
+
160
+ /** TotalCount:服务端可能给在 Data 里,也可能给在顶层。 */
161
+ export function cashCouponTotal(data) {
162
+ if (!data || typeof data !== 'object') return null
163
+ const body = data.Data ?? data.data
164
+ const raw = body?.TotalCount ?? data.TotalCount
165
+ const total = Number(raw)
166
+ return Number.isFinite(total) ? total : null
167
+ }
168
+
169
+ /** 到期时间:服务端给的是 'YYYY-MM-DD HH:mm:ss' 形式,解析失败按「无到期时间」处理。 */
170
+ function couponTime(value) {
171
+ if (value == null || value === '') return null
172
+ if (typeof value !== 'string') return NaN
173
+ return Date.parse(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value) ? value.replace(' ', 'T') + '+08:00' : value)
174
+ }
175
+
176
+ /** 券的剩余金额与原始面额是不同字段。 */
177
+ function couponBalance(item) {
178
+ const value = item?.Balance
179
+ if (typeof value === 'number') return value
180
+ return typeof value === 'string' && /^\d+(\.\d+)?$/.test(value.trim()) ? Number(value) : NaN
181
+ }
182
+
183
+ /**
184
+ * 汇总可用代金券。
185
+ * @param {Array<object>} items 券明细
186
+ * @param {number} nowMs 判定到期用的当前时间
187
+ * @returns {{total:number, count:number, nearestExpiryMs:number|null}}
188
+ */
189
+ export function summarizeCashCoupons(items, nowMs = Date.now(), currency = 'CNY') {
190
+ let totalCents = 0
191
+ let count = 0
192
+ let incomplete = false
193
+ let nearestExpiryMs = null
194
+ for (const item of dedupeCoupons(items ?? [])) {
195
+ const status = String(item?.Status ?? '').trim().toLowerCase()
196
+ if (!AVAILABLE_COUPON_STATUS.has(status)) continue
197
+ const expiresAt = couponTime(item.ExpiryTime ?? item.ExpiryDate)
198
+ const effectiveAt = couponTime(item.EffectiveTime)
199
+ if ((expiresAt !== null && expiresAt <= nowMs) || (effectiveAt !== null && effectiveAt > nowMs)) continue
200
+ const amount = couponBalance(item)
201
+ const product = typeof item.ApplicableProducts === 'string' ? item.ApplicableProducts.trim() : ''
202
+ const scenario = typeof item.ApplicableScenarios === 'string' ? item.ApplicableScenarios.trim() : ''
203
+ const couponCurrency = String(item.Currency ?? (currency === 'CNY' ? 'CNY' : '')).toUpperCase()
204
+ if (Number.isNaN(expiresAt) || Number.isNaN(effectiveAt) || !Number.isFinite(amount) || !product || !couponCurrency) {
205
+ incomplete = true
206
+ continue
207
+ }
208
+ const supportedProduct = product.split(/[,,、;;]/).some(name => /^(通用|general|(?:阿里云)?(?:大模型服务平台)?百炼|(?:alibaba cloud )?model studio|dashscope)$/i.test(name.trim()))
209
+ const supportedScenario = !scenario || scenario.split(/[,,、;;]/).some(name => /^(通用|不限|general|(?:阿里云)?按量付费(?:账单)?|(?:alibaba cloud )?pay-as-you-go(?: bills?)?)$/i.test(name.trim()))
210
+ if (couponCurrency !== currency || !supportedProduct || !supportedScenario) continue
211
+ if (!(amount > 0)) continue
212
+ const cents = Math.round(amount * 100)
213
+ if (!Number.isSafeInteger(totalCents + cents)) { incomplete = true; continue }
214
+ totalCents += cents
215
+ count += 1
216
+ if (expiresAt !== null && (nearestExpiryMs === null || expiresAt < nearestExpiryMs)) nearestExpiryMs = expiresAt
217
+ }
218
+ return { total: totalCents / 100, count, nearestExpiryMs, incomplete }
219
+ }
220
+
221
+ const dedupeKey = (item, index) => {
222
+ const id = item?.CashCouponId ?? item?.CashCouponNo
223
+ return (typeof id === 'string' && id !== '') || Number.isSafeInteger(id) ? `id:${id}` : `row:${index}`
224
+ }
225
+ const dedupeCoupons = items => {
226
+ const seen = new Set()
227
+ const out = []
228
+ items.forEach((item, index) => {
229
+ const key = dedupeKey(item, index)
230
+ if (seen.has(key)) return
231
+ seen.add(key)
232
+ out.push(item)
233
+ })
234
+ return out
235
+ }
236
+
72
237
  async function resolveCredential(ctx, name) {
73
238
  try {
74
239
  const hit = await ctx?.get?.('credentials')?.resolve(credentialRef(name))
@@ -77,47 +242,183 @@ async function resolveCredential(ctx, name) {
77
242
  return String(process.env[name] ?? '').trim()
78
243
  }
79
244
 
80
- async function readPayload(response, locale) {
245
+ /** 丢弃响应体:失败路径不该因为「body 没有 cancel」而把真正的错误盖掉。 */
246
+ async function discardBody(response) {
247
+ try { await response?.body?.cancel?.() } catch { /* 清理失败不掩盖真正的错误。 */ }
248
+ }
249
+
250
+ async function readPayload(response, locale, scope = 'balance') {
251
+ const payloadFailure = () => failure(locale, scope === 'coupon' ? 'couponPayload' : 'payload')
81
252
  if (Number(response.headers.get('content-length')) > MAX_BYTES) {
82
- await response.body?.cancel().catch(() => {})
83
- throw failure(locale, 'payload')
253
+ await discardBody(response)
254
+ throw payloadFailure()
84
255
  }
85
256
  try {
86
257
  const parts = []
87
258
  let bytes = 0
88
259
  for await (const part of response.body) {
89
260
  bytes += part.length
90
- if (bytes > MAX_BYTES) throw failure(locale, 'payload')
261
+ if (bytes > MAX_BYTES) throw payloadFailure()
91
262
  parts.push(part)
92
263
  }
93
264
  return JSON.parse(Buffer.concat(parts).toString('utf8'))
94
- } catch { throw failure(locale, 'payload') }
265
+ } catch { throw payloadFailure() }
95
266
  }
96
267
 
97
- export async function queryAliyunBalance(ctx, config, { fetchImpl = fetch, signal } = {}) {
98
- signal?.throwIfAborted()
99
- const locale = config?.locale
100
- const [ak, sk, token] = await Promise.all(ALIYUN_BALANCE_CREDENTIAL_VARS.map(name => resolveCredential(ctx, name)))
101
- if (!ak || !sk) throw Object.assign(failure(locale, 'missing'), { soft: true })
268
+ /**
269
+ * 发一次 BSS 调用并返回解析后的 JSON。
270
+ * 每次网络重试都重新签名(时间戳/nonce 必须新鲜),因此 fetchImpl 里现签。
271
+ */
272
+ async function callBss({ ak, sk, token, fetchImpl, signal, locale, action, version, params, scope = 'balance' }) {
273
+ // 两个接口的失败要说清是谁失败:券被拒需检查 bss:DescribeCoupons,
274
+ // 和余额被拒(bss:DescribeBillingAccount)是两条不同的排查路径。
275
+ const fail = (key, status) => failure(locale, scope === 'coupon'
276
+ ? `coupon${key.charAt(0).toUpperCase()}${key.slice(1)}`
277
+ : key, status)
102
278
  let response
103
279
  try {
104
- // 每次网络重试重新生成时间戳与 nonce;URL、Action、body 均固定为只读账户查询。
105
280
  response = await fetchWithRetry(ALIYUN_BALANCE_URL, { signal }, {
106
281
  attempts: 2, timeoutMs: 15000,
107
- fetchImpl: (url, init) => fetchImpl(url, { ...signAliyunBalanceRequest(ak, sk, token), signal: init.signal }),
282
+ fetchImpl: (url, init) => {
283
+ const signed = signAliyunRequest({
284
+ accessKeyId: ak, accessKeySecret: sk, securityToken: token,
285
+ action, version, params,
286
+ })
287
+ return fetchImpl(signed.query ? `${url}?${signed.query}` : url, { ...signed, signal: init.signal })
288
+ },
108
289
  })
109
290
  } catch {
110
291
  signal?.throwIfAborted()
111
- throw failure(locale, 'network')
292
+ throw fail('network')
112
293
  }
113
294
  if (!response.ok) {
114
- await response.body?.cancel().catch(() => {})
115
- if (response.status >= 300 && response.status < 400) throw failure(locale, 'redirect')
116
- if (response.status === 401 || response.status === 403) throw failure(locale, 'permission')
117
- throw failure(locale, 'http', response.status)
295
+ await discardBody(response)
296
+ if (response.status >= 300 && response.status < 400) throw fail('redirect')
297
+ if (response.status === 401 || response.status === 403) throw fail('permission')
298
+ throw fail('http', response.status)
118
299
  }
119
- const data = await readPayload(response, locale)
300
+ const data = await readPayload(response, locale, scope)
120
301
  // 不把上游 Message/RequestId/账户身份下发浏览器;即使错误响应夹带余额也不能记作成功。
121
- if ((data?.Code && data.Code !== 'Success') || data?.Success === false) throw failure(locale, 'permission')
122
- return { label: config?.customBalance?.label || '千问 / 阿里云', ...parseAliyunBalance(data, locale) }
302
+ if ((data?.Code && data.Code !== 'Success') || data?.Success === false) throw fail('permission')
303
+ return data
304
+ }
305
+
306
+ /**
307
+ * 取全部代金券明细。
308
+ *
309
+ * 先用 dsh-aliyun-balance 实测过的「不带业务参数」形状打一枪(该形状的返回范围最宽);
310
+ * 只有当它是空集时才补 EffectiveOrNot=true/false 各一次并合并 —— 省略该参数时服务端
311
+ * 到底返回哪些状态没有文档保证,两头发一枪能兜住两种实现。
312
+ */
313
+ async function fetchCashCoupons({ ak, sk, token, fetchImpl, signal, locale }) {
314
+ const call = params => callBss({
315
+ ak, sk, token, fetchImpl, signal, locale, scope: 'coupon',
316
+ action: CASH_COUPON_ACTION, version: BSS_VERSION_CASH_COUPON, params,
317
+ })
318
+ const pageWith = async baseParams => {
319
+ const first = await call(baseParams)
320
+ const items = cashCouponList(first)
321
+ const total = cashCouponTotal(first)
322
+ if (!Number.isFinite(total) || items.length >= total) return { items, incomplete: false }
323
+ // 超过一页才翻页,且**尽力而为**:PageNum/PageSize 是否被该 Action 接受没有文档保证,
324
+ // 翻页失败就退回第一页的结果 —— 宁可少算几张券,也不能因为分页参数把整段券查询判死,
325
+ // 那样连现金余额都会被拖成降级态。
326
+ const paged = [...items]
327
+ try {
328
+ for (let page = 1; page <= CASH_COUPON_MAX_PAGES; page++) {
329
+ const data = await call({ ...baseParams, PageNum: String(page), PageSize: String(CASH_COUPON_PAGE_SIZE) })
330
+ const got = cashCouponList(data)
331
+ const before = dedupeCoupons(paged).length
332
+ paged.push(...got)
333
+ const unique = dedupeCoupons(paged)
334
+ if (unique.length >= total) return { items: unique, incomplete: false }
335
+ if (unique.length === before && page > 1) break
336
+ }
337
+ } catch { signal?.throwIfAborted() }
338
+ return { items: dedupeCoupons(paged), incomplete: true }
339
+ }
340
+
341
+ const bare = await pageWith({})
342
+ if (bare.items.length > 0) return bare
343
+ const settled = await Promise.allSettled([pageWith({ EffectiveOrNot: 'true' }), pageWith({ EffectiveOrNot: 'false' })])
344
+ signal?.throwIfAborted()
345
+ if (settled.every(result => result.status === 'rejected')) throw settled[0].reason
346
+ const merged = []
347
+ for (const result of settled) if (result.status === 'fulfilled') merged.push(...result.value.items)
348
+ return { items: dedupeCoupons(merged), incomplete: settled.some(result => result.status === 'rejected' || result.value.incomplete) }
349
+ }
350
+
351
+ const CURRENCY_SYMBOL = { CNY: '¥', USD: '$', EUR: '€' }
352
+ const money = (amount, currency) => `${CURRENCY_SYMBOL[currency] ?? ''}${Number(amount).toFixed(2)}`
353
+ const formatDate = (ms) => {
354
+ if (!Number.isFinite(ms)) return ''
355
+ const date = new Date(ms)
356
+ const pad = value => String(value).padStart(2, '0')
357
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
358
+ }
359
+
360
+ export async function queryAliyunBalance(ctx, config, { fetchImpl = fetch, signal } = {}) {
361
+ signal?.throwIfAborted()
362
+ const locale = config?.locale
363
+ const [ak, sk, token] = await Promise.all(ALIYUN_BALANCE_CREDENTIAL_VARS.map(name => resolveCredential(ctx, name)))
364
+ if (!ak || !sk) throw Object.assign(failure(locale, 'missing'), { soft: true })
365
+
366
+ const data = await callBss({
367
+ ak, sk, token, fetchImpl, signal, locale,
368
+ action: 'GetFundAccountAvailableAmount', version: BSS_VERSION_FUND_ACCOUNT, params: {},
369
+ })
370
+ const cash = parseAliyunBalance(data, locale)
371
+ const currency = cash.unit
372
+
373
+ // 券是「可用额度」的一部分,但**不能**因为券查不到就把余额判成失败:
374
+ // 常见原因是 RAM 缺少 bss:DescribeCoupons 权限。
375
+ let couponSummary = null
376
+ let couponError = ''
377
+ try {
378
+ const result = await fetchCashCoupons({ ak, sk, token, fetchImpl, signal, locale })
379
+ couponSummary = summarizeCashCoupons(result.items, Date.now(), currency)
380
+ couponSummary.incomplete ||= result.incomplete
381
+ } catch (error) {
382
+ signal?.throwIfAborted()
383
+ couponError = error instanceof Error ? error.message : String(error)
384
+ }
385
+
386
+ const couponTotal = couponSummary ? couponSummary.total : 0
387
+ const remaining = couponTotal === 0 ? cash.remaining : Math.round((cash.remaining + couponTotal) * 100) / 100
388
+
389
+ let message
390
+ if (couponError) {
391
+ message = text(locale, 'cashOnly', {
392
+ cash: money(cash.remaining, currency),
393
+ reason: text(locale, 'couponFailed', { message: couponError }),
394
+ })
395
+ } else if (couponSummary && couponSummary.count > 0) {
396
+ const expiry = formatDate(couponSummary.nearestExpiryMs)
397
+ message = text(locale, expiry ? 'couponLine' : 'couponNoDate', {
398
+ cash: money(cash.remaining, currency),
399
+ coupon: money(couponTotal, currency),
400
+ count: couponSummary.count,
401
+ date: expiry,
402
+ })
403
+ } else {
404
+ message = text(locale, 'cashOnly', {
405
+ cash: money(cash.remaining, currency),
406
+ reason: text(locale, couponSummary?.incomplete ? 'couponPartial' : 'couponNone'),
407
+ })
408
+ }
409
+ if (couponSummary?.incomplete && couponSummary.count > 0) message += ' · ' + text(locale, 'couponPartial')
410
+
411
+ return {
412
+ label: config?.customBalance?.label || '千问 / 阿里云',
413
+ unit: currency,
414
+ remaining,
415
+ maxBudget: null,
416
+ spend: null,
417
+ message,
418
+ // 明细同时留结构化字段,便于后续 UI 展示或用户排查(当前客户端只透传已知键)。
419
+ cashRemaining: cash.remaining,
420
+ couponBalance: couponTotal,
421
+ couponCount: couponSummary ? couponSummary.count : 0,
422
+ couponError,
423
+ }
123
424
  }
package/lib/backfill.js CHANGED
@@ -20,7 +20,7 @@ import { localDayKey, zeroDay, splitLedgerApiCost } from './store.js'
20
20
  import { billingClassOf, enabledPlanSetOf, planProviderIdOf, isRoutedThirdPartyCall, appendHourBucket, planUsageFingerprint, HOUR_BUCKET_RETENTION_MS, localMidnightMs } from './plan-billing.js'
21
21
  import { USAGE_DEDUP_WINDOW_MS, usageFingerprint } from './usage-dedup.js'
22
22
  import { isNativeSearchUsageEvent } from './native-search-events.js'
23
- import { isWebRequestModel } from './web-request-pricing.js'
23
+ import { isWebRequestModel, requestFeeCostCny } from './web-request-pricing.js'
24
24
  import { listSessionLogFiles } from './session-log-files.js'
25
25
  import { listNativeSearchHistory, readNativeSearchHistory, nativeSearchRecordsFor } from './native-search-history.js'
26
26
  import { BILLION_USAGE_EVENT, billionRecordsFor, excludeBillionReportedUsage, listBillionFiles, iterateBillionCalls } from './billion-context-history.js'
@@ -680,7 +680,7 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
680
680
  }
681
681
  // 官方价格币种为人民币(issue #47)时,DeepSeek 主表计出的成本为人民币,
682
682
  // 按展示汇率折算为美元入账——与 store.account() 完全同口径。
683
- const priced = requestFee ? requestFee.requests * requestFee.rateCny : resolved.priced ? costOf(buckets, resolved.entry, pricedAtMs, peak) : 0
683
+ const priced = requestFee ? requestFeeCostCny(requestFee, atMs) : resolved.priced ? costOf(buckets, resolved.entry, pricedAtMs, peak) : 0
684
684
  // 每个回放样本只带冻结金额用得到的汇率,不复制整张展示币种目录。
685
685
  const fxRates = fxHistoryRatesOf(pricing)
686
686
  const canonical = usdFromCost(priced, resolved.currency, fxRates.CNY)
@@ -1152,6 +1152,7 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1152
1152
  if (explicit) result.before = Object.values(ledger.days).reduce((sum, day) => sum + amount(day), 0)
1153
1153
  if (explicit && model) for (const [unit, field] of [['Cny', 'costCny'], ['Eur', 'costEur']]) result['before' + unit] = Object.values(ledger.days).reduce((sum, day) => sum + (Number(day.byProviderModel?.[model]?.[field]) || 0), 0)
1154
1154
  const tokenFields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']
1155
+ const serverSearchOnly = model === 'deepseek-official:deepseek-search-server'
1155
1156
  const detail = (sessionId, date, model, reason, fields = []) => {
1156
1157
  if (explicit) result.skippedDetails.push({ sessionId, date, model, reason, fields })
1157
1158
  }
@@ -1162,12 +1163,12 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1162
1163
  if (row === undefined) continue // 账本无此会话行:不新增(与实时计费互斥)。
1163
1164
  const oldPm = row.byProviderModel !== null && typeof row.byProviderModel === 'object' ? row.byProviderModel : {}
1164
1165
  if (model && !Object.hasOwn(oldPm, model)) continue
1165
- const newKeys = Object.keys(pm)
1166
+ const newKeys = serverSearchOnly ? [model] : Object.keys(pm)
1166
1167
  const dayPm = day.byProviderModel !== null && typeof day.byProviderModel === 'object' ? day.byProviderModel : {}
1167
1168
  // Token 计价只要求五桶一致;按请求收费仍须核对 calls。重算只改金额,保留账本计量。
1168
- let replaceable = newKeys.length > 0 && newKeys.length === Object.keys(oldPm).length
1169
+ let replaceable = serverSearchOnly || (newKeys.length > 0 && newKeys.length === Object.keys(oldPm).length)
1169
1170
  const residualModels = []
1170
- for (const key of new Set([...Object.keys(oldPm), ...newKeys])) {
1171
+ for (const key of serverSearchOnly ? newKeys : new Set([...Object.keys(oldPm), ...newKeys])) {
1171
1172
  const oldBucket = oldPm[key]
1172
1173
  const dayBucket = dayPm[key]
1173
1174
  const newBucket = pm[key]