52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
import { AppError } from '../common/errors/app-error';
|
|
import type { Prisma } from '../generated/prisma/client';
|
|
import type { DatabaseService } from '../database/database.service';
|
|
|
|
type Db = Prisma.TransactionClient | DatabaseService;
|
|
|
|
export async function requirePriceList(
|
|
db: Db,
|
|
organizationId: string,
|
|
id: string,
|
|
) {
|
|
const list = await db.b2bPriceList.findFirst({
|
|
where: { id, organizationId },
|
|
include: { items: { orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] } },
|
|
});
|
|
if (!list) throw new AppError('B2B_PRICE_LIST_NOT_FOUND');
|
|
return list;
|
|
}
|
|
|
|
export async function requireBusinessAccount(
|
|
db: Db,
|
|
organizationId: string,
|
|
id: string,
|
|
) {
|
|
const account = await db.businessAccount.findFirst({
|
|
where: { id, organizationId },
|
|
});
|
|
if (!account) throw new AppError('BUSINESS_ACCOUNT_NOT_FOUND');
|
|
return account;
|
|
}
|
|
|
|
export async function assertEligiblePriceVariants(
|
|
db: Db,
|
|
organizationId: string,
|
|
currency: string,
|
|
items: { variantId: string }[],
|
|
) {
|
|
const variants = await db.productVariant.findMany({
|
|
where: { id: { in: items.map((item) => item.variantId) }, organizationId },
|
|
include: { product: true },
|
|
});
|
|
if (
|
|
variants.length !== items.length ||
|
|
variants.some(
|
|
(variant) => !variant.active || variant.product.status !== 'PUBLISHED',
|
|
)
|
|
)
|
|
throw new AppError('B2B_PRICE_VARIANT_INELIGIBLE');
|
|
if (variants.some((variant) => variant.currency !== currency))
|
|
throw new AppError('B2B_PRICE_CURRENCY_MISMATCH');
|
|
}
|