import currency from 'currency.js'; import { pito } from 'pito'; import { PriceType } from '..'; import { NumRangeDefine } from './range'; // export const PriceDefine = pito .Uobj('type') // 월세 가격의 일반적인 형태 .case(PriceType.Monthly, { price: pito.Num(), deposit: pito.Num(), }) // 전세 가격의 일반적인 형태 .case(PriceType.Charter, { price: pito.Num(), }) // 매매 가격의 일반적인 형태 .case(PriceType.Sale, { price: pito.Num(), },) .end(); export type PriceDefine = pito.Type; export const PriceRangeDefine = pito .Uobj('type') .case(PriceType.Monthly, { price: NumRangeDefine, deposit: NumRangeDefine, }) .case(PriceType.Charter, { price: NumRangeDefine, }) .case(PriceType.Sale, { price: NumRangeDefine, }) .end(); export type PriceRangeDefine = pito.Type; export namespace Price { // 에러 발생 가능 export function wrap( type: PriceType, price: currency.Any | undefined | null, deposit: currency.Any | undefined | null, ): PriceDefine { const p = price ?? undefined; const d = deposit ?? undefined; switch (type) { case PriceType.Monthly: if (p === undefined) { throw new Error('price : undefined'); } if (d === undefined) { throw new Error('deposit : undefined'); } return { type : PriceType.Monthly, // TODO : typio currency 업그래이드 price : currency(p).value, deposit: currency(d).value, }; case PriceType.Charter: if (p === undefined) { throw new Error('price : undefined'); } return { type : PriceType.Charter, price: currency(p).value, }; case PriceType.Sale: if (p === undefined) { throw new Error('price : undefined'); } return { type : PriceType.Sale, price: currency(p).value, }; default: throw new Error(`unknown price type ${type}`); } } export function unwrap(price: PriceDefine): { type: PriceType; price: number; deposit?: number; } { return price; } export function isBuyAvailable( sellPrice: PriceDefine, buyPrice: PriceDefine, ): boolean { if ( sellPrice.type === PriceType.Monthly && buyPrice.type === PriceType.Monthly ) { return ( sellPrice.price <= buyPrice.price && sellPrice.deposit <= buyPrice.deposit ); } if ( sellPrice.type === PriceType.Charter && buyPrice.type === PriceType.Charter ) { return sellPrice.price <= buyPrice.price; } if (sellPrice.type === PriceType.Sale && buyPrice.type === PriceType.Sale) { return sellPrice.price <= buyPrice.price; } return false; } export function Monthly(pee: number, deposit: number): PriceDefine { return { type : PriceType.Monthly, price : pee, deposit: deposit, }; } export function Charter(price: number): PriceDefine { return { type : PriceType.Charter, price: price, }; } export function Sale(price: number): PriceDefine { return { type : PriceType.Sale, price: price, }; } }