Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/app/[locale]/order/item/[id]/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { Product } from "@/db/schema";
import { MinusIcon, PlusIcon } from "@heroicons/react/24/solid";
import { useMemo, useState } from "react";
import { debounce } from "radash";
import { calculateItemPrice } from "@/utils/pricing";
import { calculateItemPricing } from "@/utils/pricing";

const Files = dynamic(() => import("./files/files"), {
ssr: false,
Expand Down Expand Up @@ -83,7 +83,7 @@ const Form = ({ session, initialCart, itemId, product }: Props) => {
pieces: quantity,
},
};
const computedPrice = calculateItemPrice(product, previewItem);
const computedPrice = calculateItemPricing(product, previewItem).price;

return (
<>
Expand Down
4 changes: 2 additions & 2 deletions src/app/[locale]/order/items.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
Tooltip,
} from "@radix-ui/themes";
import { useFormatter, useLocale, useTranslations } from "next-intl";
import { calculateItemPrice } from "@/utils/pricing";
import { calculateItemPricing } from "@/utils/pricing";

type Props = {
cart: ShoppingCart;
Expand Down Expand Up @@ -46,7 +46,7 @@ const OrderItems = ({ cart: initialCart, products }: Props) => {
(product) => product.id === item.productId
);
const itemPrice =
item.price ?? (product ? calculateItemPrice(product, item) : 0);
item.price ?? (product ? calculateItemPricing(product, item).price : 0);

return (
<Flex
Expand Down
18 changes: 17 additions & 1 deletion src/db/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,23 @@ export const productSchema = z.object({

pricing: z
.object({
baseCostFormula: z
.string()
.optional()
.describe(
"Base cost formula. Supports numbers, variables, +, -, *, /, ^ and parentheses. Example: size.area * 0.02 + files.totalPieces * 0.1 + configTotals.cost",
),
marginFormula: z
.string()
.optional()
.describe(
"Margin formula. Supports numbers, variables, +, -, *, /, ^ and parentheses. Example: size.area * 0.01 + files.totalPieces * 0.05 + configTotals.margin",
),
formula: z
.string()
.optional()
.describe(
"Pricing formula. Supports numbers, variables, +, -, *, /, ^ and parentheses. Example: size.area * 0.02 + files.totalPieces * 0.1 + configTotals.cost",
"Legacy total price formula kept for backward compatibility. Prefer baseCostFormula and marginFormula.",
),
})
.optional()
Expand Down Expand Up @@ -171,8 +183,12 @@ export const orderItemSchema = z.object({
id: z.string(),
productId: z.string(),
price: z.number().optional(),
baseCost: z.number().optional(),
margin: z.number().optional(),
pricing: z
.object({
baseCostFormula: z.string().optional(),
marginFormula: z.string().optional(),
formula: z.string().optional(),
})
.optional(),
Expand Down
14 changes: 11 additions & 3 deletions src/hooks/useCart/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
ShoppingCart,
} from "@/db/validation";
import { createThumbnail } from "@/utils/thumbnail";
import { calculateItemPrice } from "@/utils/pricing";
import { calculateItemPricing } from "@/utils/pricing";
import { eq } from "drizzle-orm";
import { DateTime } from "luxon";
import { cookies } from "next/headers";
Expand Down Expand Up @@ -615,6 +615,14 @@ const hydrateItemPricing = async (
.limit(1);
if (!product) return;

item.pricing = { formula: product.pricing?.formula };
item.price = calculateItemPrice(product, item);
const pricing = calculateItemPricing(product, item);

item.pricing = {
baseCostFormula: product.pricing?.baseCostFormula,
marginFormula: product.pricing?.marginFormula,
formula: product.pricing?.formula,
};
item.baseCost = pricing.baseCost;
item.margin = pricing.margin;
item.price = pricing.price;
};
63 changes: 56 additions & 7 deletions src/utils/pricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,14 @@ export const evaluatePriceFormula = (formula: string, context: unknown) => {
return semantics(match).eval(context);
};

export const calculateItemPrice = (
product: Product,
item: Partial<OrderItemPayload>
) => {
const formula = product.pricing?.formula;
if (!formula) return 0;
export type ItemPricingBreakdown = {
baseCost: number;
margin: number;
price: number;
};

const context = buildPriceContext(product, item);
const evaluateFormulaSafely = (formula: string | undefined, context: unknown) => {
if (!formula) return 0;

try {
const result = evaluatePriceFormula(formula, context);
Expand All @@ -200,3 +200,52 @@ export const calculateItemPrice = (
return 0;
}
};

export const calculateItemPricing = (
product: Product,
item: Partial<OrderItemPayload>
): ItemPricingBreakdown => {
const baseCostFormula = product.pricing?.baseCostFormula;
const marginFormula = product.pricing?.marginFormula;
const legacyFormula = product.pricing?.formula;

const context = buildPriceContext(product, item);

if (baseCostFormula || marginFormula) {
const baseCost = evaluateFormulaSafely(baseCostFormula, context);
const margin = evaluateFormulaSafely(marginFormula, {
...context,
pricing: { baseCost },
});

return {
baseCost,
margin,
price: baseCost + margin,
};
}

if (legacyFormula) {
const legacyPrice = evaluateFormulaSafely(legacyFormula, context);
return {
// Legacy formulas only define total price; we keep margin at 0 to avoid
// inventing profit data and treat the total as production cost.
baseCost: legacyPrice,
margin: 0,
price: legacyPrice,
};
}

return {
baseCost: 0,
margin: 0,
price: 0,
};
};

export const calculateItemPrice = (
product: Product,
item: Partial<OrderItemPayload>
) => {
return calculateItemPricing(product, item).price;
};