PliWould/lib/product.ts

86 lines
2.2 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 } from "./dimensions";
import { matchDimensions } from "./dimensions";
import { Area, Length, Unit } from "convert";
export type Id = string;
export type Currency = "USD";
export type ProductAttributes = {
2024-06-27 23:31:59 +02:00
id?: string,
name?: string,
image?: string,
description?: string,
depth?: string,
2024-06-27 23:31:59 +02:00
currency?: Currency,
2024-07-17 15:54:55 +02:00
[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;
2024-07-17 15:54:55 +02:00
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"
}
2024-07-17 15:54:55 +02:00
export function productPriceFor(product : Product, dimensions: dimensions_t, damage: number): 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
}
2024-07-17 15:54:55 +02:00
export function attributesAsList(attributes : {[key:string]: any}) {
return Object.entries(attributes).map(([key, value]) => {
return { key, value }
})
}
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;
}
)
2024-07-17 15:54:55 +02:00
);
}