import type { GetQuoteDataInput, GetQuoteDataOutput } from '../load-kp/types'; import initializeApollo from '@/apollo/client'; import type * as CRMTypes from '@/graphql/crm.types'; import { gql } from '@apollo/client'; import { sort } from 'radash'; const QUERY_GET_PAYMENTS_DATA_FROM_QUOTE = gql` query GetPaymentsDataFromQuote($quoteId: Uuid!) { quote(quoteId: $quoteId) { evo_period evo_accept_period evo_first_payment_perc evo_last_payment_perc evo_graph_type evo_payments_decrease_perc evo_seasons_type evo_high_season evo_graphs { createdon evo_sumpay_withnds evo_planpayments { evo_payment_ratio } } } } `; type QuotePaymentsProcessData = { payments: GetQuoteDataOutput['payments']; values: Partial; }; export default async function getPaymentsDataFromKP({ values: { quote: quoteId, recalcWithRevision }, }: GetQuoteDataInput): Promise { const apolloClient = initializeApollo(); const { data: { quote }, } = await apolloClient.query< CRMTypes.GetPaymentsDataFromQuoteQuery, CRMTypes.GetPaymentsDataFromQuoteQueryVariables >({ query: QUERY_GET_PAYMENTS_DATA_FROM_QUOTE, variables: { quoteId, }, }); const leasingPeriod = recalcWithRevision ? Math.min(quote?.evo_period ?? 0, quote?.evo_accept_period ?? 0) : quote?.evo_period ?? 0; let paymentsValues: number[] = []; if (quote?.evo_graphs) { paymentsValues = sort(quote?.evo_graphs, (evo_graph) => Date.parse(evo_graph?.createdon ?? '0')) .at(0) ?.evo_planpayments?.slice(1, -1) .slice(0, leasingPeriod - 2) .map((payment) => payment?.evo_payment_ratio || 0) || []; } return { payments: { values: [ quote?.evo_first_payment_perc || 0, ...paymentsValues, quote?.evo_last_payment_perc || 0, ], }, values: { firstPaymentPerc: quote?.evo_first_payment_perc || 0, graphType: quote?.evo_graph_type ?? undefined, highSeasonStart: quote?.evo_high_season, lastPaymentPerc: quote?.evo_last_payment_perc || 0, leasingPeriod, parmentsDecreasePercent: quote?.evo_payments_decrease_perc || 0, seasonType: quote?.evo_seasons_type, }, }; }