91 lines
2.7 KiB
TypeScript
91 lines
2.7 KiB
TypeScript
import type { Prisma } from '../generated/prisma/client';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import { AppError } from '../common/errors/app-error';
|
|
import { decimal, minor } from './money';
|
|
import { priceCoupon } from '../coupons/coupon-policy';
|
|
import type { CheckoutInput } from './checkout.schemas';
|
|
|
|
export async function checkoutSnapshot(
|
|
tx: Prisma.TransactionClient,
|
|
actor: Principal,
|
|
input: CheckoutInput,
|
|
) {
|
|
const cart = await tx.cart.findUnique({
|
|
where: {
|
|
userId_organizationId: {
|
|
userId: actor.userId,
|
|
organizationId: actor.organizationId,
|
|
},
|
|
},
|
|
include: {
|
|
lines: {
|
|
include: { variant: { include: { product: true } } },
|
|
orderBy: { variantId: 'asc' },
|
|
},
|
|
},
|
|
});
|
|
if (!cart || cart.lines.length === 0) throw new AppError('CART_EMPTY');
|
|
if (cart.version !== input.cartVersion) throw new AppError('CART_CHANGED');
|
|
const address = await tx.address.findFirst({
|
|
where: {
|
|
id: input.addressId,
|
|
|
|
userId: actor.userId,
|
|
organizationId: actor.organizationId,
|
|
},
|
|
});
|
|
if (!address) throw new AppError('ADDRESS_NOT_FOUND');
|
|
const currency = cart.lines[0]!.variant.currency;
|
|
const lines = cart.lines.map(({ variant, quantity }) => {
|
|
if (!variant.active || variant.product.status !== 'PUBLISHED')
|
|
throw new AppError('CART_ITEM_UNAVAILABLE');
|
|
if (variant.currency !== currency) throw new AppError('CART_CURRENCY');
|
|
return {
|
|
variantId: variant.id,
|
|
sku: variant.sku,
|
|
productName: variant.product.name,
|
|
variantName: variant.name,
|
|
quantity,
|
|
unitPrice: variant.price,
|
|
lineTotal: decimal(minor(variant.price.toString()) * BigInt(quantity)),
|
|
};
|
|
});
|
|
const subtotal = lines.reduce((sum, line) => sum + minor(line.lineTotal), 0n);
|
|
const { coupon, discount } = await priceCoupon(
|
|
tx,
|
|
actor,
|
|
input.couponCode,
|
|
currency,
|
|
subtotal,
|
|
new Date(),
|
|
);
|
|
return {
|
|
cartId: cart.id,
|
|
lines,
|
|
currency,
|
|
subtotal: decimal(subtotal),
|
|
discount: decimal(discount),
|
|
merchandiseTotal: decimal(subtotal - discount),
|
|
couponId: coupon?.id,
|
|
couponSnapshot: coupon
|
|
? {
|
|
code: coupon.code,
|
|
kind: coupon.kind,
|
|
amount: coupon.amount?.toString() ?? null,
|
|
percentBps: coupon.percentBps,
|
|
minimumSubtotal: coupon.minimumSubtotal.toString(),
|
|
}
|
|
: undefined,
|
|
addressSnapshot: {
|
|
recipient: address.recipient,
|
|
line1: address.line1,
|
|
line2: address.line2,
|
|
city: address.city,
|
|
region: address.region,
|
|
postalCode: address.postalCode,
|
|
countryCode: address.countryCode,
|
|
phone: address.phone,
|
|
},
|
|
};
|
|
}
|