260 lines
9.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable complexity */
import type { ValidationContext } from '../types';
import ValuesSchema from '@/config/schema/values';
import { MAX_MASS, VEHICLE_SEATS } from '@/constants/values';
import * as CRMTypes from '@/graphql/crm.types';
import { z } from 'zod';
export function createValidationSchema({ apolloClient }: ValidationContext) {
return ValuesSchema.pick({
addEquipmentPrice: true,
balanceHolder: true,
countSeats: true,
dealerPerson: true,
discountRub: true,
firstPaymentPerc: true,
importProgramSum: true,
lastPaymentPerc: true,
leaseObjectCategory: true,
leaseObjectCount: true,
leaseObjectPriceWthtVAT: true,
leaseObjectUsed: true,
leaseObjectYear: true,
maxMass: true,
plPriceRub: true,
product: true,
quote: true,
recalcWithRevision: true,
}).superRefine(
async (
{
addEquipmentPrice,
dealerPerson: dealerPersonId,
importProgramSum,
leaseObjectPriceWthtVAT,
leaseObjectUsed,
product: productId,
quote: quoteId,
recalcWithRevision,
discountRub,
plPriceRub,
firstPaymentPerc,
leaseObjectCount,
maxMass,
countSeats,
leaseObjectYear,
lastPaymentPerc,
balanceHolder,
leaseObjectCategory,
},
ctx
) => {
if (!recalcWithRevision) {
return;
}
if (!quoteId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Не указано предложение, по которому осуществляется Пересчет без пересмотра',
path: ['selectQuote'],
});
}
if (dealerPersonId && quoteId && productId) {
const {
data: { account: dealerPerson },
} = await apolloClient.query({
query: CRMTypes.GetDealerPersonDocument,
variables: { dealerPersonId },
});
const {
data: { quote },
} = await apolloClient.query({
query: CRMTypes.GetQuoteDocument,
variables: { quoteId },
});
const {
data: { evo_baseproduct },
} = await apolloClient.query({
query: CRMTypes.GetProductDocument,
variables: { productId },
});
const maxCondition1 =
leaseObjectUsed === false &&
dealerPerson?.evo_supplier_type !== 100_000_001 &&
!evo_baseproduct?.evo_sale_without_nds &&
Boolean(
quote?.evo_max_price_change &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote.evo_max_price_change
);
const maxCondition2 =
leaseObjectUsed === false &&
dealerPerson?.evo_supplier_type !== 100_000_001 &&
Boolean(evo_baseproduct?.evo_sale_without_nds) &&
Boolean(
quote?.evo_nds_in_price_supplier_currency &&
quote?.evo_max_price_change &&
leaseObjectPriceWthtVAT >
quote.evo_max_price_change - quote.evo_nds_in_price_supplier_currency
);
const maxCondition3 =
(leaseObjectUsed === true || dealerPerson?.evo_supplier_type === 100_000_001) &&
Boolean(
quote?.evo_supplier_currency_price &&
quote.evo_discount_supplier_currency &&
quote.evo_equip_price &&
quote.evo_program_import_subsidy_sum &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote?.evo_supplier_currency_price -
quote.evo_discount_supplier_currency +
quote.evo_equip_price -
quote.evo_program_import_subsidy_sum
);
const minCondition1 =
!evo_baseproduct?.evo_sale_without_nds &&
Boolean(
quote?.evo_min_change_price &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum <
quote.evo_min_change_price
);
const minCondition2 =
Boolean(evo_baseproduct?.evo_sale_without_nds) &&
Boolean(
quote?.evo_nds_in_price_supplier_currency &&
quote?.evo_min_change_price &&
leaseObjectPriceWthtVAT <
quote.evo_min_change_price - quote.evo_nds_in_price_supplier_currency
);
if (maxCondition1 || maxCondition2) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Указанная стоимость предмета лизинга больше возможного изменения стоимости предмета лизинга при пересчете без пересмотра. ' +
'Уменьшите стоимость предмета лизинга',
path: ['tbxLeaseObjectPrice'],
});
} else if (maxCondition3) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'При пересчете без пересмотра КП с ПЛ БУ или с непрофессиональным поставщиком недопустимо увеличение стоимости. Создайте новое КП и отправьте его на рассмотрение андеррайтингу для повторной проверки оценщиком.',
path: ['tbxLeaseObjectPrice'],
});
} else if (minCondition1 || minCondition2) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Указанная стоимость предмета лизинга меньше возможного изменения стоимости предмета лизинга при пересчете без пересмотра. ' +
'Увеличьте стоимость предмета лизинга',
path: ['tbxLeaseObjectPrice'],
});
}
}
if (quoteId) {
const {
data: { quote },
} = await apolloClient.query({
query: CRMTypes.GetQuoteDocument,
variables: { quoteId },
});
if (
quote?.evo_approved_first_payment &&
firstPaymentPerc < quote.evo_approved_first_payment
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Указанный первый платеж меньше одобренного ${quote?.evo_approved_first_payment}. При пересчете без пересмотра изменение первого платежа возможно только в большую сторону от одобренного значения`,
path: ['tbxFirstPaymentPerc'],
});
}
if (quote?.evo_recalc_limit && leaseObjectCount > quote.evo_recalc_limit) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Количество ПЛ превышает лимит пересчета без пересмотра',
path: ['tbxLeaseObjectCount'],
});
}
if (
quote?.evo_max_mass &&
((quote.evo_max_mass < MAX_MASS && maxMass >= MAX_MASS) ||
(quote?.evo_max_mass >= MAX_MASS && maxMass < MAX_MASS))
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Указанная разрешенная макс. масса выходит из утвержденного диапазона. Для изменения параметра требуется пересмотр сделки',
path: ['tbxMaxMass'],
});
}
if (
leaseObjectCategory === 100_000_003 &&
quote?.evo_seats &&
((quote.evo_seats < VEHICLE_SEATS && countSeats >= VEHICLE_SEATS) ||
(quote.evo_seats >= VEHICLE_SEATS && countSeats < VEHICLE_SEATS))
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Указанное кол-во мест выходит из утвержденного диапазона. Для изменения параметра требуется пересмотр сделки',
path: ['tbxCountSeats'],
});
}
if (quote?.evo_year && leaseObjectYear < quote.evo_year) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'При пересчете без пересмотра год выпуска нельзя уменьшать',
path: ['tbxLeaseObjectYear'],
});
}
if (
quote?.evo_last_payment_perc &&
lastPaymentPerc > 1 &&
lastPaymentPerc > quote.evo_last_payment_perc
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'При пересчете без пересмотра последний платеж можно уменьшать или увеличивать до 1%',
path: ['tbxLastPaymentPerc'],
});
}
if (balanceHolder === 100_000_001) {
if (lastPaymentPerc < 1) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'При балансе лизингодатель последний платеж не может быть меньше 1%! Увеличьте значение.',
path: ['tbxLastPaymentPerc'],
});
}
} else if (lastPaymentPerc === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Последний платеж не может быть равен 0. Увеличьте значение',
path: ['tbxLastPaymentPerc'],
});
}
}
}
);
}