import uuid from "react-native-uuid"; import { Area } from "convert"; import { Transform } from "class-transformer"; import { dimensions_t, area_t } from "./dimensions"; import { matchDimensions } from "./dimensions"; 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 type ProductData = { id?: Id; pricePerUnit: number; dimensions: dimensions_t; attributes?: ProductAttributes; }; export class Product { public id?: Id; constructor(public pricePerUnit: number, public dimensions: dimensions_t, public attributes: ProductAttributes = {}, id?: Id, ) { this.id = id || uuid.v4().toString(); } public priceFor(dimensions: dimensions_t, damage : number): number { if (Number.isNaN(damage)) damage = 0; const dim = matchDimensions(dimensions, this.dimensions); return ( dim.w ? dimensionArea(dim) / dimensionArea(this.dimensions) * this.pricePerUnit : (dim.l / this.dimensions.l) * this.pricePerUnit ) * (1.0 - damage); } get priceDisplay() { return this.pricePerUnit.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, }) } get pricePerUnitDisplay() { const p = this.priceDisplay; const { l, u } = this.dimensions; const w = (this.dimensions as area_t).w || null; const d = w ? `${l}${u} x ${w}${u}` : `${l}${u}`; return `$${p} per ${d}` } get attributesAsList() { return Object.entries(this.attributes).map(([key, value]) => { return { key, value } }) } public removeAttribute(key: string) { this.attributes = Object.fromEntries( Object.entries(this.attributes).filter( ([k, v]) => { k == key; } ) ); } get asObject(): ProductData { return { id: this.id, pricePerUnit: this.pricePerUnit, dimensions: this.dimensions, attributes: this.attributes, } } static fromObject({ id, pricePerUnit, dimensions, attributes }: ProductData) { return new Product( pricePerUnit, dimensions, attributes, id, ) } }