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]; export type Product = { id?: Id; pricePerUnit: number; dimensions: dimensions_t; type: product_type_t; attributes?: ProductAttributes; }; export type LumberProduct = Product & { type: "lumber"; }; 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) ); } export function priceDisplay(price: number) { return price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, }); } 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}`; } export function attributesAsList(attributes: ProductAttributes) { return Object.entries(attributes).map(([key, value]) => { return { key, value }; }); } 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})`; } export function removeAttribute( attributes: { [key: string]: any }, key: string ) { return Object.fromEntries( Object.entries(attributes).filter(([k, v]) => { k == key; }) ); }