Files
boursecu_user/src/utils/productOrderLimit.ts
T
2026-06-06 22:41:42 +03:30

73 lines
2.5 KiB
TypeScript

import type { Product } from '@/models/products'
import { usePriceWithoutType } from '@/utils/usePrice'
type LimitProduct = Pick<Product, 'order_limit_enabled' | 'min_order_cash' | 'max_order_cash'> | null | undefined
export function productOrderLimitEnabled(product?: LimitProduct): boolean {
if (!product?.order_limit_enabled) return false
return product.min_order_cash != null || product.max_order_cash != null
}
export function productMinOrderCash(product?: LimitProduct, isBuy = true, defaultBuyMin = 500_000): number {
if (productOrderLimitEnabled(product) && product?.min_order_cash != null) {
return Number(product.min_order_cash)
}
return isBuy ? defaultBuyMin : 0
}
export function productMaxOrderCash(product?: LimitProduct): number | undefined {
if (productOrderLimitEnabled(product) && product?.max_order_cash != null) {
return Number(product.max_order_cash)
}
return undefined
}
export function productCashValidationMessage(
product: LimitProduct,
goldCash: number | string | undefined,
isBuy: boolean,
formatPrice: (value: number) => string = usePriceWithoutType
): string {
if (goldCash === '' || goldCash === undefined) return ''
const cash = Number(goldCash ?? 0)
const min = productMinOrderCash(product, isBuy)
const max = productMaxOrderCash(product)
if (max != null && cash > max) {
return `حداکثر مبلغ این محصول ${formatPrice(max)} ریال است`
}
if (min > 0 && cash < min) {
if (productOrderLimitEnabled(product) && product?.min_order_cash != null) {
return `حداقل مبلغ این محصول ${formatPrice(min)} ریال است`
}
return `حداقل مبلغ طلا جهت ${isBuy ? 'خرید' : 'فروش'} ${formatPrice(min)} ریال می باشد.`
}
return ''
}
export function validateProductOrderLimitForm(form: {
order_limit_enabled?: boolean
min_order_cash?: number | string | null
max_order_cash?: number | string | null
}): string | null {
if (!form.order_limit_enabled) return null
const min = form.min_order_cash
const max = form.max_order_cash
const hasMin = min != null && min !== ''
const hasMax = max != null && max !== ''
if (!hasMin && !hasMax) {
return 'با فعال بودن محدودیت مبلغ سفارش، حداقل یکی از حداقل یا حداکثر مبلغ باید وارد شود'
}
if (hasMin && hasMax && Number(min) > Number(max)) {
return 'حداقل مبلغ نمی‌تواند بیشتر از حداکثر باشد'
}
return null
}