优化后端鉴权与日志安全
This commit is contained in:
@@ -23,6 +23,7 @@ export type AdminSession = {
|
||||
username: string
|
||||
role: AdminRole
|
||||
expiresAt: string
|
||||
sessionVersion: number
|
||||
}
|
||||
|
||||
type AdminRole = 'admin' | 'operator' | 'support'
|
||||
@@ -137,12 +138,22 @@ export async function verifyAdminSessionToken(token: unknown): Promise<AdminSess
|
||||
})
|
||||
}
|
||||
|
||||
const tokenSessionVersion = Number(payload?.ver || 0)
|
||||
const currentSessionVersion = normalizeAdminSessionVersion(user.session_version)
|
||||
if (tokenSessionVersion !== currentSessionVersion) {
|
||||
throw createHttpError('后台登录态已失效,请重新登录', {
|
||||
statusCode: 401,
|
||||
errorCode: 'admin_auth_stale',
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: String(payload?.sid || '').trim(),
|
||||
userId: Number(user.id),
|
||||
username: String(user.username || ''),
|
||||
role: normalizeAdminRole(user.role),
|
||||
expiresAt,
|
||||
sessionVersion: currentSessionVersion,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +259,7 @@ export async function updateManagedAdminUserRole(
|
||||
await ensureAdminUserChangeAllowed(user, { nextRole: role }, session)
|
||||
const updated = await updateAdminUser(user.id, {
|
||||
role,
|
||||
session_version: nextAdminSessionVersion(user),
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
|
||||
@@ -273,6 +285,7 @@ export async function updateManagedAdminUserStatus(
|
||||
await ensureAdminUserChangeAllowed(user, { nextStatus: status }, session)
|
||||
const updated = await updateAdminUser(user.id, {
|
||||
status,
|
||||
session_version: nextAdminSessionVersion(user),
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
|
||||
@@ -295,6 +308,7 @@ export async function resetManagedAdminUserPassword(userId: number | string, pay
|
||||
validatePassword(password)
|
||||
const updated = await updateAdminUser(user.id, {
|
||||
password_hash: hashAdminPassword(password),
|
||||
session_version: nextAdminSessionVersion(user),
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
|
||||
@@ -325,6 +339,7 @@ function createAdminSession(user: AdminUserRow): JsonObject {
|
||||
uid: Number(user.id),
|
||||
usr: String(user.username || ''),
|
||||
role: normalizeAdminRole(user.role),
|
||||
ver: normalizeAdminSessionVersion(user.session_version),
|
||||
iat: issuedAt,
|
||||
exp: expiresAt,
|
||||
}
|
||||
@@ -430,6 +445,15 @@ function validatePassword(password: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeAdminSessionVersion(value: unknown): number {
|
||||
const parsed = Number(value)
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : 1
|
||||
}
|
||||
|
||||
function nextAdminSessionVersion(user: AdminUserRow): number {
|
||||
return normalizeAdminSessionVersion(user.session_version) + 1
|
||||
}
|
||||
|
||||
async function getRequiredAdminUser(userId: number | string): Promise<AdminUserRow> {
|
||||
const user = await getAdminUserById(Number(userId))
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ export function mapKuaishouCloudFulfillmentContext(value: unknown): JsonRecord |
|
||||
prepareStatus: String(binding.prepareStatus || 'pending').trim() || 'pending',
|
||||
cloudSourceKey: String(binding.cloudSourceKey || '').trim(),
|
||||
cloudSourceKeyFallbacks: Array.isArray(binding.cloudSourceKeyFallbacks)
|
||||
? binding.cloudSourceKeyFallbacks.map((value) => String(value || '').trim()).filter(Boolean)
|
||||
? binding.cloudSourceKeyFallbacks.map((value: unknown) => String(value || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
resolvedSourceKey: String(binding.resolvedSourceKey || '').trim(),
|
||||
skuId: Number(binding.skuId || 0) || 0,
|
||||
|
||||
@@ -95,7 +95,7 @@ function mapAdminNotificationConfig(config: JsonObject = {}) {
|
||||
bark: {
|
||||
enabled: bark.enabled !== false,
|
||||
serverUrl: String(bark.serverUrl || 'https://api.day.app').trim(),
|
||||
recipients: (Array.isArray(bark.recipients) ? bark.recipients : []).map((item) => ({
|
||||
recipients: (Array.isArray(bark.recipients) ? bark.recipients : []).map((item: JsonObject) => ({
|
||||
id: String(item.id || '').trim(),
|
||||
name: String(item.name || '').trim(),
|
||||
deviceKey: String(item.deviceKey || '').trim(),
|
||||
@@ -105,7 +105,7 @@ function mapAdminNotificationConfig(config: JsonObject = {}) {
|
||||
},
|
||||
wpush: {
|
||||
enabled: wpush.enabled !== false,
|
||||
recipients: (Array.isArray(wpush.recipients) ? wpush.recipients : []).map((item) => ({
|
||||
recipients: (Array.isArray(wpush.recipients) ? wpush.recipients : []).map((item: JsonObject) => ({
|
||||
id: String(item.id || '').trim(),
|
||||
name: String(item.name || '').trim(),
|
||||
apiKey: String(item.apiKey || item.apikey || '').trim(),
|
||||
@@ -146,7 +146,7 @@ function mapAdminScheduledJobsConfig(config: JsonObject = {}) {
|
||||
function listAdminCloudtentaclesMonitorAccounts() {
|
||||
const sourcesConfig = listCloudtentaclesSources()
|
||||
const sessionsConfig = getAllCloudtentaclesSessionStates()
|
||||
const sessions = sessionsConfig.sessions || {}
|
||||
const sessions: Record<string, JsonObject> = sessionsConfig.sessions || {}
|
||||
|
||||
return (Array.isArray(sourcesConfig.sources) ? sourcesConfig.sources : []).map((source) => {
|
||||
const sourceKey = String(source.key || '').trim()
|
||||
|
||||
@@ -171,7 +171,7 @@ export async function prepareAdminTaskKuaishouCloudFulfillment(
|
||||
bindUrl: preparedBinding.bindUrl,
|
||||
bindPreparedAt: now,
|
||||
bindExpiresAt: resolveKuaishouCloudBindUrlExpiresAt(now),
|
||||
bindProbeAt: null,
|
||||
bindProbeAt: null as null,
|
||||
bindProbeStatus: 'pending',
|
||||
bindProbeMessage: '',
|
||||
roleName: '',
|
||||
@@ -181,9 +181,9 @@ export async function prepareAdminTaskKuaishouCloudFulfillment(
|
||||
status: 'pending',
|
||||
name: '',
|
||||
rid: '',
|
||||
refreshedAt: null,
|
||||
refreshedAt: null as null,
|
||||
errorMessage: '',
|
||||
rawInfo: null,
|
||||
rawInfo: null as null,
|
||||
},
|
||||
purchase: {
|
||||
...flowWithResolvedBinding.purchase,
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
replaceFulfillmentProfileRequirements,
|
||||
upsertFulfillmentProfile,
|
||||
upsertSkuFulfillmentBinding,
|
||||
type FulfillmentProfileRequirementInput,
|
||||
} from '../../repositories/fulfillment-profile-repo.js'
|
||||
import { upsertProductMatchRule } from '../../repositories/product-match-rule-repo.js'
|
||||
import { normalizeProductName } from '../order/product-match-service.js'
|
||||
@@ -14,7 +15,18 @@ import {
|
||||
} from '../order/kuaishou-cloud-fulfillment-config-service.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
|
||||
const CORE_PROFILES = [
|
||||
type JsonObject = Record<string, any>
|
||||
type CoreProfile = {
|
||||
profileKey: string
|
||||
name: string
|
||||
executorKey: string
|
||||
requiresClaim: boolean
|
||||
autoDispatch: boolean
|
||||
inventoryStrategy: string
|
||||
requirements: FulfillmentProfileRequirementInput[]
|
||||
}
|
||||
|
||||
const CORE_PROFILES: CoreProfile[] = [
|
||||
{
|
||||
profileKey: 'manual_review',
|
||||
name: '人工发货',
|
||||
@@ -35,8 +47,6 @@ const CORE_PROFILES = [
|
||||
},
|
||||
]
|
||||
|
||||
type JsonObject = Record<string, any>
|
||||
|
||||
export async function ensureFulfillmentCatalogBootstrapped() {
|
||||
const profileMap = await ensureCoreProfiles()
|
||||
await syncConfiguredFulfillmentBindings(profileMap)
|
||||
@@ -44,7 +54,7 @@ export async function ensureFulfillmentCatalogBootstrapped() {
|
||||
|
||||
async function ensureCoreProfiles() {
|
||||
const timestamp = nowIso()
|
||||
const profileMap = {}
|
||||
const profileMap: JsonObject = {}
|
||||
|
||||
for (const profile of CORE_PROFILES) {
|
||||
const saved = await upsertFulfillmentProfile({
|
||||
@@ -148,6 +158,6 @@ function resolveBindingRuntimeConfig(binding: JsonObject = {}) {
|
||||
return baseConfig
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
function isPlainObject(value: unknown): value is JsonObject {
|
||||
return Object.prototype.toString.call(value) === '[object Object]'
|
||||
}
|
||||
|
||||
@@ -7,10 +7,19 @@ import { formatFenToAmount, normalizeFen } from '../../utils/money.js'
|
||||
import { parseTaskContext as parseTaskContextValue } from '../../utils/task-json.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { buildClaimUrl } from './claim-service.js'
|
||||
import type { ClaimTokenRow, OrderItemRow, OrderRow, TaskRow } from '../../types/repository-rows.js'
|
||||
|
||||
export const CLAIM_TERMINAL_STATUSES = new Set(['expired', 'closed'])
|
||||
export const KUAISHOU_CLOUD_CLAIM_GUIDE_BASE_PATH = '/kuaishou-cloud-guide'
|
||||
|
||||
type JsonObject = Record<string, any>
|
||||
type ClaimContext = {
|
||||
claimToken: ClaimTokenRow
|
||||
task: TaskRow
|
||||
order: OrderRow
|
||||
orderItem: OrderItemRow
|
||||
}
|
||||
|
||||
export async function getClaimContext(token: unknown) {
|
||||
const normalized = String(token || '').trim()
|
||||
|
||||
@@ -76,7 +85,7 @@ export async function getClaimContext(token: unknown) {
|
||||
}
|
||||
}
|
||||
|
||||
export function buildClaimDetailPayload({ claimToken, task, order, orderItem }) {
|
||||
export function buildClaimDetailPayload({ claimToken, task, order, orderItem }: ClaimContext) {
|
||||
const kuaishouCloudFulfillment = mapClaimKuaishouCloudFulfillment(task, order)
|
||||
|
||||
return {
|
||||
@@ -113,7 +122,7 @@ export function buildClaimDetailPayload({ claimToken, task, order, orderItem })
|
||||
skuName: orderItem.sku_name,
|
||||
quantity: orderItem.quantity,
|
||||
},
|
||||
session: null,
|
||||
session: null as null,
|
||||
kuaishouCloudFulfillment,
|
||||
result: task.redeemed_at
|
||||
? {
|
||||
@@ -126,7 +135,7 @@ export function buildClaimDetailPayload({ claimToken, task, order, orderItem })
|
||||
}
|
||||
}
|
||||
|
||||
export function mapClaimKuaishouCloudFulfillment(task, order) {
|
||||
export function mapClaimKuaishouCloudFulfillment(task: TaskRow, order: OrderRow) {
|
||||
if (String(task?.executor_key || '').trim() !== 'kuaishou_ct_assisted') {
|
||||
return null
|
||||
}
|
||||
@@ -213,11 +222,11 @@ export function mapClaimKuaishouCloudFulfillment(task, order) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseTaskContext(task) {
|
||||
function parseTaskContext(task: TaskRow): JsonObject {
|
||||
return parseTaskContextValue(task)
|
||||
}
|
||||
|
||||
async function expireClaimContext(claimToken, task) {
|
||||
async function expireClaimContext(claimToken: ClaimTokenRow, task: TaskRow) {
|
||||
const now = nowIso()
|
||||
const nextClaimToken = await updateClaimToken(claimToken.id, {
|
||||
status: 'expired',
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from '../fulfillment/kuaishou-cloud-task-service.js'
|
||||
import { buildClaimDetailPayload, getClaimContext } from './kuaishou-cloud-claim-context.js'
|
||||
import { syncKuaishouCloudRoleInfo } from './kuaishou-cloud-sync-service.js'
|
||||
import type { TaskRow } from '../../types/repository-rows.js'
|
||||
|
||||
const KUAISHOU_CLOUD_GUIDE_DIR = path.resolve(PROJECT_ROOT, '../../tems/imgs')
|
||||
const ALLOWED_GUIDE_FILES = new Set(['1.png', '2.png', '3.png'])
|
||||
@@ -136,7 +137,7 @@ export async function verifyKuaishouCloudClaimTicket(token: unknown, payload: Js
|
||||
return getKuaishouCloudClaimDetail(token)
|
||||
}
|
||||
|
||||
export async function getKuaishouCloudClaimGuideAssetPath(filename) {
|
||||
export async function getKuaishouCloudClaimGuideAssetPath(filename: unknown) {
|
||||
const normalized = String(filename || '').trim()
|
||||
if (!ALLOWED_GUIDE_FILES.has(normalized)) {
|
||||
throw createHttpError('指引图片不存在', {
|
||||
@@ -172,7 +173,7 @@ export async function getKuaishouCloudClaimDetail(token: unknown) {
|
||||
})
|
||||
}
|
||||
|
||||
function parseTaskContext(task) {
|
||||
function parseTaskContext(task: Partial<TaskRow> | null | undefined): JsonObject {
|
||||
const rawValue = task?.context_json
|
||||
if (!rawValue) {
|
||||
return {}
|
||||
@@ -189,7 +190,7 @@ function parseTaskContext(task) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmKuaishouCloudClaimRole(token) {
|
||||
export async function confirmKuaishouCloudClaimRole(token: unknown) {
|
||||
const context = await getClaimContext(token)
|
||||
const now = nowIso()
|
||||
|
||||
@@ -245,7 +246,7 @@ export async function confirmKuaishouCloudClaimRole(token) {
|
||||
return getKuaishouCloudClaimDetail(token)
|
||||
}
|
||||
|
||||
export async function redeemKuaishouCloudClaim(token) {
|
||||
export async function redeemKuaishouCloudClaim(token: unknown) {
|
||||
const context = await getClaimContext(token)
|
||||
const now = nowIso()
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@ import {
|
||||
probeKuaishouCloudTaskBindUrl,
|
||||
refreshKuaishouCloudTaskRoleInfo,
|
||||
} from '../fulfillment/kuaishou-cloud-task-service.js'
|
||||
import type { TaskRow } from '../../types/repository-rows.js'
|
||||
|
||||
export async function syncKuaishouCloudRoleInfo(task) {
|
||||
export async function syncKuaishouCloudRoleInfo(task: TaskRow) {
|
||||
const flow = normalizeKuaishouCloudFlow(parseTaskContext(task).kuaishouCloudFulfillment)
|
||||
|
||||
if (!flow.binding.vnId || !flow.binding.vnKey || !flow.binding.vnPhone) {
|
||||
@@ -42,7 +43,7 @@ export async function syncKuaishouCloudRoleInfo(task) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseTaskContext(task) {
|
||||
function parseTaskContext(task: Partial<TaskRow> | null | undefined): Record<string, any> {
|
||||
const rawValue = task?.context_json
|
||||
|
||||
if (!rawValue) {
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
normalizeActor,
|
||||
parseTaskContext,
|
||||
} from "./kuaishou-cloud/task-context.js";
|
||||
import type { TaskRow } from "../../types/repository-rows.js";
|
||||
|
||||
export {
|
||||
isKuaishouCloudBindUrlFresh,
|
||||
@@ -58,7 +59,7 @@ export {
|
||||
resolvePersistedCloudtentaclesContextWithFallback,
|
||||
} from "./kuaishou-cloud/cloudtentacles-context.js";
|
||||
|
||||
export async function ensureTaskClaimLink(task) {
|
||||
export async function ensureTaskClaimLink(task: TaskRow) {
|
||||
const tokenStatus = String(task?.primary_claim_token_status || "").trim();
|
||||
const token = String(
|
||||
task?.primary_claim_token || task?.claim_token || ""
|
||||
@@ -82,7 +83,7 @@ export async function ensureTaskClaimLink(task) {
|
||||
}
|
||||
|
||||
export async function prepareKuaishouCloudFulfillmentTask(
|
||||
task,
|
||||
task: TaskRow,
|
||||
options: JsonObject = {}
|
||||
) {
|
||||
if (!isKuaishouCloudTask(task)) {
|
||||
@@ -246,7 +247,7 @@ export async function prepareKuaishouCloudFulfillmentTask(
|
||||
bindUrl: preparedBinding.bindUrl,
|
||||
bindPreparedAt: now,
|
||||
bindExpiresAt: resolveKuaishouCloudBindUrlExpiresAt(now),
|
||||
bindProbeAt: null,
|
||||
bindProbeAt: null as null,
|
||||
bindProbeStatus: "pending",
|
||||
bindProbeMessage: "",
|
||||
roleName: "",
|
||||
@@ -256,9 +257,9 @@ export async function prepareKuaishouCloudFulfillmentTask(
|
||||
status: "pending",
|
||||
name: "",
|
||||
rid: "",
|
||||
refreshedAt: null,
|
||||
refreshedAt: null as null,
|
||||
errorMessage: "",
|
||||
rawInfo: null,
|
||||
rawInfo: null as null,
|
||||
},
|
||||
purchase: {
|
||||
...flowWithResolvedBinding.purchase,
|
||||
@@ -312,7 +313,7 @@ export async function prepareKuaishouCloudFulfillmentTask(
|
||||
}
|
||||
|
||||
export async function refreshKuaishouCloudTaskBindUrl(
|
||||
task,
|
||||
task: TaskRow,
|
||||
options: JsonObject = {}
|
||||
) {
|
||||
if (!isKuaishouCloudTask(task)) {
|
||||
@@ -413,7 +414,7 @@ export async function refreshKuaishouCloudTaskBindUrl(
|
||||
bindUrl: preparedBinding.bindUrl,
|
||||
bindPreparedAt: now,
|
||||
bindExpiresAt: resolveKuaishouCloudBindUrlExpiresAt(now),
|
||||
bindProbeAt: null,
|
||||
bindProbeAt: null as null,
|
||||
bindProbeStatus: "pending",
|
||||
bindProbeMessage: "",
|
||||
roleName:
|
||||
@@ -485,7 +486,7 @@ export async function refreshKuaishouCloudTaskBindUrl(
|
||||
}
|
||||
|
||||
export async function probeKuaishouCloudTaskBindUrl(
|
||||
task,
|
||||
task: TaskRow,
|
||||
options: JsonObject = {}
|
||||
) {
|
||||
if (!isKuaishouCloudTask(task)) {
|
||||
@@ -503,7 +504,7 @@ export async function probeKuaishouCloudTaskBindUrl(
|
||||
return {
|
||||
task,
|
||||
flow,
|
||||
probe: null,
|
||||
probe: null as null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -518,7 +519,7 @@ export async function probeKuaishouCloudTaskBindUrl(
|
||||
return {
|
||||
task,
|
||||
flow,
|
||||
probe: null,
|
||||
probe: null as null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -582,7 +583,7 @@ export async function probeKuaishouCloudTaskBindUrl(
|
||||
* @param {{ taskContext?: any, flow?: any, now?: string, actor?: any, error?: unknown }} [input]
|
||||
*/
|
||||
async function markKuaishouCloudBindUrlRefreshFailed(
|
||||
task,
|
||||
task: TaskRow,
|
||||
{ taskContext, flow, now, actor, error }: JsonObject = {}
|
||||
) {
|
||||
const errorMessage =
|
||||
@@ -648,7 +649,7 @@ async function markKuaishouCloudBindUrlRefreshFailed(
|
||||
}
|
||||
|
||||
export async function refreshKuaishouCloudTaskRoleInfo(
|
||||
task,
|
||||
task: TaskRow,
|
||||
options: JsonObject = {}
|
||||
) {
|
||||
if (!isKuaishouCloudTask(task)) {
|
||||
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
import { KUAISHOU_CLOUD_FIXED_VN_KEY, type JsonObject } from "./domain.js";
|
||||
|
||||
export function resolveKuaishouCloudBindingResources(
|
||||
flow,
|
||||
{ skuItems = [], knapsackItems = [] } = {}
|
||||
flow: JsonObject,
|
||||
{ skuItems = [], knapsackItems = [] }: { skuItems?: unknown[], knapsackItems?: unknown[] } = {}
|
||||
) {
|
||||
const normalizedSkuItems = Array.isArray(skuItems)
|
||||
? skuItems.filter(isCloudSkuLikeItem)
|
||||
@@ -70,7 +70,7 @@ export function resolveKuaishouCloudBindingResources(
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveKuaishouCloudVnKeyCandidates(_input = {}) {
|
||||
export function resolveKuaishouCloudVnKeyCandidates(_input: JsonObject = {}) {
|
||||
return [KUAISHOU_CLOUD_FIXED_VN_KEY];
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ export async function prepareKuaishouCloudBindResourceWithFallback(input: JsonOb
|
||||
);
|
||||
}
|
||||
|
||||
function collectKuaishouCloudNameCandidates(flow) {
|
||||
function collectKuaishouCloudNameCandidates(flow: JsonObject) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
[
|
||||
@@ -171,10 +171,10 @@ function collectKuaishouCloudNameCandidates(flow) {
|
||||
);
|
||||
}
|
||||
|
||||
function findCloudItemByNames(items, nameCandidates, preferredId = 0) {
|
||||
function findCloudItemByNames(items: JsonObject[], nameCandidates: string[], preferredId = 0) {
|
||||
const normalizedItems = Array.isArray(items) ? items : [];
|
||||
const normalizedNames = nameCandidates
|
||||
.map((item) => ({
|
||||
.map((item: string) => ({
|
||||
raw: String(item || "").trim(),
|
||||
normalized: normalizeProductName(item),
|
||||
}))
|
||||
@@ -182,34 +182,34 @@ function findCloudItemByNames(items, nameCandidates, preferredId = 0) {
|
||||
|
||||
if (normalizedNames.length === 0 || normalizedItems.length === 0) {
|
||||
return preferredId > 0
|
||||
? normalizedItems.find((item) => Number(item.id || 0) === preferredId) ||
|
||||
? normalizedItems.find((item: JsonObject) => Number(item.id || 0) === preferredId) ||
|
||||
null
|
||||
: null;
|
||||
}
|
||||
|
||||
if (preferredId > 0) {
|
||||
const preferred =
|
||||
normalizedItems.find((item) => Number(item.id || 0) === preferredId) ||
|
||||
normalizedItems.find((item: JsonObject) => Number(item.id || 0) === preferredId) ||
|
||||
null;
|
||||
if (preferred) {
|
||||
return preferred;
|
||||
}
|
||||
}
|
||||
|
||||
const exactMatches = normalizedItems.filter((item) => {
|
||||
const exactMatches = normalizedItems.filter((item: JsonObject) => {
|
||||
const itemName = normalizeProductName(item.name);
|
||||
return normalizedNames.some(
|
||||
(candidate) => candidate.normalized === itemName
|
||||
(candidate: { normalized: string }) => candidate.normalized === itemName
|
||||
);
|
||||
});
|
||||
if (exactMatches.length > 0) {
|
||||
return exactMatches[0];
|
||||
}
|
||||
|
||||
const partialMatches = normalizedItems.filter((item) => {
|
||||
const partialMatches = normalizedItems.filter((item: JsonObject) => {
|
||||
const itemName = normalizeProductName(item.name);
|
||||
return normalizedNames.some(
|
||||
(candidate) =>
|
||||
(candidate: { normalized: string }) =>
|
||||
itemName.includes(candidate.normalized) ||
|
||||
candidate.normalized.includes(itemName)
|
||||
);
|
||||
@@ -224,13 +224,15 @@ function findCloudItemByNames(items, nameCandidates, preferredId = 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function isCloudSkuLikeItem(item) {
|
||||
return Boolean(item) && typeof item === "object" && Number(item.id || 0) > 0;
|
||||
function isCloudSkuLikeItem(item: unknown): item is JsonObject {
|
||||
const current = item && typeof item === "object" ? item as JsonObject : {};
|
||||
return Number(current.id || 0) > 0;
|
||||
}
|
||||
|
||||
function isRecoverableKuaishouCloudVnKeyError(error) {
|
||||
const errorCode = String(error?.errorCode || error?.code || "").trim();
|
||||
const errorMessage = String(error?.message || "").trim();
|
||||
function isRecoverableKuaishouCloudVnKeyError(error: unknown) {
|
||||
const current = error && typeof error === "object" ? error as JsonObject : {};
|
||||
const errorCode = String(current.errorCode || current.code || "").trim();
|
||||
const errorMessage = String(current.message || "").trim();
|
||||
return (
|
||||
errorCode === "cloudtentacles_vn_bind_url_failed" &&
|
||||
errorMessage.includes("不支持的游戏类型")
|
||||
|
||||
@@ -45,7 +45,7 @@ export function resolvePersistedCloudtentaclesContext(sourceKey = "default") {
|
||||
*/
|
||||
export function resolvePersistedCloudtentaclesContextWithFallback(
|
||||
primarySourceKey = "default",
|
||||
fallbacks = []
|
||||
fallbacks: unknown[] = []
|
||||
) {
|
||||
const candidates = [
|
||||
String(primarySourceKey || "default").trim() || "default",
|
||||
|
||||
@@ -8,12 +8,13 @@ export const KUAISHOU_CLOUD_FIXED_VN_KEY = "1";
|
||||
|
||||
export type JsonObject = Record<string, any>;
|
||||
|
||||
export function isKuaishouCloudTask(task) {
|
||||
return String(task?.executor_key || "").trim() === "kuaishou_ct_assisted";
|
||||
export function isKuaishouCloudTask(task: unknown) {
|
||||
const source = task && typeof task === "object" ? task as JsonObject : {};
|
||||
return String(source.executor_key || "").trim() === "kuaishou_ct_assisted";
|
||||
}
|
||||
|
||||
export function normalizeKuaishouCloudFlow(value) {
|
||||
const source = value && typeof value === "object" ? value : {};
|
||||
export function normalizeKuaishouCloudFlow(value: unknown) {
|
||||
const source: JsonObject = value && typeof value === "object" ? value as JsonObject : {};
|
||||
const binding =
|
||||
source.binding && typeof source.binding === "object" ? source.binding : {};
|
||||
const role =
|
||||
@@ -129,8 +130,8 @@ export function normalizeKuaishouCloudFlow(value) {
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeKuaishouCloudRoleInfo(value) {
|
||||
const rawInfo = value && typeof value === "object" ? value : null;
|
||||
export function normalizeKuaishouCloudRoleInfo(value: unknown) {
|
||||
const rawInfo: JsonObject | null = value && typeof value === "object" ? value as JsonObject : null;
|
||||
const nestedBindInfo =
|
||||
rawInfo?.sBindInfo && typeof rawInfo.sBindInfo === "object"
|
||||
? rawInfo.sBindInfo
|
||||
@@ -157,15 +158,15 @@ export function normalizeKuaishouCloudRoleInfo(value) {
|
||||
};
|
||||
}
|
||||
|
||||
export function maskPhone(value) {
|
||||
export function maskPhone(value: unknown) {
|
||||
return maskPhoneValue(value);
|
||||
}
|
||||
|
||||
export function maskCode(value) {
|
||||
export function maskCode(value: unknown) {
|
||||
return maskCodeValue(value);
|
||||
}
|
||||
|
||||
export function resolveKuaishouCloudBindUrlExpiresAt(preparedAt) {
|
||||
export function resolveKuaishouCloudBindUrlExpiresAt(preparedAt: unknown) {
|
||||
const preparedTime = Date.parse(String(preparedAt || ""));
|
||||
if (!Number.isFinite(preparedTime)) {
|
||||
return null;
|
||||
@@ -176,7 +177,7 @@ export function resolveKuaishouCloudBindUrlExpiresAt(preparedAt) {
|
||||
return new Date(preparedTime + Math.max(1, ttlSeconds) * 1000).toISOString();
|
||||
}
|
||||
|
||||
export function isKuaishouCloudBindUrlFresh(flow, now = new Date()) {
|
||||
export function isKuaishouCloudBindUrlFresh(flow: unknown, now = new Date()) {
|
||||
const normalizedFlow = normalizeKuaishouCloudFlow(flow);
|
||||
if (!normalizedFlow.binding.bindUrl) {
|
||||
return false;
|
||||
@@ -195,7 +196,7 @@ export function isKuaishouCloudBindUrlFresh(flow, now = new Date()) {
|
||||
return expiresTime > now.getTime();
|
||||
}
|
||||
|
||||
export function normalizeStringArray(value) {
|
||||
export function normalizeStringArray(value: unknown) {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v) => String(v || "").trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import { parseTaskContext as parseTaskContextValue } from "../../../utils/task-json.js";
|
||||
import type { TaskRow } from "../../../types/repository-rows.js";
|
||||
|
||||
export function normalizeActor(actor) {
|
||||
type JsonObject = Record<string, any>;
|
||||
|
||||
export function normalizeActor(actor: unknown) {
|
||||
if (!actor || typeof actor !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const source = String(actor.source || "").trim();
|
||||
const userId = Number(actor.userId || 0) || 0;
|
||||
const username = String(actor.username || "").trim();
|
||||
const role = String(actor.role || "").trim();
|
||||
const current = actor as JsonObject;
|
||||
const source = String(current.source || "").trim();
|
||||
const userId = Number(current.userId || 0) || 0;
|
||||
const username = String(current.username || "").trim();
|
||||
const role = String(current.role || "").trim();
|
||||
|
||||
if (!source && !userId && !username && !role) {
|
||||
return null;
|
||||
@@ -22,19 +26,19 @@ export function normalizeActor(actor) {
|
||||
};
|
||||
}
|
||||
|
||||
export function parseTaskContext(task) {
|
||||
export function parseTaskContext(task: Partial<TaskRow> | null | undefined) {
|
||||
return parseTaskContextValue(task);
|
||||
}
|
||||
|
||||
export function getTaskClaimExpiresAt(task) {
|
||||
export function getTaskClaimExpiresAt(task: Partial<TaskRow> | null | undefined) {
|
||||
return task?.claim_expires_at || task?.primary_claim_expires_at || null;
|
||||
}
|
||||
|
||||
export function isClaimExpired(expiredAt) {
|
||||
export function isClaimExpired(expiredAt: unknown) {
|
||||
if (!expiredAt) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const timestamp = new Date(expiredAt).getTime();
|
||||
const timestamp = new Date(expiredAt instanceof Date ? expiredAt : String(expiredAt || "")).getTime();
|
||||
return Number.isFinite(timestamp) && timestamp <= Date.now();
|
||||
}
|
||||
|
||||
@@ -20,9 +20,10 @@ import {
|
||||
} from "./domain.js";
|
||||
import { resolvePersistedCloudtentaclesContextWithFallback } from "./cloudtentacles-context.js";
|
||||
import { normalizeActor, parseTaskContext } from "./task-context.js";
|
||||
import type { TaskRow } from "../../../types/repository-rows.js";
|
||||
|
||||
export async function dispatchKuaishouCloudFulfillmentTask(
|
||||
task,
|
||||
task: TaskRow,
|
||||
options: JsonObject = {}
|
||||
) {
|
||||
if (!isKuaishouCloudTask(task)) {
|
||||
@@ -157,7 +158,7 @@ export async function dispatchKuaishouCloudFulfillmentTask(
|
||||
}
|
||||
|
||||
export async function returnKuaishouCloudFulfillmentTask(
|
||||
task,
|
||||
task: TaskRow,
|
||||
options: JsonObject = {}
|
||||
) {
|
||||
if (!isKuaishouCloudTask(task)) {
|
||||
|
||||
@@ -7,6 +7,13 @@ const NOTIFICATION_CONFIG_FILE_PATH = path.join(PROJECT_ROOT, 'data', 'notificat
|
||||
const DEFAULT_BARK_SERVER_URL = 'https://api.day.app'
|
||||
|
||||
type JsonObject = Record<string, any>
|
||||
type NotificationRecipient = {
|
||||
id: string
|
||||
name: string
|
||||
deviceKey?: string
|
||||
apiKey?: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export function getNotificationConfigFilePath() {
|
||||
return NOTIFICATION_CONFIG_FILE_PATH
|
||||
@@ -26,7 +33,7 @@ export function listEnabledBarkRecipients(config: JsonObject = getNotificationCo
|
||||
}
|
||||
|
||||
return (Array.isArray(config.channels?.bark?.recipients) ? config.channels.bark.recipients : [])
|
||||
.filter((item) => item.enabled !== false && String(item.deviceKey || '').trim())
|
||||
.filter((item: JsonObject) => item.enabled !== false && String(item.deviceKey || '').trim())
|
||||
}
|
||||
|
||||
export function listEnabledWpushRecipients(config: JsonObject = getNotificationConfig()) {
|
||||
@@ -35,7 +42,7 @@ export function listEnabledWpushRecipients(config: JsonObject = getNotificationC
|
||||
}
|
||||
|
||||
return (Array.isArray(config.channels?.wpush?.recipients) ? config.channels.wpush.recipients : [])
|
||||
.filter((item) => item.enabled !== false && String(item.apiKey || item.apikey || '').trim())
|
||||
.filter((item: JsonObject) => item.enabled !== false && String(item.apiKey || item.apikey || '').trim())
|
||||
}
|
||||
|
||||
function loadNotificationConfigFromFile() {
|
||||
@@ -58,20 +65,20 @@ export function normalizeNotificationConfig(rawValue: unknown) {
|
||||
enabled: typeof bark.enabled === 'boolean' ? bark.enabled : true,
|
||||
serverUrl: normalizeBarkServerUrl(bark.serverUrl),
|
||||
recipients: (Array.isArray(bark.recipients) ? bark.recipients : [])
|
||||
.map((item) => normalizeBarkRecipient(item))
|
||||
.map((item: unknown) => normalizeBarkRecipient(item))
|
||||
.filter(Boolean),
|
||||
},
|
||||
wpush: {
|
||||
enabled: typeof wpush.enabled === 'boolean' ? wpush.enabled : true,
|
||||
recipients: (Array.isArray(wpush.recipients) ? wpush.recipients : [])
|
||||
.map((item) => normalizeWpushRecipient(item))
|
||||
.map((item: unknown) => normalizeWpushRecipient(item))
|
||||
.filter(Boolean),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBarkRecipient(rawValue: unknown) {
|
||||
function normalizeBarkRecipient(rawValue: unknown): NotificationRecipient | null {
|
||||
if (!isPlainObject(rawValue)) {
|
||||
return null
|
||||
}
|
||||
@@ -97,7 +104,7 @@ function normalizeBarkServerUrl(value: unknown) {
|
||||
return normalized.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
function normalizeWpushRecipient(rawValue: unknown) {
|
||||
function normalizeWpushRecipient(rawValue: unknown): NotificationRecipient | null {
|
||||
if (!isPlainObject(rawValue)) {
|
||||
return null
|
||||
}
|
||||
@@ -125,11 +132,11 @@ export function createDefaultNotificationConfig() {
|
||||
bark: {
|
||||
enabled: true,
|
||||
serverUrl: DEFAULT_BARK_SERVER_URL,
|
||||
recipients: [],
|
||||
recipients: [] as NotificationRecipient[],
|
||||
},
|
||||
wpush: {
|
||||
enabled: true,
|
||||
recipients: [],
|
||||
recipients: [] as NotificationRecipient[],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { sendBarkNotification } from './bark-service.js'
|
||||
import { sendWpushNotification } from './wpush-service.js'
|
||||
|
||||
type JsonObject = Record<string, any>
|
||||
type NotificationResult = ReturnType<typeof mapNotificationResult>
|
||||
type NotificationInput = {
|
||||
title?: string
|
||||
body?: string
|
||||
@@ -31,12 +32,12 @@ export async function sendInternalNotification(input: NotificationInput = {}) {
|
||||
successCount: 0,
|
||||
failedCount: 0,
|
||||
skippedCount: barkRecipients.length + wpushRecipients.length,
|
||||
results: [],
|
||||
results: [] as NotificationResult[],
|
||||
}
|
||||
}
|
||||
|
||||
const results = [
|
||||
...(await Promise.all(barkRecipients.map(async (recipient) => {
|
||||
...(await Promise.all(barkRecipients.map(async (recipient: JsonObject) => {
|
||||
try {
|
||||
const result = await sendBarkNotification({
|
||||
serverUrl: bark.serverUrl,
|
||||
@@ -64,7 +65,7 @@ export async function sendInternalNotification(input: NotificationInput = {}) {
|
||||
)
|
||||
}
|
||||
}))),
|
||||
...(await Promise.all(wpushRecipients.map(async (recipient) => {
|
||||
...(await Promise.all(wpushRecipients.map(async (recipient: JsonObject) => {
|
||||
try {
|
||||
const result = await sendWpushNotification({
|
||||
recipient,
|
||||
|
||||
@@ -23,8 +23,11 @@ import {
|
||||
OPEN_91_PROVIDER,
|
||||
resolveOpen91QueryState,
|
||||
} from './shared.js'
|
||||
import type { OrderRow } from '../../types/repository-rows.js'
|
||||
|
||||
export async function queryOpen91Order(payload = {}, { requestId = '' } = {}) {
|
||||
type JsonObject = Record<string, any>
|
||||
|
||||
export async function queryOpen91Order(payload: JsonObject = {}, { requestId = '' } = {}) {
|
||||
const config = assertOpen91Config()
|
||||
const normalized = normalizeOpen91QueryPayload(payload)
|
||||
|
||||
@@ -168,12 +171,12 @@ export async function queryOpen91Order(payload = {}, { requestId = '' } = {}) {
|
||||
return buildOpen91SuccessResponse(responseData)
|
||||
}
|
||||
|
||||
function resolveOpen91OrderFailReason(order) {
|
||||
function resolveOpen91OrderFailReason(order: OrderRow) {
|
||||
const payload = parseJsonObject(order?.raw_payload_json)
|
||||
return String(payload.manualFailedReason || '').trim()
|
||||
}
|
||||
|
||||
function parseJsonObject(value) {
|
||||
function parseJsonObject(value: unknown): JsonObject {
|
||||
if (!value) {
|
||||
return {}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ export function assertOpen91Config() {
|
||||
return config
|
||||
}
|
||||
|
||||
export function normalizeOpen91String(value) {
|
||||
export function normalizeOpen91String(value: unknown) {
|
||||
return String(value || '').trim()
|
||||
}
|
||||
|
||||
@@ -187,7 +187,7 @@ export function assertOpen91Signature(params: JsonObject = {}, config = assertOp
|
||||
}
|
||||
}
|
||||
|
||||
export function encryptOpen91Cards(cards = [], secret = assertOpen91Config().secret) {
|
||||
export function encryptOpen91Cards(cards: unknown[] = [], secret = assertOpen91Config().secret) {
|
||||
const normalizedSecret = normalizeOpen91String(secret)
|
||||
if (normalizedSecret.length !== 32) {
|
||||
throw createHttpError('91卡券 cards 加密密钥长度必须为 32 个字符', {
|
||||
@@ -227,7 +227,7 @@ export function buildOpen91ErrorResponse(message: unknown, code = 500) {
|
||||
return {
|
||||
code,
|
||||
message: normalizeOpen91String(message) || '系统错误',
|
||||
data: null,
|
||||
data: null as null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,7 +323,7 @@ export function resolveOpen91QueryState(
|
||||
}
|
||||
}
|
||||
|
||||
export function stringifyOpen91SignValue(value) {
|
||||
export function stringifyOpen91SignValue(value: unknown) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return String(value)
|
||||
}
|
||||
@@ -339,12 +339,12 @@ export function stringifyOpen91SignValue(value) {
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function normalizeOpen91BuyNum(value) {
|
||||
function normalizeOpen91BuyNum(value: unknown) {
|
||||
const parsed = Number(value)
|
||||
return Number.isInteger(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
function normalizeOpen91OptionalAmount(value) {
|
||||
function normalizeOpen91OptionalAmount(value: unknown) {
|
||||
const normalized = normalizeOpen91String(value)
|
||||
if (!normalized) {
|
||||
return ''
|
||||
@@ -360,7 +360,7 @@ function normalizeOpen91OptionalAmount(value) {
|
||||
return normalized
|
||||
}
|
||||
|
||||
function normalizeOpen91Timestamp(value) {
|
||||
function normalizeOpen91Timestamp(value: unknown) {
|
||||
const normalized = normalizeOpen91String(value)
|
||||
if (!/^\d{10}$/.test(normalized)) {
|
||||
return 0
|
||||
|
||||
@@ -20,7 +20,7 @@ export function getKuaishouCloudFulfillmentConfig() {
|
||||
return loadKuaishouCloudFulfillmentConfigFromFile();
|
||||
}
|
||||
|
||||
export function saveKuaishouCloudFulfillmentConfig(rawValue) {
|
||||
export function saveKuaishouCloudFulfillmentConfig(rawValue: unknown) {
|
||||
return writeJsonFile(
|
||||
KUAISHOU_CLOUD_FULFILLMENT_FILE_PATH,
|
||||
rawValue,
|
||||
@@ -94,19 +94,19 @@ function loadKuaishouCloudFulfillmentConfigFromFile() {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeKuaishouCloudFulfillmentConfig(rawValue) {
|
||||
function normalizeKuaishouCloudFulfillmentConfig(rawValue: unknown) {
|
||||
const source = isPlainObject(rawValue) ? rawValue : {};
|
||||
return {
|
||||
enabled: source.enabled !== false,
|
||||
items: Array.isArray(source.items)
|
||||
? source.items
|
||||
.map((item) => normalizeKuaishouCloudFulfillmentItem(item))
|
||||
.map((item: unknown) => normalizeKuaishouCloudFulfillmentItem(item))
|
||||
.filter(Boolean)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeKuaishouCloudFulfillmentItem(rawValue) {
|
||||
function normalizeKuaishouCloudFulfillmentItem(rawValue: unknown) {
|
||||
if (!isPlainObject(rawValue)) {
|
||||
return null;
|
||||
}
|
||||
@@ -178,17 +178,17 @@ function normalizeKuaishouCloudFulfillmentItem(rawValue) {
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePositiveInteger(value) {
|
||||
function normalizePositiveInteger(value: unknown) {
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : 0;
|
||||
}
|
||||
|
||||
function normalizeNonNegativeInteger(value, fallback) {
|
||||
function normalizeNonNegativeInteger(value: unknown, fallback: number) {
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
function normalizePriority(value) {
|
||||
function normalizePriority(value: unknown) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return 100;
|
||||
@@ -196,19 +196,19 @@ function normalizePriority(value) {
|
||||
|
||||
return Math.max(1, Math.round(parsed));
|
||||
}
|
||||
function isPlainObject(value) {
|
||||
function isPlainObject(value: unknown): value is JsonObject {
|
||||
return Object.prototype.toString.call(value) === "[object Object]";
|
||||
}
|
||||
|
||||
function normalizeStringArray(value) {
|
||||
function normalizeStringArray(value: unknown) {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v) => String(v || "").trim()).filter(Boolean);
|
||||
return value.map((v: unknown) => String(v || "").trim()).filter(Boolean);
|
||||
}
|
||||
// 兼容旧格式:字符串用逗号分隔
|
||||
if (typeof value === "string") {
|
||||
return value
|
||||
.split(",")
|
||||
.map((v) => v.trim())
|
||||
.map((v: string) => v.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
|
||||
@@ -37,7 +37,7 @@ export async function runCloudtentaclesFullDebugFlow(payload: JsonObject = {}) {
|
||||
const beforeAsset = await runFlowStep('查询购买前余额', () => getCloudtentaclesAsset(payload))
|
||||
await sleep(350)
|
||||
const skuList = await runFlowStep('查询 SKU 列表', () => listCloudtentaclesSku(payload))
|
||||
const targetSku = skuList.items.find((item) => Number(item.id || 0) === skuId) || null
|
||||
const targetSku = skuList.items.find((item: JsonObject) => Number(item.id || 0) === skuId) || null
|
||||
|
||||
if (!targetSku) {
|
||||
throw createHttpError(`cloudtentacles 未找到 SKU ${skuId}`, {
|
||||
|
||||
@@ -176,7 +176,7 @@ export async function validateCloudtentaclesSession(payload: JsonObject = {}) {
|
||||
userInfo: isPlainObject(userInfoResult.payload?.data) ? userInfoResult.payload.data : {},
|
||||
asset: Number(assetResult.payload?.data || 0),
|
||||
permissions: Array.isArray(permissionResult.payload?.data)
|
||||
? permissionResult.payload.data.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
? permissionResult.payload.data.map((item: unknown) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ import { PROJECT_ROOT } from '../../../config/runtime.js'
|
||||
const CLOUDTENTACLES_SESSION_FILE_PATH = path.join(PROJECT_ROOT, 'data', 'cloudtentacles-session.json')
|
||||
|
||||
type JsonObject = Record<string, any>
|
||||
type CloudtentaclesSessionState = ReturnType<typeof createDefaultCloudtentaclesSessionState>
|
||||
type CloudtentaclesSessionStatesFile = {
|
||||
sessions: Record<string, CloudtentaclesSessionState>
|
||||
}
|
||||
|
||||
export function getCloudtentaclesSessionFilePath() {
|
||||
return CLOUDTENTACLES_SESSION_FILE_PATH
|
||||
@@ -127,7 +131,7 @@ export function pruneCloudtentaclesSessionStates(sourceKeys: unknown[] = []) {
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function loadCloudtentaclesSessionStatesFromFile() {
|
||||
function loadCloudtentaclesSessionStatesFromFile(): CloudtentaclesSessionStatesFile {
|
||||
if (!fs.existsSync(CLOUDTENTACLES_SESSION_FILE_PATH)) {
|
||||
return createDefaultCloudtentaclesSessionStates()
|
||||
}
|
||||
@@ -162,7 +166,7 @@ function normalizeCloudtentaclesSessionState(rawValue: unknown) {
|
||||
* Handles old format (single object without sessions key) by auto-wrapping
|
||||
* into { sessions: { 'default': ... } }.
|
||||
*/
|
||||
function normalizeSessionStatesFile(rawValue: unknown) {
|
||||
function normalizeSessionStatesFile(rawValue: unknown): CloudtentaclesSessionStatesFile {
|
||||
// Old format: { token: 'xxx', ... } (single object, no sessions key)
|
||||
if (isPlainObject(rawValue) && !rawValue.sessions) {
|
||||
return {
|
||||
@@ -194,7 +198,7 @@ function createDefaultCloudtentaclesSessionState() {
|
||||
}
|
||||
}
|
||||
|
||||
function createDefaultCloudtentaclesSessionStates() {
|
||||
function createDefaultCloudtentaclesSessionStates(): CloudtentaclesSessionStatesFile {
|
||||
return {
|
||||
sessions: {
|
||||
'default': createDefaultCloudtentaclesSessionState(),
|
||||
|
||||
@@ -200,7 +200,7 @@ export async function probeCloudtentaclesBindUrl(payload: JsonObject = {}) {
|
||||
finalUrl: bindUrl,
|
||||
reason: 'missing_signature_params',
|
||||
roleInfo: normalizeAmsBindRoleInfo(null),
|
||||
raw: null,
|
||||
raw: null as null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ export async function probeCloudtentaclesBindUrl(payload: JsonObject = {}) {
|
||||
finalUrl: bindUrl,
|
||||
reason: error instanceof Error ? error.message : String(error || 'probe_failed'),
|
||||
roleInfo: normalizeAmsBindRoleInfo(null),
|
||||
raw: null,
|
||||
raw: null as null,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
}
|
||||
@@ -269,7 +269,7 @@ export async function getCloudtentaclesBindInfo(payload: JsonObject = {}) {
|
||||
})
|
||||
|
||||
const items = Array.isArray(result.payload?.data) ? result.payload.data : []
|
||||
const matchedItem = items.find((item) => Number(item?.id || 0) === id) || items[0] || {}
|
||||
const matchedItem = items.find((item: JsonObject) => Number(item?.id || 0) === id) || items[0] || {}
|
||||
const bindInfo = parseBindInfo(matchedItem?.bind_info)
|
||||
|
||||
return {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '../../open-91/shared.js'
|
||||
import { createHttpError } from '../../../utils/http.js'
|
||||
import { nowIso } from '../../../utils/time.js'
|
||||
import type { OrderItemRow, OrderRow } from '../../../types/repository-rows.js'
|
||||
|
||||
export const OPEN_91_PENDING_CONFIG_STATUS = 'pending_config'
|
||||
export const OPEN_91_MANUAL_FAILED_STATUS = 'manual_failed'
|
||||
@@ -68,7 +69,7 @@ export function buildOpen91SourceEvent(payload: JsonObject = {}, config: JsonObj
|
||||
}
|
||||
}
|
||||
|
||||
export async function upsertOpen91PendingOrder(payload = {}, config = {}) {
|
||||
export async function upsertOpen91PendingOrder(payload: JsonObject = {}, config: JsonObject = {}) {
|
||||
const event = buildOpen91SourceEvent(payload, config)
|
||||
const now = nowIso()
|
||||
const existing = await findOrderByPlatformOrderId({
|
||||
@@ -127,11 +128,11 @@ export async function upsertOpen91PendingOrder(payload = {}, config = {}) {
|
||||
return {
|
||||
order,
|
||||
orderItems,
|
||||
tasks: [],
|
||||
tasks: [] as JsonObject[],
|
||||
}
|
||||
}
|
||||
|
||||
export async function retryOpen91Order(orderId) {
|
||||
export async function retryOpen91Order(orderId: string | number) {
|
||||
const order = await getRequiredOpen91Order(orderId)
|
||||
const items = await listOrderItemsByOrderId(order.id)
|
||||
const event = buildOpen91SourceEventFromOrder(order, items)
|
||||
@@ -154,7 +155,7 @@ export async function retryOpen91Order(orderId) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function failOpen91Order(orderId, reason = '') {
|
||||
export async function failOpen91Order(orderId: string | number, reason = '') {
|
||||
const order = await getRequiredOpen91Order(orderId)
|
||||
const now = nowIso()
|
||||
const rawPayload = parseJsonObject(order.raw_payload_json)
|
||||
@@ -245,7 +246,7 @@ export async function listOpen91Orders({ page = 1, pageSize = 20, status = 'pend
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRequiredOpen91Order(orderId) {
|
||||
export async function getRequiredOpen91Order(orderId: string | number) {
|
||||
const order = await getOrderById(Number(orderId))
|
||||
|
||||
if (!order || order.provider !== OPEN_91_PROVIDER || order.platform !== OPEN_91_PLATFORM) {
|
||||
@@ -258,11 +259,11 @@ export async function getRequiredOpen91Order(orderId) {
|
||||
return order
|
||||
}
|
||||
|
||||
function buildOpen91SourceEventFromOrder(order, items = []) {
|
||||
function buildOpen91SourceEventFromOrder(order: OrderRow, items: OrderItemRow[] = []) {
|
||||
const rawPayload = parseJsonObject(order.raw_payload_json)
|
||||
const body = parseJsonObject(rawPayload.body)
|
||||
const normalizedItems = Array.isArray(items) ? items : []
|
||||
const eventItems = normalizedItems.map((item) => {
|
||||
const eventItems = normalizedItems.map((item: OrderItemRow) => {
|
||||
const snapshot = parseJsonObject(item.item_snapshot_json)
|
||||
const productNo = String(snapshot.productNo || snapshot.externalSkuCode || item.sku_code || '').trim()
|
||||
|
||||
@@ -301,7 +302,7 @@ function buildOpen91SourceEventFromOrder(order, items = []) {
|
||||
}
|
||||
}
|
||||
|
||||
function mapOpen91AdminOrderRow(row) {
|
||||
function mapOpen91AdminOrderRow(row: JsonObject) {
|
||||
const rawPayload = parseJsonObject(row.raw_payload_json)
|
||||
const items = Array.isArray(row.items_json) ? row.items_json : []
|
||||
const firstItem = items[0] || {}
|
||||
@@ -327,7 +328,7 @@ function mapOpen91AdminOrderRow(row) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseJsonObject(value) {
|
||||
function parseJsonObject(value: unknown): JsonObject {
|
||||
if (!value) {
|
||||
return {}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ async function runCloudtentaclesHealthAccount(
|
||||
): Promise<CloudtentaclesHealthAccountResult> {
|
||||
const sourceKey = String(account.sourceKey || '').trim() || 'default'
|
||||
const source = getCloudtentaclesSourceByKey(sourceKey)
|
||||
const session = getCloudtentaclesSessionStateByKey(sourceKey) || {}
|
||||
const session: JsonObject = getCloudtentaclesSessionStateByKey(sourceKey) || {}
|
||||
const label = String(account.label || source?.label || source?.username || sourceKey).trim() || sourceKey
|
||||
const threshold = normalizeNonNegativeInteger(account.assetThreshold, 500)
|
||||
const checkedAt = new Date().toISOString()
|
||||
|
||||
Reference in New Issue
Block a user