删除门店的多银行账户列表

This commit is contained in:
2026-09-08 14:23:00 +08:00
parent 253430b291
commit 8f25f823d5
22 changed files with 214 additions and 902 deletions
@@ -0,0 +1,5 @@
-- v4.0.18 修订:撤销门店多收款账户,打款改回门店结算资质(主账号 bank_account_*
-- 财务目录门店行改用 storeId,旧 STORE 备注按 store_bank_account.id 已失效
DROP TABLE IF EXISTS `store_bank_account`;
DELETE FROM `finance_bank_account_note` WHERE `owner_type` = 'STORE';
-20
View File
@@ -1609,7 +1609,6 @@ model Store {
packageChangeRequests StorePackageChangeRequest[]
infoChangeRequests StoreInfoChangeRequest[]
categoryLinks StoreCategoryLink[]
bankAccounts StoreBankAccount[]
@@index([cityId, status])
@@index([partnerAccountId])
@@ -1619,25 +1618,6 @@ model Store {
@@map("store_store")
}
/// 门店收款银行账户(一个门店可维护多个,is_default 为打款默认账户)
model StoreBankAccount {
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
storeId BigInt @map("store_id") @db.UnsignedBigInt
bankAccountName String @map("bank_account_name") @db.VarChar(64)
bankAccountNo String @map("bank_account_no") @db.VarChar(32)
bankBranch String? @map("bank_branch") @db.VarChar(128)
isDefault Int @default(0) @map("is_default") @db.TinyInt
status AccountStatus @default(ACTIVE)
sortOrder Int @default(0) @map("sort_order")
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
@@index([storeId, status])
@@map("store_bank_account")
}
/// Store visibility whitelist phones (match by bound user phone)
model StoreVisibilityPhone {
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
@@ -6,55 +6,10 @@ export type StoreBankAccountSnapshot = {
bankBranch: string | null;
};
export type StoreBankAccountRow = StoreBankAccountSnapshot & {
id: bigint;
storeId: bigint;
isDefault: boolean;
status: string;
sortOrder: number;
};
/** 门店收款账户列表(默认账户优先,其次 sortOrder/创建顺序) */
export async function loadStoreBankAccounts(
prisma: PrismaClient,
storeId: bigint,
): Promise<StoreBankAccountRow[]> {
const rows = await prisma.storeBankAccount.findMany({
where: { storeId, status: 'ACTIVE' },
orderBy: [{ isDefault: 'desc' }, { sortOrder: 'asc' }, { id: 'asc' }],
});
return rows.map((r) => ({
id: r.id,
storeId: r.storeId,
bankAccountName: r.bankAccountName,
bankAccountNo: r.bankAccountNo,
bankBranch: r.bankBranch,
isDefault: r.isDefault === 1,
status: r.status,
sortOrder: r.sortOrder,
}));
}
/**
* 门店默认收款账户:优先 is_default=1;否则第一个 ACTIVE;再退回旧主账号字段(兼容未迁移数据)
* 返回 null 表示无收款账户
* 门店结算资质银行账户:主账号(is_primary=1)字段;无主账号则取最早绑定账号
* 来源为门店详情「结算资质」(StoreAccount.bank_account_*),实时查库
*/
export async function loadStoreDefaultBank(
prisma: PrismaClient,
storeId: bigint,
): Promise<StoreBankAccountSnapshot | null> {
const accounts = await loadStoreBankAccounts(prisma, storeId);
if (accounts.length) {
const def = accounts.find((a) => a.isDefault) ?? accounts[0];
return {
bankAccountName: def.bankAccountName,
bankAccountNo: def.bankAccountNo,
bankBranch: def.bankBranch,
};
}
return loadStorePrimaryBank(prisma, storeId);
}
export async function loadStorePrimaryBank(
prisma: PrismaClient,
storeId: bigint,
@@ -80,6 +35,14 @@ export async function loadStorePrimaryBank(
return fallback?.storeAccount ?? null;
}
/** 打款/提现读结算资质(主账号银行字段) */
export async function loadStoreDefaultBank(
prisma: PrismaClient,
storeId: bigint,
): Promise<StoreBankAccountSnapshot | null> {
return loadStorePrimaryBank(prisma, storeId);
}
export async function loadStorePrimaryBanksMap(
prisma: PrismaClient,
storeIds: bigint[],
@@ -87,49 +50,28 @@ export async function loadStorePrimaryBanksMap(
const map = new Map<string, StoreBankAccountSnapshot>();
if (!storeIds.length) return map;
// 优先从门店多账户表读取默认账户
const accounts = await prisma.storeBankAccount.findMany({
where: { storeId: { in: storeIds }, status: 'ACTIVE' },
orderBy: [{ storeId: 'asc' }, { isDefault: 'desc' }, { sortOrder: 'asc' }, { id: 'asc' }],
});
const seenStoreIds = new Set<string>();
for (const a of accounts) {
const key = String(a.storeId);
if (map.has(key)) continue;
map.set(key, {
bankAccountName: a.bankAccountName,
bankAccountNo: a.bankAccountNo,
bankBranch: a.bankBranch,
});
seenStoreIds.add(key);
}
// 未迁移/无多账户的门店,回退旧主账号字段
const missingIds = storeIds.filter((id) => !seenStoreIds.has(String(id)));
if (missingIds.length) {
const bindings = await prisma.storeAccountStore.findMany({
where: { storeId: { in: missingIds } },
include: {
storeAccount: {
select: {
isPrimary: true,
bankAccountName: true,
bankAccountNo: true,
bankBranch: true,
},
const bindings = await prisma.storeAccountStore.findMany({
where: { storeId: { in: storeIds } },
include: {
storeAccount: {
select: {
isPrimary: true,
bankAccountName: true,
bankAccountNo: true,
bankBranch: true,
},
},
orderBy: [{ storeAccount: { isPrimary: 'desc' } }, { storeAccountId: 'asc' }],
},
orderBy: [{ storeAccount: { isPrimary: 'desc' } }, { storeAccountId: 'asc' }],
});
for (const binding of bindings) {
const key = String(binding.storeId);
if (map.has(key)) continue;
map.set(key, {
bankAccountName: binding.storeAccount.bankAccountName,
bankAccountNo: binding.storeAccount.bankAccountNo,
bankBranch: binding.storeAccount.bankBranch,
});
for (const binding of bindings) {
const key = String(binding.storeId);
if (map.has(key)) continue;
map.set(key, {
bankAccountName: binding.storeAccount.bankAccountName,
bankAccountNo: binding.storeAccount.bankAccountNo,
bankBranch: binding.storeAccount.bankBranch,
});
}
}
return map;
}
@@ -161,11 +161,20 @@ export class FinanceBankAccountService {
}
private async collectAll(): Promise<FinanceBankAccountDto[]> {
const [storeRows, partnerRows, logisticsRows, otherRows, notes, winery] = await Promise.all([
this.prisma.storeBankAccount.findMany({
where: { status: 'ACTIVE' },
include: { store: { select: { id: true, name: true, cityId: true, cityName: true } } },
orderBy: { id: 'asc' },
const [storeBindings, partnerRows, logisticsRows, otherRows, notes, winery] = await Promise.all([
this.prisma.storeAccountStore.findMany({
include: {
store: { select: { id: true, name: true, cityId: true, cityName: true } },
storeAccount: {
select: {
isPrimary: true,
bankAccountName: true,
bankAccountNo: true,
bankBranch: true,
},
},
},
orderBy: [{ storeAccount: { isPrimary: 'desc' } }, { storeAccountId: 'asc' }],
}),
this.prisma.partnerAccount.findMany({
where: { status: 'ACTIVE', parentAccountId: null, isPrimary: 1 },
@@ -202,23 +211,25 @@ export class FinanceBankAccountService {
const items: FinanceBankAccountDto[] = [];
for (const row of storeRows) {
const name = row.bankAccountName.trim();
const no = row.bankAccountNo.replace(/\s+/g, '');
const seenStores = new Set<string>();
for (const binding of storeBindings) {
const sourceId = binding.store.id.toString();
if (seenStores.has(sourceId)) continue;
seenStores.add(sourceId);
const name = binding.storeAccount.bankAccountName?.trim() ?? '';
const no = binding.storeAccount.bankAccountNo?.replace(/\s+/g, '') ?? '';
if (!name || !no) continue;
const sourceId = row.id.toString();
items.push({
id: `STORE:${sourceId}`,
type: 'STORE',
ownerName: row.store.name,
ownerId: row.store.id.toString(),
cityId: row.store.cityId.toString(),
cityName: row.store.cityName,
ownerName: binding.store.name,
ownerId: sourceId,
cityId: binding.store.cityId.toString(),
cityName: binding.store.cityName,
bankAccountName: name,
bankAccountNo: no,
bankBranch: row.bankBranch,
bankBranch: binding.storeAccount.bankBranch,
remark: noteMap.get(`STORE:${sourceId}`) ?? null,
isDefault: row.isDefault === 1,
editable: false,
});
}
@@ -32,10 +32,9 @@ function columnDefs(): ExportColumnDef<FinanceBankAccountDto>[] {
{ key: 'type', header: '类型', value: (r) => FINANCE_BANK_ACCOUNT_TYPE_LABELS[r.type] },
{ key: 'ownerName', header: '归属', value: (r) => r.ownerName },
{ key: 'cityName', header: '城市', value: (r) => r.cityName ?? '' },
{ key: 'bankAccountName', header: '户名', value: (r) => r.bankAccountName },
{ key: 'bankAccountName', header: '结算户名', value: (r) => r.bankAccountName },
{ key: 'bankAccountNo', header: '银行账号', value: (r) => r.bankAccountNo },
{ key: 'bankBranch', header: '开户行', value: (r) => r.bankBranch ?? '' },
{ key: 'isDefault', header: '默认', value: (r) => (r.type === 'STORE' ? (r.isDefault ? '是' : '否') : '') },
{ key: 'bankBranch', header: '开户行', value: (r) => r.bankBranch ?? '' },
{ key: 'remark', header: '备注', value: (r) => r.remark ?? '' },
];
}
@@ -43,7 +42,7 @@ function columnDefs(): ExportColumnDef<FinanceBankAccountDto>[] {
export async function buildFinanceBankAccountsXlsx(rows: FinanceBankAccountDto[]): Promise<Buffer> {
const cols = pickExportColumns(columnDefs());
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('银行账户');
const sheet = workbook.addWorksheet('全部银行账户');
sheet.addRow(cols.map((c) => c.header));
for (const row of rows) {
sheet.addRow(cols.map((c) => c.value(row)));
@@ -66,7 +65,7 @@ export async function buildFinanceBankAccountsPdf(rows: FinanceBankAccountDto[])
doc.on('end', () => resolve(Buffer.concat(chunks)));
doc.on('error', reject);
doc.font(fontPath);
doc.fontSize(12).text('银行账户');
doc.fontSize(12).text('全部银行账户');
doc.moveDown(0.4);
doc.fontSize(9).text(cols.map((c) => c.header).join(' | '));
doc.moveDown(0.3);
@@ -79,5 +78,5 @@ export async function buildFinanceBankAccountsPdf(rows: FinanceBankAccountDto[])
export function buildFinanceBankExportFilename(format: 'xlsx' | 'pdf', count: number): string {
const stamp = new Date().toISOString().slice(0, 10);
return `银行账户_${stamp}_${count}.${format}`;
return `全部银行账户_${stamp}_${count}.${format}`;
}
@@ -1,93 +0,0 @@
import { Body, Controller, Delete, Get, Param, Post, Put, UseGuards } from '@nestjs/common';
import { IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
import { ShopStoreGuard } from '../../common/guards/shop-store.guard';
import { ShopPrimaryGuard } from '../../common/guards/shop-primary.guard';
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { StoreBankService } from './store-bank.service';
class StoreBankDto {
@IsString()
@IsNotEmpty({ message: '请填写收款人' })
@MaxLength(64)
bankAccountName!: string;
@IsString()
@IsNotEmpty({ message: '请填写银行账号' })
@MaxLength(32)
bankAccountNo!: string;
@IsOptional()
@IsString()
@MaxLength(128)
bankBranch?: string;
}
/** 门店端:主账号管理本店收款账户(子账号只读) */
@Controller('shop/store/bank-accounts')
@UseGuards(JwtAuthGuard, ShopStoreGuard)
export class ShopStoreBankController {
constructor(private readonly storeBankService: StoreBankService) {}
@Get()
list(@CurrentUser() user: AuthUser) {
return this.storeBankService.list(user.storeId!);
}
@Post()
@UseGuards(ShopPrimaryGuard)
create(@CurrentUser() user: AuthUser, @Body() dto: StoreBankDto) {
return this.storeBankService.create(user.storeId!, dto);
}
@Put(':id')
@UseGuards(ShopPrimaryGuard)
update(@CurrentUser() user: AuthUser, @Param('id') id: string, @Body() dto: StoreBankDto) {
return this.storeBankService.update(user.storeId!, BigInt(id), dto);
}
@Delete(':id')
@UseGuards(ShopPrimaryGuard)
remove(@CurrentUser() user: AuthUser, @Param('id') id: string) {
return this.storeBankService.remove(user.storeId!, BigInt(id));
}
@Post(':id/default')
@UseGuards(ShopPrimaryGuard)
setDefault(@CurrentUser() user: AuthUser, @Param('id') id: string) {
return this.storeBankService.setDefault(user.storeId!, BigInt(id));
}
}
/** 总部端:管理指定门店的收款账户 */
@Controller('admin/stores/:storeId/bank-accounts')
@UseGuards(HqAuthGuard)
export class AdminStoreBankController {
constructor(private readonly storeBankService: StoreBankService) {}
@Get()
list(@Param('storeId') storeId: string) {
return this.storeBankService.list(BigInt(storeId));
}
@Post()
create(@Param('storeId') storeId: string, @Body() dto: StoreBankDto) {
return this.storeBankService.create(BigInt(storeId), dto);
}
@Put(':id')
update(@Param('storeId') storeId: string, @Param('id') id: string, @Body() dto: StoreBankDto) {
return this.storeBankService.update(BigInt(storeId), BigInt(id), dto);
}
@Delete(':id')
remove(@Param('storeId') storeId: string, @Param('id') id: string) {
return this.storeBankService.remove(BigInt(storeId), BigInt(id));
}
@Post(':id/default')
setDefault(@Param('storeId') storeId: string, @Param('id') id: string) {
return this.storeBankService.setDefault(BigInt(storeId), BigInt(id));
}
}
@@ -1,121 +0,0 @@
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../common/prisma/prisma.module';
export interface StoreBankInput {
bankAccountName?: string;
bankAccountNo?: string;
bankBranch?: string;
}
const BANK_NO_RE = /^\d{8,32}$/;
@Injectable()
export class StoreBankService {
constructor(private readonly prisma: PrismaService) {}
private serialize(row: {
id: bigint;
storeId: bigint;
bankAccountName: string;
bankAccountNo: string;
bankBranch: string | null;
isDefault: number;
status: string;
sortOrder: number;
}) {
return {
id: row.id.toString(),
storeId: row.storeId.toString(),
bankAccountName: row.bankAccountName,
bankAccountNo: row.bankAccountNo,
bankBranch: row.bankBranch,
isDefault: row.isDefault === 1,
status: row.status,
sortOrder: row.sortOrder,
};
}
private normalize(dto: StoreBankInput) {
const bankAccountName = dto.bankAccountName?.trim() ?? '';
const bankAccountNo = dto.bankAccountNo?.replace(/\s+/g, '') ?? '';
const bankBranch = dto.bankBranch?.trim() || null;
if (!bankAccountName) throw new BadRequestException('请填写收款人');
if (!BANK_NO_RE.test(bankAccountNo)) throw new BadRequestException('请填写正确的银行账号');
return { bankAccountName, bankAccountNo, bankBranch };
}
async list(storeId: bigint) {
const rows = await this.prisma.storeBankAccount.findMany({
where: { storeId },
orderBy: [{ isDefault: 'desc' }, { sortOrder: 'asc' }, { id: 'asc' }],
});
return rows.map((r) => this.serialize(r));
}
async create(storeId: bigint, dto: StoreBankInput) {
const data = this.normalize(dto);
const count = await this.prisma.storeBankAccount.count({
where: { storeId, status: 'ACTIVE' },
});
const created = await this.prisma.storeBankAccount.create({
data: {
storeId,
bankAccountName: data.bankAccountName,
bankAccountNo: data.bankAccountNo,
bankBranch: data.bankBranch,
isDefault: count === 0 ? 1 : 0,
status: 'ACTIVE',
sortOrder: count,
},
});
return this.serialize(created);
}
async update(storeId: bigint, accountId: bigint, dto: StoreBankInput) {
const account = await this.findAccount(storeId, accountId);
const data = this.normalize(dto);
const updated = await this.prisma.storeBankAccount.update({
where: { id: account.id },
data: {
bankAccountName: data.bankAccountName,
bankAccountNo: data.bankAccountNo,
bankBranch: data.bankBranch,
},
});
return this.serialize(updated);
}
async remove(storeId: bigint, accountId: bigint) {
const account = await this.findAccount(storeId, accountId);
if (account.isDefault === 1) {
throw new BadRequestException('请先取消默认账户再删除');
}
await this.prisma.storeBankAccount.delete({ where: { id: account.id } });
return { ok: true };
}
async setDefault(storeId: bigint, accountId: bigint) {
const account = await this.findAccount(storeId, accountId);
if (account.isDefault === 1) return this.serialize(account);
await this.prisma.$transaction([
this.prisma.storeBankAccount.updateMany({
where: { storeId },
data: { isDefault: 0 },
}),
this.prisma.storeBankAccount.update({
where: { id: account.id },
data: { isDefault: 1, status: 'ACTIVE' },
}),
]);
const updated = await this.findAccount(storeId, accountId);
return this.serialize(updated);
}
private async findAccount(storeId: bigint, accountId: bigint) {
const account = await this.prisma.storeBankAccount.findFirst({
where: { id: accountId, storeId },
});
if (!account) throw new NotFoundException('收款账户不存在');
return account;
}
}
@@ -31,8 +31,6 @@ import {
} from './store-info-change.controller';
import { StoreInfoChangeService } from './store-info-change.service';
import { PartnerAssocService } from './partner-assoc.service';
import { StoreBankService } from './store-bank.service';
import { AdminStoreBankController, ShopStoreBankController } from './store-bank.controller';
import {
PartnerAssocController,
PartnerCommissionController,
@@ -69,10 +67,8 @@ import {
UserPartnerAssocController,
PartnerAssocController,
PartnerCommissionController,
ShopStoreBankController,
AdminStoreBankController,
],
providers: [StoreService, StoreCategoryService, StorePackageService, StoreInfoChangeService, PartnerAssocService, StoreBankService],
exports: [StoreService, StoreCategoryService, StorePackageService, PartnerAssocService, StoreBankService],
providers: [StoreService, StoreCategoryService, StorePackageService, StoreInfoChangeService, PartnerAssocService],
exports: [StoreService, StoreCategoryService, StorePackageService, PartnerAssocService],
})
export class StoreModule {}