2023-04-21 11:13:58 +03:00

101 lines
2.8 KiB
TypeScript

import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import { generateDegressionRows } from './lib/degression-tools';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
import * as CRMTypes from '@/graphql/crm.types';
import { gql } from '@apollo/client';
import { sort } from 'radash';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const QUERY_GET_QUOTE_PAYMENTS_DATA = gql`
query GetQuotePaymentsData($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
}
}
}
}
`;
// eslint-disable-next-line sonarjs/cognitive-complexity
export async function getKPData({
values: { quote: quoteId, recalcWithRevision },
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const apolloClient = initializeApollo();
const {
data: { quote },
} = await apolloClient.query({
query: CRMTypes.GetQuotePaymentsDataDocument,
variables: {
quoteId,
},
});
const leasingPeriod = recalcWithRevision
? Math.min(quote?.evo_period ?? 0, quote?.evo_accept_period ?? 0)
: quote?.evo_period ?? 0;
const graphType = quote?.evo_graph_type ?? defaultValues.graphType;
const firstPaymentPerc = quote?.evo_first_payment_perc ?? defaultValues.firstPaymentPerc;
const lastPaymentPerc = quote?.evo_last_payment_perc ?? defaultValues.lastPaymentPerc;
const seasonType = quote?.evo_seasons_type;
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) || [];
}
const isDegression =
graphType === 100_000_001 &&
seasonType !== null &&
seasonType !== undefined &&
seasonType !== 100_000_007;
if (recalcWithRevision && isDegression) {
paymentsValues = generateDegressionRows({
leasingPeriod,
seasonType,
}).map((x) => x.value);
}
return {
payments: {
sums: [],
values: [
quote?.evo_first_payment_perc ?? 0,
...paymentsValues,
quote?.evo_last_payment_perc ?? 0,
],
},
values: {
firstPaymentPerc,
graphType,
highSeasonStart: quote?.evo_high_season,
lastPaymentPerc,
leasingPeriod,
parmentsDecreasePercent:
quote?.evo_payments_decrease_perc ?? defaultValues.parmentsDecreasePercent,
seasonType,
},
};
}