import { UpdateUsage, Usage } from '../interfaces/Usage'; import { Invoice, InvoiceUsage } from '../services/InvoiceService'; export type InvoiceCheck = { hasCredits: boolean; hasDocuments: boolean; hasSyncs: boolean; } const checkInvoice = (invoice: Invoice | null): InvoiceCheck => { return { hasCredits: (invoice?.usage?.credits ?? 0) <= (invoice?.usageLimits?.credits ?? 0), hasDocuments: (invoice?.usage?.documents ?? 0) <= (invoice?.usageLimits?.documents ?? 0), hasSyncs: (invoice?.usage?.syncs ?? 0) <= (invoice?.usageLimits?.syncs ?? 0), }; }; const changeReport = ( invoice: Invoice | null, usageDiff: UpdateUsage, ): InvoiceCheck => { if (!invoice) return checkInvoice(null); const newUsage = Object.keys(invoice.usage).reduce((cur, nextKey: string) => { const value = usageDiff?.[nextKey as keyof InvoiceUsage] ?? 0; cur[nextKey as keyof Usage] += value; return cur; }, { ...invoice.usage }); return checkInvoice({ ...invoice, usage: newUsage, }); }; const addUsage = (current: Usage, addend: UpdateUsage): Usage => { return Object.keys(addend).reduce((cur, nextKey: string) => { const value = addend?.[nextKey as keyof Usage] ?? 0; cur[nextKey as keyof Usage] += value; return cur; }, { ...current }); }; const usagePercentage = (invoice: Invoice | null): Usage | null => { if (!invoice) return null; const current = invoice.usage; const limits = invoice.usageLimits; return { credits: Math.round((current.credits / limits.credits) * 100), documents: Math.round((current.documents / limits.documents) * 100), syncs: Math.round((current.syncs / limits.syncs) * 100), }; }; const InvoiceUtil = { checkInvoice, changeReport, addUsage, usagePercentage, }; export default InvoiceUtil;