feat(M08-B): 接入保洁微信转账适配器
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
import type { RowDataPacket } from 'mysql2/promise';
|
||||
import type { MySqlPool } from '../db/mysql.js';
|
||||
import {
|
||||
WechatPayClient,
|
||||
WechatPayError,
|
||||
type WechatPayCredential
|
||||
} from '../payments/wechat-pay-client.js';
|
||||
import {
|
||||
CleaningTaskError,
|
||||
type CleaningActor,
|
||||
type CleaningTaskRepository
|
||||
} from './cleaning-task-repository.js';
|
||||
|
||||
interface SettlementPayoutRow extends RowDataPacket {
|
||||
id: string;
|
||||
settlementNo: string;
|
||||
cleanerUserId: string;
|
||||
storeId: string | null;
|
||||
status: 'DRAFT' | 'CONFIRMED' | 'PAID' | 'CANCELLED';
|
||||
totalRewardCents: number;
|
||||
payoutReference: string;
|
||||
payoutState: string;
|
||||
}
|
||||
|
||||
interface AccountRow extends RowDataPacket {
|
||||
id: string;
|
||||
platformAppId: string | null;
|
||||
storeId: string | null;
|
||||
merchantId: string;
|
||||
credentialRef: string;
|
||||
authorizationStatus: string;
|
||||
}
|
||||
|
||||
interface IdentityRow extends RowDataPacket {
|
||||
openid: string;
|
||||
}
|
||||
|
||||
export class CleaningPayoutError extends Error {
|
||||
constructor(public readonly code: string, message = code) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export class CleaningPayoutService {
|
||||
constructor(
|
||||
private readonly pool: MySqlPool,
|
||||
private readonly repository: Pick<CleaningTaskRepository,
|
||||
'markSettlementPaid' | 'recordSettlementPayoutFailure' | 'recordSettlementPayoutPending'>,
|
||||
private readonly client: WechatPayClient,
|
||||
private readonly credentials: ReadonlyMap<string, WechatPayCredential>,
|
||||
private readonly mockEnabled: boolean
|
||||
) {}
|
||||
|
||||
async executeWechatTransfer(input: CleaningActor & {
|
||||
settlementId: string;
|
||||
mode: 'API' | 'MOCK';
|
||||
note?: string;
|
||||
}) {
|
||||
const settlement = await this.loadSettlement(input.tenantId, input.settlementId);
|
||||
if (settlement.status === 'PAID') {
|
||||
return { settlement, idempotent: true, transferState: 'SUCCESS' };
|
||||
}
|
||||
if (settlement.status !== 'CONFIRMED') {
|
||||
throw new CleaningPayoutError('CLEANING_PAYOUT_SETTLEMENT_NOT_CONFIRMED');
|
||||
}
|
||||
if (Number(settlement.totalRewardCents) <= 0) {
|
||||
throw new CleaningPayoutError('CLEANING_PAYOUT_AMOUNT_INVALID');
|
||||
}
|
||||
if (input.mode === 'MOCK' && !this.mockEnabled) {
|
||||
throw new CleaningPayoutError('CLEANING_PAYOUT_MOCK_DISABLED');
|
||||
}
|
||||
const account = await this.resolveCollectionAccount(input.tenantId, settlement.storeId);
|
||||
if (account.authorizationStatus !== 'AUTHORIZED') {
|
||||
throw new CleaningPayoutError('CLEANING_PAYOUT_ACCOUNT_NOT_AUTHORIZED');
|
||||
}
|
||||
const credential = this.resolveCredential(account.credentialRef);
|
||||
if (!credential) throw new CleaningPayoutError('WECHAT_CREDENTIAL_NOT_CONFIGURED');
|
||||
if (credential.merchantId !== account.merchantId) {
|
||||
throw new CleaningPayoutError('CLEANING_PAYOUT_MERCHANT_MISMATCH');
|
||||
}
|
||||
const outBillNo = normalizeOutBillNo(settlement.settlementNo, settlement.id);
|
||||
if (input.mode === 'MOCK') {
|
||||
const paid = await this.repository.markSettlementPaid({
|
||||
...input,
|
||||
payoutChannel: 'WECHAT_TRANSFER_MOCK',
|
||||
payoutReference: outBillNo,
|
||||
note: input.note
|
||||
});
|
||||
return { settlement: paid, idempotent: false, transferState: 'SUCCESS' };
|
||||
}
|
||||
const openid = await this.resolveCleanerOpenid(
|
||||
input.tenantId,
|
||||
account.platformAppId,
|
||||
settlement.cleanerUserId
|
||||
);
|
||||
const sceneId = credential.transferSceneId;
|
||||
if (!sceneId) throw new CleaningPayoutError('WECHAT_TRANSFER_SCENE_NOT_CONFIGURED');
|
||||
try {
|
||||
const result = await this.client.createMerchantTransfer(credential, {
|
||||
outBillNo,
|
||||
openid,
|
||||
amountCents: Number(settlement.totalRewardCents),
|
||||
remark: `Cleaning settlement ${settlement.id}`,
|
||||
sceneId,
|
||||
notifyUrl: credential.transferNotifyUrl || undefined,
|
||||
reportInfos: credential.transferSceneReportInfos ?? []
|
||||
});
|
||||
if (result.state === 'SUCCESS') {
|
||||
const paid = await this.repository.markSettlementPaid({
|
||||
...input,
|
||||
payoutChannel: 'WECHAT_TRANSFER',
|
||||
payoutReference: result.transferBillNo || result.outBillNo,
|
||||
note: input.note
|
||||
});
|
||||
return { settlement: paid, idempotent: false, transferState: result.state };
|
||||
}
|
||||
if (result.state === 'FAIL') {
|
||||
const failed = await this.repository.recordSettlementPayoutFailure({
|
||||
...input,
|
||||
payoutChannel: 'WECHAT_TRANSFER',
|
||||
payoutReference: result.transferBillNo || result.outBillNo,
|
||||
error: result.failReason || 'WECHAT_TRANSFER_FAILED',
|
||||
note: input.note
|
||||
});
|
||||
return { settlement: failed, idempotent: false, transferState: result.state };
|
||||
}
|
||||
const pending = await this.repository.recordSettlementPayoutPending({
|
||||
...input,
|
||||
payoutChannel: 'WECHAT_TRANSFER',
|
||||
payoutReference: result.transferBillNo || result.outBillNo,
|
||||
payoutState: result.state,
|
||||
payoutPackageInfo: result.packageInfo,
|
||||
note: input.note
|
||||
});
|
||||
return { settlement: pending, idempotent: false, transferState: result.state };
|
||||
} catch (error) {
|
||||
if (error instanceof WechatPayError) {
|
||||
await this.repository.recordSettlementPayoutFailure({
|
||||
...input,
|
||||
payoutChannel: 'WECHAT_TRANSFER',
|
||||
payoutReference: outBillNo,
|
||||
error: error.code,
|
||||
note: input.note
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async loadSettlement(tenantId: string, settlementId: string) {
|
||||
const [rows] = await this.pool.execute<SettlementPayoutRow[]>(
|
||||
`SELECT id, settlement_no AS settlementNo, cleaner_user_id AS cleanerUserId,
|
||||
store_id AS storeId, status, total_reward_cents AS totalRewardCents,
|
||||
payout_reference AS payoutReference, payout_state AS payoutState
|
||||
FROM qipai_cleaning_settlements
|
||||
WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL LIMIT 1`,
|
||||
[tenantId, settlementId]
|
||||
);
|
||||
if (!rows[0]) throw new CleaningTaskError('CLEANING_SETTLEMENT_NOT_FOUND');
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
private async resolveCollectionAccount(tenantId: string, storeId: string | null) {
|
||||
const [rows] = await this.pool.execute<AccountRow[]>(
|
||||
`SELECT id, platform_app_id AS platformAppId, store_id AS storeId,
|
||||
merchant_id AS merchantId, credential_ref AS credentialRef,
|
||||
authorization_status AS authorizationStatus
|
||||
FROM qipai_collection_accounts
|
||||
WHERE tenant_id = ? AND provider = 'WECHAT' AND enabled = 1
|
||||
AND (store_id IS NULL OR store_id <=> ?)
|
||||
ORDER BY (store_id IS NOT NULL) DESC, id DESC LIMIT 1`,
|
||||
[tenantId, storeId]
|
||||
);
|
||||
if (!rows[0]) throw new CleaningPayoutError('CLEANING_PAYOUT_ACCOUNT_NOT_FOUND');
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
private async resolveCleanerOpenid(tenantId: string, platformAppId: string | null, cleanerUserId: string) {
|
||||
const params: Array<string | number> = [tenantId, cleanerUserId];
|
||||
const platformFilter = platformAppId ? 'AND platform_app_id = ?' : '';
|
||||
if (platformAppId) params.push(platformAppId);
|
||||
const [rows] = await this.pool.execute<IdentityRow[]>(
|
||||
`SELECT openid FROM qipai_user_identities
|
||||
WHERE tenant_id = ? AND user_id = ? AND provider = 'WECHAT_MINIAPP'
|
||||
AND deleted_at IS NULL ${platformFilter}
|
||||
ORDER BY updated_at DESC, id DESC LIMIT 1`,
|
||||
params
|
||||
);
|
||||
if (!rows[0]?.openid) throw new CleaningPayoutError('WECHAT_OPENID_NOT_FOUND');
|
||||
return rows[0].openid;
|
||||
}
|
||||
|
||||
private resolveCredential(reference: string) {
|
||||
return this.credentials.get(reference)
|
||||
?? this.credentials.get(reference.replace(/^env:/, ''));
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeOutBillNo(settlementNo: string, settlementId: string) {
|
||||
const normalized = settlementNo.replace(/[^A-Za-z0-9_-]/g, '');
|
||||
return (normalized || `CLP${settlementId}`).slice(0, 32);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ export const cleaningTaskStatuses = [
|
||||
'REJECTED', 'EXEMPT', 'SETTLED', 'CANCELLED'
|
||||
] as const;
|
||||
export type CleaningTaskStatus = typeof cleaningTaskStatuses[number];
|
||||
export type CleaningSettlementStatus = 'DRAFT' | 'CONFIRMED' | 'PAID' | 'CANCELLED';
|
||||
|
||||
export class CleaningTaskError extends Error {
|
||||
constructor(public readonly code: string) { super(code); }
|
||||
@@ -79,7 +80,7 @@ interface SettlementRow extends RowDataPacket {
|
||||
cleanerName: string;
|
||||
storeId: string | null;
|
||||
storeName: string | null;
|
||||
status: 'DRAFT' | 'CONFIRMED' | 'PAID' | 'CANCELLED';
|
||||
status: CleaningSettlementStatus;
|
||||
taskCount: number;
|
||||
totalRewardCents: number;
|
||||
periodStart: Date | null;
|
||||
@@ -89,6 +90,8 @@ interface SettlementRow extends RowDataPacket {
|
||||
paidAt: Date | null;
|
||||
payoutChannel: string;
|
||||
payoutReference: string;
|
||||
payoutState: string;
|
||||
payoutPackageInfo: string;
|
||||
payoutError: string;
|
||||
note: string;
|
||||
createdAt: Date;
|
||||
@@ -321,7 +324,7 @@ export class CleaningTaskRepository {
|
||||
}
|
||||
|
||||
async listSettlements(input: CleaningActor & {
|
||||
page: number; pageSize: number; status?: 'DRAFT' | 'CONFIRMED' | 'PAID' | 'CANCELLED';
|
||||
page: number; pageSize: number; status?: CleaningSettlementStatus;
|
||||
}) {
|
||||
this.assertSettlement(input.access, 'read');
|
||||
const where = [
|
||||
@@ -348,6 +351,7 @@ export class CleaningTaskRepository {
|
||||
s.period_start AS periodStart, s.period_end AS periodEnd,
|
||||
s.paid_by AS paidBy, s.confirmed_at AS confirmedAt, s.paid_at AS paidAt,
|
||||
s.payout_channel AS payoutChannel, s.payout_reference AS payoutReference,
|
||||
s.payout_state AS payoutState, s.payout_package_info AS payoutPackageInfo,
|
||||
s.payout_error AS payoutError,
|
||||
s.note, s.created_at AS createdAt
|
||||
FROM qipai_cleaning_settlements s
|
||||
@@ -478,7 +482,8 @@ export class CleaningTaskRepository {
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_cleaning_settlements s
|
||||
SET s.status = 'PAID', s.paid_by = ?, s.paid_at = UTC_TIMESTAMP(3),
|
||||
s.payout_channel = ?, s.payout_reference = ?, s.payout_error = '',
|
||||
s.payout_channel = ?, s.payout_reference = ?, s.payout_state = 'SUCCESS',
|
||||
s.payout_package_info = '', s.payout_error = '',
|
||||
s.note = CASE WHEN ? = '' THEN s.note ELSE ? END
|
||||
WHERE s.tenant_id = ? AND s.id = ? AND s.status = 'CONFIRMED' AND s.deleted_at IS NULL
|
||||
AND ${storeScopeSql(input.access, 'COALESCE(s.store_id, 0)')}`,
|
||||
@@ -501,7 +506,7 @@ export class CleaningTaskRepository {
|
||||
`UPDATE qipai_cleaning_settlements s
|
||||
SET s.payout_channel = CASE WHEN ? = '' THEN s.payout_channel ELSE ? END,
|
||||
s.payout_reference = CASE WHEN ? = '' THEN s.payout_reference ELSE ? END,
|
||||
s.payout_error = ?,
|
||||
s.payout_state = 'FAIL', s.payout_package_info = '', s.payout_error = ?,
|
||||
s.note = CASE WHEN ? = '' THEN s.note ELSE ? END
|
||||
WHERE s.tenant_id = ? AND s.id = ? AND s.status = 'CONFIRMED' AND s.deleted_at IS NULL
|
||||
AND ${storeScopeSql(input.access, 'COALESCE(s.store_id, 0)')}`,
|
||||
@@ -517,6 +522,30 @@ export class CleaningTaskRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async recordSettlementPayoutPending(input: CleaningActor & {
|
||||
settlementId: string; payoutChannel: string; payoutReference: string;
|
||||
payoutState: string; payoutPackageInfo?: string; note?: string;
|
||||
}) {
|
||||
this.assertSettlement(input.access, 'write');
|
||||
return this.transaction(async (connection) => {
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_cleaning_settlements s
|
||||
SET s.payout_channel = ?, s.payout_reference = ?, s.payout_state = ?,
|
||||
s.payout_package_info = ?, s.payout_error = '',
|
||||
s.note = CASE WHEN ? = '' THEN s.note ELSE ? END
|
||||
WHERE s.tenant_id = ? AND s.id = ? AND s.status = 'CONFIRMED' AND s.deleted_at IS NULL
|
||||
AND ${storeScopeSql(input.access, 'COALESCE(s.store_id, 0)')}`,
|
||||
[
|
||||
input.payoutChannel, input.payoutReference, input.payoutState.slice(0, 32),
|
||||
(input.payoutPackageInfo ?? '').slice(0, 1024),
|
||||
input.note ?? '', input.note ?? '', input.tenantId, input.settlementId
|
||||
]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new CleaningTaskError('CLEANING_SETTLEMENT_STATUS_CONFLICT');
|
||||
return this.getSettlement(connection, input.tenantId, input.settlementId);
|
||||
});
|
||||
}
|
||||
|
||||
async reclaimTimeouts(input: CleaningActor & { olderThanMinutes: number; limit: number }) {
|
||||
this.assertCleaner(input.access, 'write');
|
||||
const [rows] = await this.pool.execute<RowDataPacket[]>(
|
||||
@@ -921,6 +950,7 @@ export class CleaningTaskRepository {
|
||||
s.period_start AS periodStart, s.period_end AS periodEnd,
|
||||
s.paid_by AS paidBy, s.confirmed_at AS confirmedAt, s.paid_at AS paidAt,
|
||||
s.payout_channel AS payoutChannel, s.payout_reference AS payoutReference,
|
||||
s.payout_state AS payoutState, s.payout_package_info AS payoutPackageInfo,
|
||||
s.payout_error AS payoutError,
|
||||
s.note, s.created_at AS createdAt
|
||||
FROM qipai_cleaning_settlements s
|
||||
@@ -1017,6 +1047,8 @@ function publicSettlement(row: SettlementRow) {
|
||||
paidAt: row.paidAt,
|
||||
payoutChannel: row.payoutChannel,
|
||||
payoutReference: row.payoutReference,
|
||||
payoutState: row.payoutState,
|
||||
payoutPackageInfo: row.payoutPackageInfo,
|
||||
payoutError: row.payoutError,
|
||||
note: row.note,
|
||||
createdAt: row.createdAt
|
||||
|
||||
@@ -19,6 +19,7 @@ const configSchema = z.object({
|
||||
QIPAI_TEST_PAYMENT_ENABLED: z.enum(['true', 'false']).default('false'),
|
||||
QIPAI_WECHAT_PAY_CREDENTIALS: z.string().default('{}'),
|
||||
QIPAI_PROFIT_SHARE_MOCK_ENABLED: z.enum(['true', 'false']).default('false'),
|
||||
QIPAI_CLEANING_PAYOUT_MOCK_ENABLED: z.enum(['true', 'false']).default('false'),
|
||||
QIPAI_THIRD_PARTY_CREDENTIALS: z.string().default('{}'),
|
||||
QIPAI_MQTT_URL: z.string().url().default('mqtt://101.42.38.246:1883'),
|
||||
QIPAI_MQTT_CLIENT_ID: z.string().min(1).max(128).default('qipai-backend'),
|
||||
@@ -74,7 +75,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env) {
|
||||
&& parsed.QIPAI_TEST_PAYMENT_ENABLED === 'true',
|
||||
wechatCredentialsJson: parsed.QIPAI_WECHAT_PAY_CREDENTIALS,
|
||||
profitShareMockEnabled: parsed.NODE_ENV !== 'production'
|
||||
&& parsed.QIPAI_PROFIT_SHARE_MOCK_ENABLED === 'true'
|
||||
&& parsed.QIPAI_PROFIT_SHARE_MOCK_ENABLED === 'true',
|
||||
cleaningPayoutMockEnabled: parsed.NODE_ENV !== 'production'
|
||||
&& parsed.QIPAI_CLEANING_PAYOUT_MOCK_ENABLED === 'true'
|
||||
},
|
||||
thirdParty: {
|
||||
credentialsJson: parsed.QIPAI_THIRD_PARTY_CREDENTIALS
|
||||
|
||||
@@ -48,7 +48,8 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.up.sql',
|
||||
'database/migrations/2026062626_m08b_cleaning_settlements.up.sql',
|
||||
'database/migrations/2026062627_m08b_cleaning_collaboration.up.sql',
|
||||
'database/migrations/2026062728_m08b_cleaning_payouts.up.sql'
|
||||
'database/migrations/2026062728_m08b_cleaning_payouts.up.sql',
|
||||
'database/migrations/2026062729_m08b_cleaning_transfer_state.up.sql'
|
||||
],
|
||||
verify: [
|
||||
'database/migrations/2026061601_m01b_core_schema.verify.sql',
|
||||
@@ -78,9 +79,11 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.verify.sql',
|
||||
'database/migrations/2026062626_m08b_cleaning_settlements.verify.sql',
|
||||
'database/migrations/2026062627_m08b_cleaning_collaboration.verify.sql',
|
||||
'database/migrations/2026062728_m08b_cleaning_payouts.verify.sql'
|
||||
'database/migrations/2026062728_m08b_cleaning_payouts.verify.sql',
|
||||
'database/migrations/2026062729_m08b_cleaning_transfer_state.verify.sql'
|
||||
],
|
||||
down: [
|
||||
'database/migrations/2026062729_m08b_cleaning_transfer_state.down.sql',
|
||||
'database/migrations/2026062728_m08b_cleaning_payouts.down.sql',
|
||||
'database/migrations/2026062627_m08b_cleaning_collaboration.down.sql',
|
||||
'database/migrations/2026062626_m08b_cleaning_settlements.down.sql',
|
||||
@@ -251,7 +254,8 @@ export async function executeMigrationPlan(
|
||||
2, 8, 4, 3, 1,
|
||||
2, 9, 5, 2, 1,
|
||||
1, 7, 5, 1,
|
||||
4, 1, 1, 1
|
||||
4, 1, 1, 1,
|
||||
2, 1, 1
|
||||
][index] ?? 1;
|
||||
if (!Array.isArray(result) || result.length < minimumRows) {
|
||||
throw new Error(
|
||||
|
||||
@@ -10,6 +10,9 @@ export interface WechatPayCredential {
|
||||
apiV3Key: string;
|
||||
platformCertificates: Record<string, string>;
|
||||
profitShareReceivers?: Record<string, string>;
|
||||
transferSceneId?: string;
|
||||
transferSceneReportInfos?: Array<{ infoType: string; infoContent: string }>;
|
||||
transferNotifyUrl?: string;
|
||||
}
|
||||
|
||||
export interface WechatPayTransport {
|
||||
@@ -173,6 +176,40 @@ export class WechatPayClient {
|
||||
});
|
||||
}
|
||||
|
||||
async createMerchantTransfer(
|
||||
credential: WechatPayCredential,
|
||||
input: {
|
||||
outBillNo: string;
|
||||
openid: string;
|
||||
amountCents: number;
|
||||
remark: string;
|
||||
sceneId: string;
|
||||
notifyUrl?: string;
|
||||
reportInfos: Array<{ infoType: string; infoContent: string }>;
|
||||
}
|
||||
) {
|
||||
const result = await this.apiRequest(credential, 'POST', '/v3/fund-app/mch-transfer/transfer-bills', {
|
||||
appid: credential.appId,
|
||||
out_bill_no: input.outBillNo,
|
||||
transfer_scene_id: input.sceneId,
|
||||
openid: input.openid,
|
||||
transfer_amount: input.amountCents,
|
||||
transfer_remark: input.remark.slice(0, 32),
|
||||
notify_url: input.notifyUrl,
|
||||
transfer_scene_report_infos: input.reportInfos.length > 0 ? input.reportInfos.map((item) => ({
|
||||
info_type: item.infoType.slice(0, 15),
|
||||
info_content: item.infoContent.slice(0, 32)
|
||||
})) : undefined
|
||||
});
|
||||
return {
|
||||
outBillNo: stringField(result, 'out_bill_no'),
|
||||
transferBillNo: optionalStringField(result, 'transfer_bill_no'),
|
||||
state: stringField(result, 'state'),
|
||||
failReason: optionalStringField(result, 'fail_reason'),
|
||||
packageInfo: optionalStringField(result, 'package_info')
|
||||
};
|
||||
}
|
||||
|
||||
verifyAndDecrypt(
|
||||
credential: WechatPayCredential,
|
||||
headers: WechatNotificationHeaders,
|
||||
@@ -279,7 +316,10 @@ export function parseWechatPayCredentials(value: string) {
|
||||
}
|
||||
return [reference, account];
|
||||
})
|
||||
) : {}
|
||||
) : {},
|
||||
transferSceneId: optionalStringField(item, 'transferSceneId'),
|
||||
transferSceneReportInfos: parseTransferReportInfos(item.transferSceneReportInfos),
|
||||
transferNotifyUrl: optionalStringField(item, 'transferNotifyUrl')
|
||||
});
|
||||
}
|
||||
return credentials;
|
||||
@@ -327,3 +367,17 @@ function optionalStringField(value: Record<string, unknown>, key: string) {
|
||||
const field = value[key];
|
||||
return typeof field === 'string' ? field : '';
|
||||
}
|
||||
|
||||
function parseTransferReportInfos(value: unknown) {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
return value.map((item) => {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
||||
throw new WechatPayError('WECHAT_TRANSFER_REPORT_INVALID');
|
||||
}
|
||||
const raw = item as Record<string, unknown>;
|
||||
return {
|
||||
infoType: stringField(raw, 'infoType'),
|
||||
infoContent: stringField(raw, 'infoContent')
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
type CleaningActor,
|
||||
type CleaningTaskRepository
|
||||
} from '../cleaning/cleaning-task-repository.js';
|
||||
import {
|
||||
CleaningPayoutError,
|
||||
type CleaningPayoutService
|
||||
} from '../cleaning/cleaning-payout-service.js';
|
||||
import { WechatPayError } from '../payments/wechat-pay-client.js';
|
||||
|
||||
const listSchema = z.object({
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
@@ -65,6 +70,10 @@ const settlementPayoutFailureSchema = z.object({
|
||||
error: z.string().trim().min(1).max(512),
|
||||
note: z.string().trim().max(512).optional()
|
||||
}).strict();
|
||||
const settlementWechatTransferSchema = z.object({
|
||||
mode: z.enum(['API', 'MOCK']).default('API'),
|
||||
note: z.string().trim().max(512).optional()
|
||||
}).strict();
|
||||
const reclaimSchema = z.object({
|
||||
olderThanMinutes: z.coerce.number().int().min(5).max(1440).default(60),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20)
|
||||
@@ -78,6 +87,7 @@ export interface CleaningRouteOptions {
|
||||
| 'recordSettlementPayoutFailure' | 'reclaimTimeouts'
|
||||
| 'assertCanUploadPhoto' | 'stats'>;
|
||||
mediaStorage?: MediaStorage;
|
||||
payoutService?: Pick<CleaningPayoutService, 'executeWechatTransfer'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
@@ -424,6 +434,29 @@ export async function registerCleaningRoutes(
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/admin-api/cleaning/settlements/:settlementId/wechat-transfer', async (request, reply) => {
|
||||
if (!options.payoutService) return reply.status(501).send({
|
||||
code: 'CLEANING_PAYOUT_UNAVAILABLE',
|
||||
message: 'Cleaning payout service is not configured.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
const params = settlementParamsSchema.safeParse(request.params);
|
||||
const body = settlementWechatTransferSchema.safeParse(request.body ?? {});
|
||||
if (!params.success || !body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.payoutService!.executeWechatTransfer({
|
||||
...actor,
|
||||
settlementId: params.data.settlementId,
|
||||
mode: body.data.mode,
|
||||
note: body.data.note
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function requireActor(
|
||||
@@ -474,11 +507,14 @@ async function handle(reply: FastifyReply, traceId: string, work: () => Promise<
|
||||
traceId
|
||||
});
|
||||
}
|
||||
if (!(error instanceof CleaningTaskError)) throw error;
|
||||
const statusCode = error.code === 'CLEANING_TASK_FORBIDDEN'
|
||||
|| error.code === 'CLEANING_SETTLEMENT_FORBIDDEN' ? 403 : 409;
|
||||
if (!(error instanceof CleaningTaskError)
|
||||
&& !(error instanceof CleaningPayoutError)
|
||||
&& !(error instanceof WechatPayError)) throw error;
|
||||
const code = error.code;
|
||||
const statusCode = code === 'CLEANING_TASK_FORBIDDEN'
|
||||
|| code === 'CLEANING_SETTLEMENT_FORBIDDEN' ? 403 : 409;
|
||||
return reply.status(statusCode).send({
|
||||
code: error.code,
|
||||
code,
|
||||
message: 'The cleaning task request cannot be completed.',
|
||||
traceId
|
||||
});
|
||||
|
||||
@@ -38,6 +38,7 @@ import { RechargeService } from './wallets/recharge-service.js';
|
||||
import { WalletLedgerService } from './wallets/wallet-ledger-service.js';
|
||||
import { MarketingBenefitService } from './wallets/marketing-benefit-service.js';
|
||||
import { CleaningTaskRepository } from './cleaning/cleaning-task-repository.js';
|
||||
import { CleaningPayoutService } from './cleaning/cleaning-payout-service.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const pool = createMySqlPool(config);
|
||||
@@ -50,6 +51,13 @@ const cleaningTaskRepository = new CleaningTaskRepository(pool);
|
||||
const paymentRepository = new PaymentRepository(pool, walletLedgerService, marketingBenefits);
|
||||
const wechatCredentials = parseWechatPayCredentials(config.payment.wechatCredentialsJson);
|
||||
const wechatPayClient = new WechatPayClient(new FetchWechatPayTransport());
|
||||
const cleaningPayoutService = new CleaningPayoutService(
|
||||
pool,
|
||||
cleaningTaskRepository,
|
||||
wechatPayClient,
|
||||
wechatCredentials,
|
||||
config.payment.cleaningPayoutMockEnabled
|
||||
);
|
||||
const thirdPartyCredentials = parseThirdPartyCredentials(config.thirdParty.credentialsJson);
|
||||
const iotMessages = new IotMessageService(pool);
|
||||
const mqtt = new MqttService(config.mqtt, undefined, (topic, payload) =>
|
||||
@@ -189,6 +197,7 @@ const app = await buildApp({
|
||||
},
|
||||
cleaning: {
|
||||
repository: cleaningTaskRepository,
|
||||
payoutService: cleaningPayoutService,
|
||||
mediaStorage: new MediaStorage(resolve(process.cwd(), 'shared', 'uploads')),
|
||||
authRepository,
|
||||
accessControl,
|
||||
|
||||
Reference in New Issue
Block a user