style(backend): 格式化代码并修复floating-promises以通过pre-push检查

This commit is contained in:
yml2213
2026-09-12 17:46:47 +08:00
parent 8cc3aa2a35
commit fea82bff36
12 changed files with 55 additions and 71 deletions
@@ -86,7 +86,6 @@ export async function findLatestOrderByAnyPlatformOrderId(
return result.rows[0] || null return result.rows[0] || null
} }
export async function findExistingPlatformOrderIds({ export async function findExistingPlatformOrderIds({
provider = 'pdd', provider = 'pdd',
platform = 'pdd', platform = 'pdd',
@@ -376,7 +376,7 @@ export async function pruneWorkProductMatchLogs(
} }
const remainingRes = await query<{ total: number }>( const remainingRes = await query<{ total: number }>(
"SELECT COUNT(*)::int AS total FROM work_product_match_logs", 'SELECT COUNT(*)::int AS total FROM work_product_match_logs',
) )
const remainingTotal = Number(remainingRes.rows[0]?.total || 0) const remainingTotal = Number(remainingRes.rows[0]?.total || 0)
@@ -71,19 +71,16 @@ router.post(
*/ */
router.post( router.post(
'/pdd/stores/:shopId', '/pdd/stores/:shopId',
createJsonHandler( createJsonHandler((req) => savePddStore(req.params.shopId, (req.body || {}) as JsonObject), {
(req) => savePddStore(req.params.shopId, (req.body || {}) as JsonObject), successMessage: '拼多多店铺配置已更新',
{ errorMessage: '更新拼多多店铺配置失败',
successMessage: '拼多多店铺配置已更新', scope: '[admin/platform-config/pdd/stores/:shopId]',
errorMessage: '更新拼多多店铺配置失败', audit: (req) => ({
scope: '[admin/platform-config/pdd/stores/:shopId]', action: 'platform_pdd_store_updated',
audit: (req) => ({ targetType: 'platform_store',
action: 'platform_pdd_store_updated', targetId: String(req.params.shopId || ''),
targetType: 'platform_store', }),
targetId: String(req.params.shopId || ''), }),
}),
},
),
) )
/** /**
@@ -150,7 +147,7 @@ router.post(
}) })
if (!result.valid) { if (!result.valid) {
notifyPddCookieExpired({ void notifyPddCookieExpired({
shopId: existingStore.shopId, shopId: existingStore.shopId,
shopName: existingStore.shopName, shopName: existingStore.shopName,
message: result.message, message: result.message,
@@ -293,7 +293,6 @@ function markNotificationCooldown(cooldownKey: unknown) {
notificationCooldownMap.set(key, Date.now()) notificationCooldownMap.set(key, Date.now())
} }
export interface PddCookieExpiredPayload { export interface PddCookieExpiredPayload {
shopId: string shopId: string
shopName?: string | undefined shopName?: string | undefined
@@ -219,19 +219,14 @@ export function normalizePddSourcesConfig(rawValue: unknown): PddSourcesConfig {
: 20 : 20
const rawOrderType = Number(source.orderType) const rawOrderType = Number(source.orderType)
const orderType = Number.isInteger(rawOrderType) && [0, 1, 2].includes(rawOrderType) const orderType =
? rawOrderType Number.isInteger(rawOrderType) && [0, 1, 2].includes(rawOrderType) ? rawOrderType : 2
: 2
const rawPageSize = Number(source.pageSize) const rawPageSize = Number(source.pageSize)
const pageSize = Number.isInteger(rawPageSize) const pageSize = Number.isInteger(rawPageSize) ? Math.min(100, Math.max(10, rawPageSize)) : 50
? Math.min(100, Math.max(10, rawPageSize))
: 50
const rawMaxPages = Number(source.maxPages) const rawMaxPages = Number(source.maxPages)
const maxPages = Number.isInteger(rawMaxPages) const maxPages = Number.isInteger(rawMaxPages) ? Math.min(20, Math.max(1, rawMaxPages)) : 5
? Math.min(20, Math.max(1, rawMaxPages))
: 5
return { return {
enabled: source.enabled !== false, enabled: source.enabled !== false,
@@ -85,7 +85,10 @@ export async function syncStoreOrders(
const client = new PddClient(store) const client = new PddClient(store)
const sourcesConfig = getPddSourcesConfig() const sourcesConfig = getPddSourcesConfig()
const pageSize = Math.min(100, Math.max(1, Number(options.pageSize || sourcesConfig.pageSize || 50))) const pageSize = Math.min(
100,
Math.max(1, Number(options.pageSize || sourcesConfig.pageSize || 50)),
)
const initialPage = Math.max(1, Number(options.pageNumber || 1)) const initialPage = Math.max(1, Number(options.pageNumber || 1))
const orderType = options.orderType ?? sourcesConfig.orderType ?? 2 // 2: 已发货 (Shipped, default) const orderType = options.orderType ?? sourcesConfig.orderType ?? 2 // 2: 已发货 (Shipped, default)
@@ -130,9 +133,7 @@ export async function syncStoreOrders(
totalFetched += items.length totalFetched += items.length
// 提取本页订单号并批量排查数据库已有状态 // 提取本页订单号并批量排查数据库已有状态
const pageOrderSns = items const pageOrderSns = items.map((item) => String(item.order_sn || '').trim()).filter(Boolean)
.map((item) => String(item.order_sn || '').trim())
.filter(Boolean)
const checkExisting = const checkExisting =
options.checkExistingOrderIds || options.checkExistingOrderIds ||
@@ -279,7 +280,7 @@ export async function syncStoreOrders(
lastCheckedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(),
}).catch(() => null) }).catch(() => null)
notifyPddCookieExpired({ void notifyPddCookieExpired({
shopId, shopId,
shopName, shopName,
message: errMsg, message: errMsg,
@@ -1,10 +1,10 @@
import { query } from "../../db/client.js" import { query } from '../../db/client.js'
import { runtimeConfig } from "../../config/runtime.js" import { runtimeConfig } from '../../config/runtime.js'
import { getWorkerProductMatchConfig } from "../worker-platform/worker-product-match-config-service.js" import { getWorkerProductMatchConfig } from '../worker-platform/worker-product-match-config-service.js'
import { pruneWorkProductMatchLogs } from "../../repositories/worker-platform/product-match-repo.js" import { pruneWorkProductMatchLogs } from '../../repositories/worker-platform/product-match-repo.js'
export type DataRetentionResult = { export type DataRetentionResult = {
status: "ok" status: 'ok'
message: string message: string
rawPayloadRows: number rawPayloadRows: number
taskEventRows: number taskEventRows: number
@@ -31,20 +31,20 @@ export async function runDataRetentionJob(): Promise<DataRetentionResult> {
// 2. 清理其他报文与日志 // 2. 清理其他报文与日志
const rawPayloadRows = const rawPayloadRows =
(await scrubJsonColumnInBatches("orders", "updated_at", rawPayloadDays)) + (await scrubJsonColumnInBatches('orders', 'updated_at', rawPayloadDays)) +
(await scrubJsonColumnInBatches("kuaishou_industry_vouchers", "updated_at", rawPayloadDays)) (await scrubJsonColumnInBatches('kuaishou_industry_vouchers', 'updated_at', rawPayloadDays))
const matchLogRows = await scrubJsonColumnInBatches( const matchLogRows = await scrubJsonColumnInBatches(
"work_product_match_logs", 'work_product_match_logs',
"created_at", 'created_at',
rawPayloadDays, rawPayloadDays,
) )
const taskEventRows = await deleteOldRowsInBatches("task_events", taskEventDays) const taskEventRows = await deleteOldRowsInBatches('task_events', taskEventDays)
const webhookEventRows = await deleteOldRowsInBatches("webhook_events", webhookEventDays) const webhookEventRows = await deleteOldRowsInBatches('webhook_events', webhookEventDays)
const auditLogRows = await deleteOldRowsInBatches("admin_audit_logs", auditLogDays) const auditLogRows = await deleteOldRowsInBatches('admin_audit_logs', auditLogDays)
return { return {
status: "ok", status: 'ok',
message: "数据保留清理完成", message: '数据保留清理完成',
rawPayloadRows, rawPayloadRows,
matchLogRows, matchLogRows,
matchLogDeletedRows: matchLogPruneResult.totalDeleted, matchLogDeletedRows: matchLogPruneResult.totalDeleted,
@@ -14,7 +14,10 @@ export async function runPddOrderSyncJob(job: JsonObject) {
? (job.config as JsonObject) ? (job.config as JsonObject)
: {} : {}
const sourcesConfig = getPddSourcesConfig() const sourcesConfig = getPddSourcesConfig()
const pageSize = Math.min(100, Math.max(1, Number(config.pageSize || sourcesConfig.pageSize || 50))) const pageSize = Math.min(
100,
Math.max(1, Number(config.pageSize || sourcesConfig.pageSize || 50)),
)
const maxPages = Math.min(20, Math.max(1, Number(config.maxPages || sourcesConfig.maxPages || 5))) const maxPages = Math.min(20, Math.max(1, Number(config.maxPages || sourcesConfig.maxPages || 5)))
const orderType = Number(config.orderType ?? sourcesConfig.orderType ?? 2) const orderType = Number(config.orderType ?? sourcesConfig.orderType ?? 2)
@@ -251,21 +251,15 @@ export async function listAdminKuaishouMatchSources(payload: JsonObject = {}) {
for (const row of recentOrderItemsResult.rows) { for (const row of recentOrderItemsResult.rows) {
const snapshot = safeParseJson(row.item_snapshot_json) const snapshot = safeParseJson(row.item_snapshot_json)
const ksc = safeParseJson(snapshot.kuaishouSendCode) const ksc = safeParseJson(snapshot.kuaishouSendCode)
const sellerId = normalizeKuaishouMatchId( const sellerId = normalizeKuaishouMatchId(ksc.sellerId || row.shop_id || row.platform)
ksc.sellerId || row.shop_id || row.platform,
)
const relItemId = normalizeKuaishouMatchId( const relItemId = normalizeKuaishouMatchId(
ksc.relItemId || row.sku_code || snapshot.goodsId || snapshot.goods_id, ksc.relItemId || row.sku_code || snapshot.goodsId || snapshot.goods_id,
) )
const itemTitle = String( const itemTitle = String(
ksc.itemTitle || snapshot.goodsName || snapshot.goods_name || row.sku_name || '', ksc.itemTitle || snapshot.goodsName || snapshot.goods_name || row.sku_name || '',
).trim() ).trim()
const relSkuId = normalizeKuaishouMatchId( const relSkuId = normalizeKuaishouMatchId(ksc.relSkuId || snapshot.spec || row.sku_code)
ksc.relSkuId || snapshot.spec || row.sku_code, const skuNick = String(ksc.skuNick || snapshot.spec || row.sku_name || '').trim()
)
const skuNick = String(
ksc.skuNick || snapshot.spec || row.sku_name || '',
).trim()
if (!sellerId || (!relItemId && !itemTitle)) continue if (!sellerId || (!relItemId && !itemTitle)) continue
@@ -62,12 +62,8 @@ export async function syncWorkerOrdersForSourceOrder(
const itemTitle = const itemTitle =
matchContext.itemTitle || matchContext.itemTitle ||
String(snapshot.goodsName || snapshot.goods_name || item.sku_name || '').trim() String(snapshot.goodsName || snapshot.goods_name || item.sku_name || '').trim()
const relSkuId = const relSkuId = matchContext.relSkuId || String(snapshot.spec || item.sku_code || '').trim()
matchContext.relSkuId || const skuNick = matchContext.skuNick || String(snapshot.spec || item.sku_name || '').trim()
String(snapshot.spec || item.sku_code || '').trim()
const skuNick =
matchContext.skuNick ||
String(snapshot.spec || item.sku_name || '').trim()
// Record product match diagnostics for all platform orders (including PDD) // Record product match diagnostics for all platform orders (including PDD)
if (sellerId || relItemId || itemTitle) { if (sellerId || relItemId || itemTitle) {
@@ -1,7 +1,7 @@
import { APP_CONFIG_KEYS } from "../../config/app-config-keys.js" import { APP_CONFIG_KEYS } from '../../config/app-config-keys.js'
import type { JsonObject } from "../../types/json.js" import type { JsonObject } from '../../types/json.js'
import { readAppConfigEntry, saveAppConfigEntry } from "../config/app-config-store.js" import { readAppConfigEntry, saveAppConfigEntry } from '../config/app-config-store.js'
import { pruneWorkProductMatchLogs } from "../../repositories/worker-platform/product-match-repo.js" import { pruneWorkProductMatchLogs } from '../../repositories/worker-platform/product-match-repo.js'
export type WorkerProductMatchConfig = { export type WorkerProductMatchConfig = {
legacyFallbackEnabled: boolean legacyFallbackEnabled: boolean
@@ -50,7 +50,7 @@ export function normalizeWorkerProductMatchConfig(rawValue: unknown): WorkerProd
return { return {
// 默认关闭旧规则,避免大标题中的公共词触发错误接单。 // 默认关闭旧规则,避免大标题中的公共词触发错误接单。
legacyFallbackEnabled: legacyFallbackEnabled:
typeof source.legacyFallbackEnabled === "boolean" ? source.legacyFallbackEnabled : false, typeof source.legacyFallbackEnabled === 'boolean' ? source.legacyFallbackEnabled : false,
// 匹配日志保留上限条数,默认 10000 条,0 为不限 // 匹配日志保留上限条数,默认 10000 条,0 为不限
maxMatchLogs: Number.isInteger(maxLogs) && maxLogs >= 0 ? maxLogs : 10000, maxMatchLogs: Number.isInteger(maxLogs) && maxLogs >= 0 ? maxLogs : 10000,
// 匹配日志保留天数,默认 30 天,0 为不限 // 匹配日志保留天数,默认 30 天,0 为不限
@@ -60,5 +60,5 @@ export function normalizeWorkerProductMatchConfig(rawValue: unknown): WorkerProd
} }
function isPlainObject(value: unknown): value is JsonObject { function isPlainObject(value: unknown): value is JsonObject {
return Object.prototype.toString.call(value) === "[object Object]" return Object.prototype.toString.call(value) === '[object Object]'
} }
+4 -4
View File
@@ -14,10 +14,10 @@ export function randomId(prefix: string, bytes = 6): string {
*/ */
export function generateWorkOrderNo(date: Date = new Date()): string { export function generateWorkOrderNo(date: Date = new Date()): string {
const yy = String(date.getFullYear()).slice(-2) const yy = String(date.getFullYear()).slice(-2)
const mm = String(date.getMonth() + 1).padStart(2, "0") const mm = String(date.getMonth() + 1).padStart(2, '0')
const dd = String(date.getDate()).padStart(2, "0") const dd = String(date.getDate()).padStart(2, '0')
const hh = String(date.getHours()).padStart(2, "0") const hh = String(date.getHours()).padStart(2, '0')
const min = String(date.getMinutes()).padStart(2, "0") const min = String(date.getMinutes()).padStart(2, '0')
const rand = Math.floor(1000 + Math.random() * 9000) const rand = Math.floor(1000 + Math.random() * 9000)
return `WO${yy}${mm}${dd}${hh}${min}${rand}` return `WO${yy}${mm}${dd}${hh}${min}${rand}`
} }