统一前后端代码格式化配置
This commit is contained in:
@@ -33,8 +33,10 @@ export function getKuaishouIndustryConfig(overrides: Partial<KuaishouIndustrySou
|
||||
sellerId: String(config.sellerId || '').trim(),
|
||||
lastRefreshedAt: String(config.lastRefreshedAt || '').trim(),
|
||||
lastRefreshError: String(config.lastRefreshError || '').trim(),
|
||||
provider: String(config.provider || KUISHOU_INDUSTRY_PROVIDER).trim() || KUISHOU_INDUSTRY_PROVIDER,
|
||||
platform: String(config.platform || KUISHOU_INDUSTRY_PLATFORM).trim() || KUISHOU_INDUSTRY_PLATFORM,
|
||||
provider:
|
||||
String(config.provider || KUISHOU_INDUSTRY_PROVIDER).trim() || KUISHOU_INDUSTRY_PROVIDER,
|
||||
platform:
|
||||
String(config.platform || KUISHOU_INDUSTRY_PLATFORM).trim() || KUISHOU_INDUSTRY_PLATFORM,
|
||||
shopId: String(config.shopId || KUISHOU_INDUSTRY_PROVIDER).trim() || KUISHOU_INDUSTRY_PROVIDER,
|
||||
shopName: String(config.shopName || '快手行业电子凭证').trim() || '快手行业电子凭证',
|
||||
version: String(config.version || '1').trim() || '1',
|
||||
|
||||
+13
-9
@@ -6,11 +6,13 @@ import { buildConsumeCallbackBizParams } from './consume-callback-service.js'
|
||||
test('buildConsumeCallbackBizParams omits unsupported consume fields', () => {
|
||||
const bizParams = buildConsumeCallbackBizParams({
|
||||
oid: '2619000086068982',
|
||||
etickets: [{
|
||||
id: 'KSVASXT6Q955WT4SS36',
|
||||
num: 1,
|
||||
status: 'CONSUMED',
|
||||
} as any],
|
||||
etickets: [
|
||||
{
|
||||
id: 'KSVASXT6Q955WT4SS36',
|
||||
num: 1,
|
||||
status: 'CONSUMED',
|
||||
} as any,
|
||||
],
|
||||
status: 'CONSUMED',
|
||||
consumeType: 'consume',
|
||||
consumeTime: 1783596649024,
|
||||
@@ -19,10 +21,12 @@ test('buildConsumeCallbackBizParams omits unsupported consume fields', () => {
|
||||
seriallNum: 'CONSUME-KSVASXT6Q955WT4SS36',
|
||||
} as any)
|
||||
|
||||
assert.deepEqual(bizParams.etickets, [{
|
||||
id: 'KSVASXT6Q955WT4SS36',
|
||||
num: 1,
|
||||
}])
|
||||
assert.deepEqual(bizParams.etickets, [
|
||||
{
|
||||
id: 'KSVASXT6Q955WT4SS36',
|
||||
num: 1,
|
||||
},
|
||||
])
|
||||
assert.equal(bizParams.consumeType, 'consume')
|
||||
assert.equal('eticketType' in bizParams, false)
|
||||
})
|
||||
|
||||
@@ -4,16 +4,10 @@ import { normalizeTimestampIso } from '../../../utils/time.js'
|
||||
import { logWarn } from '../../../utils/logger.js'
|
||||
import { TASK_STATUS } from '../../../domain/task-status.js'
|
||||
import type { JsonObject } from '../../../types/json.js'
|
||||
import {
|
||||
getKuaishouIndustryConfig,
|
||||
assertMatchingAppKey,
|
||||
} from './config.js'
|
||||
import { getKuaishouIndustryConfig, assertMatchingAppKey } from './config.js'
|
||||
import { normalizeConsumeCodePayload, assertConsumeCodePayload } from './payload.js'
|
||||
import { assertKuaishouIndustrySignature } from './crypto.js'
|
||||
import {
|
||||
buildIndustrySuccessResponse,
|
||||
buildIndustryErrorResponse,
|
||||
} from './response.js'
|
||||
import { buildIndustrySuccessResponse, buildIndustryErrorResponse } from './response.js'
|
||||
import { consumeCallback } from './consume-callback-service.js'
|
||||
import { consumeKuaishouIndustryVoucher } from './voucher-service.js'
|
||||
import { attachKuaishouIndustryVoucherToTask } from './voucher-binding-service.js'
|
||||
@@ -85,7 +79,10 @@ export async function handleConsumeCode(rawBody: JsonObject = {}) {
|
||||
}
|
||||
|
||||
if (consumedCount === 0) {
|
||||
return buildIndustryErrorResponse(4012005, `未找到匹配的卡券: ${params.etickets.map((e) => e.id).join(',')}`)
|
||||
return buildIndustryErrorResponse(
|
||||
4012005,
|
||||
`未找到匹配的卡券: ${params.etickets.map((e) => e.id).join(',')}`,
|
||||
)
|
||||
}
|
||||
|
||||
fireConsumeCallback({
|
||||
|
||||
@@ -7,7 +7,10 @@ import { assertKuaishouIndustryConfig } from './config.js'
|
||||
|
||||
export type SignMethod = 'MD5' | 'HMAC_SHA256'
|
||||
|
||||
export function buildKuaishouIndustrySignSource(params: JsonObject = {}, { signSecret } = assertKuaishouIndustryConfig()) {
|
||||
export function buildKuaishouIndustrySignSource(
|
||||
params: JsonObject = {},
|
||||
{ signSecret } = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
const entries = Object.entries(params)
|
||||
.filter(([key]) => key !== 'sign' && key !== 'signSecret')
|
||||
.sort(([left], [right]) => {
|
||||
@@ -17,9 +20,7 @@ export function buildKuaishouIndustrySignSource(params: JsonObject = {}, { signS
|
||||
return left < right ? -1 : 1
|
||||
})
|
||||
|
||||
const queryString = entries
|
||||
.map(([key, value]) => `${key}=${stringifySignValue(value)}`)
|
||||
.join('&')
|
||||
const queryString = entries.map(([key, value]) => `${key}=${stringifySignValue(value)}`).join('&')
|
||||
|
||||
return `${queryString}&signSecret=${signSecret}`
|
||||
}
|
||||
@@ -35,11 +36,7 @@ export function signKuaishouIndustryPayload(
|
||||
return hmacSha256Sign(source, config.signSecret)
|
||||
}
|
||||
|
||||
return crypto
|
||||
.createHash('md5')
|
||||
.update(source, 'utf8')
|
||||
.digest('hex')
|
||||
.toLowerCase()
|
||||
return crypto.createHash('md5').update(source, 'utf8').digest('hex').toLowerCase()
|
||||
}
|
||||
|
||||
export function verifyKuaishouIndustrySignature(
|
||||
@@ -64,7 +61,10 @@ export function verifyKuaishouIndustrySignature(
|
||||
return true
|
||||
}
|
||||
|
||||
export function assertKuaishouIndustrySignature(params: JsonObject = {}, config = assertKuaishouIndustryConfig()) {
|
||||
export function assertKuaishouIndustrySignature(
|
||||
params: JsonObject = {},
|
||||
config = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
if (!verifyKuaishouIndustrySignature(params, config)) {
|
||||
throw createHttpError('签名验证失败', {
|
||||
statusCode: 400,
|
||||
@@ -74,14 +74,13 @@ export function assertKuaishouIndustrySignature(params: JsonObject = {}, config
|
||||
}
|
||||
|
||||
function hmacSha256Sign(source: string, secret: string) {
|
||||
return crypto
|
||||
.createHmac('sha256', secret)
|
||||
.update(source, 'utf8')
|
||||
.digest('base64')
|
||||
return crypto.createHmac('sha256', secret).update(source, 'utf8').digest('base64')
|
||||
}
|
||||
|
||||
function normalizeSignMethod(value: unknown): SignMethod {
|
||||
const normalized = String(value || '').trim().toUpperCase()
|
||||
const normalized = String(value || '')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
if (normalized === 'HMAC_SHA256' || normalized === 'HMAC-SHA256') {
|
||||
return 'HMAC_SHA256'
|
||||
}
|
||||
|
||||
@@ -28,10 +28,7 @@ test('normalizeDestroyCodePayload keeps destroy callback token when provided', (
|
||||
})
|
||||
|
||||
test('resolveDestroyCallbackToken falls back to stored voucher token', () => {
|
||||
const token = resolveDestroyCallbackToken([
|
||||
{ token: '' },
|
||||
{ token: ' stored-token ' },
|
||||
])
|
||||
const token = resolveDestroyCallbackToken([{ token: '' }, { token: ' stored-token ' }])
|
||||
|
||||
assert.equal(token, 'stored-token')
|
||||
})
|
||||
|
||||
@@ -7,15 +7,10 @@ import {
|
||||
import { normalizeTimestampIso } from '../../../utils/time.js'
|
||||
import { logWarn } from '../../../utils/logger.js'
|
||||
import { TASK_STATUS } from '../../../domain/task-status.js'
|
||||
import {
|
||||
getKuaishouIndustryConfig,
|
||||
assertMatchingAppKey,
|
||||
} from './config.js'
|
||||
import { getKuaishouIndustryConfig, assertMatchingAppKey } from './config.js'
|
||||
import { normalizeDestroyCodePayload, assertDestroyCodePayload } from './payload.js'
|
||||
import { assertKuaishouIndustrySignature } from './crypto.js'
|
||||
import {
|
||||
buildIndustrySuccessResponse,
|
||||
} from './response.js'
|
||||
import { buildIndustrySuccessResponse } from './response.js'
|
||||
import { destroyCallback } from './destroy-callback-service.js'
|
||||
import { attachKuaishouIndustryVoucherToTask } from './voucher-binding-service.js'
|
||||
import { resolveKuaishouIndustryEticketType } from './voucher-service.js'
|
||||
@@ -34,18 +29,22 @@ export async function handleDestroyCode(rawBody: JsonObject = {}) {
|
||||
|
||||
const vouchers = await listKuaishouIndustryVouchersByOid(normalizedOid)
|
||||
const targetIds = new Set(params.etickets.map((e) => String(e.id || '').trim()).filter(Boolean))
|
||||
const targetVouchers = targetIds.size > 0
|
||||
? vouchers.filter((voucher) => targetIds.has(String(voucher.voucher_code || '').trim()))
|
||||
: vouchers
|
||||
const callbackSellerId = params.sellerId
|
||||
|| String(targetVouchers.find((voucher) => String(voucher.seller_id || '').trim())?.seller_id || '').trim()
|
||||
const targetVouchers =
|
||||
targetIds.size > 0
|
||||
? vouchers.filter((voucher) => targetIds.has(String(voucher.voucher_code || '').trim()))
|
||||
: vouchers
|
||||
const callbackSellerId =
|
||||
params.sellerId ||
|
||||
String(
|
||||
targetVouchers.find((voucher) => String(voucher.seller_id || '').trim())?.seller_id || '',
|
||||
).trim()
|
||||
const callbackToken = params.token || resolveDestroyCallbackToken(targetVouchers)
|
||||
const eticketType = resolveKuaishouIndustryEticketType(
|
||||
targetVouchers[0] || null,
|
||||
)
|
||||
const eticketType = resolveKuaishouIndustryEticketType(targetVouchers[0] || null)
|
||||
|
||||
for (const voucher of targetVouchers) {
|
||||
const status = String(voucher.status || '').trim().toUpperCase()
|
||||
const status = String(voucher.status || '')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
if (status === 'CONSUMED') {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -36,11 +36,7 @@ export async function requestKuaishouIndustryOpenApi(
|
||||
const apiLabel = formatKuaishouOpenApiLabel(input.apiMethod)
|
||||
|
||||
if (!config.enabled) {
|
||||
logKuaishouOpenApi(
|
||||
input,
|
||||
`快手 OpenAPI 未启用,跳过 ${apiLabel}`,
|
||||
undefined,
|
||||
)
|
||||
logKuaishouOpenApi(input, `快手 OpenAPI 未启用,跳过 ${apiLabel}`, undefined)
|
||||
return { success: true, skippedReason: 'disabled' }
|
||||
}
|
||||
|
||||
@@ -70,12 +66,7 @@ export async function requestKuaishouIndustryOpenApi(
|
||||
}
|
||||
|
||||
if (!config.accessToken) {
|
||||
logKuaishouOpenApi(
|
||||
input,
|
||||
`快手 OpenAPI accessToken 缺失 ${apiLabel}`,
|
||||
undefined,
|
||||
'warn',
|
||||
)
|
||||
logKuaishouOpenApi(input, `快手 OpenAPI accessToken 缺失 ${apiLabel}`, undefined, 'warn')
|
||||
return {
|
||||
success: false,
|
||||
skippedReason: 'missing_access_token',
|
||||
@@ -115,13 +106,14 @@ export async function requestKuaishouIndustryOpenApi(
|
||||
|
||||
try {
|
||||
const startedAt = Date.now()
|
||||
const res = httpMethod === 'GET'
|
||||
? await fetch(`${url}?${body.toString()}`, { method: 'GET' })
|
||||
: await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
})
|
||||
const res =
|
||||
httpMethod === 'GET'
|
||||
? await fetch(`${url}?${body.toString()}`, { method: 'GET' })
|
||||
: await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
})
|
||||
const text = await res.text()
|
||||
let json: JsonObject = {}
|
||||
try {
|
||||
@@ -134,9 +126,7 @@ export async function requestKuaishouIndustryOpenApi(
|
||||
const success = res.ok && Number(json.result) === 1
|
||||
logKuaishouOpenApi(
|
||||
input,
|
||||
success
|
||||
? `快手 OpenAPI 调用成功 ${apiLabel}`
|
||||
: `快手 OpenAPI 调用失败 ${apiLabel}`,
|
||||
success ? `快手 OpenAPI 调用成功 ${apiLabel}` : `快手 OpenAPI 调用失败 ${apiLabel}`,
|
||||
{
|
||||
durationMs,
|
||||
httpStatus: res.status,
|
||||
@@ -201,17 +191,21 @@ export function buildKuaishouOpenApiRequestLog({
|
||||
}
|
||||
|
||||
export function resolveKuaishouOpenApiBaseUrl(value: unknown): string {
|
||||
return String(value || DEFAULT_KUAISHOU_OPEN_API).trim().replace(/\/+$/, '') ||
|
||||
DEFAULT_KUAISHOU_OPEN_API
|
||||
return (
|
||||
String(value || DEFAULT_KUAISHOU_OPEN_API)
|
||||
.trim()
|
||||
.replace(/\/+$/, '') || DEFAULT_KUAISHOU_OPEN_API
|
||||
)
|
||||
}
|
||||
|
||||
export function resolveKuaishouOpenApiErrorDetail(error: unknown): JsonObject {
|
||||
const detail: JsonObject = {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
const cause = error && typeof error === 'object' && 'cause' in error
|
||||
? (error as { cause?: unknown }).cause
|
||||
: null
|
||||
const cause =
|
||||
error && typeof error === 'object' && 'cause' in error
|
||||
? (error as { cause?: unknown }).cause
|
||||
: null
|
||||
if (!cause || typeof cause !== 'object') {
|
||||
return detail
|
||||
}
|
||||
@@ -285,16 +279,16 @@ function resolveKuaishouOpenApiName(method: unknown): string {
|
||||
'integration.callback.virtual.eticket.destroy': '电子凭证销毁回调',
|
||||
'integration.callback.virtual.eticket.reverse': '电子凭证冲正回调',
|
||||
'open.virtual.eticket.checkavailable': '检查电子凭证有效性',
|
||||
'kwaishop_refund_addRefund': '新增退款单消息',
|
||||
'kwaishop_refund_updateRefund': '退款单更新消息',
|
||||
'kwaishop_aftersales_addRefund': '售后单新增消息',
|
||||
'kwaishop_order_addOrder': '订单新增消息',
|
||||
'kwaishop_order_statusChange': '订单状态变更消息',
|
||||
'kwaishop_order_totalFeeChange': '订单费用变更消息',
|
||||
'kwaishop_order_addNote': '订单备注消息',
|
||||
'KwaishopVirtualEticketSendService': '快手电子凭证通知发货',
|
||||
'KwaishopVirtualEticketQueryService': '电子凭证查询发码结果或券码状态',
|
||||
'KwaishopDigitalETicketDestoryService': '电子凭证发起销毁',
|
||||
kwaishop_refund_addRefund: '新增退款单消息',
|
||||
kwaishop_refund_updateRefund: '退款单更新消息',
|
||||
kwaishop_aftersales_addRefund: '售后单新增消息',
|
||||
kwaishop_order_addOrder: '订单新增消息',
|
||||
kwaishop_order_statusChange: '订单状态变更消息',
|
||||
kwaishop_order_totalFeeChange: '订单费用变更消息',
|
||||
kwaishop_order_addNote: '订单备注消息',
|
||||
KwaishopVirtualEticketSendService: '快手电子凭证通知发货',
|
||||
KwaishopVirtualEticketQueryService: '电子凭证查询发码结果或券码状态',
|
||||
KwaishopDigitalETicketDestoryService: '电子凭证发起销毁',
|
||||
'integration.virtual.eticket.send': '电子凭证通知发码',
|
||||
'integration.virtual.eticket.query': '电子凭证查询发码结果或券码状态',
|
||||
'integration.virtual.eticket.destroy': '电子凭证发起销毁',
|
||||
|
||||
@@ -47,7 +47,5 @@ export function normalizeStringList(value: unknown): string[] {
|
||||
return []
|
||||
}
|
||||
|
||||
return value
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
return value.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHttpError } from '../../../utils/http.js'
|
||||
import { assertKuaishouIndustryConfig } from './config.js'
|
||||
import { asJsonObject, type JsonObject } from '../../../types/json.js'
|
||||
import { asJsonObject, type JsonObject } from '../../../types/json.js'
|
||||
|
||||
export function normalizeIndustryString(value: unknown) {
|
||||
return String(value || '').trim()
|
||||
@@ -80,7 +80,10 @@ export function normalizeQueryCodePayload(raw: JsonObject = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSendCodePayload(payload: ReturnType<typeof normalizeSendCodePayload>, config = assertKuaishouIndustryConfig()) {
|
||||
export function assertSendCodePayload(
|
||||
payload: ReturnType<typeof normalizeSendCodePayload>,
|
||||
config = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
if (!payload.oid) {
|
||||
throw createHttpError('缺少 oid', {
|
||||
statusCode: 400,
|
||||
@@ -105,7 +108,10 @@ export function assertSendCodePayload(payload: ReturnType<typeof normalizeSendCo
|
||||
assertCommonPayload(payload, config)
|
||||
}
|
||||
|
||||
export function assertDestroyCodePayload(payload: ReturnType<typeof normalizeDestroyCodePayload>, config = assertKuaishouIndustryConfig()) {
|
||||
export function assertDestroyCodePayload(
|
||||
payload: ReturnType<typeof normalizeDestroyCodePayload>,
|
||||
config = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
if (!payload.oid) {
|
||||
throw createHttpError('缺少 oid', {
|
||||
statusCode: 400,
|
||||
@@ -123,7 +129,10 @@ export function assertDestroyCodePayload(payload: ReturnType<typeof normalizeDes
|
||||
assertCommonPayload(payload, config)
|
||||
}
|
||||
|
||||
export function assertQueryCodePayload(payload: ReturnType<typeof normalizeQueryCodePayload>, config = assertKuaishouIndustryConfig()) {
|
||||
export function assertQueryCodePayload(
|
||||
payload: ReturnType<typeof normalizeQueryCodePayload>,
|
||||
config = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
if (!payload.oid) {
|
||||
throw createHttpError('缺少 oid', {
|
||||
statusCode: 400,
|
||||
@@ -165,7 +174,10 @@ export function normalizeConsumeCodePayload(raw: JsonObject = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export function assertConsumeCodePayload(payload: ReturnType<typeof normalizeConsumeCodePayload>, config = assertKuaishouIndustryConfig()) {
|
||||
export function assertConsumeCodePayload(
|
||||
payload: ReturnType<typeof normalizeConsumeCodePayload>,
|
||||
config = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
if (!payload.oid) {
|
||||
throw createHttpError('缺少 oid', {
|
||||
statusCode: 400,
|
||||
@@ -205,7 +217,16 @@ export function assertConsumeCodePayload(payload: ReturnType<typeof normalizeCon
|
||||
}
|
||||
|
||||
function assertCommonPayload(
|
||||
payload: { appKey: string, version: string, timestamp: number, signMethod: string, sign: string, method: string, accessToken: string, paramRaw: string },
|
||||
payload: {
|
||||
appKey: string
|
||||
version: string
|
||||
timestamp: number
|
||||
signMethod: string
|
||||
sign: string
|
||||
method: string
|
||||
accessToken: string
|
||||
paramRaw: string
|
||||
},
|
||||
config = assertKuaishouIndustryConfig(),
|
||||
) {
|
||||
if (!payload.signMethod) {
|
||||
@@ -223,7 +244,11 @@ function assertCommonPayload(
|
||||
}
|
||||
|
||||
const normalizedMethod = payload.signMethod.toUpperCase()
|
||||
if (normalizedMethod !== 'MD5' && normalizedMethod !== 'HMAC_SHA256' && normalizedMethod !== 'HMAC-SHA256') {
|
||||
if (
|
||||
normalizedMethod !== 'MD5' &&
|
||||
normalizedMethod !== 'HMAC_SHA256' &&
|
||||
normalizedMethod !== 'HMAC-SHA256'
|
||||
) {
|
||||
throw createHttpError(`不支持的签名算法: ${payload.signMethod},仅支持 MD5 或 HMAC_SHA256`, {
|
||||
statusCode: 400,
|
||||
errorCode: 'kuaishou_industry_unsupported_sign_method',
|
||||
|
||||
@@ -3,10 +3,7 @@ import {
|
||||
findKuaishouIndustryVoucherByCode,
|
||||
listKuaishouIndustryVouchersByOid,
|
||||
} from '../../../repositories/kuaishou-industry-voucher-repo.js'
|
||||
import {
|
||||
getKuaishouIndustryConfig,
|
||||
assertMatchingAppKey,
|
||||
} from './config.js'
|
||||
import { getKuaishouIndustryConfig, assertMatchingAppKey } from './config.js'
|
||||
import { normalizeQueryCodePayload, assertQueryCodePayload } from './payload.js'
|
||||
import { assertKuaishouIndustrySignature } from './crypto.js'
|
||||
import {
|
||||
@@ -50,8 +47,9 @@ export async function handleQueryCode(rawBody: JsonObject = {}) {
|
||||
)
|
||||
}
|
||||
|
||||
const vouchers = (await listKuaishouIndustryVouchersByOid(normalizedOid))
|
||||
.filter(isKuaishouIndustryVoucherSendCallbackSuccess)
|
||||
const vouchers = (await listKuaishouIndustryVouchersByOid(normalizedOid)).filter(
|
||||
isKuaishouIndustryVoucherSendCallbackSuccess,
|
||||
)
|
||||
if (vouchers.length === 0) {
|
||||
return buildIndustryErrorResponse(4012002, `订单不存在: ${normalizedOid}`)
|
||||
}
|
||||
|
||||
@@ -51,15 +51,23 @@ export function listKuaishouIndustryRefunds(input: KuaishouIndustryRefundListInp
|
||||
type: normalizeOpenApiInteger(input.type, 8),
|
||||
pageSize: normalizeOpenApiPositiveInteger(input.pageSize, 50),
|
||||
currentPage: normalizeOpenApiPositiveInteger(input.currentPage, 1),
|
||||
sort: input.sort === undefined || input.sort === '' ? undefined : normalizeOpenApiInteger(input.sort, 1),
|
||||
queryType: input.queryType === undefined || input.queryType === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.queryType, 1),
|
||||
negotiateStatus: input.negotiateStatus === undefined || input.negotiateStatus === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.negotiateStatus, 0),
|
||||
sort:
|
||||
input.sort === undefined || input.sort === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.sort, 1),
|
||||
queryType:
|
||||
input.queryType === undefined || input.queryType === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.queryType, 1),
|
||||
negotiateStatus:
|
||||
input.negotiateStatus === undefined || input.negotiateStatus === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.negotiateStatus, 0),
|
||||
pcursor: String(input.pcursor ?? ''),
|
||||
status: input.status === undefined || input.status === '' ? undefined : normalizeOpenApiInteger(input.status, 0),
|
||||
status:
|
||||
input.status === undefined || input.status === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.status, 0),
|
||||
option: input.option && typeof input.option === 'object' ? input.option : undefined,
|
||||
orderId: normalizeOpenApiLong(input.orderId),
|
||||
})
|
||||
@@ -78,13 +86,18 @@ export function approveKuaishouIndustryRefund(input: KuaishouIndustryRefundAppro
|
||||
refundId: normalizeOpenApiLong(input.refundId),
|
||||
desc: String(input.desc ?? '').trim(),
|
||||
refundAmount: normalizeOpenApiLong(input.refundAmount),
|
||||
status: input.status === undefined || input.status === '' ? undefined : normalizeOpenApiInteger(input.status, 0),
|
||||
negotiateStatus: input.negotiateStatus === undefined || input.negotiateStatus === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.negotiateStatus, 0),
|
||||
refundHandingWay: input.refundHandingWay === undefined || input.refundHandingWay === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.refundHandingWay, 0),
|
||||
status:
|
||||
input.status === undefined || input.status === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.status, 0),
|
||||
negotiateStatus:
|
||||
input.negotiateStatus === undefined || input.negotiateStatus === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.negotiateStatus, 0),
|
||||
refundHandingWay:
|
||||
input.refundHandingWay === undefined || input.refundHandingWay === ''
|
||||
? undefined
|
||||
: normalizeOpenApiInteger(input.refundHandingWay, 0),
|
||||
})
|
||||
|
||||
return requestKuaishouIndustryOpenApi({
|
||||
|
||||
@@ -21,7 +21,9 @@ type SendCallbackInput = {
|
||||
expressNo?: string
|
||||
}
|
||||
|
||||
export async function sendCallback(input: SendCallbackInput): Promise<{ success: boolean; response?: JsonObject; error?: string }> {
|
||||
export async function sendCallback(
|
||||
input: SendCallbackInput,
|
||||
): Promise<{ success: boolean; response?: JsonObject; error?: string }> {
|
||||
const bizParams: JsonObject = {
|
||||
oid: input.oid,
|
||||
sendType: input.sendType,
|
||||
@@ -56,7 +58,11 @@ export async function sendCallback(input: SendCallbackInput): Promise<{ success:
|
||||
sellerId: input.sellerId || '',
|
||||
...request,
|
||||
}
|
||||
logIntegration('[kuaishou-industry/send-callback]', `发起电子凭证发货回调 oid=${input.oid}`, requestLog)
|
||||
logIntegration(
|
||||
'[kuaishou-industry/send-callback]',
|
||||
`发起电子凭证发货回调 oid=${input.oid}`,
|
||||
requestLog,
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -67,9 +73,14 @@ export async function sendCallback(input: SendCallbackInput): Promise<{ success:
|
||||
|
||||
if (result.skippedReason === 'token_error') {
|
||||
const message = result.error || 'accessToken 刷新失败'
|
||||
logIntegration('[kuaishou-industry/send-callback]', 'accessToken 刷新失败,无法发起发货回调', {
|
||||
error: message,
|
||||
}, { level: 'warn' })
|
||||
logIntegration(
|
||||
'[kuaishou-industry/send-callback]',
|
||||
'accessToken 刷新失败,无法发起发货回调',
|
||||
{
|
||||
error: message,
|
||||
},
|
||||
{ level: 'warn' },
|
||||
)
|
||||
return { success: false, error: message }
|
||||
}
|
||||
|
||||
@@ -94,17 +105,27 @@ export async function sendCallback(input: SendCallbackInput): Promise<{ success:
|
||||
response: result.response || null,
|
||||
})
|
||||
} else if (result.error) {
|
||||
logIntegration('[kuaishou-industry/send-callback]', `电子凭证发货回调异常 oid=${input.oid}`, {
|
||||
...(result.errorDetail || { error: result.error }),
|
||||
request: requestLog,
|
||||
}, { level: 'warn' })
|
||||
logIntegration(
|
||||
'[kuaishou-industry/send-callback]',
|
||||
`电子凭证发货回调异常 oid=${input.oid}`,
|
||||
{
|
||||
...(result.errorDetail || { error: result.error }),
|
||||
request: requestLog,
|
||||
},
|
||||
{ level: 'warn' },
|
||||
)
|
||||
} else {
|
||||
logIntegration('[kuaishou-industry/send-callback]', `电子凭证发货回调失败 oid=${input.oid}`, {
|
||||
durationMs: result.durationMs,
|
||||
status: result.httpStatus,
|
||||
request: requestLog,
|
||||
response: result.response || null,
|
||||
}, { level: 'warn' })
|
||||
logIntegration(
|
||||
'[kuaishou-industry/send-callback]',
|
||||
`电子凭证发货回调失败 oid=${input.oid}`,
|
||||
{
|
||||
durationMs: result.durationMs,
|
||||
status: result.httpStatus,
|
||||
request: requestLog,
|
||||
response: result.response || null,
|
||||
},
|
||||
{ level: 'warn' },
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -29,11 +29,7 @@ test('resolveSendCallbackPreferredTotalGoodsValue falls back to order total amou
|
||||
})
|
||||
|
||||
test('resolveSendCallbackGoodsValuePlan prefers 91 amount over ext payment', () => {
|
||||
const plan = resolveSendCallbackGoodsValuePlan(
|
||||
[{}],
|
||||
'{"payment":100,"platformBearAmount":0}',
|
||||
1,
|
||||
)
|
||||
const plan = resolveSendCallbackGoodsValuePlan([{}], '{"payment":100,"platformBearAmount":0}', 1)
|
||||
|
||||
assert.deepEqual(plan.goodsValues, [1])
|
||||
assert.equal(plan.totalGoodsValue, 1)
|
||||
@@ -41,11 +37,7 @@ test('resolveSendCallbackGoodsValuePlan prefers 91 amount over ext payment', ()
|
||||
})
|
||||
|
||||
test('resolveSendCallbackGoodsValuePlan splits preferred amount and keeps sum equal to total', () => {
|
||||
const plan = resolveSendCallbackGoodsValuePlan(
|
||||
[{}, {}, {}],
|
||||
'{"payment":999}',
|
||||
100,
|
||||
)
|
||||
const plan = resolveSendCallbackGoodsValuePlan([{}, {}, {}], '{"payment":999}', 100)
|
||||
|
||||
assert.deepEqual(plan.goodsValues, [33, 33, 34])
|
||||
assert.equal(plan.totalGoodsValue, 100)
|
||||
@@ -53,20 +45,14 @@ test('resolveSendCallbackGoodsValuePlan splits preferred amount and keeps sum eq
|
||||
})
|
||||
|
||||
test('resolveSendCallbackGoodsValuePlan uses ext payment for a single voucher', () => {
|
||||
const plan = resolveSendCallbackGoodsValuePlan(
|
||||
[{}],
|
||||
'{"payment":1,"platformBearAmount":0}',
|
||||
)
|
||||
const plan = resolveSendCallbackGoodsValuePlan([{}], '{"payment":1,"platformBearAmount":0}')
|
||||
|
||||
assert.deepEqual(plan.goodsValues, [1])
|
||||
assert.equal(plan.totalGoodsValue, 1)
|
||||
})
|
||||
|
||||
test('resolveSendCallbackGoodsValuePlan splits ext payment and keeps sum equal to total', () => {
|
||||
const plan = resolveSendCallbackGoodsValuePlan(
|
||||
[{}, {}, {}],
|
||||
'{"payment":100}',
|
||||
)
|
||||
const plan = resolveSendCallbackGoodsValuePlan([{}, {}, {}], '{"payment":100}')
|
||||
|
||||
assert.deepEqual(plan.goodsValues, [33, 33, 34])
|
||||
assert.equal(plan.totalGoodsValue, 100)
|
||||
|
||||
@@ -505,9 +505,9 @@ async function syncOpen91OrderAfterSendCallbackSuccess(
|
||||
function isOpen91OrderAwaitingFulfillmentConfig(error: unknown) {
|
||||
return Boolean(
|
||||
error &&
|
||||
typeof error === 'object' &&
|
||||
String((error as { errorCode?: unknown }).errorCode || '').trim() ===
|
||||
'open91_order_still_unconfigured',
|
||||
typeof error === 'object' &&
|
||||
String((error as { errorCode?: unknown }).errorCode || '').trim() ===
|
||||
'open91_order_still_unconfigured',
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,13 @@ import type { JsonObject } from '../../../types/json.js'
|
||||
|
||||
import { APP_CONFIG_KEYS } from '../../../config/app-config-keys.js'
|
||||
import { PROJECT_ROOT, runtimeConfig } from '../../../config/runtime.js'
|
||||
import {
|
||||
readAppConfigEntry,
|
||||
saveAppConfigEntry,
|
||||
} from '../../config/app-config-store.js'
|
||||
import { readAppConfigEntry, saveAppConfigEntry } from '../../config/app-config-store.js'
|
||||
|
||||
const KUAISHOU_INDUSTRY_SOURCE_FILE_PATH = path.join(PROJECT_ROOT, 'data', 'kuaishou-industry-source.json')
|
||||
const KUAISHOU_INDUSTRY_SOURCE_FILE_PATH = path.join(
|
||||
PROJECT_ROOT,
|
||||
'data',
|
||||
'kuaishou-industry-source.json',
|
||||
)
|
||||
const DEFAULT_CALLBACK_BASE_URL = 'https://openapi.kwaixiaodian.com'
|
||||
const DEFAULT_AUTH_BASE_URL = 'https://open.kwaixiaodian.com'
|
||||
const LEGACY_DEFAULT_REDIRECT_URI = 'https://ks.khhao.com/oauth-callback'
|
||||
@@ -73,7 +74,9 @@ export function getKuaishouIndustrySourceConfig(): KuaishouIndustrySourceConfig
|
||||
})
|
||||
}
|
||||
|
||||
export function saveKuaishouIndustrySourceConfig(rawValue: unknown): Promise<KuaishouIndustrySourceConfig> {
|
||||
export function saveKuaishouIndustrySourceConfig(
|
||||
rawValue: unknown,
|
||||
): Promise<KuaishouIndustrySourceConfig> {
|
||||
return saveAppConfigEntry({
|
||||
configKey: APP_CONFIG_KEYS.kuaishouIndustrySource,
|
||||
legacyFilePath: KUAISHOU_INDUSTRY_SOURCE_FILE_PATH,
|
||||
@@ -106,8 +109,11 @@ export function findKuaishouIndustryShopConfig(
|
||||
return null
|
||||
}
|
||||
|
||||
return listKuaishouIndustryShopConfigs(source)
|
||||
.find((shop) => String(shop.sellerId || shop.shopId || '').trim() === normalizedSellerId) || null
|
||||
return (
|
||||
listKuaishouIndustryShopConfigs(source).find(
|
||||
(shop) => String(shop.sellerId || shop.shopId || '').trim() === normalizedSellerId,
|
||||
) || null
|
||||
)
|
||||
}
|
||||
|
||||
export function patchKuaishouIndustryShopConfig(
|
||||
@@ -127,8 +133,9 @@ export function patchKuaishouIndustryShopConfig(
|
||||
return Promise.resolve(source)
|
||||
}
|
||||
|
||||
const shops = listKuaishouIndustryShopConfigs(source)
|
||||
.filter((shop) => String(shop.sellerId || shop.shopId || '').trim() !== normalizedSellerId)
|
||||
const shops = listKuaishouIndustryShopConfigs(source).filter(
|
||||
(shop) => String(shop.sellerId || shop.shopId || '').trim() !== normalizedSellerId,
|
||||
)
|
||||
|
||||
return saveKuaishouIndustrySourceConfig({
|
||||
...source,
|
||||
@@ -136,7 +143,9 @@ export function patchKuaishouIndustryShopConfig(
|
||||
})
|
||||
}
|
||||
|
||||
export function normalizeKuaishouIndustrySourceConfig(rawValue: unknown): KuaishouIndustrySourceConfig {
|
||||
export function normalizeKuaishouIndustrySourceConfig(
|
||||
rawValue: unknown,
|
||||
): KuaishouIndustrySourceConfig {
|
||||
const fallback = createDefaultKuaishouIndustrySourceConfig()
|
||||
const source = isPlainObject(rawValue) ? rawValue : {}
|
||||
const shops = normalizeKuaishouIndustryShopList(source)
|
||||
@@ -204,9 +213,7 @@ function createDefaultKuaishouIndustrySourceConfig(): KuaishouIndustrySourceConf
|
||||
}
|
||||
|
||||
function normalizeKuaishouIndustryShopList(source: JsonObject): KuaishouIndustryShopConfig[] {
|
||||
const rawShops = Array.isArray(source.shops)
|
||||
? source.shops
|
||||
: buildLegacySingleShopList(source)
|
||||
const rawShops = Array.isArray(source.shops) ? source.shops : buildLegacySingleShopList(source)
|
||||
|
||||
const deduped = new Map<string, KuaishouIndustryShopConfig>()
|
||||
let unnamedIndex = 0
|
||||
@@ -237,7 +244,15 @@ function normalizeKuaishouIndustryShopConfig(rawValue: unknown): KuaishouIndustr
|
||||
const refreshToken = normalizeString(rawValue.refreshToken, '')
|
||||
const openId = normalizeString(rawValue.openId, '')
|
||||
|
||||
if (!sellerId && !shopId && !shopName && !customShopName && !accessToken && !refreshToken && !openId) {
|
||||
if (
|
||||
!sellerId &&
|
||||
!shopId &&
|
||||
!shopName &&
|
||||
!customShopName &&
|
||||
!accessToken &&
|
||||
!refreshToken &&
|
||||
!openId
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -336,7 +351,11 @@ function normalizeScopeText(value: unknown): string {
|
||||
}
|
||||
|
||||
function normalizeUrlLike(value: unknown, fallback: string): string {
|
||||
return String(value || fallback).trim().replace(/\/+$/, '') || fallback
|
||||
return (
|
||||
String(value || fallback)
|
||||
.trim()
|
||||
.replace(/\/+$/, '') || fallback
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeNullableIso(value: unknown): string {
|
||||
|
||||
@@ -1,54 +1,77 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
ensureKuaishouIndustryAccessToken,
|
||||
shouldRefreshAccessToken,
|
||||
} from './token-service.js'
|
||||
import { ensureKuaishouIndustryAccessToken, shouldRefreshAccessToken } from './token-service.js'
|
||||
import type {
|
||||
KuaishouIndustryShopConfig,
|
||||
KuaishouIndustrySourceConfig,
|
||||
} from './source-config-service.js'
|
||||
|
||||
test('shouldRefreshAccessToken refreshes missing or expiring tokens', () => {
|
||||
assert.equal(shouldRefreshAccessToken(createConfig({
|
||||
accessToken: '',
|
||||
accessTokenExpiresAt: '',
|
||||
})), true)
|
||||
assert.equal(
|
||||
shouldRefreshAccessToken(
|
||||
createConfig({
|
||||
accessToken: '',
|
||||
accessTokenExpiresAt: '',
|
||||
}),
|
||||
),
|
||||
true,
|
||||
)
|
||||
|
||||
assert.equal(shouldRefreshAccessToken(createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
|
||||
})), true)
|
||||
assert.equal(
|
||||
shouldRefreshAccessToken(
|
||||
createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
|
||||
}),
|
||||
),
|
||||
true,
|
||||
)
|
||||
|
||||
assert.equal(shouldRefreshAccessToken(createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: new Date(Date.now() - 10 * 1000).toISOString(),
|
||||
})), true)
|
||||
assert.equal(
|
||||
shouldRefreshAccessToken(
|
||||
createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: new Date(Date.now() - 10 * 1000).toISOString(),
|
||||
}),
|
||||
),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('shouldRefreshAccessToken keeps valid tokens without a forced refresh', () => {
|
||||
assert.equal(shouldRefreshAccessToken(createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: '',
|
||||
})), false)
|
||||
assert.equal(
|
||||
shouldRefreshAccessToken(
|
||||
createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: '',
|
||||
}),
|
||||
),
|
||||
false,
|
||||
)
|
||||
|
||||
assert.equal(shouldRefreshAccessToken(createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
|
||||
})), false)
|
||||
assert.equal(
|
||||
shouldRefreshAccessToken(
|
||||
createConfig({
|
||||
accessToken: 'token',
|
||||
accessTokenExpiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
|
||||
}),
|
||||
),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test('ensureKuaishouIndustryAccessToken requires sellerId when multiple shops are enabled', async () => {
|
||||
await assert.rejects(
|
||||
() => ensureKuaishouIndustryAccessToken({
|
||||
config: createConfig({
|
||||
shops: [
|
||||
createShop({ sellerId: 'seller-a', accessToken: 'token-a' }),
|
||||
createShop({ sellerId: 'seller-b', accessToken: 'token-b' }),
|
||||
],
|
||||
() =>
|
||||
ensureKuaishouIndustryAccessToken({
|
||||
config: createConfig({
|
||||
shops: [
|
||||
createShop({ sellerId: 'seller-a', accessToken: 'token-a' }),
|
||||
createShop({ sellerId: 'seller-b', accessToken: 'token-b' }),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
{
|
||||
message: '存在多个快手行业电子凭证店铺授权,请指定 sellerId',
|
||||
errorCode: 'kuaishou_industry_missing_seller_id',
|
||||
@@ -105,9 +128,7 @@ function createConfig(
|
||||
}
|
||||
}
|
||||
|
||||
function createShop(
|
||||
patch: Partial<KuaishouIndustryShopConfig> = {},
|
||||
): KuaishouIndustryShopConfig {
|
||||
function createShop(patch: Partial<KuaishouIndustryShopConfig> = {}): KuaishouIndustryShopConfig {
|
||||
return {
|
||||
enabled: true,
|
||||
sellerId: 'seller-a',
|
||||
|
||||
@@ -159,12 +159,18 @@ export async function exchangeKuaishouIndustryAuthorizationCode(
|
||||
await patchKuaishouIndustrySourceConfig({
|
||||
lastRefreshError: message,
|
||||
})
|
||||
logWarn('[kuaishou-industry/token]', '授权码换取 accessToken 失败', resolveRefreshErrorDetail(error))
|
||||
logWarn(
|
||||
'[kuaishou-industry/token]',
|
||||
'授权码换取 accessToken 失败',
|
||||
resolveRefreshErrorDetail(error),
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldRefreshAccessToken(config: Pick<KuaishouIndustryShopConfig, 'accessToken' | 'accessTokenExpiresAt'>): boolean {
|
||||
export function shouldRefreshAccessToken(
|
||||
config: Pick<KuaishouIndustryShopConfig, 'accessToken' | 'accessTokenExpiresAt'>,
|
||||
): boolean {
|
||||
if (!String(config.accessToken || '').trim()) {
|
||||
return true
|
||||
}
|
||||
@@ -201,8 +207,9 @@ function resolveTokenShop(
|
||||
return matched
|
||||
}
|
||||
|
||||
const enabledShops = listKuaishouIndustryShopConfigs(config)
|
||||
.filter((shop) => shop.enabled !== false)
|
||||
const enabledShops = listKuaishouIndustryShopConfigs(config).filter(
|
||||
(shop) => shop.enabled !== false,
|
||||
)
|
||||
|
||||
if (enabledShops.length === 1) {
|
||||
return enabledShops[0] as KuaishouIndustryShopConfig
|
||||
@@ -237,7 +244,10 @@ function createEmptyShopConfig(): KuaishouIndustryShopConfig {
|
||||
}
|
||||
}
|
||||
|
||||
function assertRefreshConfig(config: KuaishouIndustrySourceConfig, shop: KuaishouIndustryShopConfig) {
|
||||
function assertRefreshConfig(
|
||||
config: KuaishouIndustrySourceConfig,
|
||||
shop: KuaishouIndustryShopConfig,
|
||||
) {
|
||||
if (!config.baseUrl) {
|
||||
throw createHttpError('快手开放平台 API 地址未配置', {
|
||||
statusCode: 400,
|
||||
@@ -298,15 +308,18 @@ async function requestKuaishouIndustryToken({
|
||||
failureMessage: string
|
||||
errorCode: string
|
||||
}) {
|
||||
const baseUrl = String(config.baseUrl || '').trim().replace(/\/+$/, '')
|
||||
const baseUrl = String(config.baseUrl || '')
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
const url = new URL(`${baseUrl}${path}`)
|
||||
const response = method === 'GET'
|
||||
? await fetch(appendSearchParams(url, params))
|
||||
: await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: params.toString(),
|
||||
})
|
||||
const response =
|
||||
method === 'GET'
|
||||
? await fetch(appendSearchParams(url, params))
|
||||
: await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: params.toString(),
|
||||
})
|
||||
const text = await response.text()
|
||||
const json = parseJsonObject(text)
|
||||
const tokenPayload = normalizeTokenResponse(json, config)
|
||||
@@ -347,8 +360,11 @@ async function saveTokenPayload(
|
||||
accessToken: tokenPayload.accessToken,
|
||||
refreshToken: nextRefreshToken,
|
||||
accessTokenExpiresAt: tokenPayload.accessTokenExpiresAt,
|
||||
refreshTokenExpiresAt: tokenPayload.refreshTokenExpiresAt
|
||||
|| (tokenPayload.refreshToken ? new Date(Date.now() + DEFAULT_REFRESH_TOKEN_TTL_MS).toISOString() : shop.refreshTokenExpiresAt),
|
||||
refreshTokenExpiresAt:
|
||||
tokenPayload.refreshTokenExpiresAt ||
|
||||
(tokenPayload.refreshToken
|
||||
? new Date(Date.now() + DEFAULT_REFRESH_TOKEN_TTL_MS).toISOString()
|
||||
: shop.refreshTokenExpiresAt),
|
||||
openId: tokenPayload.openId || shop.openId,
|
||||
grantedScopes: tokenPayload.grantedScopes || shop.grantedScopes,
|
||||
lastRefreshedAt: new Date().toISOString(),
|
||||
@@ -361,16 +377,9 @@ async function saveTokenPayload(
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTokenResponse(
|
||||
json: JsonObject,
|
||||
currentConfig: KuaishouIndustrySourceConfig,
|
||||
) {
|
||||
function normalizeTokenResponse(json: JsonObject, currentConfig: KuaishouIndustrySourceConfig) {
|
||||
const payload = isPlainObject(json.data) ? json.data : json
|
||||
const accessToken = pickFirstString(payload, [
|
||||
'access_token',
|
||||
'accessToken',
|
||||
'accessTokenValue',
|
||||
])
|
||||
const accessToken = pickFirstString(payload, ['access_token', 'accessToken', 'accessTokenValue'])
|
||||
const refreshToken = pickFirstString(payload, [
|
||||
'refresh_token',
|
||||
'refreshToken',
|
||||
@@ -386,26 +395,24 @@ function normalizeTokenResponse(
|
||||
sellerId,
|
||||
openId,
|
||||
grantedScopes,
|
||||
accessTokenExpiresAt: resolveExpiresAt(payload, [
|
||||
'access_token_expires_at',
|
||||
'accessTokenExpiresAt',
|
||||
'accessTokenExpireAt',
|
||||
'expires_at',
|
||||
'expireAt',
|
||||
], [
|
||||
'expires_in',
|
||||
'expiresIn',
|
||||
'access_token_expires_in',
|
||||
'accessTokenExpiresIn',
|
||||
], DEFAULT_ACCESS_TOKEN_TTL_MS),
|
||||
refreshTokenExpiresAt: resolveExpiresAt(payload, [
|
||||
'refresh_token_expires_at',
|
||||
'refreshTokenExpiresAt',
|
||||
'refreshTokenExpireAt',
|
||||
], [
|
||||
'refresh_token_expires_in',
|
||||
'refreshTokenExpiresIn',
|
||||
], 0),
|
||||
accessTokenExpiresAt: resolveExpiresAt(
|
||||
payload,
|
||||
[
|
||||
'access_token_expires_at',
|
||||
'accessTokenExpiresAt',
|
||||
'accessTokenExpireAt',
|
||||
'expires_at',
|
||||
'expireAt',
|
||||
],
|
||||
['expires_in', 'expiresIn', 'access_token_expires_in', 'accessTokenExpiresIn'],
|
||||
DEFAULT_ACCESS_TOKEN_TTL_MS,
|
||||
),
|
||||
refreshTokenExpiresAt: resolveExpiresAt(
|
||||
payload,
|
||||
['refresh_token_expires_at', 'refreshTokenExpiresAt', 'refreshTokenExpireAt'],
|
||||
['refresh_token_expires_in', 'refreshTokenExpiresIn'],
|
||||
0,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -438,15 +445,11 @@ function resolveExpiresAt(
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackDurationMs > 0
|
||||
? new Date(Date.now() + fallbackDurationMs).toISOString()
|
||||
: ''
|
||||
return fallbackDurationMs > 0 ? new Date(Date.now() + fallbackDurationMs).toISOString() : ''
|
||||
}
|
||||
|
||||
function parseTimestampLike(value: unknown): number {
|
||||
const raw = typeof value === 'number'
|
||||
? value
|
||||
: Number(String(value || '').trim())
|
||||
const raw = typeof value === 'number' ? value : Number(String(value || '').trim())
|
||||
|
||||
if (Number.isFinite(raw) && raw > 0) {
|
||||
return raw > 10_000_000_000 ? raw : raw * 1000
|
||||
@@ -467,14 +470,16 @@ function isTokenResponseSuccess(json: JsonObject): boolean {
|
||||
|
||||
function resolveTokenErrorMessage(json: JsonObject, status: number, fallback: string): string {
|
||||
const payload = isPlainObject(json.data) ? json.data : json
|
||||
return pickFirstString(payload, [
|
||||
'error_msg',
|
||||
'errorMsg',
|
||||
'message',
|
||||
'msg',
|
||||
'error_description',
|
||||
'errorDescription',
|
||||
]) || `${fallback},HTTP ${status}`
|
||||
return (
|
||||
pickFirstString(payload, [
|
||||
'error_msg',
|
||||
'errorMsg',
|
||||
'message',
|
||||
'msg',
|
||||
'error_description',
|
||||
'errorDescription',
|
||||
]) || `${fallback},HTTP ${status}`
|
||||
)
|
||||
}
|
||||
|
||||
function parseJsonObject(text: string): JsonObject {
|
||||
@@ -500,7 +505,10 @@ function pickFirstString(payload: JsonObject, keys: string[]): string {
|
||||
function pickScopes(payload: JsonObject): string {
|
||||
const value = payload.scopes ?? payload.scope
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => String(item || '').trim()).filter(Boolean).join(',')
|
||||
return value
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
.join(',')
|
||||
}
|
||||
|
||||
return String(value || '').trim()
|
||||
@@ -510,9 +518,10 @@ function resolveRefreshErrorDetail(error: unknown): JsonObject {
|
||||
const detail: JsonObject = {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
const cause = error && typeof error === 'object' && 'cause' in error
|
||||
? (error as { cause?: unknown }).cause
|
||||
: null
|
||||
const cause =
|
||||
error && typeof error === 'object' && 'cause' in error
|
||||
? (error as { cause?: unknown }).cause
|
||||
: null
|
||||
if (!cause || typeof cause !== 'object') {
|
||||
return detail
|
||||
}
|
||||
|
||||
@@ -79,11 +79,14 @@ export async function attachKuaishouIndustryVoucherToTask(
|
||||
|
||||
if (
|
||||
sendCallbackConfirmed &&
|
||||
(String(task.executor_key || '').trim() === 'kuaishou_ct_assisted' || context.kuaishouCloudFulfillment)
|
||||
(String(task.executor_key || '').trim() === 'kuaishou_ct_assisted' ||
|
||||
context.kuaishouCloudFulfillment)
|
||||
) {
|
||||
const flow = normalizeKuaishouCloudFlow(context.kuaishouCloudFulfillment)
|
||||
const consumedAt = voucher.consumed_at || nextVoucherContext.consumedAt || null
|
||||
const status = String(voucher.status || 'UNUSED').trim().toUpperCase()
|
||||
const status = String(voucher.status || 'UNUSED')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
|
||||
nextContext.kuaishouCloudFulfillment = {
|
||||
...flow,
|
||||
@@ -138,10 +141,13 @@ export function buildKuaishouIndustryVoucherContext(
|
||||
existingValue: unknown,
|
||||
now: string,
|
||||
) {
|
||||
const existing = existingValue && typeof existingValue === 'object' && !Array.isArray(existingValue)
|
||||
? existingValue as JsonObject
|
||||
: {}
|
||||
const status = String(voucher.status || 'UNUSED').trim().toUpperCase()
|
||||
const existing =
|
||||
existingValue && typeof existingValue === 'object' && !Array.isArray(existingValue)
|
||||
? (existingValue as JsonObject)
|
||||
: {}
|
||||
const status = String(voucher.status || 'UNUSED')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
|
||||
return {
|
||||
...existing,
|
||||
|
||||
@@ -81,12 +81,15 @@ test('normalizeKuaishouIndustryConsumeType defaults to consume', () => {
|
||||
})
|
||||
|
||||
test('buildKuaishouIndustryEticketFromVoucher mirrors voucher code into id and code', () => {
|
||||
const eticket = buildKuaishouIndustryEticketFromVoucher({
|
||||
voucher_code: 'KSV15K821FDHPMTX1ST',
|
||||
status: 'UNUSED',
|
||||
valid_start_time: 1783427213868,
|
||||
valid_end_time: 1786019213868,
|
||||
} as any, 'GAME_OPEN_TICKET_CONSUME')
|
||||
const eticket = buildKuaishouIndustryEticketFromVoucher(
|
||||
{
|
||||
voucher_code: 'KSV15K821FDHPMTX1ST',
|
||||
status: 'UNUSED',
|
||||
valid_start_time: 1783427213868,
|
||||
valid_end_time: 1786019213868,
|
||||
} as any,
|
||||
'GAME_OPEN_TICKET_CONSUME',
|
||||
)
|
||||
|
||||
assert.equal(eticket.id, 'KSV15K821FDHPMTX1ST')
|
||||
assert.equal(eticket.code, 'KSV15K821FDHPMTX1ST')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createTaskEvent } from '../../../repositories/task-event-repo.js'
|
||||
import { getTaskById, updateTask } from '../../../repositories/task-repo.js'
|
||||
import { asJsonObject, type JsonObject } from '../../../types/json.js'
|
||||
import { asJsonObject, type JsonObject } from '../../../types/json.js'
|
||||
import {
|
||||
findKuaishouIndustryVoucherByCode,
|
||||
listKuaishouIndustryVouchersByTaskId,
|
||||
@@ -104,7 +104,9 @@ export function buildKuaishouIndustryEticketFromVoucher(
|
||||
}
|
||||
|
||||
export function normalizeKuaishouIndustrySendCallbackStatus(value: unknown) {
|
||||
const normalized = String(value || '').trim().toLowerCase()
|
||||
const normalized = String(value || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (
|
||||
normalized === KUAISHOU_INDUSTRY_SEND_CALLBACK_STATUS.PENDING ||
|
||||
normalized === KUAISHOU_INDUSTRY_SEND_CALLBACK_STATUS.FAILED
|
||||
@@ -118,8 +120,10 @@ export function normalizeKuaishouIndustrySendCallbackStatus(value: unknown) {
|
||||
export function isKuaishouIndustryVoucherSendCallbackSuccess(
|
||||
voucher: Pick<KuaishouIndustryVoucherRow, 'send_callback_status'>,
|
||||
) {
|
||||
return normalizeKuaishouIndustrySendCallbackStatus(voucher.send_callback_status) ===
|
||||
return (
|
||||
normalizeKuaishouIndustrySendCallbackStatus(voucher.send_callback_status) ===
|
||||
KUAISHOU_INDUSTRY_SEND_CALLBACK_STATUS.SUCCESS
|
||||
)
|
||||
}
|
||||
|
||||
export function resolveKuaishouIndustryVoucherSendCallbackMessage(
|
||||
@@ -237,7 +241,9 @@ export async function consumeKuaishouIndustryVoucher(
|
||||
const now = new Date().toISOString()
|
||||
const consumeTime = Number(input.consumeTime || Date.now()) || Date.now()
|
||||
const consumeType = normalizeKuaishouIndustryConsumeType(input.consumeType)
|
||||
const serialNum = String(input.serialNum || voucher.consume_serial_num || `CONSUME-${voucher.voucher_code}`).trim()
|
||||
const serialNum = String(
|
||||
input.serialNum || voucher.consume_serial_num || `CONSUME-${voucher.voucher_code}`,
|
||||
).trim()
|
||||
const token = String(input.token || voucher.token || '').trim()
|
||||
const consumeDetail = {
|
||||
serialNum,
|
||||
@@ -255,10 +261,12 @@ export async function consumeKuaishouIndustryVoucher(
|
||||
: await consumeCallback({
|
||||
oid: voucher.oid,
|
||||
sellerId: String(voucher.seller_id || '').trim(),
|
||||
etickets: [{
|
||||
id: voucher.voucher_code,
|
||||
num: 1,
|
||||
}],
|
||||
etickets: [
|
||||
{
|
||||
id: voucher.voucher_code,
|
||||
num: 1,
|
||||
},
|
||||
],
|
||||
status: 'CONSUMED',
|
||||
consumeType,
|
||||
consumeTime,
|
||||
@@ -349,12 +357,14 @@ export async function destroyKuaishouIndustryVoucher(
|
||||
: await destroyCallback({
|
||||
oid: voucher.oid,
|
||||
sellerId: String(voucher.seller_id || '').trim(),
|
||||
etickets: [{
|
||||
id: voucher.voucher_code,
|
||||
code: voucher.voucher_code,
|
||||
num: 1,
|
||||
...(input.goodsValue != null ? { goodsValue: input.goodsValue } : {}),
|
||||
}],
|
||||
etickets: [
|
||||
{
|
||||
id: voucher.voucher_code,
|
||||
code: voucher.voucher_code,
|
||||
num: 1,
|
||||
...(input.goodsValue != null ? { goodsValue: input.goodsValue } : {}),
|
||||
},
|
||||
],
|
||||
reason,
|
||||
token,
|
||||
...(eticketType ? { eticketType } : {}),
|
||||
@@ -375,25 +385,23 @@ export async function destroyKuaishouIndustryVoucher(
|
||||
status: 'DESTROYED',
|
||||
destroyedAt: now,
|
||||
updatedAt: now,
|
||||
...(eticketType && !String(voucher.eticket_type || '').trim()
|
||||
? { eticketType }
|
||||
: {}),
|
||||
...(eticketType && !String(voucher.eticket_type || '').trim() ? { eticketType } : {}),
|
||||
})
|
||||
updated = next || voucher
|
||||
}
|
||||
|
||||
let task =
|
||||
input.task ||
|
||||
(voucher.task_id ? await getTaskById(voucher.task_id).catch(() => null) : null)
|
||||
input.task || (voucher.task_id ? await getTaskById(voucher.task_id).catch(() => null) : null)
|
||||
|
||||
if (task && !alreadyDestroyed) {
|
||||
task = await updateTask(task.id, {
|
||||
task_status: TASK_STATUS.CLOSED,
|
||||
delivery_status: 'cancelled',
|
||||
result_code: reason,
|
||||
result_message: `电子凭证销毁: ${reason}`,
|
||||
updated_at: now,
|
||||
}) || task
|
||||
task =
|
||||
(await updateTask(task.id, {
|
||||
task_status: TASK_STATUS.CLOSED,
|
||||
delivery_status: 'cancelled',
|
||||
result_code: reason,
|
||||
result_message: `电子凭证销毁: ${reason}`,
|
||||
updated_at: now,
|
||||
})) || task
|
||||
|
||||
await createTaskEvent(
|
||||
task.id,
|
||||
@@ -420,7 +428,9 @@ export async function destroyKuaishouIndustryVoucher(
|
||||
}
|
||||
|
||||
export function normalizeKuaishouIndustryDestroyReason(value: unknown): string {
|
||||
const normalized = String(value || '').trim().toUpperCase()
|
||||
const normalized = String(value || '')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
if (
|
||||
normalized === KUAISHOU_INDUSTRY_DESTROY_REASONS.ETICKET_EXPIRED ||
|
||||
normalized === KUAISHOU_INDUSTRY_DESTROY_REASONS.USER_APPLY_REFUND ||
|
||||
@@ -448,7 +458,7 @@ function resolveTaskVouchers(task: TaskRow): Promise<KuaishouIndustryVoucherRow[
|
||||
}
|
||||
|
||||
return findKuaishouIndustryVoucherByCode(voucherCode, oid)
|
||||
.then((row) => row ? [row] : [])
|
||||
.then((row) => (row ? [row] : []))
|
||||
.catch((error) => {
|
||||
logWarn('[kuaishou-industry/voucher]', '按上下文查询电子凭证失败', {
|
||||
taskId: task?.id || null,
|
||||
@@ -469,11 +479,13 @@ function resolveVoucherConsumeDetails(voucher: KuaishouIndustryVoucherRow): Json
|
||||
return []
|
||||
}
|
||||
|
||||
return [{
|
||||
serialNum: voucher.consume_serial_num,
|
||||
consumeType: KUAISHOU_INDUSTRY_DEFAULT_CONSUME_TYPE,
|
||||
consumeTime: voucher.consumed_at ? Date.parse(voucher.consumed_at) : 0,
|
||||
}]
|
||||
return [
|
||||
{
|
||||
serialNum: voucher.consume_serial_num,
|
||||
consumeType: KUAISHOU_INDUSTRY_DEFAULT_CONSUME_TYPE,
|
||||
consumeTime: voucher.consumed_at ? Date.parse(voucher.consumed_at) : 0,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function appendConsumeDetail(details: JsonObject[], nextDetail: JsonObject): JsonObject[] {
|
||||
@@ -486,7 +498,9 @@ function appendConsumeDetail(details: JsonObject[], nextDetail: JsonObject): Jso
|
||||
}
|
||||
|
||||
function normalizeVoucherStatus(value: unknown): string {
|
||||
const normalized = String(value || '').trim().toUpperCase()
|
||||
const normalized = String(value || '')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
if (normalized === 'CONSUMED' || normalized === 'DESTROYED') {
|
||||
return normalized
|
||||
}
|
||||
@@ -495,8 +509,10 @@ function normalizeVoucherStatus(value: unknown): string {
|
||||
}
|
||||
|
||||
export function normalizeKuaishouIndustryConsumeType(value: unknown): string {
|
||||
return String(value || KUAISHOU_INDUSTRY_DEFAULT_CONSUME_TYPE).trim() ||
|
||||
return (
|
||||
String(value || KUAISHOU_INDUSTRY_DEFAULT_CONSUME_TYPE).trim() ||
|
||||
KUAISHOU_INDUSTRY_DEFAULT_CONSUME_TYPE
|
||||
)
|
||||
}
|
||||
|
||||
function normalizePositiveTimestamp(value: unknown): number {
|
||||
|
||||
Reference in New Issue
Block a user