@@ -26,6 +26,7 @@ import {
|
||||
loadStorePrimaryBank,
|
||||
loadStorePrimaryBanksMap,
|
||||
loadWineryBankConfig,
|
||||
formatWecomBankAccount,
|
||||
} from '../../common/store/store-bank.util';
|
||||
|
||||
function generateBillNo(prefix: string) {
|
||||
@@ -62,6 +63,14 @@ function round2(n: number) {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
const BILL_DIGEST_MAX_LINES = 15;
|
||||
|
||||
function capBillSummary(lines: string[]): string {
|
||||
if (!lines.length) return '无';
|
||||
if (lines.length <= BILL_DIGEST_MAX_LINES) return lines.join('\n');
|
||||
return `${lines.slice(0, BILL_DIGEST_MAX_LINES).join('\n')}\n…等共 ${lines.length} 笔`;
|
||||
}
|
||||
|
||||
function getStoreWithdrawDailyLimit(): number {
|
||||
const raw = process.env.STORE_WITHDRAW_DAILY_LIMIT;
|
||||
const n = raw != null && raw !== '' ? Number(raw) : DEFAULT_STORE_WITHDRAW_DAILY_LIMIT;
|
||||
@@ -95,6 +104,59 @@ export class SettlementService {
|
||||
private readonly wecomPush: WecomMessagePushService,
|
||||
) {}
|
||||
|
||||
private notifyPartnerBillDigest(
|
||||
period: string,
|
||||
rows: Array<{
|
||||
label: string;
|
||||
amount: number;
|
||||
bankAccountName?: string | null;
|
||||
bankBranch?: string | null;
|
||||
bankAccountNo?: string | null;
|
||||
}>,
|
||||
) {
|
||||
if (!rows.length) return;
|
||||
const lines = rows.map(
|
||||
(r) =>
|
||||
`${r.label} ¥${Number(r.amount).toFixed(2)} ${formatWecomBankAccount(r)}`,
|
||||
);
|
||||
void this.wecomPush.dispatchEvent(
|
||||
'finance.partner_bill',
|
||||
{
|
||||
period,
|
||||
billCount: String(rows.length),
|
||||
billSummary: capBillSummary(lines),
|
||||
},
|
||||
{ handlePath: '/finance/partner-bills' },
|
||||
);
|
||||
}
|
||||
|
||||
private notifyLogisticsBillDigest(
|
||||
period: string,
|
||||
rows: Array<{
|
||||
label: string;
|
||||
amount: number;
|
||||
bankAccountName?: string | null;
|
||||
bankName?: string | null;
|
||||
bankBranch?: string | null;
|
||||
bankAccountNo?: string | null;
|
||||
}>,
|
||||
) {
|
||||
if (!rows.length) return;
|
||||
const lines = rows.map(
|
||||
(r) =>
|
||||
`${r.label} ¥${Number(r.amount).toFixed(2)} ${formatWecomBankAccount(r)}`,
|
||||
);
|
||||
void this.wecomPush.dispatchEvent(
|
||||
'finance.logistics_bill',
|
||||
{
|
||||
period,
|
||||
billCount: String(rows.length),
|
||||
billSummary: capBillSummary(lines),
|
||||
},
|
||||
{ handlePath: '/finance/logistics-bills' },
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Store payout (line) ─────────────────────────────
|
||||
|
||||
async createStorePayout(
|
||||
@@ -584,6 +646,27 @@ export class SettlementService {
|
||||
},
|
||||
});
|
||||
|
||||
const [store, bank] = await Promise.all([
|
||||
this.prisma.store.findUnique({
|
||||
where: { id: row.storeId },
|
||||
select: { name: true },
|
||||
}),
|
||||
loadStorePrimaryBank(this.prisma, row.storeId),
|
||||
]);
|
||||
void this.wecomPush.dispatchEvent(
|
||||
'store.withdraw_approved',
|
||||
{
|
||||
storeName: store?.name || String(row.storeId),
|
||||
withdrawNo: row.withdrawNo,
|
||||
amount: Number(row.amount).toFixed(2),
|
||||
bankAccount: formatWecomBankAccount(bank),
|
||||
storeId: row.storeId.toString(),
|
||||
},
|
||||
{
|
||||
handlePath: `/finance/store-bills?kind=WITHDRAW&status=PAID&storeId=${row.storeId.toString()}`,
|
||||
},
|
||||
);
|
||||
|
||||
return serializeBigInt(updated);
|
||||
}
|
||||
|
||||
@@ -651,7 +734,7 @@ export class SettlementService {
|
||||
);
|
||||
this.alert.notify({
|
||||
level: 'P1',
|
||||
category: 'finance',
|
||||
category: 'settlement',
|
||||
title: '门店提现超时未审',
|
||||
detail: [
|
||||
`待审 ${summary.pendingCount} 笔,超时 ${summary.overdueCount} 笔,超时金额 ¥${summary.overdueAmount.toFixed(2)}`,
|
||||
@@ -847,7 +930,7 @@ export class SettlementService {
|
||||
withdrawItem: { is: null },
|
||||
status: 'PENDING',
|
||||
},
|
||||
include: { store: { select: { id: true, settlementRate: true } } },
|
||||
include: { store: { select: { id: true, name: true, settlementRate: true } } },
|
||||
});
|
||||
|
||||
const byStore = new Map<string, typeof payouts>();
|
||||
@@ -860,8 +943,10 @@ export class SettlementService {
|
||||
|
||||
let created = 0;
|
||||
let skipped = 0;
|
||||
const createdBills: Array<{ storeId: bigint; storeName: string; amount: number }> = [];
|
||||
for (const [storeIdStr, list] of byStore) {
|
||||
const storeId = BigInt(storeIdStr);
|
||||
const storeName = list[0]?.store?.name || storeIdStr;
|
||||
const existing = await this.prisma.storeBill.findUnique({
|
||||
where: { storeId_billDate: { storeId, billDate } },
|
||||
});
|
||||
@@ -873,13 +958,14 @@ export class SettlementService {
|
||||
const redeemAmount = round2(list.reduce((s, p) => s + Number(p.redeemAmount), 0));
|
||||
const payoutAmount = round2(list.reduce((s, p) => s + Number(p.payoutAmount), 0));
|
||||
const rate = Number(list[0].settlementRate);
|
||||
const updatedTotal = round2(Number(existing.payoutAmount) + payoutAmount);
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.storeBill.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
redeemCount: existing.redeemCount + list.length,
|
||||
redeemAmount: round2(Number(existing.redeemAmount) + redeemAmount),
|
||||
payoutAmount: round2(Number(existing.payoutAmount) + payoutAmount),
|
||||
payoutAmount: updatedTotal,
|
||||
settlementRate: rate,
|
||||
},
|
||||
});
|
||||
@@ -889,6 +975,7 @@ export class SettlementService {
|
||||
});
|
||||
});
|
||||
created += 1;
|
||||
createdBills.push({ storeId, storeName, amount: updatedTotal });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -914,9 +1001,31 @@ export class SettlementService {
|
||||
});
|
||||
});
|
||||
created += 1;
|
||||
createdBills.push({ storeId, storeName, amount: payoutAmount });
|
||||
}
|
||||
|
||||
return { billDate: billDate.toISOString().slice(0, 10), created, skipped, payoutLinked: payouts.length };
|
||||
const period = billDate.toISOString().slice(0, 10);
|
||||
if (createdBills.length) {
|
||||
const banks = await loadStorePrimaryBanksMap(
|
||||
this.prisma,
|
||||
createdBills.map((b) => b.storeId),
|
||||
);
|
||||
const lines = createdBills.map(
|
||||
(b) =>
|
||||
`${b.storeName} ¥${b.amount.toFixed(2)} ${formatWecomBankAccount(banks.get(b.storeId.toString()) ?? null)}`,
|
||||
);
|
||||
void this.wecomPush.dispatchEvent(
|
||||
'finance.store_bill',
|
||||
{
|
||||
period,
|
||||
billCount: String(createdBills.length),
|
||||
billSummary: capBillSummary(lines),
|
||||
},
|
||||
{ handlePath: '/finance/store-bills?kind=T1_BILL' },
|
||||
);
|
||||
}
|
||||
|
||||
return { billDate: period, created, skipped, payoutLinked: payouts.length };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1360,17 +1469,43 @@ export class SettlementService {
|
||||
async generateAllPartnerBills(body: { year: number; month: number }) {
|
||||
const partners = await this.prisma.partnerAccount.findMany({
|
||||
where: { isPrimary: 1, status: 'ACTIVE' },
|
||||
select: { id: true, companyName: true },
|
||||
select: {
|
||||
id: true,
|
||||
companyName: true,
|
||||
name: true,
|
||||
bankAccountName: true,
|
||||
bankBranch: true,
|
||||
bankAccountNo: true,
|
||||
},
|
||||
});
|
||||
const results: Array<{ partnerId: string; companyName: string; ok: boolean; message?: string }> = [];
|
||||
const created: Array<{
|
||||
label: string;
|
||||
amount: number;
|
||||
bankAccountName: string | null;
|
||||
bankBranch: string | null;
|
||||
bankAccountNo: string | null;
|
||||
}> = [];
|
||||
for (const p of partners) {
|
||||
try {
|
||||
await this.generatePartnerBill({
|
||||
partnerId: p.id.toString(),
|
||||
year: body.year,
|
||||
month: body.month,
|
||||
});
|
||||
const bill = await this.generatePartnerBill(
|
||||
{
|
||||
partnerId: p.id.toString(),
|
||||
year: body.year,
|
||||
month: body.month,
|
||||
},
|
||||
{ notify: false },
|
||||
);
|
||||
results.push({ partnerId: p.id.toString(), companyName: p.companyName ?? '', ok: true });
|
||||
const label =
|
||||
[p.companyName?.trim(), p.name?.trim()].filter(Boolean).join(' · ') || p.id.toString();
|
||||
created.push({
|
||||
label,
|
||||
amount: Number(bill.totalAmount),
|
||||
bankAccountName: p.bankAccountName,
|
||||
bankBranch: p.bankBranch,
|
||||
bankAccountNo: p.bankAccountNo,
|
||||
});
|
||||
} catch (e) {
|
||||
results.push({
|
||||
partnerId: p.id.toString(),
|
||||
@@ -1380,6 +1515,10 @@ export class SettlementService {
|
||||
});
|
||||
}
|
||||
}
|
||||
this.notifyPartnerBillDigest(
|
||||
`${body.year}-${String(body.month).padStart(2, '0')}`,
|
||||
created,
|
||||
);
|
||||
return {
|
||||
total: partners.length,
|
||||
success: results.filter((r) => r.ok).length,
|
||||
@@ -1403,7 +1542,10 @@ export class SettlementService {
|
||||
return serializeBigInt(bill);
|
||||
}
|
||||
|
||||
async generatePartnerBill(body: { partnerId: string; year: number; month: number }) {
|
||||
async generatePartnerBill(
|
||||
body: { partnerId: string; year: number; month: number },
|
||||
opts?: { notify?: boolean },
|
||||
) {
|
||||
const partnerAccountId = BigInt(body.partnerId);
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const periodStart = new Date(body.year, body.month - 1, 1);
|
||||
@@ -1485,6 +1627,24 @@ export class SettlementService {
|
||||
},
|
||||
});
|
||||
|
||||
if (opts?.notify !== false) {
|
||||
const label =
|
||||
[primary.companyName?.trim(), primary.name?.trim()].filter(Boolean).join(' · ') ||
|
||||
primary.id.toString();
|
||||
this.notifyPartnerBillDigest(
|
||||
`${body.year}-${String(body.month).padStart(2, '0')}`,
|
||||
[
|
||||
{
|
||||
label,
|
||||
amount: totalAmount,
|
||||
bankAccountName: primary.bankAccountName,
|
||||
bankBranch: primary.bankBranch,
|
||||
bankAccountNo: primary.bankAccountNo,
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return serializeBigInt(bill);
|
||||
}
|
||||
|
||||
@@ -1775,8 +1935,21 @@ export class SettlementService {
|
||||
return header;
|
||||
});
|
||||
|
||||
const period = billDate.toISOString().slice(0, 10);
|
||||
const wineryBank = await loadWineryBankConfig(this.prisma);
|
||||
void this.wecomPush.dispatchEvent(
|
||||
'finance.winery_bill',
|
||||
{
|
||||
period,
|
||||
amount: wineryAmount.toFixed(2),
|
||||
orderCount: String(orders.length),
|
||||
bankAccount: formatWecomBankAccount(wineryBank),
|
||||
},
|
||||
{ handlePath: '/finance/winery-bills' },
|
||||
);
|
||||
|
||||
return serializeBigInt({
|
||||
billDate: billDate.toISOString().slice(0, 10),
|
||||
billDate: period,
|
||||
skipped: false,
|
||||
bill,
|
||||
});
|
||||
@@ -1997,14 +2170,25 @@ export class SettlementService {
|
||||
message?: string;
|
||||
billId?: string;
|
||||
}> = [];
|
||||
const created: Array<{
|
||||
label: string;
|
||||
amount: number;
|
||||
bankAccountName: string | null;
|
||||
bankName: string | null;
|
||||
bankBranch: string | null;
|
||||
bankAccountNo: string | null;
|
||||
}> = [];
|
||||
|
||||
for (const p of providers) {
|
||||
try {
|
||||
const bill = await this.generateLogisticsBill({
|
||||
providerId: p.id.toString(),
|
||||
year: body.year,
|
||||
month: body.month,
|
||||
});
|
||||
const bill = await this.generateLogisticsBill(
|
||||
{
|
||||
providerId: p.id.toString(),
|
||||
year: body.year,
|
||||
month: body.month,
|
||||
},
|
||||
{ notify: false },
|
||||
);
|
||||
results.push({
|
||||
providerId: p.id.toString(),
|
||||
providerCode: p.code,
|
||||
@@ -2019,6 +2203,16 @@ export class SettlementService {
|
||||
: String(bill.bill.id)
|
||||
: undefined,
|
||||
});
|
||||
if (!bill.skipped && bill.bill) {
|
||||
created.push({
|
||||
label: p.name,
|
||||
amount: Number(bill.bill.logisticsAmount ?? 0),
|
||||
bankAccountName: p.bankAccountName,
|
||||
bankName: p.bankName,
|
||||
bankBranch: p.bankBranch,
|
||||
bankAccountNo: p.bankAccountNo,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
results.push({
|
||||
providerId: p.id.toString(),
|
||||
@@ -2030,6 +2224,11 @@ export class SettlementService {
|
||||
}
|
||||
}
|
||||
|
||||
this.notifyLogisticsBillDigest(
|
||||
`${body.year}-${String(body.month).padStart(2, '0')}`,
|
||||
created,
|
||||
);
|
||||
|
||||
return {
|
||||
total: providers.length,
|
||||
success: results.filter((r) => r.ok).length,
|
||||
@@ -2038,7 +2237,10 @@ export class SettlementService {
|
||||
};
|
||||
}
|
||||
|
||||
async generateLogisticsBill(body: { providerId: string; year: number; month: number }) {
|
||||
async generateLogisticsBill(
|
||||
body: { providerId: string; year: number; month: number },
|
||||
opts?: { notify?: boolean },
|
||||
) {
|
||||
const fulfillmentProviderId = BigInt(body.providerId);
|
||||
const provider = await this.prisma.fulfillmentProvider.findUnique({
|
||||
where: { id: fulfillmentProviderId },
|
||||
@@ -2190,6 +2392,22 @@ export class SettlementService {
|
||||
return header;
|
||||
});
|
||||
|
||||
if (opts?.notify !== false) {
|
||||
this.notifyLogisticsBillDigest(
|
||||
`${body.year}-${String(body.month).padStart(2, '0')}`,
|
||||
[
|
||||
{
|
||||
label: provider.name,
|
||||
amount: Number(bill.logisticsAmount),
|
||||
bankAccountName: provider.bankAccountName,
|
||||
bankName: provider.bankName,
|
||||
bankBranch: provider.bankBranch,
|
||||
bankAccountNo: provider.bankAccountNo,
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
skipped: false,
|
||||
bill: serializeBigInt(bill),
|
||||
|
||||
Reference in New Issue
Block a user