import type { PrismaClient } from '@prisma/client'; export type StoreBankAccountSnapshot = { bankAccountName: string | null; bankAccountNo: string | null; bankBranch: string | null; }; export async function loadStorePrimaryBank( prisma: PrismaClient, storeId: bigint, ): Promise { const binding = await prisma.storeAccountStore.findFirst({ where: { storeId, storeAccount: { isPrimary: 1 } }, include: { storeAccount: { select: { bankAccountName: true, bankAccountNo: true, bankBranch: true }, }, }, }); if (binding) return binding.storeAccount; const fallback = await prisma.storeAccountStore.findFirst({ where: { storeId }, orderBy: { storeAccountId: 'asc' }, include: { storeAccount: { select: { bankAccountName: true, bankAccountNo: true, bankBranch: true }, }, }, }); return fallback?.storeAccount ?? null; } export async function loadStorePrimaryBanksMap( prisma: PrismaClient, storeIds: bigint[], ): Promise> { const map = new Map(); if (!storeIds.length) return map; 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' }], }); 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; } export async function loadWineryBankConfig( prisma: PrismaClient, ): Promise { const keys = [ 'WINERY_BANK_ACCOUNT_NAME', 'WINERY_BANK_NAME', 'WINERY_BANK_BRANCH', 'WINERY_BANK_ACCOUNT_NO', ]; const rows = await prisma.systemConfig.findMany({ where: { configKey: { in: keys } }, select: { configKey: true, value: true }, }); const map = new Map(rows.map((r) => [r.configKey, r.value])); return { bankAccountName: map.get('WINERY_BANK_ACCOUNT_NAME') ?? null, bankName: map.get('WINERY_BANK_NAME') ?? null, bankBranch: map.get('WINERY_BANK_BRANCH') ?? null, bankAccountNo: map.get('WINERY_BANK_ACCOUNT_NO') ?? null, }; }