PliWould/lib/product.ts

104 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-06-27 23:31:59 +02:00
import uuid from "react-native-uuid";
import { dimensions_t, area_t, dimensionsDisplay } from "./dimensions";
import { matchDimensions } from "./dimensions";
import { Area, Length, Unit } from "convert";
export type Id = string;
export type Currency = "USD";
export type ProductAttributes = {
id?: string;
name?: string;
image?: string;
description?: string;
depth?: string;
currency?: Currency;
[index: string]: any;
};
export function dimensionArea(d: dimensions_t) {
return "w" in d ? d.w * d.l : 0;
}
export const PRODUCT_TYPES = ["lumber", "area_rug"] as const;
export type product_type_t = (typeof PRODUCT_TYPES)[number];
2024-07-17 15:54:55 +02:00
export type Product = {
id?: Id;
pricePerUnit: number;
dimensions: dimensions_t;
type: product_type_t;
attributes?: ProductAttributes;
};
2024-07-17 15:54:55 +02:00
export type LumberProduct = Product & {
type: "lumber";
};
2024-07-17 15:54:55 +02:00
export type AreaRugProduct = Product & {
type: "lumber";
};
export function productPriceFor(
product: Product,
dimensions: dimensions_t,
damage: number = 0
): number {
if (Number.isNaN(damage)) damage = 0;
const dim = matchDimensions(dimensions, product.dimensions);
return (
(dim.w
? (dimensionArea(dim) / dimensionArea(product.dimensions)) *
product.pricePerUnit
: (dim.l / product.dimensions.l) * product.pricePerUnit) *
(1.0 - damage)
);
2024-07-17 15:54:55 +02:00
}
export function priceDisplay(price: number) {
return price.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
2024-07-17 15:54:55 +02:00
}
export function pricePerUnitDisplay(product: Product) {
const p = priceDisplay(product.pricePerUnit);
const { l, u } = product.dimensions;
const w = (product.dimensions as area_t).w || null;
const d = w ? `${l}${u} x ${w}${u}` : `${l}${u}`;
return `$${p} per ${d}`;
2024-07-17 15:54:55 +02:00
}
export function attributesAsList(attributes: ProductAttributes) {
return Object.entries(attributes).map(([key, value]) => {
return { key, value };
});
2024-07-17 15:54:55 +02:00
}
export function productLabel(
product: Product,
{ pricing }: { pricing: boolean } = { pricing: false }
) {
const n = product.attributes?.name || `Product ${product.id}`;
const p = priceDisplay(product.pricePerUnit);
const d = dimensionsDisplay(product.dimensions);
if (!pricing) {
return n;
}
return `${n} ($${p} per ${d})`;
2024-07-17 15:54:55 +02:00
}
export function removeAttribute(
attributes: { [key: string]: any },
key: string
) {
return Object.fromEntries(
Object.entries(attributes).filter(([k, v]) => {
k == key;
})
);
}