Compare commits

...

42 Commits
v2.10.1 ... dev

Author SHA1 Message Date
vchikalkin
3c25ba30d0 merge branch 'release/dyn-4885' 2024-12-10 10:11:43 +03:00
vchikalkin
ba36eb502b merge branch 'release/dyn-4872' 2024-12-03 12:09:07 +03:00
vchikalkin
2c9a2bd30c fix selectDealerPerson validation 2024-10-18 16:29:07 +03:00
vchikalkin
f35acee64b fix tbxVATInLeaseObjectPrice block/unblock by cbxPartialVAT 2024-10-18 14:56:50 +03:00
vchikalkin
a4c02a747f merge branch 'release/dyn-4790' 2024-10-18 13:39:03 +03:00
vchikalkin
66b1e2cdcb merge branch 'fix/irr-bonus-reaction' 2024-09-23 09:59:51 +03:00
vchikalkin
81eca1c6e0 merge branch 'release/dyn-4762' 2024-09-19 10:12:18 +03:00
vchikalkin
89f2b3b68c merge branch 'release/dyn-4760' 2024-09-19 10:11:30 +03:00
vchikalkin
549bd901da partial fix release/4710 2024-09-12 16:50:38 +03:00
vchikalkin
6aad2d3aa2 apps/web: countSeats default value = 4 2024-09-12 16:25:04 +03:00
vchikalkin
09959e3ac3 apps/web: graphql: GetInsuranceCompanies -> sort совком first 2024-09-09 16:00:20 +03:00
vchikalkin
7014462d42 merge branch 'release/dyn-4744' 2024-09-09 15:39:50 +03:00
vchikalkin
62417b88ba merge branch release/dyn-4710 2024-09-05 17:36:38 +03:00
vchikalkin
bf0b5c9907 apps/web: sort evo_planpayments by evo_plandate 2024-08-20 17:42:24 +03:00
vchikalkin
5347c3ef6c apps/web: add check min bonus 2024-08-20 15:52:21 +03:00
vchikalkin
194292c083 apps/web: fix elt kasko list filter 2024-08-19 10:23:14 +03:00
vchikalkin
7d023dba1e apps/web: change elt/kasko error text 2024-08-19 10:03:13 +03:00
vchikalkin
9c63cadf29 merge branch release/dyn-4497 2024-08-15 11:54:28 +03:00
vchikalkin
88b7501b4d apps/web: pass device info to create-kp 2024-08-01 13:06:33 +03:00
vchikalkin
8f53187a3c apps/web: elt kasko fix outsideRoads 2024-07-23 11:09:05 +03:00
vchikalkin
ef8059b3b1 Reapply "web: process/add-product: disable selectInsNSIB reaction"
This reverts commit 0eccd799c79840fe8aa93461880b6ae61a217857.
2024-07-22 16:38:22 +03:00
vchikalkin
8627233a17 favicon: change icons for android & iphone 2024-07-19 13:48:51 +03:00
vchikalkin
2ece25dcb6 apps/web: changes site.webmanifest & add favicon.ico to <head> 2024-07-18 23:08:29 +03:00
vchikalkin
0eccd799c7 Revert "web: process/add-product: disable selectInsNSIB reaction"
This reverts commit 671b25a087ac9dc32bd25c209a7d5797d58d8bcd.
2024-07-18 11:37:29 +03:00
vchikalkin
2e8c333374 web\process\configurator\lib\helper: fix getRates 2024-07-18 11:33:32 +03:00
vchikalkin
671b25a087 web: process/add-product: disable selectInsNSIB reaction 2024-07-16 10:13:15 +03:00
vchikalkin
4a314326fb packages: upgrade next@14.2.5 2024-07-15 17:44:44 +03:00
vchikalkin
d0270a3c9e web: add service worker for pwa install 2024-07-15 15:08:11 +03:00
vchikalkin
71fc44e7a6 Dockerfile: specify pnpm version 2024-07-15 11:07:39 +03:00
vchikalkin
d6f5c73b9d merge branch dyn-4250_migrate-to-new-graphql 2024-07-15 11:04:47 +03:00
vchikalkin
d7908bb5da merge branch release/dyn-4515 2024-07-09 11:16:30 +03:00
vchikalkin
ed5391076c merge branch release/dyn-4514 2024-07-05 11:08:17 +03:00
vchikalkin
4a190e962a fix build: specify turbo version 2024-06-21 16:10:28 +03:00
vchikalkin
4644dbb404 merge branch feature/clear-cache-button 2024-06-21 16:05:49 +03:00
vchikalkin
5c6b419452 merge branch release/dyn-4312_recalc-after-kk 2024-05-22 09:31:51 +03:00
vchikalkin
048d132da2 apps/web: increase proxyTimeout up to 90s 2024-05-13 12:24:47 +03:00
vchikalkin
dd154a3004 merge branch fix/dyn-4368_credit-rate 2024-05-04 11:08:59 +03:00
vchikalkin
8dbcf4bb7f build: fix antd generate css for production 2024-04-24 15:23:13 +03:00
vchikalkin
c0f825a587 merge branch release/dyn-4331_fingap-rat 2024-04-20 10:26:00 +03:00
vchikalkin
2b3dd5e7b9 merge branch release/dyn-4284_dangerous-goods 2024-04-15 10:18:13 +03:00
vchikalkin
5d1aa99d75 apps/web: globals.css: revert text-decoration: none for 'a' tag 2024-04-11 19:55:48 +03:00
vchikalkin
4be47fced5 apps/web: replace normalize.css -> modern-normalize 2024-04-11 16:32:30 +03:00
137 changed files with 16684 additions and 9561 deletions

View File

@ -2,14 +2,14 @@
# Make sure you update both files!
FROM node:alpine AS builder
RUN corepack enable && corepack prepare pnpm@latest --activate
RUN corepack enable && corepack prepare pnpm@8.9.0 --activate
ENV PNPM_HOME=/usr/local/bin
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
RUN apk update
# Set working directory
WORKDIR /app
RUN pnpm add -g turbo dotenv-cli
RUN pnpm add -g turbo@1.12.4 dotenv-cli
COPY . .
RUN turbo prune --scope=api --docker

View File

@ -14,6 +14,7 @@ export const queryTTL: Record<string, number | false> = {
GetDealerPerson: seconds().fromHours(1),
GetDealerPersons: seconds().fromHours(1),
GetDealers: seconds().fromMinutes(15),
GetEltInsuranceRules: seconds().fromHours(12),
GetFuelCards: seconds().fromHours(12),
GetGPSBrands: seconds().fromHours(24),
GetGPSModels: seconds().fromHours(24),
@ -32,6 +33,7 @@ export const queryTTL: Record<string, number | false> = {
GetOpportunities: false,
GetOpportunity: false,
GetOpportunityUrl: seconds().fromHours(12),
GetOsagoAddproductTypes: seconds().fromHours(12),
GetProduct: seconds().fromHours(12),
GetProducts: seconds().fromHours(12),
GetQuote: false,

View File

@ -16,7 +16,7 @@ generates:
object: true
defaultValue: true
scalars:
Uuid: string
UUID: string
Decimal: number
DateTime: string
# exclude: './graphql/crm.schema.graphql'

19
apps/web/@types/errors.ts Normal file
View File

@ -0,0 +1,19 @@
import elementsToValues from '@/Components/Calculation/config/map/values';
export const ERR_ELT_KASKO = 'ERR_ELT_KASKO';
export const ERR_ELT_OSAGO = 'ERR_ELT_OSAGO';
export const ERR_FINGAP_TABLE = 'ERR_FINGAP_TABLE';
export const ERR_INSURANCE_TABLE = 'ERR_INSURANCE_TABLE';
export const ERR_PAYMENTS_TABLE = 'ERR_PAYMENTS_TABLE';
export const ERROR_TABLE_KEYS = [
ERR_ELT_KASKO,
ERR_ELT_OSAGO,
ERR_FINGAP_TABLE,
ERR_INSURANCE_TABLE,
ERR_PAYMENTS_TABLE,
];
export const ERROR_ELEMENTS_KEYS = Object.keys(elementsToValues);
export const ERROR_KEYS = [...ERROR_ELEMENTS_KEYS, ...ERROR_TABLE_KEYS];

View File

@ -1,9 +1,10 @@
import Background from '../../Layout/Background';
import { useFilteredQueries } from './lib/hooks';
import { QueryList } from './QueryList';
import { reset } from '@/api/cache/query';
import { min } from '@/styles/mq';
import styled from 'styled-components';
import { Collapse, Divider, Input } from 'ui/elements';
import { Button, Collapse, Divider, Input } from 'ui/elements';
const Wrapper = styled(Background)`
padding: 4px 6px;
@ -21,13 +22,21 @@ const Wrapper = styled(Background)`
const Flex = styled.div`
display: flex;
margin-bottom: 16px;
justify-content: space-between;
flex-direction: column;
gap: 10px;
`;
const ButtonWrapper = styled.div`
display: flex;
justify-content: flex-end;
`;
export function Cache() {
const { filteredQueries, setFilterString } = useFilteredQueries();
const { filteredQueries, refetch, setFilterString } = useFilteredQueries();
function handleDeleteQuery() {
return reset().then(() => refetch());
}
if (!filteredQueries) {
return <div>Загрузка...</div>;
@ -42,15 +51,20 @@ export function Cache() {
allowClear
onChange={(e) => setFilterString(e.target.value)}
/>
<Collapse
accordion
items={Object.keys(filteredQueries).map((queryGroupName) => ({
children: <QueryList {...filteredQueries[queryGroupName]} />,
key: queryGroupName,
label: queryGroupName,
}))}
/>
<ButtonWrapper>
<Button type="primary" danger disabled={false} onClick={() => handleDeleteQuery()}>
Очистить кэш
</Button>
</ButtonWrapper>
</Flex>
<Collapse
accordion
items={Object.keys(filteredQueries).map((queryGroupName) => ({
children: <QueryList {...filteredQueries[queryGroupName]} />,
key: queryGroupName,
label: queryGroupName,
}))}
/>
</Wrapper>
);
}

View File

@ -7,7 +7,7 @@ export const rows: FormTabRows = [
{
title: 'Регистрация',
},
[['radioObjectRegistration', 'radioTypePTS'], { gridTemplateColumns: ['1fr 1fr'] }],
[['radioObjectRegistration', 'radioTypePTS'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
[['selectRegionRegistration', 'selectTownRegistration', 'selectObjectRegionRegistration']],
[['selectObjectCategoryTax', 'selectObjectTypeTax', 'tbxVehicleTaxInYear']],
[['tbxLeaseObjectYear', 'tbxLeaseObjectMotorPower', 'tbxVehicleTaxInLeasingPeriod']],

View File

@ -12,5 +12,6 @@ export const rows: FormTabRows = [
[['cbxInsurance', 'cbxRegistrationQuote'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
[['cbxTechnicalCardQuote', 'cbxNSIB'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
[['cbxQuoteRedemptionGraph', 'cbxShowFinGAP'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
[['cbxQuoteShowAcceptLimit'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
[['tbxQuoteName', 'radioQuoteContactGender'], { gridTemplateColumns: ['1fr', '2fr 1fr'] }],
];

View File

@ -1,129 +1,41 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { makeEltKaskoRequest } from './lib/make-request';
import { resetRow } from './lib/tools';
import type { Row, StoreSelector } from './types';
import { getEltKasko } from '@/api/elt/query';
import { MAX_FRANCHISE, MAX_INSURANCE, MIN_INSURANCE } from '@/constants/values';
import helper from '@/process/elt/lib/helper';
import { useStore } from '@/stores/hooks';
import { defaultRow } from '@/stores/tables/elt/default-values';
import { useApolloClient } from '@apollo/client';
import { trpcClient } from '@/trpc/client';
import { observer } from 'mobx-react-lite';
import { omit, sift } from 'radash';
import { useCallback } from 'react';
import { Flex } from 'ui/grid';
const storeSelector: StoreSelector = ({ kasko }) => kasko;
const initialData = {
...omit(defaultRow, ['name', 'key', 'id']),
error: null,
kaskoSum: 0,
paymentPeriods: [
{
kaskoSum: 0,
},
],
};
export const Kasko = observer(() => {
const store = useStore();
const { $calculation, $tables } = store;
const apolloClient = useApolloClient();
const { init } = helper({ apolloClient, store });
const handleOnClick = useCallback(async () => {
$tables.elt.kasko.abortController?.abort();
$tables.elt.kasko.abortController = new AbortController();
const calculateKasko = trpcClient.eltKasko.useMutation({
onError() {
$tables.elt.kasko.setRows(
$tables.elt.kasko.getRows.map((row) => ({ ...row, status: 'error' }))
);
},
onMutate: () => {
const rows = $tables.elt.kasko.getRows;
$tables.elt.kasko.setRows(rows.map((row) => ({ ...resetRow(row), status: 'fetching' })));
},
onSuccess: ({ rows }) => {
$tables.elt.kasko.setRows(rows);
},
});
const { kasko } = await init();
$tables.elt.kasko.setRows(kasko);
const kaskoCompanyIds = sift(
$tables.insurance
.row('kasko')
.getOptions('insuranceCompany')
.map((x) => x.value)
);
const values = $calculation.$values.getValues();
kaskoCompanyIds.forEach((key) => {
const row = $tables.elt.kasko.getRow(key);
if (row) {
$tables.elt.kasko.setRow({ key, status: 'fetching' });
makeEltKaskoRequest({ apolloClient, store }, row)
.then((payload) =>
getEltKasko(payload, { signal: $tables.elt.kasko.abortController?.signal })
)
.then((res) => {
if (res) {
const {
kaskoSum = 0,
message,
paymentPeriods,
requestId,
skCalcId,
totalFranchise = 0,
} = res;
let { error } = res;
const sum =
values.leasingPeriod <= 16 ? kaskoSum : paymentPeriods?.[0]?.kaskoSum || 0;
if (totalFranchise > MAX_FRANCHISE) {
error ||= `Франшиза по страховке превышает максимально допустимое значение: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_FRANCHISE)}`;
}
if (sum > MAX_INSURANCE) {
error ||= `Сумма по страховке превышает максимально допустимое значение по стоимости КАСКО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_INSURANCE)}`;
}
if (sum < MIN_INSURANCE) {
error ||= `Сумма по страховке не должна быть меньше допустимого значения по стоимости КАСКО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MIN_INSURANCE)}`;
}
$tables.elt.kasko.setRow({
key,
message: error || message,
numCalc: '0',
requestId,
skCalcId,
status: error ? 'error' : null,
sum,
totalFranchise,
});
}
})
.catch((error) => {
const _err = error as Error;
$tables.elt.kasko.setRow({
...initialData,
key,
message: _err.message || String(error),
status: 'error',
});
});
}
function handleOnClick() {
calculateKasko.mutate({
calculation: {
values: store.$calculation.$values.getValues(),
},
});
}, [$calculation.$values, $tables.elt.kasko, $tables.insurance, apolloClient, init, store]);
}
function handleOnSelectRow(row: Row) {
$tables.insurance.row('kasko').column('insuranceCompany').setValue(row.key);

View File

@ -2,125 +2,41 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { makeEltOsagoRequest, makeOwnOsagoRequest } from './lib/make-request';
import { resetRow } from './lib/tools';
import type { Row, StoreSelector } from './types';
import { getEltOsago } from '@/api/elt/query';
import { MAX_INSURANCE, MIN_INSURANCE } from '@/constants/values';
import helper from '@/process/elt/lib/helper';
import { useStore } from '@/stores/hooks';
import { defaultRow } from '@/stores/tables/elt/default-values';
import { useApolloClient } from '@apollo/client';
import { trpcClient } from '@/trpc/client';
import { observer } from 'mobx-react-lite';
import { omit, sift } from 'radash';
import { useCallback } from 'react';
import { Flex } from 'ui/grid';
const storeSelector: StoreSelector = ({ osago }) => osago;
const initialData = {
...omit(defaultRow, ['name', 'key', 'id']),
error: null,
premiumSum: 0,
};
export const Osago = observer(() => {
const store = useStore();
const { $tables } = store;
const apolloClient = useApolloClient();
const { init } = helper({ apolloClient, store });
const handleOnClick = useCallback(async () => {
$tables.elt.osago.abortController?.abort();
$tables.elt.osago.abortController = new AbortController();
const calculateOsago = trpcClient.eltOsago.useMutation({
onError() {
$tables.elt.osago.setRows(
$tables.elt.osago.getRows.map((row) => ({ ...row, status: 'error' }))
);
},
onMutate: () => {
const rows = $tables.elt.osago.getRows;
$tables.elt.osago.setRows(rows.map((row) => ({ ...resetRow(row), status: 'fetching' })));
},
onSuccess: ({ rows }) => {
$tables.elt.osago.setRows(rows);
},
});
const { osago } = await init();
$tables.elt.osago.setRows(osago);
const osagoCompanyIds = sift(
$tables.insurance
.row('osago')
.getOptions('insuranceCompany')
.map((x) => x.value)
);
osagoCompanyIds.forEach((key) => {
const row = $tables.elt.osago.getRow(key);
if (row) {
row.status = 'fetching';
$tables.elt.osago.setRow(row);
if (row.metodCalc === 'CRM') {
makeOwnOsagoRequest({ apolloClient, store }, row).then((res) => {
if (!res) {
$tables.elt.osago.setRow({
key,
message:
'Для получения расчета ОСАГО следует использовать калькулятор ЭЛТ или Индивидуальный запрос',
numCalc: undefined,
skCalcId: undefined,
status: 'error',
sum: 0,
totalFranchise: 0,
});
} else {
$tables.elt.osago.setRow({
key,
message: null,
numCalc: res.evo_id || undefined,
status: null,
sum: res.evo_graph_price_withoutnds || undefined,
});
}
});
} else {
makeEltOsagoRequest({ apolloClient, store }, row)
.then((payload) =>
getEltOsago(payload, { signal: $tables.elt.osago.abortController.signal })
)
.then((res) => {
if (res) {
const { message, numCalc, premiumSum = 0, skCalcId } = res;
let { error } = res;
if (premiumSum > MAX_INSURANCE) {
error ||= `Сумма по страховке превышает максимально допустимое значение по стоимости ОСАГО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_INSURANCE)}`;
}
if (premiumSum < MIN_INSURANCE) {
error ||= `Сумма по страховке не должна быть меньше допустимого значения по стоимости ОСАГО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MIN_INSURANCE)}`;
}
$tables.elt.osago.setRow({
key,
message: error || message,
numCalc: `${numCalc}`,
skCalcId,
status: error ? 'error' : null,
sum: premiumSum,
});
}
})
.catch((error) => {
const _err = error as Error;
$tables.elt.osago.setRow({
...initialData,
key,
message: _err.message || String(error),
status: 'error',
});
});
}
}
async function handleOnClick() {
calculateOsago.mutate({
calculation: {
values: store.$calculation.$values.getValues(),
},
});
}, [$tables.elt.osago, $tables.insurance, apolloClient, init, store]);
}
function handleOnSelectRow(row: Row) {
$tables.insurance.row('osago').column('insuranceCompany').setValue(row.key);

View File

@ -1,10 +1,7 @@
import type { RowSchema } from '@/config/schema/elt';
import type { Row } from '../types';
import type { ColumnsType } from 'antd/lib/table';
import { CloseOutlined, LoadingOutlined } from 'ui/elements/icons';
import { Flex } from 'ui/grid';
import type { z } from 'zod';
type Row = z.infer<typeof RowSchema>;
const formatter = Intl.NumberFormat('ru', {
currency: 'RUB',

View File

@ -0,0 +1,12 @@
import type { Row } from '@/Components/Calculation/Form/ELT/types';
import { defaultRow } from '@/stores/tables/elt/default-values';
export function resetRow(row: Row): Row {
return {
...defaultRow,
id: row.id,
key: row.key,
metodCalc: row.metodCalc,
name: row.name,
};
}

View File

@ -1,13 +1,14 @@
import type { FormTabRows } from '../../lib/render-rows';
import { transformRowsForMobile } from '../lib/utils';
export const id = 'insurance';
export const title = 'Страхование';
export const rows: FormTabRows = [
[['tbxLeaseObjectYear', 'selectLeaseObjectUseFor', 'selectLegalClientRegion']],
[['selectEngineType', 'tbxInsFranchise', 'selectLegalClientTown']],
[['selectLeaseObjectCategory', 'tbxMileage']],
[['tbxLeaseObjectMotorPower', 'cbxWithTrailer', 'selectGPSBrand']],
[['tbxEngineVolume', 'cbxInsDecentral', 'selectGPSModel']],
[['selectLeasingWithoutKasko', 'selectInsNSIB']],
[['tbxMileage', 'tbxInsFranchise', 'selectLegalClientTown']],
[['selectGPSBrand', 'cbxWithTrailer', 'selectInsNSIB']],
[['selectGPSModel', 'cbxInsDecentral', 'selectLeasingWithoutKasko']],
];
export const mobileRows = transformRowsForMobile(rows);

View File

@ -1,15 +1,15 @@
import renderFormRows from '../../lib/render-rows';
import { id, rows, title } from './config';
import { id, mobileRows, rows, title } from './config';
import FinGAPTable from './FinGAPTable';
import InsuranceTable from './InsuranceTable';
import { Media } from '@/styles/media';
import { Flex } from 'ui/grid';
function Insurance() {
const renderedRows = renderFormRows(rows);
return (
<Flex flexDirection="column">
{renderedRows}
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
<InsuranceTable />
<FinGAPTable />
</Flex>

View File

@ -1,4 +1,5 @@
import type { FormTabRows } from '../../lib/render-rows';
import { transformRowsForMobile } from '../lib/utils';
export const id = 'leasing-object';
export const title = 'ПЛ';
@ -16,3 +17,5 @@ export const rows: FormTabRows = [
[['selectLeaseObjectCategory', 'tbxEngineVolume', 'tbxMileage']],
[['tbxMaxMass', 'tbxEngineHours', 'tbxVIN']],
];
export const mobileRows = transformRowsForMobile(rows);

View File

@ -1,8 +1,14 @@
import renderFormRows from '../../lib/render-rows';
import { id, rows, title } from './config';
import { id, mobileRows, rows, title } from './config';
import { Media } from '@/styles/media';
function LeasingObject() {
return renderFormRows(rows);
return (
<>
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
</>
);
}
export default {

View File

@ -1,4 +1,5 @@
import type { FormTabRows } from '../../lib/render-rows';
import { transformRowsForMobile } from '../lib/utils';
export const id = 'supplier-agent';
export const title = 'Поставщик/агент';
@ -20,3 +21,5 @@ export const rows: FormTabRows = [
[['selectCalcBrokerRewardCondition', 'selectFinDepartmentRewardCondtion'], defaultRowStyle],
[['tbxCalcBrokerRewardSum', 'tbxFinDepartmentRewardSumm'], defaultRowStyle],
];
export const mobileRows = transformRowsForMobile(rows);

View File

@ -1,8 +1,14 @@
import renderFormRows from '../../lib/render-rows';
import { id, rows, title } from './config';
import { id, mobileRows, rows, title } from './config';
import { Media } from '@/styles/media';
function Leasing() {
return renderFormRows(rows);
return (
<>
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
</>
);
}
export default {

View File

@ -8,7 +8,9 @@ import Payments from './Payments';
import SupplierAgent from './SupplierAgent';
import Unlimited from './Unlimited';
import Background from '@/Components/Layout/Background';
import { useStore } from '@/stores/hooks';
import { min } from '@/styles/mq';
import { memo } from 'react';
import styled from 'styled-components';
import { Tabs } from 'ui/elements';
@ -44,20 +46,23 @@ const ComponentWrapper = styled.div`
}
`;
export function Form({ prune }) {
export const Form = memo(() => {
const { $process } = useStore();
const filteredTabs =
$process.has('Unlimited') === false ? formTabs.filter((x) => x.id !== 'unlimited') : formTabs;
return (
<Wrapper>
<Tabs type="card" tabBarGutter="5px">
{formTabs
.filter((tab) => !prune?.includes(tab.id))
.map(({ Component, id, title }) => (
<Tabs.TabPane tab={title} key={id}>
<ComponentWrapper>
<Component />
</ComponentWrapper>
</Tabs.TabPane>
))}
{filteredTabs.map(({ Component, id, title }) => (
<Tabs.TabPane tab={title} key={id}>
<ComponentWrapper>
<Component />
</ComponentWrapper>
</Tabs.TabPane>
))}
</Tabs>
</Wrapper>
);
}
});

View File

@ -0,0 +1,32 @@
/**
*
* @param {import('../../lib/render-rows').FormTabRows} rows
* @returns {import('../../lib/render-rows').FormTabRows}
*/
export function transformRowsForMobile(rows) {
const mobileRows = [];
let columnGroups = {};
rows.forEach((row) => {
if (Array.isArray(row)) {
row[0].forEach((item, index) => {
if (!columnGroups[index]) {
columnGroups[index] = [];
}
columnGroups[index].push(item);
});
} else {
Object.values(columnGroups).forEach((group) => {
mobileRows.push([group, { gridTemplateColumns: '1fr' }]);
});
columnGroups = {};
mobileRows.push(row);
}
});
Object.values(columnGroups).forEach((group) => {
mobileRows.push([group, { gridTemplateColumns: '1fr' }]);
});
return mobileRows;
}

View File

@ -23,73 +23,34 @@ const AlertWrapper = styled(Box)`
margin: 0 0 5px 0;
`;
function getAlerts(errors, title, $process) {
return errors.map(({ key, message }) => (
<AlertWrapper>
<Alert
key={key}
type={$process.has('Unlimited') ? 'warning' : 'error'}
showIcon
message={Message(title, message)}
/>
</AlertWrapper>
));
}
function getElementsErrors({ $calculation, $process }) {
return Object.values($calculation.$validation).map((validation) => {
const elementErrors = validation.getErrors();
const elementTitle = validation.params.err_title;
return elementErrors.map(({ key, message }) => (
<AlertWrapper>
<Alert
key={key}
type={$process.has('Unlimited') ? 'warning' : 'error'}
showIcon
message={Message(elementTitle, message)}
/>
</AlertWrapper>
));
return getAlerts(elementErrors, elementTitle, $process);
});
}
function getPaymentsTableErrors({ $process, $tables }) {
const { payments } = $tables;
const errors = payments.validation.getErrors();
const title = payments.validation.params.err_title;
function getTableErrors(tableName, { $process, $tables }) {
const table = $tables[tableName];
const errors = table.validation.getErrors();
const title = table.validation.params.err_title;
return errors.map(({ key, message }) => (
<AlertWrapper>
<Alert
key={key}
type={$process.has('Unlimited') ? 'warning' : 'error'}
showIcon
message={Message(title, message)}
/>
</AlertWrapper>
));
}
function getInsuranceTableErrors({ $process, $tables }) {
const { insurance } = $tables;
const errors = insurance.validation.getErrors();
const title = insurance.validation.params.err_title;
return errors.map(({ key, message }) => (
<AlertWrapper>
<Alert
key={key}
type={$process.has('Unlimited') ? 'warning' : 'error'}
showIcon
message={Message(title, message)}
/>
</AlertWrapper>
));
}
function getFingapTableErrors({ $process, $tables }) {
const { fingap } = $tables;
const errors = fingap.validation.getErrors();
const title = fingap.validation.params.err_title;
return errors.map(({ key, message }) => (
<AlertWrapper>
<Alert
key={key}
type={$process.has('Unlimited') ? 'warning' : 'error'}
showIcon
message={Message(title, message)}
/>
</AlertWrapper>
));
return getAlerts(errors, title, $process);
}
const Errors = observer(() => {
@ -101,15 +62,16 @@ const Errors = observer(() => {
);
const hasPaymentsErrors = $tables.payments.validation.hasErrors;
const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
const hasFingapErrors = $tables.fingap.validation.hasErrors;
if (!hasElementsErrors && !hasPaymentsErrors && !hasInsuranceErrors) {
if (!hasElementsErrors && !hasPaymentsErrors && !hasInsuranceErrors && !hasFingapErrors) {
return <Alert type="success" showIcon message="Ошибок нет 🙂" />;
}
const elementsErrors = getElementsErrors(store);
const paymentsErrors = getPaymentsTableErrors(store);
const insuranceErrors = getInsuranceTableErrors(store);
const fingapErrors = getFingapTableErrors(store);
const paymentsErrors = getTableErrors('payments', store);
const insuranceErrors = getTableErrors('insurance', store);
const fingapErrors = getTableErrors('fingap', store);
const errors = [...elementsErrors, ...paymentsErrors, ...insuranceErrors, ...fingapErrors];

View File

@ -42,7 +42,7 @@ const Wrapper = styled(Background)`
}
`;
export const Output = observer(() => {
export const Output = observer(({ tabs }) => {
const { $results } = useStore();
const [activeKey, setActiveKey] = useState(undefined);
const { hasErrors } = useErrors();
@ -52,15 +52,15 @@ export const Output = observer(() => {
setActiveKey('payments-table');
}
if (hasErrors) {
if (!tabs && hasErrors) {
setActiveKey('validation');
}
}, [$results.payments.length, hasErrors]);
}, [$results.payments.length, hasErrors, tabs]);
return (
<Wrapper>
<Tabs
items={items}
items={tabs ? items.filter((x) => x.key !== 'validation') : items}
activeKey={activeKey}
onChange={(key) => {
setActiveKey(key);

View File

@ -18,8 +18,8 @@ export const mainRows: FormTabRows = [
[
['btnCreateKP', 'linkDownloadKp'],
{
gap: [0, '10px'],
gridTemplateColumns: ['1fr', '1fr 1fr'],
gap: ['10px'],
gridTemplateColumns: ['1fr 1fr'],
},
],
];
@ -41,8 +41,8 @@ export const unlimitedMainRows: FormTabRows = [
[
['btnCreateKP', 'linkDownloadKp'],
{
gap: [0, '10px'],
gridTemplateColumns: ['1fr', '1fr 1fr'],
gap: ['10px'],
gridTemplateColumns: ['1fr 1fr'],
},
],
];

View File

@ -3,6 +3,7 @@ import * as config from './config';
import Background from '@/Components/Layout/Background';
import { useStore } from '@/stores/hooks';
import { min } from '@/styles/mq';
import { memo } from 'react';
import styled from 'styled-components';
const Wrapper = styled(Background)`
@ -17,7 +18,7 @@ const Wrapper = styled(Background)`
}
`;
export function Settings() {
export const Settings = memo(() => {
const { $process } = useStore();
const mainRows = $process.has('Unlimited')
@ -33,4 +34,4 @@ export function Settings() {
{paramsRows}
</Wrapper>
);
}
});

View File

@ -0,0 +1,19 @@
import Validation from '../Output/Validation';
import Background from '@/Components/Layout/Background';
import { min } from '@/styles/mq';
import { memo } from 'react';
import styled from 'styled-components';
const Wrapper = styled(Background)`
padding: 4px 10px;
${min('laptop')} {
padding: 4px 18px;
}
`;
export const Component = memo(() => (
<Wrapper>
<Validation.Component />
</Wrapper>
));

View File

@ -136,6 +136,7 @@ const components = wrapComponentsMap({
cbxPartialVAT: e.Switch,
cbxFloatingRate: e.Switch,
cbxQuotePriceWithFullVAT: e.Switch,
cbxQuoteShowAcceptLimit: e.Switch,
/** Readonly Elements */
labelLeaseObjectRisk: e.Text,

View File

@ -130,6 +130,7 @@ const titles: Record<ActionElements | ValuesElements, string> = {
cbxPartialVAT: 'Частичный НДС',
cbxFloatingRate: 'Плавающая ставка',
cbxQuotePriceWithFullVAT: 'Отображать Стоимость ПЛ с полным НДС',
cbxQuoteShowAcceptLimit: 'Отображать одобренный лимит',
/** Link Elements */
linkDownloadKp: '',

View File

@ -195,6 +195,7 @@ const types = wrapElementsTypes({
cbxPartialVAT: t.Switch,
cbxFloatingRate: t.Switch,
cbxQuotePriceWithFullVAT: t.Switch,
cbxQuoteShowAcceptLimit: t.Switch,
labelLeaseObjectRisk: t.Readonly,
tbxInsKaskoPriceLeasePeriod: t.Readonly,

View File

@ -133,6 +133,7 @@ const elementsToValues = wrapElementsMap({
cbxPartialVAT: 'partialVAT',
cbxFloatingRate: 'floatingRate',
cbxQuotePriceWithFullVAT: 'quotePriceWithFullVAT',
cbxQuoteShowAcceptLimit: 'quoteShowAcceptLimit',
/** Readonly Elements */
labelLeaseObjectRisk: 'leaseObjectRiskName',

View File

@ -1,4 +0,0 @@
export * from './Form';
export * from './Layout';
export * from './Output';
export * from './Settings';

View File

@ -0,0 +1,101 @@
import { Form } from './Form';
import { Layout } from './Layout';
import { Output } from './Output';
import { Settings } from './Settings';
import { Component as Validation } from './Validation';
import { Notification } from '@/Components/Common';
import { NavigationBar, Tabs } from '@/Components/Layout/Navigation';
import { NavigationProvider } from '@/context/navigation';
import { useErrors, useResults } from '@/stores/hooks';
import { Media } from '@/styles/media';
import { getPageTitle } from '@/utils/page';
import { observer } from 'mobx-react-lite';
import Head from 'next/head';
import styled from 'styled-components';
import { Badge } from 'ui/elements';
import {
BarChartOutlined,
CalculatorOutlined,
ProfileOutlined,
WarningOutlined,
} from 'ui/elements/icons';
const defaultIconStyle = { fontSize: '1.2rem' };
const StyledBadge = styled(Badge)`
color: unset !important;
`;
export const tabs = [
{
Component: Settings,
Icon: () => <ProfileOutlined style={defaultIconStyle} />,
key: 'settings',
title: 'Интерес/Расчет',
},
{
Component: Form,
Icon: () => <CalculatorOutlined style={defaultIconStyle} />,
key: 'form',
title: 'Параметры',
},
{
Component: Output,
Icon: observer(() => {
const { hasResults } = useResults();
return (
<StyledBadge status="success" dot={hasResults}>
<BarChartOutlined style={defaultIconStyle} />
</StyledBadge>
);
}),
key: 'output',
title: 'Результаты',
},
{
Component: Validation,
Icon: observer(() => {
const { hasErrors } = useErrors();
return (
<StyledBadge status="error" dot={hasErrors}>
<WarningOutlined style={defaultIconStyle} />
</StyledBadge>
);
}),
key: 'errors',
title: 'Ошибки',
},
];
type ContentProps = {
readonly initHooks: () => void;
readonly title: string;
};
export function Content({ initHooks, title }: ContentProps) {
initHooks();
return (
<>
<Head>
<title>{getPageTitle(title)}</title>
</Head>
<Notification />
<Media lessThan="laptop">
<NavigationProvider>
<Tabs tabs={tabs} />
<NavigationBar />
</NavigationProvider>
</Media>
<Media greaterThanOrEqual="laptop">
<Layout>
<Form />
<Settings />
<Output />
</Layout>
</Media>
</>
);
}

View File

@ -1,4 +1,7 @@
/* eslint-disable import/no-mutable-exports */
import { ERROR_KEYS } from '@/@types/errors';
import { Media } from '@/styles/media';
import { getDevice } from '@/utils/device';
import type { MessageInstance } from 'antd/es/message/interface';
import type { NotificationInstance } from 'antd/es/notification/interface';
import type { ReactNode } from 'react';
@ -7,9 +10,44 @@ import { message as antdMessage, notification as antdNotification } from 'ui/ele
export let message: Readonly<MessageInstance>;
export let notification: Readonly<NotificationInstance>;
export function Notification({ children }: { readonly children: ReactNode }) {
function createWrapper<T extends NotificationInstance, M extends MessageInstance>(
notificationObj: T,
messageObj: M
): T {
const handler: ProxyHandler<T> = {
get(target, prop, receiver) {
const notificationMethod = target[prop as keyof T];
const messageMethod = messageObj[prop as keyof M];
if (typeof notificationMethod === 'function' && typeof messageMethod === 'function') {
return function (...args: any[]) {
const device = getDevice();
if (device?.isMobile) {
if (typeof args[0] === 'object') {
if (ERROR_KEYS.includes(args[0].key)) return;
args[0].content = args[0].description || args[0].message;
}
messageMethod.apply(messageObj, args);
}
notificationMethod.apply(target, args);
};
}
return Reflect.get(target, prop, receiver);
},
};
return new Proxy(notificationObj, handler);
}
export function Notification({ children }: { readonly children?: ReactNode }) {
const device = getDevice();
const [messageApi, messageContextHolder] = antdMessage.useMessage({
duration: 1.2,
duration: device?.isMobile ? 1.5 : 1.2,
maxCount: 3,
top: 70,
});
@ -21,12 +59,12 @@ export function Notification({ children }: { readonly children: ReactNode }) {
});
message = messageApi;
notification = notificationApi;
notification = createWrapper(notificationApi, messageApi);
return (
<>
{messageContextHolder}
{notificationContextHolder}
<Media greaterThanOrEqual="laptop">{notificationContextHolder}</Media>
{children}
</>
);

View File

@ -10,7 +10,7 @@ const UserText = styled.span`
padding: 0;
text-transform: uppercase;
color: #fff;
font-size: 0.5rem;
font-size: 0.55rem;
font-family: 'Montserrat';
font-weight: 500;
line-height: 1;

View File

@ -49,7 +49,7 @@ const items: MenuProps['items'] = [
},
];
export function AppNavigation() {
export function AppMenu() {
const { pathname } = useRouter();
return (

View File

@ -0,0 +1,64 @@
import { NavigationContext } from '@/context/navigation';
import { useContext, useEffect } from 'react';
import styled from 'styled-components';
import { Flex } from 'ui/grid';
const Container = styled.div`
background-color: white;
bottom: 0;
display: flex;
flex-direction: row;
gap: 10px;
height: 46px;
justify-content: space-around;
position: fixed;
width: 100%;
border-top: 1px solid rgba(5, 5, 5, 0.06);
z-index: 999999;
`;
const TabButton = styled.button`
background: ${({ active }) => (active ? 'var(--color-primary)' : 'white')};
color: ${({ active }) => (active ? 'white' : 'black')};
border-radius: 2px 2px 0 0;
border: none;
cursor: pointer;
height: 100%;
width: 100%;
font-size: 0.75rem;
`;
export function NavigationBar() {
const { currentTab, setCurrentTab, tabsList } = useContext(NavigationContext);
return (
<Container>
{tabsList.map(({ Icon, key, title }) => (
<TabButton key={key} active={key === currentTab} onClick={() => setCurrentTab(key)}>
<Flex flexDirection="column" alignItems="center">
<Icon />
{title}
</Flex>
</TabButton>
))}
</Container>
);
}
const Display = styled.div`
display: ${(props) => (props.visible ? 'block' : 'none')};
`;
export function Tabs({ tabs }) {
const { currentTab, setTabsList } = useContext(NavigationContext);
useEffect(() => {
setTabsList(tabs);
}, [setTabsList, tabs]);
return tabs.map(({ Component, key }) => (
<Display key={key} visible={key === currentTab}>
<Component key={key} tabs />
</Display>
));
}

View File

@ -1,11 +1,15 @@
import Header from './Header';
import { AppNavigation } from './Navigation';
import { min } from '@/styles/mq';
import { AppMenu } from './Menu';
import { max, min } from '@/styles/mq';
import styled from 'styled-components';
const Main = styled.main`
margin: 8px 0;
${max('laptop')} {
margin-bottom: calc(46px + 8px); // height of the navigation bar
}
${min('desktop-xl')} {
margin: 8px 10%;
}
@ -15,7 +19,7 @@ export default function Layout({ children, user }) {
return (
<>
<Header />
{user?.admin ? <AppNavigation /> : false}
{user?.admin ? <AppMenu /> : false}
<Main>{children}</Main>
</>
);

View File

@ -2,14 +2,14 @@
# Make sure you update both files!
FROM node:alpine AS builder
RUN corepack enable && corepack prepare pnpm@latest --activate
RUN corepack enable && corepack prepare pnpm@8.9.0 --activate
ENV PNPM_HOME=/usr/local/bin
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
RUN apk update
# Set working directory
WORKDIR /app
RUN pnpm add -g turbo dotenv-cli
RUN pnpm add -g turbo@1.12.4 dotenv-cli
COPY . .
RUN turbo prune --scope=web --docker
@ -47,6 +47,8 @@ ARG URL_CORE_CALCULATE_DIRECT
ARG URL_1C_TRANSTAX_DIRECT
ARG URL_ELT_OSAGO_DIRECT
ARG URL_ELT_KASKO_DIRECT
ARG USERNAME_1C_TRANSTAX
ARG PASSWORD_1C_TRANSTAX
RUN pnpm dotenv -v NODE_ENV=production -e .env turbo run prebuild --filter=web...
RUN pnpm dotenv -e .env turbo run build --filter=web...

View File

@ -1,11 +1,12 @@
export type RequestTransTax = {
CalcDate: string;
CarCategory: string;
OKTMO: string;
calcDate: Date;
carCategory: string;
power: number;
year: number;
Power: number;
Year: number;
};
export type ResponseTransTax = {
error: string;
tax: number;
Error: string;
Tax: number;
TaxRate: number;
};

View File

@ -6,6 +6,7 @@ import ValuesSchema from '@/config/schema/values';
import { z } from 'zod';
export const RequestCreateKPSchema = z.object({
__info: z.record(z.any()).optional(),
calculation: z
.object({
calculationValues: ValuesSchema,

View File

@ -6,24 +6,18 @@ import axios from 'axios';
const { URL_ELT_KASKO, URL_ELT_OSAGO } = getUrls();
export async function getEltOsago(
payload: ELT.RequestEltOsago,
{ signal }: { signal: AbortSignal }
) {
export async function getEltOsago(payload: ELT.RequestEltOsago) {
return withHandleError(
axios
.post<ELT.ResponseEltOsago>(URL_ELT_OSAGO, payload, { signal, timeout: TIMEOUT })
.post<ELT.ResponseEltOsago>(URL_ELT_OSAGO, payload, { timeout: TIMEOUT })
.then(({ data }) => data)
);
}
export async function getEltKasko(
payload: ELT.RequestEltKasko,
{ signal }: { signal: AbortSignal }
) {
export async function getEltKasko(payload: ELT.RequestEltKasko) {
return withHandleError(
axios
.post<ELT.ResponseEltKasko>(URL_ELT_KASKO, payload, { signal, timeout: TIMEOUT })
.post<ELT.ResponseEltKasko>(URL_ELT_KASKO, payload, { timeout: TIMEOUT })
.then(({ data }) => data)
);
}

View File

@ -1,20 +1,24 @@
import { link } from './link';
import { createLink } from './link';
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { isServer } from 'tools/common';
/** @type {import('@apollo/client').ApolloClient<import('@apollo/client').NormalizedCacheObject>} */
let apolloClient;
function createApolloClient() {
function createApolloClient(headers) {
return new ApolloClient({
cache: new InMemoryCache(),
link,
link: createLink(headers),
ssrMode: isServer(),
});
}
export default function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient();
export default function initializeApollo(initialState, headers) {
if (isServer() && !headers) {
throw new Error('initializeApollo: headers must be provided in server side');
}
const _apolloClient = apolloClient ?? createApolloClient(headers);
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here

View File

@ -1,86 +1,133 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { message } from '@/Components/Common/Notification';
import { publicRuntimeConfigSchema } from '@/config/schema/runtime-config';
import getUrls from '@/config/urls';
import { ApolloLink, from, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { getCurrentScope } from '@sentry/nextjs';
import getConfig from 'next/config';
import { isServer } from 'tools';
const { URL_CRM_GRAPHQL } = getUrls();
function isSovkom(account) {
return account.label.toLowerCase().includes('совком');
}
const modifyDataLink = new ApolloLink((operation, forward) => {
const context = operation?.getContext();
export function createLink(headers) {
const { URL_CRM_GRAPHQL } = getUrls();
return forward(operation).map((response) => {
if (!context?.disableModify) {
if (Object.keys(response?.data).includes('evo_addproduct_types')) {
response.data.evo_addproduct_types = response.data.evo_addproduct_types.map(
(evo_addproduct_type) => {
if (evo_addproduct_type.evo_graph_price)
const modifyDataLink = new ApolloLink((operation, forward) => {
const context = operation?.getContext();
return forward(operation).map((response) => {
if (!context?.disableModify) {
if (Object.keys(response?.data).includes('evo_addproduct_types')) {
response.data.evo_addproduct_types = response.data.evo_addproduct_types.map(
(evo_addproduct_type) => {
if (evo_addproduct_type.evo_graph_price)
return {
...evo_addproduct_type,
label: `${evo_addproduct_type.label} (${evo_addproduct_type.evo_graph_price} руб.)`,
};
return evo_addproduct_type;
}
);
}
if (Object.keys(response?.data).includes('evo_equipments')) {
response.data.evo_equipments = response.data.evo_equipments.map((evo_equipment) => {
if (evo_equipment.evo_start_production_year)
return {
...evo_addproduct_type,
label: `${evo_addproduct_type.label} (${evo_addproduct_type.evo_graph_price} руб.)`,
...evo_equipment,
label: `${evo_equipment.label} (${evo_equipment.evo_start_production_year})`,
};
return evo_addproduct_type;
}
);
return evo_equipment;
});
}
if (operation.operationName === 'GetInsuranceCompanies') {
response.data.accounts = response.data.accounts
.sort((a, b) => {
if (isSovkom(a)) return -1;
if (isSovkom(b)) return 1;
return 0;
})
.map((account) => {
const substring = account.label.match(/"(.+)"/u);
if (substring)
return {
...account,
label: substring ? substring[1].replaceAll('"', '').trim() : account.label,
};
return account;
});
}
}
if (Object.keys(response?.data).includes('evo_equipments')) {
response.data.evo_equipments = response.data.evo_equipments.map((evo_equipment) => {
if (evo_equipment.evo_start_production_year)
return {
...evo_equipment,
label: `${evo_equipment.label} (${evo_equipment.evo_start_production_year})`,
};
return response;
});
});
return evo_equipment;
});
}
const httpLink = new HttpLink({
uri: URL_CRM_GRAPHQL,
});
if (operation.operationName === 'GetInsuranceCompanies') {
response.data.accounts = response.data.accounts.map((account) => {
const substring = account.label.match(/"(.+)"/u);
if (substring)
return {
...account,
label: substring ? substring[1].replaceAll('"', '').trim() : account.label,
};
const authLink = setContext((_, { headers: existingHeaders }) => {
if (process.env.NODE_ENV === 'development') {
const { publicRuntimeConfig } = getConfig();
const { DEV_AUTH_TOKEN } = publicRuntimeConfigSchema.parse(publicRuntimeConfig);
return account;
});
}
if (DEV_AUTH_TOKEN)
return {
headers: {
...existingHeaders,
authorization: `Bearer ${DEV_AUTH_TOKEN}`,
},
};
}
return response;
if (isServer()) {
return {
headers: {
...existingHeaders,
authorization: headers?.authorization,
},
};
}
return {
headers: {
...existingHeaders,
},
};
});
});
const httpLink = new HttpLink({
uri: URL_CRM_GRAPHQL,
});
const key = 'APOLLO_GRAPHQL';
const key = 'APOLLO_GRAPHQL';
const errorLink = onError(({ graphQLErrors, networkError, operation, response }) => {
const scope = getCurrentScope();
scope.setTag('operationName', operation.operationName);
const errorLink = onError(({ graphQLErrors, networkError, operation, response }) => {
const scope = getCurrentScope();
scope.setTag('operationName', operation.operationName);
if (!isServer()) {
message.error({
content: `Ошибка во время загрузки данных из CRM`,
key,
onClick: () => message.destroy(key),
});
}
if (!isServer()) {
message.error({
content: `Ошибка во время загрузки данных из CRM`,
key,
onClick: () => message.destroy(key),
scope.setExtras({
graphQLErrors,
networkError,
operation,
response,
});
}
scope.setExtras({
graphQLErrors,
networkError,
operation,
response,
});
});
export const link = from([errorLink, modifyDataLink, httpLink]);
return from([authLink, errorLink, modifyDataLink, httpLink]);
}

View File

@ -104,7 +104,7 @@ export const selectObjectCategoryTax = [
export const selectLeaseObjectUseFor = alphabetical(
[
{
label: 'Для представительских целей',
label: 'Для представительских целей / перевозки сотрудников ЛП',
value: 100_000_000,
},
{
@ -151,10 +151,10 @@ export const selectLeaseObjectUseFor = alphabetical(
label: 'Для перевозки сотрудников других организаций (водитель ЛП)',
value: 100_000_011,
},
{
label: 'Для перевозки сотрудников ЛП',
value: 100_000_012,
},
// {
// label: 'Для перевозки сотрудников ЛП',
// value: 100_000_012,
// },
{
label: 'Для экскурсионных перевозок в т.ч. на торжества; трансфер в аэропорт и пр.',
value: 100_000_013,
@ -183,6 +183,10 @@ export const selectLeaseObjectUseFor = alphabetical(
label: 'Строительство',
value: 100_000_019,
},
{
label: 'Перевозка опасных и легковоспламеняющихся грузов',
value: 100_000_020,
},
],
(objectUseFor) => objectUseFor.label.toLowerCase(),
'asc'
@ -507,6 +511,7 @@ const defaultOptions: CalculationOptions = {
cbxPartialVAT: [],
cbxFloatingRate: [],
cbxQuotePriceWithFullVAT: [],
cbxQuoteShowAcceptLimit: [],
};
export default defaultOptions;

View File

@ -18,6 +18,7 @@ const defaultStatuses: CalculationStatuses = {
cbxPriceWithDiscount: 'Default',
cbxQuotePriceWithFullVAT: 'Default',
cbxQuoteRedemptionGraph: 'Default',
cbxQuoteShowAcceptLimit: 'Default',
cbxRecalcWithRevision: 'Default',
cbxRegistrationQuote: 'Default',
cbxShowFinGAP: 'Default',

View File

@ -22,7 +22,7 @@ const defaultValues: CalculationValues = {
comissionRub: 0,
configuration: null,
costIncrease: true,
countSeats: 0,
countSeats: 4,
creditRate: RATE,
dealer: null,
dealerBroker: null,
@ -144,6 +144,7 @@ const defaultValues: CalculationValues = {
partialVAT: false,
floatingRate: false,
quotePriceWithFullVAT: false,
quoteShowAcceptLimit: true,
};
export default defaultValues;

View File

@ -2,6 +2,7 @@ import { withBasePath } from '@/config/urls';
export const metaFavicon = (
<>
<link rel="icon" type="image/x-icon" href={withBasePath('/favicon.ico')} sizes="32x32" />
<link rel="apple-touch-icon" sizes="180x180" href={withBasePath('/apple-touch-icon.png')} />
<link rel="icon" type="image/png" sizes="32x32" href={withBasePath('/favicon-32x32.png')} />
<link rel="icon" type="image/png" sizes="16x16" href={withBasePath('/favicon-16x16.png')} />

View File

@ -270,6 +270,7 @@ export const ResultEltOsagoSchema = z.object({
export const RowSchema = z.object({
id: z.string(),
insuranceCondition: z.string().nullable(),
key: z.string(),
message: z.string().nullable(),
metodCalc: z.union([z.literal('CRM'), z.literal('ELT')]),

View File

@ -2,6 +2,8 @@ const { z } = require('zod');
const envSchema = z.object({
BASE_PATH: z.string().optional().default(''),
DEV_AUTH_TOKEN: z.string().optional(),
PASSWORD_1C_TRANSTAX: z.string(),
PORT: z.string().optional(),
SENTRY_AUTH_TOKEN: z.string(),
SENTRY_DSN: z.string(),
@ -21,6 +23,7 @@ const envSchema = z.object({
URL_ELT_OSAGO_DIRECT: z.string(),
URL_GET_USER_DIRECT: z.string(),
USE_DEV_COLORS: z.unknown().optional().transform(Boolean),
USERNAME_1C_TRANSTAX: z.string(),
});
module.exports = envSchema;

View File

@ -2,6 +2,7 @@ const envSchema = require('./env');
const publicRuntimeConfigSchema = envSchema.pick({
BASE_PATH: true,
DEV_AUTH_TOKEN: true,
SENTRY_DSN: true,
SENTRY_ENVIRONMENT: true,
USE_DEV_COLORS: true,
@ -9,6 +10,8 @@ const publicRuntimeConfigSchema = envSchema.pick({
const serverRuntimeConfigSchema = envSchema.pick({
BASE_PATH: true,
DEV_AUTH_TOKEN: true,
PASSWORD_1C_TRANSTAX: true,
PORT: true,
SENTRY_DSN: true,
SENTRY_ENVIRONMENT: true,
@ -25,6 +28,7 @@ const serverRuntimeConfigSchema = envSchema.pick({
URL_ELT_KASKO_DIRECT: true,
URL_ELT_OSAGO_DIRECT: true,
URL_GET_USER_DIRECT: true,
USERNAME_1C_TRANSTAX: true,
});
module.exports = {

View File

@ -129,6 +129,7 @@ const ValuesSchema = z.object({
withTrailer: z.boolean(),
partialVAT: z.boolean(),
floatingRate: z.boolean(),
quoteShowAcceptLimit: z.boolean(),
/**
* Link Values

View File

@ -12,3 +12,5 @@ export const VEHICLE_SEATS = 20;
export const ESN = 1.3;
export const NSIB_MAX = 5_000_000;
export const NDFL = 0.13;
export const IRR_THRESHOLD = 0.001;

View File

@ -0,0 +1,34 @@
import { createContext, useEffect, useMemo, useState } from 'react';
type Tab = {
icon: JSX.Element;
key: string;
title: string;
useShowBadge?: () => boolean;
};
type NavigationContextType = {
currentTab: string;
setCurrentTab: (tab: string) => void;
setTabsList: (list: Tab[]) => void;
tabsList: Tab[];
};
export const NavigationContext = createContext<NavigationContextType>({} as NavigationContextType);
export function NavigationProvider({ children }: { readonly children: React.ReactNode }) {
const [currentTab, setCurrentTab] = useState('');
const [tabsList, setTabsList] = useState<Tab[]>([]);
useEffect(() => {
const defaultTab = tabsList.at(0);
if (defaultTab) setCurrentTab(defaultTab.key);
}, [tabsList]);
const value = useMemo(
() => ({ currentTab, setCurrentTab, setTabsList, tabsList }),
[currentTab, setCurrentTab, setTabsList, tabsList]
);
return <NavigationContext.Provider value={value}>{children}</NavigationContext.Provider>;
}

View File

@ -8,7 +8,7 @@ query GetTransactionCurrencies {
}
}
query GetTransactionCurrency($currencyid: Uuid!) {
query GetTransactionCurrency($currencyid: UUID!) {
transactioncurrency(transactioncurrencyid: $currencyid) {
currencysymbol
isocurrencycode
@ -17,20 +17,33 @@ query GetTransactionCurrency($currencyid: Uuid!) {
}
query GetCurrencyChanges($currentDate: DateTime) {
evo_currencychanges(statecode: 0, evo_coursedate_param: { eq: $currentDate }) {
evo_currencychanges(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_coursedate", eq: $currentDate } }
]
}
) {
evo_currencychange
evo_ref_transactioncurrency
}
}
query GetLeads($domainname: String) {
leads(owner_domainname: $domainname) {
label: fullname
value: leadid
systemusers(
filterConditionGroup: {
andFilterConditions: { filterConditionString: { fieldName: "domainname", eq: $domainname } }
}
) {
leads(orderby: { fieldName: "createdon", sortingType: DESC }) {
label: fullname
value: leadid
}
}
}
query GetLead($leadid: Uuid!) {
query GetLead($leadid: UUID!) {
lead(leadid: $leadid) {
evo_agent_accountid
evo_double_agent_accountid
@ -52,7 +65,7 @@ query GetLead($leadid: Uuid!) {
}
}
query GetOpportunity($opportunityid: Uuid!) {
query GetOpportunity($opportunityid: UUID!) {
opportunity(opportunityid: $opportunityid) {
evo_leadid
accountidData {
@ -67,14 +80,28 @@ query GetOpportunity($opportunityid: Uuid!) {
}
query GetOpportunities($domainname: String) {
opportunities(owner_domainname: $domainname) {
label: name
value: opportunityid
systemusers(
filterConditionGroup: {
andFilterConditions: { filterConditionString: { fieldName: "domainname", eq: $domainname } }
}
) {
opportunities(orderby: { fieldName: "createdon", sortingType: DESC }) {
label: name
value: opportunityid
}
}
}
query GetQuotes($leadid: Uuid!) {
quotes(evo_leadid: $leadid) {
query GetQuotes($leadid: UUID!) {
quotes(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionGuid: { fieldName: "evo_leadid", eq: $leadid } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
orderby: { fieldName: "createdon", sortingType: DESC }
) {
label: evo_quotename
value: quoteid
evo_recalc_limit
@ -85,8 +112,8 @@ query GetQuotes($leadid: Uuid!) {
}
}
query GetQuote($quoteId: Uuid!) {
quote(quoteId: $quoteId) {
query GetQuote($quoteId: UUID!) {
quote(quoteid: $quoteId) {
evo_baseproductid
evo_one_year_insurance
evo_min_change_price
@ -110,11 +137,30 @@ query GetQuote($quoteId: Uuid!) {
evo_promotion
evo_sale_without_nds
link
evo_committee_quote
evo_msfo_irr
evo_accept_quoteid
evo_power
evo_engine_volume
evo_nsib
evo_addproduct_types {
evo_product_type
}
evo_db_accept_registration
evo_product_risks {
evo_addproduct_typeid
}
evo_fingap_payer
evo_osago_payer
evo_kasko_payer
evo_leasing_bonus_summ
evo_card_bonus_summ
evo_nsib_bonus_summ
}
}
query GetQuoteData($quoteId: Uuid!) {
quote(quoteId: $quoteId) {
query GetQuoteData($quoteId: UUID!) {
quote(quoteid: $quoteId) {
evo_addproduct_types {
evo_product_type
evo_addproduct_typeid
@ -209,7 +255,7 @@ query GetQuoteData($quoteId: Uuid!) {
evo_graphs {
createdon
evo_sumpay_withnds
evo_planpayments {
evo_planpayments(orderby: { fieldName: "evo_plandate", sortingType: ASC }) {
evo_payment_ratio
}
}
@ -263,14 +309,25 @@ query GetQuoteData($quoteId: Uuid!) {
evo_transactioncurrencyid
evo_equip_price
evo_coefficien_bonus_reducttion
evo_accept_limit_quote
evo_kasko_insurance_rulesidData {
evo_id
}
evo_osago_insurance_rulesiddData {
evo_id
}
}
}
query GetTarifs($currentDate: DateTime) {
evo_tarifs(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
) {
label: evo_name
value: evo_tarifid
@ -293,7 +350,7 @@ query GetTarifs($currentDate: DateTime) {
}
}
query GetTarif($tarifId: Uuid!) {
query GetTarif($tarifId: UUID!) {
evo_tarif(evo_tarifid: $tarifId) {
label: evo_name
value: evo_tarifid
@ -308,6 +365,7 @@ query GetTarif($tarifId: Uuid!) {
evo_datefrom
evo_rateid
evo_type
statecode
}
evo_irr_plan
evo_margin_min
@ -316,9 +374,13 @@ query GetTarif($tarifId: Uuid!) {
query GetRates($currentDate: DateTime) {
evo_rates(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
) {
label: evo_name
value: evo_rateid
@ -330,7 +392,7 @@ query GetRates($currentDate: DateTime) {
}
}
query GetRate($rateId: Uuid!) {
query GetRate($rateId: UUID!) {
evo_rate(evo_rateid: $rateId) {
evo_base_rate
evo_credit_period
@ -341,10 +403,14 @@ query GetRate($rateId: Uuid!) {
query GetProducts($currentDate: DateTime) {
evo_baseproducts(
statecode: 0
evo_relation: [100000000]
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionMultyPicklist: { fieldName: "evo_relation", oneof: [100000000] } }
]
}
) {
label: evo_name
value: evo_baseproductid
@ -355,7 +421,7 @@ query GetProducts($currentDate: DateTime) {
}
}
query GetProduct($productId: Uuid!) {
query GetProduct($productId: UUID!) {
evo_baseproduct(evo_baseproductid: $productId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -381,9 +447,13 @@ query GetProduct($productId: Uuid!) {
query GetSubsidies($currentDate: DateTime) {
evo_subsidies(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
) {
label: evo_name
value: evo_subsidyid
@ -391,7 +461,7 @@ query GetSubsidies($currentDate: DateTime) {
}
}
query GetSubsidy($subsidyId: Uuid!) {
query GetSubsidy($subsidyId: UUID!) {
evo_subsidy(evo_subsidyid: $subsidyId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -413,7 +483,7 @@ query GetSubsidy($subsidyId: Uuid!) {
}
}
query GetImportProgram($importProgramId: Uuid!) {
query GetImportProgram($importProgramId: UUID!) {
importProgram: evo_subsidy(evo_subsidyid: $importProgramId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -431,7 +501,7 @@ query GetImportProgram($importProgramId: Uuid!) {
}
query GetRegions {
evo_regions {
evo_regions(orderby: { fieldName: "evo_name", sortingType: ASC }) {
label: evo_name
value: evo_regionid
evo_fias_id
@ -439,7 +509,7 @@ query GetRegions {
}
}
query GetRegion($regionId: Uuid!) {
query GetRegion($regionId: UUID!) {
evo_region(evo_regionid: $regionId) {
evo_oktmo
accounts {
@ -449,8 +519,16 @@ query GetRegion($regionId: Uuid!) {
}
}
query GetTowns($regionId: Uuid!) {
evo_towns(evo_regionid: $regionId) {
query GetTowns($regionId: UUID!) {
evo_towns(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionGuid: { fieldName: "evo_regionid", eq: $regionId } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
orderby: { fieldName: "evo_name", sortingType: ASC }
) {
evo_fias_id
label: evo_name
value: evo_townid
@ -458,22 +536,33 @@ query GetTowns($regionId: Uuid!) {
}
}
query GetTown($townId: Uuid!) {
query GetTown($townId: UUID!) {
evo_town(evo_townid: $townId) {
evo_kladr_id
}
}
query GetGPSBrands {
evo_gps_brands(statecode: 0) {
evo_gps_brands(
filterConditionGroup: {
andFilterConditions: { filterConditionInt: { fieldName: "statecode", eq: 0 } }
}
) {
label: evo_name
value: evo_gps_brandid
evo_id
}
}
query GetGPSModels($gpsBrandId: Uuid!) {
evo_gps_models(evo_gps_brandid: $gpsBrandId) {
query GetGPSModels($gpsBrandId: UUID!) {
evo_gps_models(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionGuid: { fieldName: "evo_gps_brandid", eq: $gpsBrandId } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
) {
label: evo_name
value: evo_gps_modelid
evo_id
@ -481,14 +570,18 @@ query GetGPSModels($gpsBrandId: Uuid!) {
}
query GetLeaseObjectTypes {
evo_leasingobject_types(statecode: 0) {
evo_leasingobject_types(
filterConditionGroup: {
andFilterConditions: { filterConditionInt: { fieldName: "statecode", eq: 0 } }
}
) {
label: evo_name
value: evo_leasingobject_typeid
evo_leasingobject_typeid
}
}
query GetLeaseObjectType($leaseObjectTypeId: Uuid!) {
query GetLeaseObjectType($leaseObjectTypeId: UUID!) {
evo_leasingobject_type(evo_leasingobject_typeid: $leaseObjectTypeId) {
evo_vehicle_type
evo_id
@ -508,7 +601,12 @@ query GetLeaseObjectType($leaseObjectTypeId: Uuid!) {
}
query GetBrands {
evo_brands(statecode: 0) {
evo_brands(
filterConditionGroup: {
andFilterConditions: { filterConditionInt: { fieldName: "statecode", eq: 0 } }
}
orderby: { fieldName: "evo_name", sortingType: ASC }
) {
label: evo_name
value: evo_brandid
evo_brandid
@ -516,7 +614,7 @@ query GetBrands {
}
}
query GetBrand($brandId: Uuid!) {
query GetBrand($brandId: UUID!) {
evo_brand(evo_brandid: $brandId) {
evo_id
evo_importer_reward_perc
@ -526,8 +624,16 @@ query GetBrand($brandId: Uuid!) {
}
}
query GetModels($brandId: Uuid!) {
evo_models(statecode: 0, evo_brandid: $brandId) {
query GetModels($brandId: UUID!) {
evo_models(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionGuid: { fieldName: "evo_brandid", eq: $brandId } }
]
}
orderby: { fieldName: "evo_name", sortingType: ASC }
) {
label: evo_name
value: evo_modelid
evo_modelid
@ -537,7 +643,7 @@ query GetModels($brandId: Uuid!) {
}
}
query GetModel($modelId: Uuid!) {
query GetModel($modelId: UUID!) {
evo_model(evo_modelid: $modelId) {
evo_impairment_groupidData {
evo_name
@ -554,15 +660,22 @@ query GetModel($modelId: Uuid!) {
}
}
query GetConfigurations($modelId: Uuid!) {
evo_equipments(statecode: 0, evo_modelid: $modelId) {
query GetConfigurations($modelId: UUID!) {
evo_equipments(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionGuid: { fieldName: "evo_modelid", eq: $modelId } }
]
}
) {
label: evo_name
value: evo_equipmentid
evo_start_production_year
}
}
query GetConfiguration($configurationId: Uuid!) {
query GetConfiguration($configurationId: UUID!) {
evo_equipment(evo_equipmentid: $configurationId) {
evo_impairment_groupidData {
evo_name
@ -571,7 +684,7 @@ query GetConfiguration($configurationId: Uuid!) {
}
query GetDealers {
dealers: accounts(evo_account_type: [100000001], statecode: 0, evo_legal_form: 100000001) {
dealers {
label: name
value: accountid
accountid
@ -579,16 +692,16 @@ query GetDealers {
}
}
query GetDealer($dealerId: Uuid!) {
dealer: account(accountid: $dealerId) {
query GetDealer($dealerId: UUID!) {
dealer(accountid: $dealerId) {
evo_return_leasing_dealer
evo_broker_accountid
evo_supplier_financing_accept
}
}
query GetDealerPersons($dealerId: Uuid!) {
dealerPersons: salon_providers(statecode: 0, salonaccountid: $dealerId) {
query GetDealerPersons($dealerId: UUID!) {
dealerPersons: dealer_persons(salonaccountid: $dealerId) {
label: name
value: accountid
accountid
@ -598,27 +711,46 @@ query GetDealerPersons($dealerId: Uuid!) {
}
}
query GetDealerPerson($dealerPersonId: Uuid!) {
account(accountid: $dealerPersonId) {
query GetDealerPerson($dealerPersonId: UUID!) {
dealer_person(accountid: $dealerPersonId) {
evo_supplier_type
evo_supplier_financing_accept
evo_return_leasing_dealer
evo_broker_accountid
evo_supplier_financing_accept
evo_legal_form
evo_inn
}
}
query GetAgent($agentid: Uuid!) {
agent: account(accountid: $agentid) {
query GetAgent($agentid: UUID!) {
agent(accountid: $agentid) {
label: name
value: accountid
evo_inn
}
}
query GetRewardConditions($agentid: Uuid!, $currentDate: DateTime) {
query GetRewardConditions($agentid: UUID!, $currentDate: DateTime) {
evo_reward_conditions(
evo_agent_accountid: $agentid
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
statecode: 0
evo_agency_agreementid_param: { has: true }
filterConditionGroup: {
andFilterConditionGroup: [
{
orFilterConditions: [
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", eq: null } }
]
}
{
andFilterConditions: [
{ filterConditionGuid: { fieldName: "evo_agent_accountid", eq: $agentid } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionGuid: { fieldName: "evo_agency_agreementid", neq: null } }
]
}
]
}
) {
label: evo_name
value: evo_reward_conditionid
@ -627,7 +759,7 @@ query GetRewardConditions($agentid: Uuid!, $currentDate: DateTime) {
}
}
query GetRewardCondition($conditionId: Uuid!) {
query GetRewardCondition($conditionId: UUID!) {
evo_reward_condition(evo_reward_conditionid: $conditionId) {
evo_reward_summ
evo_reduce_reward
@ -642,16 +774,27 @@ query GetRewardCondition($conditionId: Uuid!) {
}
query GetSotCoefficientType($evo_id: String) {
evo_sot_coefficient_type(evo_id: $evo_id) {
evo_sot_coefficient_types(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionString: { fieldName: "evo_id", eq: $evo_id } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
) {
evo_sot_coefficient_typeid
}
}
query GetCoefficients($currentDate: DateTime) {
evo_coefficients(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
) {
evo_job_titleid
evo_sot_coefficient_typeid
@ -677,7 +820,11 @@ query GetCoefficients($currentDate: DateTime) {
}
query GetSystemUser($domainname: String) {
systemuser(domainname: $domainname) {
systemusers(
filterConditionGroup: {
filterCondition: { filterConditionString: { fieldName: "domainname", eq: $domainname } }
}
) {
evo_job_titleid
businessunitid
roles {
@ -695,9 +842,13 @@ fragment CoreAddProductTypesFields on evo_addproduct_type {
query GetAddproductTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
) {
...CoreAddProductTypesFields
evo_product_type
@ -711,7 +862,7 @@ query GetAddproductTypes($currentDate: DateTime) {
}
}
query GetAddProductType($addproductTypeId: Uuid!) {
query GetAddProductType($addproductTypeId: UUID!) {
evo_addproduct_type(evo_addproduct_typeid: $addproductTypeId) {
evo_description
evo_helpcard_type
@ -735,10 +886,14 @@ query GetAddProductType($addproductTypeId: Uuid!) {
query GetRegistrationTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000001
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000001 } }
]
}
) {
...CoreAddProductTypesFields
evo_leasingobject_types {
@ -754,10 +909,14 @@ query GetRegistrationTypes($currentDate: DateTime) {
query GetTechnicalCards($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000000
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000000 } }
]
}
) {
...CoreAddProductTypesFields
evo_min_period
@ -771,10 +930,14 @@ query GetTechnicalCards($currentDate: DateTime) {
query GetFuelCards($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000005
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000005 } }
]
}
) {
...CoreAddProductTypesFields
evo_min_period
@ -787,10 +950,14 @@ query GetFuelCards($currentDate: DateTime) {
query GetTelematicTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000004
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000004 } }
]
}
) {
...CoreAddProductTypesFields
evo_controls_program
@ -800,10 +967,14 @@ query GetTelematicTypes($currentDate: DateTime) {
query GetTrackerTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000003
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000003 } }
]
}
) {
...CoreAddProductTypesFields
evo_controls_program
@ -813,10 +984,14 @@ query GetTrackerTypes($currentDate: DateTime) {
query GetInsNSIBTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000002
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000002 } }
]
}
) {
...CoreAddProductTypesFields
evo_max_period
@ -834,10 +1009,14 @@ query GetInsNSIBTypes($currentDate: DateTime) {
query GetLeasingWithoutKaskoTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_product_type: 100000007
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000007 } }
]
}
) {
...CoreAddProductTypesFields
evo_product_type
@ -859,10 +1038,14 @@ query GetLeasingWithoutKaskoTypes($currentDate: DateTime) {
query GetOsagoAddproductTypes($currentDate: DateTime) {
evo_addproduct_types(
statecode: 0
evo_product_type: 100000008
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "evo_product_type", eq: 100000008 } }
]
}
) {
evo_product_type
evo_visible_calc
@ -880,16 +1063,18 @@ query GetOsagoAddproductTypes($currentDate: DateTime) {
}
}
query GetInsuranceCompany($accountId: Uuid!) {
account(accountid: $accountId) {
query GetInsuranceCompany($accountId: UUID!) {
account: insurance(accountid: $accountId) {
evo_osago_with_kasko
evo_legal_region_calc
accountid
evo_kasko_fact_part
evo_kasko_plan_part
}
}
query GetInsuranceCompanies {
accounts(evo_account_type: [100000002], statecode: 0) {
accounts: insurances {
evo_type_ins_policy
evo_evokasko_access
evo_inn
@ -899,11 +1084,73 @@ query GetInsuranceCompanies {
evo_id_elt
evo_id_elt_smr
evo_osago_id
evo_kasko_category
evo_osago_category
}
}
query GetEltInsuranceRules($currentDate: DateTime) {
evo_insurance_ruleses(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
) {
evo_id
evo_datefrom
evo_dateto
evo_risk
evo_category
evo_min_period
evo_max_period
evo_object_type
evo_use_for
evo_min_price
evo_max_price
evo_min_year
evo_max_year
evo_min_power
evo_max_power
evo_enginie_type
evo_opf
evo_min_mileage
evo_max_mileage
evo_brand
evo_model
evo_region
evo_dealer
evo_rules_type
evo_message
evo_discount
evo_insurer_accountid
evo_brand
evo_model
evo_region
evo_dealer
evo_brands {
evo_brandid
}
evo_models {
evo_modelid
}
accounts {
accountid
}
evo_regions {
evo_regionid
}
}
}
query GetRoles($roleName: String) {
roles(name: $roleName) {
roles(
filterConditionGroup: {
andFilterConditions: { filterConditionString: { fieldName: "name", eq: $roleName } }
}
) {
systemusers {
label: fullname
value: domainname

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,14 @@
import type * as CRMTypes from '@/graphql/crm.types';
function evo_baseproducts(evo_baseproducts: CRMTypes.GetProductsQuery['evo_baseproducts']) {
type SystemUser = NonNullable<CRMTypes.GetSystemUserQuery['systemusers']>[number];
function evo_baseproducts(baseproducts: CRMTypes.GetProductsQuery['evo_baseproducts']) {
return {
filterBy: {
systemuser(systemuser: CRMTypes.GetSystemUserQuery['systemuser']) {
if (!evo_baseproducts?.length || !systemuser) return [];
systemuser(systemuser: SystemUser) {
if (!baseproducts?.length || !systemuser) return [];
return evo_baseproducts?.filter(
return baseproducts?.filter(
(evo_baseproduct) =>
!evo_baseproduct?.systemusers?.length ||
evo_baseproduct?.systemusers?.some(

File diff suppressed because one or more lines are too long

17
apps/web/hooks/worker.ts Normal file
View File

@ -0,0 +1,17 @@
/* eslint-disable no-console */
import { useEffect } from 'react';
export function useServiceWorker() {
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((error) => {
console.log('Service Worker registration failed:', error);
});
}
}, []);
}

View File

@ -39,20 +39,23 @@ export const handlers = [
rest.post(URL_1C_TRANSTAX, (req, res, ctx) =>
res(
ctx.json({
error: null,
tax: _.random(100000, 200000),
Error: null,
Tax: _.random(100000, 200000),
})
)
),
rest.post(URL_ELT_OSAGO, async (req, res, ctx) => res(
rest.post(URL_ELT_OSAGO, async (req, res, ctx) =>
res(
ctx.json({
numCalc: _.random(1000000, 3000000),
skCalcId: _.random(50000000, 60000000).toString(),
premiumSum: _.random(10000, 20000),
message: 'OSAGO Message',
})
)),
rest.post(URL_ELT_KASKO, async (req, res, ctx) => res(
)
),
rest.post(URL_ELT_KASKO, async (req, res, ctx) =>
res(
ctx.json({
requestId: _.random(3000000, 4000000).toString(),
skCalcId: _.random(50000000, 60000000).toString(),
@ -67,7 +70,8 @@ export const handlers = [
],
totalFranchise: _.random(20000, 40000),
})
)),
)
),
// rest.post(URL_CRM_GRAPHQL, (req, res, ctx) => {
// return res(ctx.status(503));

View File

@ -29,6 +29,7 @@ module.exports = withSentryConfig(
},
experimental: {
outputFileTracingRoot: path.join(__dirname, '../../'),
proxyTimeout: 1000 * 90,
},
images: {
deviceSizes: devices,
@ -65,10 +66,10 @@ module.exports = withSentryConfig(
destination: env.URL_CORE_FINGAP_DIRECT,
source: urls.URL_CORE_FINGAP_PROXY,
},
{
destination: env.URL_1C_TRANSTAX_DIRECT,
source: urls.URL_1C_TRANSTAX_PROXY,
},
// {
// destination: env.URL_1C_TRANSTAX_DIRECT,
// source: urls.URL_1C_TRANSTAX_PROXY,
// },
{
destination: env.URL_ELT_KASKO_DIRECT,
source: urls.URL_ELT_KASKO_PROXY,

View File

@ -4,7 +4,7 @@
"private": true,
"scripts": {
"build": "next build",
"prebuild": "ts-node --project ./tsconfig.node.json ./scripts/generate-antd-css.ts",
"prebuild": "NODE_ENV=production ts-node --project ./tsconfig.node.json ./scripts/generate-antd-css.ts",
"dev": "next dev",
"predev": "ts-node --project ./tsconfig.node.json ./scripts/generate-antd-css.ts",
"lint": "next lint",
@ -16,6 +16,7 @@
},
"dependencies": {
"@apollo/client": "^3.9.5",
"@artsy/fresnel": "^7.1.4",
"@fontsource/montserrat": "^4.5.14",
"@sentry/nextjs": "^7.102.0",
"@sentry/node": "^7.102.0",
@ -28,14 +29,15 @@
"dayjs": "^1.11.10",
"mobx": "^6.12.0",
"mobx-react-lite": "^4.0.5",
"next": "^14.1.0",
"normalize.css": "^8.0.1",
"modern-normalize": "^2.0.0",
"next": "^14.2.5",
"radash": "^11.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"styled-components": "^5.3.11",
"superjson": "^2.2.1",
"tools": "workspace:*",
"ua-parser-js": "^1.0.38",
"ui": "workspace:*",
"use-debounce": "^9.0.4",
"zod": "^3.22.4"
@ -53,10 +55,11 @@
"@types/react": "^18.2.14",
"@types/react-dom": "^18.2.6",
"@types/styled-components": "^5.1.26",
"@types/ua-parser-js": "^0.7.39",
"@vchikalkin/eslint-config-awesome": "^1.1.6",
"antd": "^5.14.2",
"eslint": "^8.52.0",
"gql-sdl": "^1.0.0",
"gql-sdl": "^1.1.0",
"jest": "^29.4.3",
"jest-environment-jsdom": "^29.3.1",
"msw": "^1.1.0",

View File

@ -1,17 +1,18 @@
import 'normalize.css';
import '../styles/fonts.css';
import '../styles/globals.css';
import '../styles/antd-fix.css';
import '../styles/antd.min.css';
import initializeQueryClient from '@/api/client';
import initializeApollo from '@/apollo/client';
import { Loading, Notification } from '@/Components/Common';
import { Loading } from '@/Components/Common';
import Layout from '@/Components/Layout';
import { theme } from '@/config/ui';
import { usePageLoading } from '@/hooks';
import { useServiceWorker } from '@/hooks/worker';
import StoreProvider from '@/stores/Provider';
import getColors from '@/styles/colors';
import { GlobalStyle } from '@/styles/global-style';
import { MediaContextProvider } from '@/styles/media';
import { trpcClient } from '@/trpc/client';
import { ApolloProvider } from '@apollo/client';
import { QueryClientProvider } from '@tanstack/react-query';
@ -28,10 +29,14 @@ const colorPrimary = getColors().COLOR_PRIMARY;
function App({ Component, pageProps }) {
const { initialApolloState, initialQueryState } = pageProps;
const apolloClient = useMemo(() => initializeApollo(initialApolloState), [initialApolloState]);
const apolloClient = useMemo(
() => initializeApollo(initialApolloState, {}),
[initialApolloState]
);
const queryClient = useMemo(() => initializeQueryClient(initialQueryState), [initialQueryState]);
const { loading } = usePageLoading();
useServiceWorker();
return (
<ThemeProvider theme={theme}>
@ -55,11 +60,11 @@ function App({ Component, pageProps }) {
},
}}
>
<Notification>
<MediaContextProvider>
<Layout {...pageProps}>
{loading ? <Loading /> : <Component {...pageProps} />}
</Layout>
</Notification>
</MediaContextProvider>
</AntdConfig>
</QueryClientProvider>
</ApolloProvider>

View File

@ -29,7 +29,7 @@ export async function getServerSideProps({ req }) {
const { cookie = '' } = req.headers;
const queryClient = new QueryClient();
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, req.headers);
const getUserType = makeGetUserType({ apolloClient, queryClient });
try {

View File

@ -0,0 +1,38 @@
import type { ResponseTransTax } from '@/api/1c/types';
import { serverRuntimeConfigSchema } from '@/config/schema/runtime-config';
import { withHandleError } from '@/utils/axios';
import type { HttpError } from '@/utils/error';
import axios from 'axios';
import type { NextApiRequest, NextApiResponse } from 'next';
import getConfig from 'next/config';
const { serverRuntimeConfig } = getConfig();
const { USERNAME_1C_TRANSTAX, PASSWORD_1C_TRANSTAX, URL_1C_TRANSTAX_DIRECT } =
serverRuntimeConfigSchema.parse(serverRuntimeConfig);
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const abortController = new AbortController();
req.on('close', () => {
abortController.abort();
});
const params = req.body as ResponseTransTax;
withHandleError(
axios.get<ResponseTransTax>(URL_1C_TRANSTAX_DIRECT, {
auth: {
password: PASSWORD_1C_TRANSTAX,
username: USERNAME_1C_TRANSTAX,
},
params,
signal: abortController.signal,
})
)
.then(({ data }) => res.json(data))
.catch((error) => {
const _err = error as HttpError;
return res.json({ message: _err.message });
});
}

View File

@ -1,34 +1,23 @@
import initializeApollo from '@/apollo/client';
import * as Calculation from '@/Components/Calculation';
import { Content } from '@/Components/Calculation';
import { Error } from '@/Components/Common/Error';
import * as hooks from '@/process/hooks';
import { getPageTitle } from '@/utils/page';
import { makeGetUserType } from '@/utils/user';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Head from 'next/head';
function Content() {
hooks.useSentryScope();
hooks.useMainData();
hooks.useInsuranceData();
hooks.useReactions();
return (
<Calculation.Layout>
<Head>
<title>{getPageTitle()}</title>
</Head>
<Calculation.Form prune={['unlimited']} />
<Calculation.Settings />
<Calculation.Output />
</Calculation.Layout>
);
}
export default function Page(props) {
if (props.statusCode !== 200) return <Error {...props} />;
return <Content />;
return (
<Content
initHooks={() => {
hooks.useSentryScope();
hooks.useMainData();
hooks.useInsuranceData();
hooks.useReactions();
}}
/>
);
}
/** @type {import('next').GetServerSideProps} */
@ -36,7 +25,7 @@ export async function getServerSideProps({ req }) {
const { cookie = '' } = req.headers;
const queryClient = new QueryClient();
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, req.headers);
const getUserType = makeGetUserType({ apolloClient, queryClient });
try {

View File

@ -1,35 +1,25 @@
import initializeApollo from '@/apollo/client';
import * as Calculation from '@/Components/Calculation';
import { Content } from '@/Components/Calculation';
import { Error } from '@/Components/Common/Error';
import * as hooks from '@/process/hooks';
import { getPageTitle } from '@/utils/page';
import { makeGetUserType } from '@/utils/user';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Head from 'next/head';
function Content() {
hooks.useSentryScope();
hooks.useMainData();
hooks.useGetUsers();
hooks.useInsuranceData();
hooks.useReactions();
return (
<Calculation.Layout>
<Head>
<title>{getPageTitle('Без ограничений')}</title>
</Head>
<Calculation.Form />
<Calculation.Settings />
<Calculation.Output />
</Calculation.Layout>
);
}
export default function Page(props) {
if (props.statusCode !== 200) return <Error {...props} />;
return <Content />;
return (
<Content
title="Без ограничений"
initHooks={() => {
hooks.useSentryScope();
hooks.useMainData();
hooks.useGetUsers();
hooks.useInsuranceData();
hooks.useReactions();
}}
/>
);
}
/** @type {import('next').GetServerSideProps} */
@ -37,7 +27,7 @@ export async function getServerSideProps({ req }) {
const { cookie = '' } = req.headers;
const queryClient = new QueryClient();
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, req.headers);
const getUserType = makeGetUserType({ apolloClient, queryClient });
try {

View File

@ -1,14 +1,12 @@
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
import * as CRMTypes from '@/graphql/crm.types';
export async function getKPData({
values: { recalcWithRevision },
quote,
ctx: { apolloClient },
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const apolloClient = initializeApollo();
const registration =
quote?.evo_addproduct_types?.find((x) => x?.evo_product_type === 100_000_001)
?.evo_addproduct_typeid ?? defaultValues.registration;

View File

@ -4,13 +4,14 @@ import type { ProcessContext } from '../types';
import { createValidationSchema } from './validation';
import { selectRequirementTelematic } from '@/config/default-options';
import * as CRMTypes from '@/graphql/crm.types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import { debouncedReaction } from '@/utils/mobx';
import { reaction, toJS } from 'mobx';
import { reaction } from 'mobx';
import { max } from 'radash';
export default function reactions({ store, apolloClient }: ProcessContext) {
const { $calculation, $tables } = store;
const { $calculation, $process } = store;
reaction(
() => $calculation.$values.getValues(['leasingPeriod', 'leaseObjectType', 'maxMass']),
@ -20,7 +21,7 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
return;
}
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -47,9 +48,9 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
)
);
$calculation.element('selectTechnicalCard').setOptions(normalizeOptions(options));
const currentTechnicalCardId = $calculation.element('selectTechnicalCard').getValue();
$calculation.element('selectTechnicalCard').setOptions(normalizeOptions(options));
if (currentTechnicalCardId) {
const {
data: { evo_addproduct_type },
@ -74,10 +75,58 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
}
);
/**
* Устанавливаем самую дорогую техническую карточку по умолчанию первый раз при формировании списка карт
*/
{
const dispose = reaction(
() => {
const technicalCards = $calculation.element('selectTechnicalCard').getOptions();
const isLoadKP = $process.has('LoadKP');
return { isLoadKP, technicalCards };
},
async ({ technicalCards, isLoadKP }) => {
if (isLoadKP) {
dispose();
return;
}
const currentTechnicalCard = $calculation.element('selectTechnicalCard').getValue();
if (technicalCards.length && !currentTechnicalCard) {
const evo_addproduct_types = await Promise.all(
technicalCards.map(async (x) => {
const {
data: { evo_addproduct_type },
} = await apolloClient.query({
query: CRMTypes.GetAddProductTypeDocument,
variables: { addproductTypeId: x.value },
});
return evo_addproduct_type;
})
);
const maxPriceTechnicalCard = max(evo_addproduct_types, (x) => x?.evo_graph_price ?? 0);
if (maxPriceTechnicalCard) {
$calculation
.element('selectTechnicalCard')
.setValue(maxPriceTechnicalCard?.evo_addproduct_typeid);
}
dispose();
}
}
);
}
reaction(
() => $calculation.$values.getValues(['leasingPeriod', 'leaseObjectType']),
async ({ leasingPeriod, leaseObjectType }) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -111,35 +160,35 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
}
);
reaction(
() => {
const values = $calculation.$values.getValues(['leasingPeriod', 'leasingWithoutKasko']);
const kaskoInsured = toJS($tables.insurance.row('kasko').getValue('insured'));
const fingapInsured = toJS($tables.insurance.row('fingap').getValue('insured'));
// reaction(
// () => {
// const values = $calculation.$values.getValues(['leasingPeriod', 'leasingWithoutKasko']);
// const kaskoInsured = toJS($tables.insurance.row('kasko').getValue('insured'));
// const fingapInsured = toJS($tables.insurance.row('fingap').getValue('insured'));
return {
...values,
fingapInsured,
kaskoInsured,
};
},
({ leasingPeriod, fingapInsured, kaskoInsured, leasingWithoutKasko }) => {
if (
leasingPeriod < 12 ||
leasingWithoutKasko ||
kaskoInsured === 100_000_001 ||
(fingapInsured === 100_000_001 && leasingPeriod < 36)
) {
$calculation.element('selectInsNSIB').resetValue().block();
} else {
$calculation.element('selectInsNSIB').unblock();
}
},
{
delay: 10,
fireImmediately: true,
}
);
// return {
// ...values,
// fingapInsured,
// kaskoInsured,
// };
// },
// ({ leasingPeriod, fingapInsured, kaskoInsured, leasingWithoutKasko }) => {
// if (
// leasingPeriod < 12 ||
// leasingWithoutKasko ||
// kaskoInsured === 100_000_001 ||
// (fingapInsured === 100_000_001 && leasingPeriod < 36)
// ) {
// $calculation.element('selectInsNSIB').resetValue().block();
// } else {
// $calculation.element('selectInsNSIB').unblock();
// }
// },
// {
// delay: 10,
// fireImmediately: true,
// }
// );
debouncedReaction(
() =>
@ -161,7 +210,7 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
leasingPeriod,
plPriceRub,
}) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -274,7 +323,7 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
leaseObjectType: leaseObjectTypeId,
engineType,
}) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types: trackerTypes },
} = await apolloClient.query({

View File

@ -1,7 +1,7 @@
import type { ValidationContext } from '../../types';
import type { ElementsTypes } from '@/Components/Calculation/config/map/values';
import * as CRMTypes from '@/graphql/crm.types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
export type ProductId = ElementsTypes['selectProduct'];
@ -13,7 +13,7 @@ export default function helper({ apolloClient, user }: ValidationContext) {
}
const {
data: { systemuser },
data: { systemusers },
} = await apolloClient.query({
query: CRMTypes.GetSystemUserDocument,
variables: {
@ -21,11 +21,13 @@ export default function helper({ apolloClient, user }: ValidationContext) {
},
});
const systemuser = systemusers?.[0];
if (!systemuser?.evo_job_titleid) {
return null;
}
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_coefficients },

View File

@ -10,8 +10,17 @@ export function createValidationSchema(context: ValidationContext) {
return ValuesSchema.pick({ product: true, saleBonus: true }).superRefine(
async ({ product, saleBonus }, ctx) => {
const coefficient = await getCoefficient(product);
const minBonus = (coefficient?.evo_correction_coefficient || 0) * 100;
const maxBonus = (coefficient?.evo_sot_coefficient || 0) * 100;
if (round(saleBonus, 2) < round(minBonus, 2)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Бонус не может быть ниже установленного по СОТ',
path: ['tbxSaleBonus'],
});
}
if (round(saleBonus, 2) > round(maxBonus, 2)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,

View File

@ -1,4 +1,5 @@
import helper from '../lib/helper';
import { IRR_THRESHOLD } from '@/constants/values';
import type { ProcessContext } from '@/process/types';
import { disposableReaction } from '@/utils/mobx';
import { comparer, reaction } from 'mobx';
@ -31,7 +32,8 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
const { getIrr } = helper({ apolloClient });
reaction(
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.$values.getValues(['product', 'tarif', 'bonusCoefficient']),
async (values) => {
const { min, max } = await getIrr(values);
@ -40,6 +42,19 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
}
);
// костыль
disposableReaction(
() =>
$process.has('LoadKP') ||
$calculation.element('radioLastPaymentRule').getValue() === 100_000_002,
() => $calculation.element('labelIrrInfo').getValue(),
({ min }) => {
if ($calculation.element('radioLastPaymentRule').getValue() === 100_000_002) return;
$calculation.element('tbxIRR_Perc').setValue(min + IRR_THRESHOLD);
}
);
disposableReaction(
() => $process.has('Calculate') || $process.has('CreateKP'),
() => {

View File

@ -2,7 +2,6 @@
/* eslint-disable complexity */
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import helper from './lib/helper';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
import calculateHelper from '@/process/calculate/lib/helper';
import { getKPData as getKPDataPrice } from '@/process/price/get-kp-data';
@ -13,15 +12,16 @@ import { normalizeOptions } from '@/utils/entity';
export async function getKPData({
values,
quote,
ctx,
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const { apolloClient } = ctx;
const { recalcWithRevision } = values;
const apolloClient = initializeApollo();
const leasingPeriod = recalcWithRevision
? Math.min(quote?.evo_period ?? 0, quote?.evo_accept_period ?? 0)
: quote?.evo_period ?? 0;
const { getTarifs, getRates, getPriceChange } = helper({ apolloClient });
const { getTarifs, getRates, getPriceChange, getCreditRate } = helper({ apolloClient });
let tarif = defaultValues.tarif;
let evo_tarif: unknown = null;
@ -61,8 +61,8 @@ export async function getKPData({
let minPriceChange = quote?.evo_min_change_price ?? defaultValues.minPriceChange;
if (!recalcWithRevision) {
const kpDataPrice = await getKPDataPrice({ quote, values });
const kpDataSubsidy = await getKPDataSubsidy({ quote, values });
const kpDataPrice = await getKPDataPrice({ ctx, quote, values });
const kpDataSubsidy = await getKPDataSubsidy({ ctx, quote, values });
const supplierCurrency = kpDataPrice.values?.supplierCurrency ?? defaultValues.supplierCurrency;
const leaseObjectPrice = kpDataPrice.values?.leaseObjectPrice ?? defaultValues.leaseObjectPrice;
@ -106,6 +106,8 @@ export async function getKPData({
tarif,
});
const creditRate = await getCreditRate({ rate: evo_rate?.evo_rateid ?? null });
return {
options: {
selectTarif: evo_tarif ? normalizeOptions([evo_tarif]) : [],
@ -113,6 +115,7 @@ export async function getKPData({
values: {
IRR_Perc: quote?.evo_msfo_irr ?? defaultValues.IRR_Perc,
clientType: quote?.evo_client_typeid,
creditRate,
floatingRate: quote?.evo_floating_rate ?? false,
irrInfo,
maxPriceChange,

View File

@ -1,9 +1,10 @@
/* eslint-disable sonarjs/cognitive-complexity */
import defaultValues from '@/config/default-values';
import { RATE } from '@/constants/values';
import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import type { CalculationValues } from '@/stores/calculation/values/types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import dayjs from 'dayjs';
import { first, sort } from 'radash';
@ -22,6 +23,8 @@ type GetTarifInputValues = Pick<
type GetRatesInputValues = Pick<CalculationValues, 'tarif'>;
type GetCreditRateInputValues = Pick<CalculationValues, 'rate'>;
type GetPriceChangeInputValues = Pick<
CalculationValues,
| 'addEquipmentPrice'
@ -34,6 +37,22 @@ type GetPriceChangeInputValues = Pick<
export default function helper({ apolloClient }: Pick<ProcessContext, 'apolloClient'>) {
return {
async getCreditRate({ rate: rateId }: GetCreditRateInputValues) {
if (!rateId) return RATE;
const {
data: { evo_rate },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetRateDocument,
variables: {
rateId,
},
});
return evo_rate?.evo_base_rate ?? RATE;
},
async getPriceChange({
discountRub,
importProgramSum,
@ -80,7 +99,7 @@ export default function helper({ apolloClient }: Pick<ProcessContext, 'apolloCli
},
async getRates({ tarif: tarifId }: GetRatesInputValues) {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_rates },
@ -106,7 +125,7 @@ export default function helper({ apolloClient }: Pick<ProcessContext, 'apolloCli
});
const filtered_evo_tarif_evo_rates =
evo_tarif?.evo_rates?.filter((x) => x?.evo_type === 100_000_000) || [];
evo_tarif?.evo_rates?.filter((x) => x?.evo_type === 100_000_000 && x.statecode === 0) || [];
const evo_tarif_evo_rate =
evo_tarif?.evo_rates &&
@ -138,7 +157,7 @@ export default function helper({ apolloClient }: Pick<ProcessContext, 'apolloCli
floatingRate,
partialVAT,
}: GetTarifInputValues) {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_tarifs = [] },

View File

@ -4,7 +4,7 @@ import { crmTools } from '@/graphql/crm.tools';
import * as CRMTypes from '@/graphql/crm.types';
import { SEASON_TYPES } from '@/process/payments/lib/seasons-constants';
import type { ProcessContext } from '@/process/types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import { disposableReaction } from '@/utils/mobx';
import { reaction } from 'mobx';
@ -355,7 +355,7 @@ export default function reactions({ store, apolloClient, user }: ProcessContext)
reaction(
() => $calculation.element('selectQuote').getValue(),
async (quoteId) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
let {
data: { evo_baseproducts },
@ -369,7 +369,7 @@ export default function reactions({ store, apolloClient, user }: ProcessContext)
if (user && evo_baseproducts) {
const {
data: { systemuser },
data: { systemusers },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetSystemUserDocument,
@ -378,9 +378,13 @@ export default function reactions({ store, apolloClient, user }: ProcessContext)
},
});
evo_baseproducts = crmTools
.evo_baseproducts(evo_baseproducts)
.filterBy.systemuser(systemuser);
const systemuser = systemusers?.[0];
if (systemuser) {
evo_baseproducts = crmTools
.evo_baseproducts(evo_baseproducts)
.filterBy.systemuser(systemuser);
}
}
if (!$calculation.element('cbxRecalcWithRevision').getValue()) {

View File

@ -16,23 +16,35 @@ export default function unlimitedReactions({ store, apolloClient }: ProcessConte
return;
}
const {
data: { leads },
} = await apolloClient.query({
query: CRMTypes.GetLeadsDocument,
variables: { domainname },
});
$calculation.element('selectLead').setOptions(normalizeOptions(leads));
{
const { data } = await apolloClient.query({
query: CRMTypes.GetLeadsDocument,
variables: { domainname },
});
const {
data: { opportunities },
} = await apolloClient.query({
query: CRMTypes.GetOpportunitiesDocument,
variables: { domainname },
});
const systemuser = data?.systemusers?.[0];
$calculation.element('selectOpportunity').setOptions(normalizeOptions(opportunities));
if (systemuser) {
const { leads } = systemuser;
$calculation.element('selectLead').setOptions(normalizeOptions(leads));
}
}
{
const { data } = await apolloClient.query({
query: CRMTypes.GetOpportunitiesDocument,
variables: { domainname },
});
const systemuser = data?.systemusers?.[0];
if (systemuser) {
const { opportunities } = systemuser;
$calculation.element('selectOpportunity').setOptions(normalizeOptions(opportunities));
}
}
}
);
}

View File

@ -10,7 +10,7 @@ export default function valuesReactions({ store, apolloClient, trpcClient }: Pro
let abortController = new AbortController();
const { $calculation, $process } = store;
const { getRates, getPriceChange } = helper({ apolloClient });
const { getRates, getPriceChange, getCreditRate } = helper({ apolloClient });
disposableDebouncedReaction(
() => $process.has('LoadKP'),
@ -123,32 +123,13 @@ export default function valuesReactions({ store, apolloClient, trpcClient }: Pro
}
);
reaction(
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('selectRate').getValue(),
async (rateId) => {
if (!rateId) {
$calculation.element('tbxCreditRate').resetValue();
async (rate) => {
const creditRate = await getCreditRate({ rate });
return;
}
const {
data: { evo_rate },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetRateDocument,
variables: {
rateId,
},
});
if (evo_rate?.evo_base_rate === null || evo_rate?.evo_base_rate === undefined) {
$calculation.element('tbxCreditRate').resetValue();
return;
}
$calculation.element('tbxCreditRate').setValue(evo_rate?.evo_base_rate);
$calculation.element('tbxCreditRate').setValue(creditRate);
}
);

View File

@ -16,6 +16,7 @@ export async function getKPData({ quote }: GetQuoteInputData): Promise<GetQuoteP
quoteName: quote?.evo_contact_name ?? defaultValues.quoteName,
quotePriceWithFullVAT: quote?.evo_full_nds_price ?? defaultValues.quotePriceWithFullVAT,
quoteRedemptionGraph: quote?.evo_redemption_graph ?? defaultValues.quoteRedemptionGraph,
quoteShowAcceptLimit: quote?.evo_accept_limit_quote ?? defaultValues.quoteShowAcceptLimit,
registrationQuote: quote?.evo_registration_quote ?? defaultValues.registrationQuote,
showFinGAP: quote?.evo_fingap_quote ?? defaultValues.showFinGAP,
technicalCardQuote: quote?.evo_card_quote ?? defaultValues.technicalCardQuote,

View File

@ -1,28 +1,37 @@
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import { defaultRow } from '@/stores/tables/elt/default-values';
export async function getKPData({ quote }: GetQuoteInputData): Promise<GetQuoteProcessData> {
const elt: NonNullable<GetQuoteProcessData['elt']> = { kasko: undefined, osago: undefined };
if (
quote?.evo_kasko_accountid &&
quote?.evo_id_elt_kasko &&
quote?.evo_id_kasko_calc &&
((quote?.evo_id_elt_kasko && quote?.evo_id_kasko_calc) ||
quote.evo_kasko_insurance_rulesidData?.evo_id) &&
quote?.evo_kasko_price &&
quote?.evo_franchise !== null
) {
elt.kasko = {
insuranceCondition:
quote.evo_kasko_insurance_rulesidData?.evo_id ?? defaultRow.insuranceCondition,
key: quote?.evo_kasko_accountid,
requestId: quote?.evo_id_elt_kasko,
skCalcId: quote?.evo_id_kasko_calc,
requestId: quote?.evo_id_elt_kasko ?? defaultRow.requestId,
skCalcId: quote?.evo_id_kasko_calc ?? defaultRow.skCalcId,
sum: quote?.evo_kasko_price,
totalFranchise: quote?.evo_franchise,
};
}
if (quote?.evo_osago_accountid && quote?.evo_id_elt_osago && quote?.evo_osago_price) {
if (
quote?.evo_osago_accountid &&
(quote?.evo_id_elt_osago || quote.evo_osago_insurance_rulesiddData?.evo_id) &&
quote?.evo_osago_price
) {
elt.osago = {
insuranceCondition:
quote.evo_osago_insurance_rulesiddData?.evo_id ?? defaultRow.insuranceCondition,
key: quote?.evo_osago_accountid,
numCalc: quote?.evo_id_elt_osago,
numCalc: quote?.evo_id_elt_osago ?? defaultRow.numCalc,
sum: quote?.evo_osago_price,
};
}

View File

@ -30,14 +30,19 @@ export default function helper({
({ evo_leasingobject_type } = data);
}
// const leaseObjectCategory = $calculation.element('selectLeaseObjectCategory').getValue();
return {
kasko: (accounts
?.filter((x) =>
x?.evo_type_ins_policy?.includes(100_000_000) &&
evo_leasingobject_type?.evo_id &&
['6', '9', '10'].includes(evo_leasingobject_type?.evo_id)
? Boolean(x.evo_id_elt_smr)
: Boolean(x?.evo_id_elt)
?.filter(
(x) =>
x?.evo_type_ins_policy?.includes(100_000_000) &&
// leaseObjectCategory &&
// x.evo_kasko_category?.includes(leaseObjectCategory) &&
(evo_leasingobject_type?.evo_id &&
['6', '9', '10'].includes(evo_leasingobject_type.evo_id)
? x?.evo_id_elt_smr
: x?.evo_id_elt)
)
.map((x) => ({
...defaultRow,
@ -53,6 +58,8 @@ export default function helper({
?.filter(
(x) =>
x?.evo_type_ins_policy?.includes(100_000_001) &&
// leaseObjectCategory &&
// x.evo_osago_category?.includes(leaseObjectCategory) &&
(x?.evo_id_elt_osago || x.evo_osago_id)
)
.map((x) => ({

View File

@ -1,18 +1,18 @@
/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable complexity */
import type { Row } from '../types';
import type { RequestEltKasko, RequestEltOsago } from '@/api/elt/types';
import type { Row } from '@/Components/Calculation/Form/ELT/types';
import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import dayjs from 'dayjs';
import { first, sort } from 'radash';
export async function makeOwnOsagoRequest(
export async function ownOsagoRequest(
{ store, apolloClient }: Pick<ProcessContext, 'apolloClient' | 'store'>,
row: Row
): Promise<NonNullable<CRMTypes.GetOsagoAddproductTypesQuery['evo_addproduct_types']>[number]> {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -471,7 +471,8 @@ export async function makeEltKaskoRequest(
let selfIgnitionSpecified = false;
if (
leaseObjectCategory === 100_000_002 ||
(evo_leasingobject_type?.evo_id && ['6', '9', '10'].includes(evo_leasingobject_type?.evo_id))
(evo_leasingobject_type?.evo_id &&
['6', '8', '9', '10'].includes(evo_leasingobject_type?.evo_id))
) {
notConfirmedGlassesDamages = 3;
notConfirmedGlassesDamagesSpecified = true;
@ -572,6 +573,7 @@ export async function makeEltKaskoRequest(
100_000_011: 3,
100_000_012: 3,
100_000_013: 9,
100_000_020: 10,
};
const leaseObjectUseFor = $calculation.element('selectLeaseObjectUseFor').getValue();
@ -616,10 +618,26 @@ export async function makeEltKaskoRequest(
}
}
const classification =
leaseObjectCategory && [100_000_002, 100_000_003, 100_000_004].includes(leaseObjectCategory)
? '11635'
: '0';
let classification = '11606';
switch (evo_leasingobject_type?.evo_id) {
case '7': {
classification = '11611';
break;
}
case '3': {
classification = '11607';
break;
}
case '8': {
classification = '11650';
break;
}
default: {
classification = '11606';
break;
}
}
let INN = '';
const leadid = $calculation.element('selectLead').getValue();

View File

@ -0,0 +1,284 @@
/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable complexity */
import type { ownOsagoRequest } from './request';
import { getInsuranceRule } from './tools';
import type { BaseConvertResponseInput } from './types';
import type * as ELT from '@/api/elt/types';
import type { Row } from '@/Components/Calculation/Form/ELT/types';
import { MAX_FRANCHISE, MAX_INSURANCE, MIN_INSURANCE } from '@/constants/values';
import * as CRMTypes from '@/graphql/crm.types';
import { defaultRow } from '@/stores/tables/elt/default-values';
import { round } from 'tools';
type ConvertEltOsagoResponseInput = BaseConvertResponseInput & {
response: ELT.ResponseEltOsago;
};
export async function convertEltOsagoResponse(input: ConvertEltOsagoResponseInput): Promise<Row> {
const { context, response, row } = input;
const { store } = context;
const { premiumSum = 0 } = response;
let { message, numCalc, skCalcId, error } = response;
let sum = premiumSum;
const { $calculation } = store;
const cost =
$calculation.$values.getValue('plPriceRub') -
$calculation.$values.getValue('discountRub') -
$calculation.$values.getValue('importProgramSum') +
$calculation.$values.getValue('addEquipmentPrice');
const selectedRule = await getInsuranceRule(input, { cost, riskType: 'osago' });
const insuranceCondition = selectedRule?.evo_id ?? null;
if (selectedRule) {
const rule_evo_discount = selectedRule.evo_discount ?? 0;
switch (selectedRule.evo_rules_type) {
// "не выводить результат расчета"
case 100_000_000: {
sum = 0;
numCalc = Number.parseInt(defaultRow.numCalc, 2);
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
break;
}
// "проверка на мин.тариф"
case 100_000_001: {
const newSum = round((sum / cost) * 100, 2);
if (newSum < rule_evo_discount) {
sum = 0;
numCalc = Number.parseInt(defaultRow.numCalc, 2);
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
}
break;
}
// "скидка за счет КВ"
case 100_000_002: {
sum = (sum * (100 - rule_evo_discount)) / 100;
numCalc = Number.parseInt(defaultRow.numCalc, 2);
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
break;
}
// "акционный тариф"
case 100_000_003: {
sum = (rule_evo_discount / 100) * cost;
numCalc = Number.parseInt(defaultRow.numCalc, 2);
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
break;
}
}
}
if (sum > MAX_INSURANCE) {
error ||= `Сумма по страховке превышает максимально допустимое значение по стоимости ОСАГО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_INSURANCE)}`;
}
if (sum < MIN_INSURANCE) {
error ||= `Сумма по страховке не должна быть меньше допустимого значения по стоимости ОСАГО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MIN_INSURANCE)}`;
}
return {
...row,
insuranceCondition,
message: error || message,
numCalc: `${numCalc}`,
skCalcId,
status: error ? 'error' : null,
sum,
};
}
type ResponseOwnOsago = Awaited<ReturnType<typeof ownOsagoRequest>>;
export function convertOwnOsagoResult(result: ResponseOwnOsago | undefined, row: Row): Row {
if (!result) {
return {
...row,
message:
'Для получения расчета ОСАГО следует использовать калькулятор ЭЛТ или Индивидуальный запрос',
numCalc: '',
skCalcId: '',
status: 'error',
sum: 0,
totalFranchise: 0,
};
}
if (!result.evo_id) {
return {
...row,
message: 'Сервер не вернул идентификатор страховки evo_id',
numCalc: '',
skCalcId: '',
status: 'error',
sum: result.evo_graph_price_withoutnds || 0,
};
}
return {
...row,
message: null,
numCalc: result.evo_id,
status: null,
sum: result.evo_graph_price_withoutnds || 0,
};
}
type ConvertEltKaskoResponseInput = BaseConvertResponseInput & {
response: ELT.ResponseEltKasko;
};
export async function convertEltKaskoResponse(input: ConvertEltKaskoResponseInput): Promise<Row> {
const { context, response, row } = input;
const { apolloClient, store } = context;
const { kaskoSum = 0, paymentPeriods } = response;
let { message, requestId, skCalcId, totalFranchise = 0, error } = response;
const { $calculation } = store;
const leasingPeriod = $calculation.element('tbxLeasingPeriod').getValue();
let sum = leasingPeriod <= 16 ? kaskoSum : paymentPeriods?.[0]?.kaskoSum || 0;
const {
data: { account: insuranceCompany },
} = await apolloClient.query({
query: CRMTypes.GetInsuranceCompanyDocument,
variables: { accountId: row.key },
});
if (
insuranceCompany?.evo_kasko_fact_part !== null &&
insuranceCompany?.evo_kasko_plan_part !== undefined &&
insuranceCompany?.evo_kasko_plan_part !== null &&
insuranceCompany?.evo_kasko_plan_part !== undefined &&
insuranceCompany?.evo_kasko_fact_part > insuranceCompany?.evo_kasko_plan_part
) {
requestId = defaultRow.requestId;
skCalcId = defaultRow.skCalcId;
sum = defaultRow.sum;
totalFranchise = defaultRow.totalFranchise;
error = 'Расчет закрыт';
}
const cost =
$calculation.$values.getValue('plPriceRub') -
$calculation.$values.getValue('discountRub') -
$calculation.$values.getValue('importProgramSum') +
$calculation.$values.getValue('addEquipmentPrice');
const selectedRule = await getInsuranceRule(input, { cost, riskType: 'kasko' });
const insuranceCondition = selectedRule?.evo_id ?? null;
if (selectedRule) {
const rule_evo_discount = selectedRule.evo_discount ?? 0;
switch (selectedRule.evo_rules_type) {
// "не выводить результат расчета"
case 100_000_000: {
sum = 0;
requestId = defaultRow.requestId;
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
totalFranchise = 0;
break;
}
// "проверка на мин.тариф"
case 100_000_001: {
const newSum = round((sum / cost) * 100, 2);
if (newSum < rule_evo_discount) {
sum = 0;
requestId = defaultRow.requestId;
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
totalFranchise = 0;
}
break;
}
// "скидка за счет КВ"
case 100_000_002: {
sum = (sum * (100 - rule_evo_discount)) / 100;
requestId = defaultRow.requestId;
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
totalFranchise = 0;
break;
}
// "акционный тариф"
case 100_000_003: {
sum = (rule_evo_discount / 100) * cost;
requestId = defaultRow.requestId;
skCalcId = defaultRow.skCalcId;
if (selectedRule.evo_message) message = selectedRule.evo_message;
totalFranchise = 0;
break;
}
}
}
if (totalFranchise > MAX_FRANCHISE) {
error ||= `Франшиза по страховке превышает максимально допустимое значение: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_FRANCHISE)}`;
}
if (sum > MAX_INSURANCE) {
error ||= `Сумма по страховке превышает максимально допустимое значение по стоимости КАСКО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_INSURANCE)}`;
}
if (sum < MIN_INSURANCE) {
error ||= `Сумма по страховке не должна быть меньше допустимого значения по стоимости КАСКО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MIN_INSURANCE)}`;
}
return {
...row,
insuranceCondition,
message: error || message,
numCalc: '0',
requestId,
skCalcId,
status: error ? 'error' : null,
sum,
totalFranchise,
};
}

View File

@ -0,0 +1,142 @@
/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable complexity */
import type { BaseConvertResponseInput } from './types';
import * as CRMTypes from '@/graphql/crm.types';
import { getCurrentDateString } from '@/utils/date';
import dayjs from 'dayjs';
import { sort } from 'radash';
type GetInsuranceConditionParams = {
cost: number;
riskType: 'osago' | 'kasko';
};
type Rule =
| NonNullable<CRMTypes.GetEltInsuranceRulesQuery['evo_insurance_ruleses']>[number]
| undefined;
export async function getInsuranceRule(
input: BaseConvertResponseInput,
{ cost, riskType }: GetInsuranceConditionParams
) {
const { context, row } = input;
const { apolloClient, store } = context;
const { $calculation } = store;
const leasingPeriod = $calculation.element('tbxLeasingPeriod').getValue();
const currentDate = getCurrentDateString();
const leaseObjectCategory = $calculation.element('selectLeaseObjectCategory').getValue();
const leaseObjectYear = $calculation.element('tbxLeaseObjectYear').getValue();
const leaseObjectMotorPower = $calculation.element('tbxLeaseObjectMotorPower').getValue();
const engineType = $calculation.element('selectEngineType').getValue();
const tbxMileage = $calculation.element('tbxMileage').getValue();
const brand = $calculation.element('selectBrand').getValue();
const model = $calculation.element('selectModel').getValue();
const selectLeaseObjectUseFor = $calculation.element('selectLeaseObjectUseFor').getValue();
const legalClientRegion = $calculation.element('selectLegalClientRegion').getValue();
const dealerPerson = $calculation.element('selectDealerPerson').getValue();
const cbxLeaseObjectUsed = $calculation.element('cbxLeaseObjectUsed').getValue();
let lead: CRMTypes.GetLeadQuery['lead'] = null;
const leadid = $calculation.element('selectLead').getValue();
if (leadid) {
const { data } = await apolloClient.query({
query: CRMTypes.GetLeadDocument,
variables: { leadid },
});
({ lead } = data);
}
const insuranceOPF = lead?.evo_inn?.length === 12 ? 100_000_001 : 100_000_000;
const {
data: { evo_insurance_ruleses },
} = await apolloClient.query({
query: CRMTypes.GetEltInsuranceRulesDocument,
variables: {
currentDate,
},
});
const {
data: { account: insuranceCompany },
} = await apolloClient.query({
query: CRMTypes.GetInsuranceCompanyDocument,
variables: { accountId: row.key },
});
const filteredRules = evo_insurance_ruleses?.filter(
(rule) =>
rule &&
rule.evo_insurer_accountid === insuranceCompany?.accountid &&
(riskType === 'kasko' ? rule.evo_risk === 100_000_000 : rule.evo_risk === 100_000_003) &&
leaseObjectCategory &&
rule.evo_category?.includes(leaseObjectCategory) &&
rule.evo_min_period !== null &&
rule.evo_max_period !== null &&
leasingPeriod !== null &&
rule.evo_min_period <= leasingPeriod &&
rule.evo_max_period >= leasingPeriod &&
(rule.evo_object_type === 100_000_000 ||
(rule.evo_object_type === 100_000_001 && cbxLeaseObjectUsed === false) ||
(rule.evo_object_type === 100_000_002 && cbxLeaseObjectUsed === true)) &&
selectLeaseObjectUseFor &&
rule.evo_use_for?.includes(selectLeaseObjectUseFor) &&
rule.evo_min_price !== null &&
rule.evo_max_price !== null &&
cost !== null &&
rule.evo_min_price <= cost &&
rule.evo_max_price >= cost &&
rule.evo_min_year !== null &&
rule.evo_max_year !== null &&
leaseObjectYear !== null &&
rule.evo_min_year <= leaseObjectYear &&
rule.evo_max_year >= leaseObjectYear &&
rule.evo_min_power !== null &&
rule.evo_max_power !== null &&
leaseObjectMotorPower !== null &&
rule.evo_min_power <= leaseObjectMotorPower &&
rule.evo_max_power >= leaseObjectMotorPower &&
engineType &&
rule.evo_enginie_type?.includes(engineType) &&
rule.evo_opf === insuranceOPF &&
rule.evo_min_mileage !== null &&
rule.evo_max_mileage !== null &&
tbxMileage !== null &&
rule.evo_min_mileage <= tbxMileage &&
rule.evo_max_mileage >= tbxMileage &&
(rule.evo_brand === 100_000_000 ||
(rule.evo_brand === 100_000_001 &&
rule.evo_brands?.some((x) => x?.evo_brandid === brand)) ||
(rule.evo_brand === 100_000_002 &&
!rule.evo_brands?.some((x) => x?.evo_brandid === brand))) &&
(rule.evo_model === 100_000_000 ||
(rule.evo_model === 100_000_001 &&
rule.evo_models?.some((x) => x?.evo_modelid === model)) ||
(rule.evo_model === 100_000_002 &&
!rule.evo_models?.some((x) => x?.evo_modelid === model))) &&
(rule.evo_region === 100_000_000 ||
(rule.evo_region === 100_000_001 &&
rule.evo_regions?.some((x) => x?.evo_regionid === legalClientRegion)) ||
(rule.evo_region === 100_000_002 &&
!rule.evo_regions?.some((x) => x?.evo_regionid === legalClientRegion))) &&
(rule.evo_dealer === 100_000_000 ||
(rule.evo_dealer === 100_000_001 &&
rule.accounts?.some((x) => x?.accountid === dealerPerson)) ||
(rule.evo_dealer === 100_000_002 &&
!rule.accounts?.some((x) => x?.accountid === dealerPerson)))
);
// Обработка найденных записей по приоритету
const sortedRules = filteredRules
? sort(filteredRules, (x) => dayjs(x?.evo_datefrom).date(), true)
: [];
const priorities = [100_000_000, 100_000_003, 100_000_001, 100_000_002];
return priorities.reduce(
(found, priority) => found || sortedRules.find((rule) => rule?.evo_rules_type === priority),
null as Rule
);
}

View File

@ -0,0 +1,7 @@
import type { Row } from '@/Components/Calculation/Form/ELT/types';
import type { ProcessContext } from '@/process/types';
export type BaseConvertResponseInput = {
context: Pick<ProcessContext, 'apolloClient' | 'store'>;
row: Row;
};

View File

@ -259,6 +259,8 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
}
let okved: string | null | undefined;
let evo_inn: string | null | undefined;
if (leadid) {
const {
data: { lead },
@ -268,6 +270,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
});
okved = lead?.accountidData?.evo_okved;
evo_inn = lead?.evo_inn;
}
if (!okved && opportunityid) {
@ -302,6 +305,14 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
path: ['eltKasko', 'eltOsago'],
});
}
if (!evo_inn) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'ИНН в интересе не заполнен',
path: ['eltKasko', 'eltOsago'],
});
}
}
);
}

View File

@ -1,17 +1,18 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import helper from './lib/helper';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
import { getKPData as getKPDataPayments } from '@/process/payments/get-kp-data';
import { getKPData as getKPDataPrice } from '@/process/price/get-kp-data';
import { createCurrencyUtility } from '@/utils/currency';
import { QueryClient } from '@tanstack/react-query';
export async function getKPData({
quote,
values,
ctx,
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const { apolloClient, queryClient } = ctx;
if (!quote?.evo_fingap_accountid) {
return {
fingap: {
@ -21,13 +22,10 @@ export async function getKPData({
};
}
const apolloClient = initializeApollo();
const queryClient = new QueryClient();
const { getFingapRisks } = helper({ apolloClient, queryClient });
const kpDataPrice = await getKPDataPrice({ quote, values });
const kpDataPayments = await getKPDataPayments({ quote, values });
const kpDataPrice = await getKPDataPrice({ ctx, quote, values });
const kpDataPayments = await getKPDataPayments({ ctx, quote, values });
const leaseObjectPrice = kpDataPrice.values?.leaseObjectPrice ?? defaultValues.leaseObjectPrice;
const firstPaymentRub = kpDataPrice.values?.firstPaymentRub ?? defaultValues.firstPaymentRub;

View File

@ -6,7 +6,7 @@ import { STALE_TIME } from '@/constants/request';
import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import type { CalculationValues } from '@/stores/calculation/values/types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import type { QueryFunctionContext } from '@tanstack/react-query';
import { flatten } from 'tools/object';
@ -38,7 +38,7 @@ export default function helper({
} = await apolloClient.query({
query: CRMTypes.GetAddproductTypesDocument,
variables: {
currentDate: getCurrentISODate(),
currentDate: getCurrentDateString(),
},
});

View File

@ -1 +1,2 @@
export { default as common } from './common';
export { default as init } from './init';

View File

@ -0,0 +1,34 @@
import type { ProcessContext } from '@/process/types';
import { when } from 'mobx';
export default function reactions({ store }: ProcessContext) {
const { $tables } = store;
/**
* Устанавливаем СК фингап по умолчанию при загрузке страницы
*/
when(() => {
const finGAPInsuranceCompanies = $tables.insurance.row('fingap').getOptions('insuranceCompany');
if (finGAPInsuranceCompanies.length) {
$tables.insurance
.row('fingap')
.setValue('insuranceCompany', finGAPInsuranceCompanies[0]?.value)
.setValue('insured', 100_000_001);
}
return Boolean(finGAPInsuranceCompanies.length);
});
/**
* Устанавливаем все риски ФинГАП по умолчанию при загрузке страницы
*/
when(() => {
const { risks } = $tables.fingap;
if (risks.length) {
$tables.fingap.setSelectedKeys(risks.map((x) => x.key));
}
return Boolean(risks.length);
});
}

View File

@ -1,17 +1,15 @@
/* eslint-disable sonarjs/cognitive-complexity */
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import helper from './lib/helper';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
export async function getKPData({
values,
quote,
ctx: { apolloClient },
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const { recalcWithRevision, lead: leadId, opportunity: opportunityId } = values;
const apolloClient = initializeApollo();
const { getData } = helper({
apolloClient,
});

View File

@ -6,10 +6,9 @@ import { getTransTax } from '@/api/1c/query';
import { selectObjectCategoryTax } from '@/config/default-options';
import { STALE_TIME } from '@/constants/request';
import * as CRMTypes from '@/graphql/crm.types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import { disposableReaction } from '@/utils/mobx';
import dayjs from 'dayjs';
import { reaction } from 'mobx';
export function common({ store, apolloClient, queryClient }: ProcessContext) {
@ -186,18 +185,16 @@ export function common({ store, apolloClient, queryClient }: ProcessContext) {
const carCategory = getCarCategory(objectTypeTax);
if (OKTMO) {
const currentDate = dayjs().utc(false).toDate();
const response = await queryClient.fetchQuery(
['1c', 'trans-tax', carCategory, leaseObjectMotorPower, leaseObjectYear],
['1c', 'trans-tax', carCategory, leaseObjectMotorPower, leaseObjectYear, OKTMO],
(context) =>
getTransTax(
{
CalcDate: getCurrentDateString(),
CarCategory: carCategory,
OKTMO,
calcDate: currentDate,
carCategory,
power: leaseObjectMotorPower,
year: leaseObjectYear,
Power: leaseObjectMotorPower,
Year: leaseObjectYear,
},
context
),
@ -206,8 +203,8 @@ export function common({ store, apolloClient, queryClient }: ProcessContext) {
}
);
if (response?.tax) {
$calculation.element('tbxVehicleTaxInYear').setValue(response.tax);
if (response?.Tax) {
$calculation.element('tbxVehicleTaxInYear').setValue(response.Tax);
} else {
$calculation.element('tbxVehicleTaxInYear').resetValue();
}
@ -250,7 +247,7 @@ export function common({ store, apolloClient, queryClient }: ProcessContext) {
data: { evo_addproduct_types },
} = await apolloClient.query({
query: CRMTypes.GetRegistrationTypesDocument,
variables: { currentDate: getCurrentISODate() },
variables: { currentDate: getCurrentDateString() },
});
const options = evo_addproduct_types?.filter((x) => {

View File

@ -4,7 +4,7 @@ import { STALE_TIME } from '@/constants/request';
import { crmTools } from '@/graphql/crm.tools';
import * as CRMTypes from '@/graphql/crm.types';
import { useStore } from '@/stores/hooks';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import { useApolloClient } from '@apollo/client';
import { useQuery } from '@tanstack/react-query';
@ -16,24 +16,34 @@ import { useEffect } from 'react';
* @param {*} onCompleted
*/
function getMainData({ query }, onCompleted, user) {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
query({
query: CRMTypes.GetLeadsDocument,
variables: { domainname: user.domainName },
}).then(({ data }) => {
onCompleted({
selectLead: data?.leads,
});
const systemuser = data?.systemusers?.[0];
if (systemuser) {
const { leads } = systemuser;
onCompleted({
selectLead: leads,
});
}
});
query({
query: CRMTypes.GetOpportunitiesDocument,
variables: { domainname: user.domainName },
}).then(({ data }) => {
onCompleted({
selectOpportunity: data?.opportunities,
});
const systemuser = data?.systemusers?.[0];
if (systemuser) {
const { opportunities } = systemuser;
onCompleted({
selectOpportunity: opportunities,
});
}
});
query({ query: CRMTypes.GetTransactionCurrenciesDocument }).then(({ data }) => {
@ -46,16 +56,22 @@ function getMainData({ query }, onCompleted, user) {
fetchPolicy: 'network-only',
query: CRMTypes.GetSystemUserDocument,
variables: { domainname: user?.domainName },
}).then(({ data: { systemuser } }) => {
query({
fetchPolicy: 'network-only',
query: CRMTypes.GetProductsDocument,
variables: { currentDate },
}).then(({ data: { evo_baseproducts } }) => {
onCompleted({
selectProduct: crmTools.evo_baseproducts(evo_baseproducts).filterBy.systemuser(systemuser),
}).then(({ data: { systemusers } }) => {
const systemuser = systemusers?.[0];
if (systemuser) {
query({
fetchPolicy: 'network-only',
query: CRMTypes.GetProductsDocument,
variables: { currentDate },
}).then(({ data: { evo_baseproducts } }) => {
onCompleted({
selectProduct: crmTools
.evo_baseproducts(evo_baseproducts)
.filterBy.systemuser(systemuser),
});
});
});
}
});
// query({

View File

@ -11,8 +11,9 @@ import { sum } from 'radash';
export async function getKPData({
values,
quote,
ctx,
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const kpDataFingap = await getKPDataFingap({ quote, values });
const kpDataFingap = await getKPDataFingap({ ctx, quote, values });
const risks = kpDataFingap.fingap?.risks;

View File

@ -68,6 +68,7 @@ export function common({ store, apolloClient }: ProcessContext) {
selectLeaseObjectUseFor.filter((x) =>
[
100_000_002, 100_000_004, 100_000_005, 100_000_006, 100_000_009, 100_000_010,
100_000_020,
].includes(x.value)
)
);
@ -90,7 +91,9 @@ export function common({ store, apolloClient }: ProcessContext) {
$calculation
.element('selectLeaseObjectUseFor')
.setOptions(
selectLeaseObjectUseFor.filter((x) => [100_000_002, 100_000_009].includes(x.value))
selectLeaseObjectUseFor.filter((x) =>
[100_000_002, 100_000_009, 100_000_020].includes(x.value)
)
);
break;
}
@ -204,6 +207,7 @@ export function common({ store, apolloClient }: ProcessContext) {
}
);
// объединить со строчкой 308
debouncedReaction(
() => $calculation.$values.getValues(['leaseObjectCategory', 'leasingWithoutKasko']),
async ({ leaseObjectCategory, leasingWithoutKasko }) => {
@ -300,6 +304,70 @@ export function common({ store, apolloClient }: ProcessContext) {
}
}
);
// объединить со строчкой 210
reaction(
() => $calculation.$values.getValues(['leaseObjectType', 'maxSpeed']),
async ({ leaseObjectType: leaseObjectTypeId, maxSpeed }) => {
if (!leaseObjectTypeId) {
$tables.insurance.row('osago').column('insuranceCompany').unblock();
$tables.insurance.row('osago').column('insured').unblock();
$tables.insurance.row('osago').column('insCost').unblock();
return;
}
const {
data: { evo_leasingobject_type },
} = await apolloClient.query({
query: CRMTypes.GetLeaseObjectTypeDocument,
variables: {
leaseObjectTypeId,
},
});
const {
data: { accounts },
} = await apolloClient.query({
query: CRMTypes.GetInsuranceCompaniesDocument,
});
if (
evo_leasingobject_type?.evo_id &&
['9', '6', '10'].includes(evo_leasingobject_type.evo_id) &&
maxSpeed < 20
) {
const otherInsuranceCompany = accounts?.find(
(x) => x?.evo_type_ins_policy === null && x.label?.includes('ПРОЧИЕ')
);
if (otherInsuranceCompany) {
$tables.insurance
.row('osago')
.column('insuranceCompany')
.setOptions(normalizeOptions([otherInsuranceCompany]))
.setValue(otherInsuranceCompany.value)
.block();
}
$tables.insurance.row('osago').column('insured').setValue(100_000_000).block();
$tables.insurance.row('osago').column('insCost').setValue(0).block();
} else {
const defaultOsagoOptions = accounts?.filter((x) =>
x?.evo_type_ins_policy?.includes(100_000_001)
);
$tables.insurance
.row('osago')
.column('insuranceCompany')
.setOptions(normalizeOptions(defaultOsagoOptions))
.unblock();
$tables.insurance.row('osago').column('insured').unblock();
$tables.insurance.row('osago').column('insCost').unblock();
}
}
);
}
export const validation = createValidationReaction(createValidationSchema);

View File

@ -16,6 +16,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
leaseObjectType: true,
leasingPeriod: true,
leasingWithoutKasko: true,
maxSpeed: true,
partialVAT: true,
plPriceRub: true,
product: true,
@ -42,6 +43,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
leaseObjectType: leaseObjectTypeId,
firstPaymentPerc,
plPriceRub,
maxSpeed,
},
ctx
) => {
@ -251,6 +253,19 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
path: ['tbxLeaseObjectPrice'],
});
}
if (
evo_leasingobject_type?.evo_id &&
['9', '6', '10'].includes(evo_leasingobject_type?.evo_id) &&
maxSpeed < 20 &&
insurance.values.osago.insured === 100_000_001
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя включать в график ОСАГО по Спецтехнике, т.к. полис не требуется',
path: ['insurance'],
});
}
}
);
}

View File

@ -1,14 +1,12 @@
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import helper from './lib/helper';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
export async function getKPData({
values: { recalcWithRevision },
quote,
ctx: { apolloClient },
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const apolloClient = initializeApollo();
const brand = quote?.evo_brandid ?? defaultValues.brand;
const model = quote?.evo_modelid ?? defaultValues.model;
const leaseObjectUsed = quote?.evo_leasingobject_used ?? defaultValues.leaseObjectUsed;

View File

@ -17,6 +17,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
leaseObjectType: true,
leaseObjectUseFor: true,
maxMass: true,
maxSpeed: true,
model: true,
}).superRefine(
async (
@ -32,6 +33,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
model: modelId,
leaseObjectUseFor,
configuration,
maxSpeed,
},
ctx
) => {
@ -134,21 +136,21 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
}
}
if (evo_leasingobject_type?.evo_id === '1' && countSeats >= 9) {
if (evo_leasingobject_type?.evo_id === '1' && (countSeats <= 0 || countSeats > 9)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Количество мест должно быть меньше 9',
message: 'Количество мест должно быть от 0 до 9',
path: ['tbxCountSeats'],
});
}
if (
(evo_leasingobject_type?.evo_id === '4' || evo_leasingobject_type?.evo_id === '5') &&
countSeats <= 8
countSeats <= 9
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Количество мест должно быть больше 8',
message: 'Количество мест должно быть не меньше 9',
path: ['tbxCountSeats'],
});
}
@ -174,6 +176,18 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
path: ['selectLeaseObjectCategory'],
});
}
if (
evo_leasingobject_type?.evo_id &&
['6', '9', '10'].includes(evo_leasingobject_type?.evo_id) &&
!maxSpeed
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Не заполнено поле',
path: ['tbxMaxSpeed'],
});
}
}
}
);

View File

@ -3,7 +3,7 @@
import { notification } from '@/Components/Common/Notification';
import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import { reaction } from 'mobx';
import { uid } from 'radash';
@ -64,7 +64,7 @@ export function common({ store, apolloClient }: ProcessContext) {
firstPaymentPerc,
model: modelId,
}) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },

View File

@ -15,7 +15,7 @@ export function common({ store, trpcClient, apolloClient }: ProcessContext) {
reaction(
() => $calculation.$values.getValue('quote'),
async () => {
() => {
const quote = $calculation.element('selectQuote').getOption();
if (!quote || $process.has('LoadKP') || $process.has('Calculate') || $process.has('CreateKP'))
@ -29,8 +29,6 @@ export function common({ store, trpcClient, apolloClient }: ProcessContext) {
onClick: () => message.destroy(key),
});
const eltInitialValues = await initElt();
trpcClient.getQuote
.query({
values: {
@ -38,7 +36,7 @@ export function common({ store, trpcClient, apolloClient }: ProcessContext) {
...$calculation.$values.getValues(['lead', 'opportunity', 'recalcWithRevision']),
},
})
.then(({ values, payments, insurance, fingap, elt, options }) => {
.then(async ({ values, payments, insurance, fingap, elt, options }) => {
if (options?.selectTarif) {
$calculation.element('selectTarif').setOptions(normalizeOptions(options.selectTarif));
} else {
@ -76,6 +74,7 @@ export function common({ store, trpcClient, apolloClient }: ProcessContext) {
$tables.fingap.setRisks(fingap.risks);
$tables.fingap.setSelectedKeys(fingap.keys);
}
const eltInitialValues = await initElt();
if (eltInitialValues) {
$tables.elt.kasko.setRows(eltInitialValues.kasko);

View File

@ -1,10 +1,11 @@
import type { ProcessContext } from '../types';
import { createValidationSchema } from './validation';
import type { Elements } from '@/Components/Calculation/config/map/values';
import * as CRMTypes from '@/graphql/crm.types';
import { createValidationReaction } from '@/process/tools';
import { reaction } from 'mobx';
export function common({ store }: ProcessContext) {
export function common({ store, apolloClient }: ProcessContext) {
const { $calculation, $tables } = store;
reaction(
@ -65,6 +66,7 @@ export function common({ store }: ProcessContext) {
// 'tbxLastPaymentRub',
'cbxPartialVAT',
];
reaction(
() => $calculation.element('cbxRecalcWithRevision').getValue(),
(recalcWithRevision) => {
@ -79,7 +81,53 @@ export function common({ store }: ProcessContext) {
}
}
);
}
{
/**
* Закрыть на редактирование поля при Пересчете без пересмотра recalcWithRevision = True и если в Предложении selectQuote в поле "КП по итогам КК" = Да
* Срок поставки* radioDeliveryTime
* Цель использования* selectLeaseObjectUseFor
* Тип двигателя selectEngineType
* Децентрализованное страхование cbxInsDecentral
*/
const elements: Elements[] = [
'radioDeliveryTime',
'selectLeaseObjectUseFor',
'selectEngineType',
'cbxInsDecentral',
];
reaction(
() => $calculation.$values.getValues(['recalcWithRevision', 'quote']),
async ({ recalcWithRevision, quote: quoteId }) => {
if (!recalcWithRevision || !quoteId) {
elements.forEach((elementName) => $calculation.$status.clearOverridedStatus(elementName));
return;
}
const {
data: { quote },
} = await apolloClient.query({
query: CRMTypes.GetQuoteDocument,
variables: {
quoteId,
},
});
if (quote?.evo_committee_quote === 100_000_000) {
elements.forEach((elementName) =>
$calculation.$status.overrideStatus(elementName, 'Disabled')
);
} else {
elements.forEach((elementName) => $calculation.$status.clearOverridedStatus(elementName));
}
}
);
}
{
const agents: Elements[] = [
'selectCalcBrokerRewardCondition',
'selectCalcDoubleAgentRewardCondition',

View File

@ -1,6 +1,9 @@
/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable complexity */
import type { ValidationContext } from '../types';
import type { Elements } from '@/Components/Calculation/config/map/values';
import { FinGAPSchema } from '@/config/schema/fingap';
import { InsuranceSchema } from '@/config/schema/insurance';
import ValuesSchema from '@/config/schema/values';
import { MAX_MASS, VEHICLE_SEATS } from '@/constants/values';
import * as CRMTypes from '@/graphql/crm.types';
@ -8,221 +11,367 @@ import { z } from 'zod';
export function createValidationSchema({ apolloClient }: ValidationContext) {
return ValuesSchema.pick({
IRR_Perc: true,
addEquipmentPrice: true,
countSeats: true,
dealerPerson: true,
discountRub: true,
engineVolume: true,
firstPaymentPerc: true,
importProgramSum: true,
insNSIB: true,
lastPaymentPerc: true,
leaseObjectCategory: true,
leaseObjectCount: true,
leaseObjectMotorPower: true,
leaseObjectPriceWthtVAT: true,
leaseObjectUsed: true,
leaseObjectYear: true,
maxMass: true,
objectRegistration: true,
partialVAT: 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,
leaseObjectCategory,
partialVAT,
},
ctx
) => {
if (!recalcWithRevision) {
return;
}
technicalCard: true,
})
.extend({
fingap: FinGAPSchema,
insurance: InsuranceSchema,
})
.superRefine(
async (
{
addEquipmentPrice,
dealerPerson: dealerPersonId,
importProgramSum,
leaseObjectPriceWthtVAT,
leaseObjectUsed,
product: productId,
quote: quoteId,
recalcWithRevision,
discountRub,
plPriceRub,
firstPaymentPerc,
leaseObjectCount,
maxMass,
countSeats,
leaseObjectYear,
lastPaymentPerc,
leaseObjectCategory,
partialVAT,
IRR_Perc,
leaseObjectMotorPower,
engineVolume,
insNSIB,
technicalCard,
objectRegistration,
fingap: fingapRisks,
insurance,
},
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 maxCondition1 =
leaseObjectUsed === false &&
dealerPerson?.evo_supplier_type !== 100_000_001 &&
quote?.evo_max_price_change &&
!partialVAT &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote.evo_max_price_change;
const maxCondition2 =
leaseObjectUsed === false &&
dealerPerson?.evo_supplier_type !== 100_000_001 &&
quote?.evo_max_price_change &&
partialVAT &&
leaseObjectPriceWthtVAT >
quote.evo_max_price_change - (quote.evo_nds_in_price_supplier_currency || 0);
const maxCondition3 =
(leaseObjectUsed === true || dealerPerson?.evo_supplier_type === 100_000_001) &&
quote?.evo_supplier_currency_price &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote.evo_supplier_currency_price -
(quote.evo_discount_supplier_currency || 0) +
(quote.evo_equip_price || 0) -
(quote.evo_program_import_subsidy_sum || 0);
const minCondition1 =
!partialVAT &&
quote?.evo_min_change_price &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum <
quote.evo_min_change_price;
const minCondition2 =
partialVAT &&
quote?.evo_min_change_price &&
leaseObjectPriceWthtVAT <
quote.evo_min_change_price - (quote.evo_nds_in_price_supplier_currency || 0);
if (maxCondition1 || maxCondition2) {
if (!quoteId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Указанная стоимость предмета лизинга больше возможного изменения стоимости предмета лизинга при пересчете без пересмотра. ' +
'Уменьшите стоимость предмета лизинга',
path: ['tbxLeaseObjectPrice'],
message: 'Не указано предложение, по которому осуществляется Пересчет без пересмотра',
path: ['selectQuote'],
});
} else if (maxCondition3) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'При пересчете без пересмотра КП с ПЛ БУ или с непрофессиональным поставщиком недопустимо увеличение стоимости. Создайте новое КП и отправьте его на рассмотрение андеррайтингу для повторной проверки оценщиком.',
path: ['tbxLeaseObjectPrice'],
}
if (dealerPersonId && quoteId && productId) {
const {
data: { dealer_person },
} = await apolloClient.query({
query: CRMTypes.GetDealerPersonDocument,
variables: { dealerPersonId },
});
} else if (minCondition1 || minCondition2) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Указанная стоимость предмета лизинга меньше возможного изменения стоимости предмета лизинга при пересчете без пересмотра. ' +
'Увеличьте стоимость предмета лизинга',
path: ['tbxLeaseObjectPrice'],
const {
data: { quote },
} = await apolloClient.query({
query: CRMTypes.GetQuoteDocument,
variables: { quoteId },
});
const maxCondition1 =
leaseObjectUsed === false &&
dealer_person?.evo_supplier_type !== 100_000_001 &&
quote?.evo_max_price_change &&
!partialVAT &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote.evo_max_price_change;
const maxCondition2 =
leaseObjectUsed === false &&
dealer_person?.evo_supplier_type !== 100_000_001 &&
quote?.evo_max_price_change &&
partialVAT &&
leaseObjectPriceWthtVAT >
quote.evo_max_price_change - (quote.evo_nds_in_price_supplier_currency || 0);
const maxCondition3 =
(leaseObjectUsed === true || dealer_person?.evo_supplier_type === 100_000_001) &&
quote?.evo_supplier_currency_price &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote.evo_supplier_currency_price -
(quote.evo_discount_supplier_currency || 0) +
(quote.evo_equip_price || 0) -
(quote.evo_program_import_subsidy_sum || 0);
const minCondition1 =
!partialVAT &&
quote?.evo_min_change_price &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum <
quote.evo_min_change_price;
const minCondition2 =
partialVAT &&
quote?.evo_min_change_price &&
leaseObjectPriceWthtVAT <
quote.evo_min_change_price - (quote.evo_nds_in_price_supplier_currency || 0);
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 (
firstPaymentPerc <
(quote?.evo_approved_first_payment || 0) + (quote?.evo_percent_subsidy || 0)
) {
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 (partialVAT !== quote?.evo_sale_without_nds) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя менять частичный НДС при пересчете без пересмотра',
path: ['selectProduct'],
});
}
if (quote?.evo_committee_quote === 100_000_000 && quote.evo_accept_quoteid) {
const {
data: { quote: accept_quote },
} = await apolloClient.query({
query: CRMTypes.GetQuoteDocument,
variables: { quoteId: quote.evo_accept_quoteid },
});
if (accept_quote?.evo_msfo_irr && IRR_Perc - accept_quote?.evo_msfo_irr > 0.1)
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя увеличивать IRR после рассмотрения предложения на КК',
path: ['tbxIRR_Perc'] as Elements[],
});
if (
accept_quote?.evo_power &&
Math.abs(leaseObjectMotorPower - accept_quote.evo_power) > 10
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Нельзя корректировать мощность более чем на 10 л.с. после рассмотрения предложения на КК',
path: ['tbxLeaseObjectMotorPower'] as Elements[],
});
}
if (
accept_quote?.evo_engine_volume &&
Math.abs(engineVolume - accept_quote.evo_engine_volume) > 0.1
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Нельзя корректировать объем двигателя более чем на 0.1 л после рассмотрения предложения на КК',
path: ['tbxEngineVolume'] as Elements[],
});
}
if (insNSIB && !accept_quote?.evo_nsib) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя включать в график НСИБ после рассмотрения предложения на КК',
path: ['selectInsNSIB'] as Elements[],
});
}
if (
technicalCard &&
!accept_quote?.evo_addproduct_types?.some((x) => x?.evo_product_type === 100_000_000)
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Нельзя включать в график карту тех.помощи после рассмотрения предложения на КК',
path: ['selectTechnicalCard'] as Elements[],
});
}
if (
objectRegistration &&
objectRegistration !== accept_quote?.evo_db_accept_registration
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя менять регистрацию после рассмотрения предложения на КК',
path: ['radioObjectRegistration'] as Elements[],
});
}
if (
insurance.values.fingap.insured === 100_000_001 &&
fingapRisks?.length > 0 &&
fingapRisks.some(
(fingapRisk) =>
!accept_quote?.evo_product_risks?.some(
(evo_product_risk) =>
fingapRisk.riskId === evo_product_risk?.evo_addproduct_typeid
)
)
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Нельзя включать новые риски Safe Finance после рассмотрения предложения на КК',
path: ['fingap'],
});
}
if (
insurance.values.fingap.insured === 100_000_001 &&
accept_quote?.evo_fingap_payer &&
insurance.values.fingap.insured !== accept_quote?.evo_fingap_payer
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
'Нельзя включать в график SafeFinance после рассмотрения предложения на КК',
path: ['insurance'],
});
}
if (
insurance.values.osago.insured === 100_000_001 &&
accept_quote?.evo_osago_payer &&
insurance.values.osago.insured !== accept_quote?.evo_osago_payer
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя включать в график ОСАГО после рассмотрения предложения на КК',
path: ['insurance'],
});
}
if (
insurance.values.kasko.insured === 100_000_001 &&
accept_quote?.evo_kasko_payer &&
insurance.values.kasko.insured !== accept_quote?.evo_kasko_payer
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя включать в график КАСКО после рассмотрения предложения на КК',
path: ['insurance'],
});
}
}
}
}
if (quoteId) {
const {
data: { quote },
} = await apolloClient.query({
query: CRMTypes.GetQuoteDocument,
variables: { quoteId },
});
if (
firstPaymentPerc <
(quote?.evo_approved_first_payment || 0) + (quote?.evo_percent_subsidy || 0)
) {
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 (partialVAT !== quote?.evo_sale_without_nds) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Нельзя менять частичный НДС при пересчете без пересмотра',
path: ['selectProduct'],
});
}
}
}
);
);
}

View File

@ -1,6 +1,5 @@
import type { GetQuoteInputData, GetQuoteProcessData } from '../load-kp/types';
import helper from './lib/helper';
import initializeApollo from '@/apollo/client';
import defaultValues from '@/config/default-values';
import { getKPData as getKPDataPrice } from '@/process/price/get-kp-data';
import { createCurrencyUtility } from '@/utils/currency';
@ -8,10 +7,11 @@ import { createCurrencyUtility } from '@/utils/currency';
export async function getKPData({
values,
quote,
ctx,
}: GetQuoteInputData): Promise<GetQuoteProcessData> {
const apolloClient = initializeApollo();
const { apolloClient } = ctx;
const kpDataPrice = await getKPDataPrice({ quote, values });
const kpDataPrice = await getKPDataPrice({ ctx, quote, values });
const { RUB } = createCurrencyUtility({ apolloClient });
const supplierCurrency = kpDataPrice.values?.supplierCurrency ?? defaultValues.supplierCurrency;

View File

@ -1,5 +1,5 @@
import initializeApollo from '@/apollo/client';
import * as CRMTypes from '@/graphql/crm.types';
import type { GetQuoteContext } from '@/server/routers/quote/types';
type Quote = NonNullable<CRMTypes.GetQuoteDataQuery['quote']>;
@ -19,39 +19,42 @@ type QuoteTotalFields =
| 'evo_double_agent_reward_total'
| 'evo_fin_department_reward_total';
async function getRewardSum(
conditionId: string | null | undefined,
quote: Quote,
quoteRewardSummField: keyof Pick<Quote, QuoteSumFields>,
quoteRewardTotalField: keyof Pick<Quote, QuoteTotalFields>
) {
if (!conditionId) return 0;
function makeGetRewardSum({ apolloClient }: GetQuoteContext) {
return async function (
conditionId: string | null | undefined,
quote: Quote,
quoteRewardSummField: keyof Pick<Quote, QuoteSumFields>,
quoteRewardTotalField: keyof Pick<Quote, QuoteTotalFields>
) {
if (!conditionId) return 0;
const apolloClient = initializeApollo();
const {
data: { evo_reward_condition },
} = await apolloClient.query<
CRMTypes.GetRewardConditionQuery,
CRMTypes.GetRewardConditionQueryVariables
>({
query: CRMTypes.GetRewardConditionDocument,
variables: {
conditionId,
},
});
const {
data: { evo_reward_condition },
} = await apolloClient.query<
CRMTypes.GetRewardConditionQuery,
CRMTypes.GetRewardConditionQueryVariables
>({
query: CRMTypes.GetRewardConditionDocument,
variables: {
conditionId,
},
});
if (evo_reward_condition?.evo_calc_reward_rules === 100_000_001) {
return quote[quoteRewardSummField];
}
if (evo_reward_condition?.evo_calc_reward_rules === 100_000_001) {
return quote[quoteRewardSummField];
}
return quote[quoteRewardTotalField];
return quote[quoteRewardTotalField];
};
}
export default async function getSums(quote: Quote | null) {
export default async function getSums(quote: Quote | null, ctx: GetQuoteContext) {
if (!quote) {
return null;
}
const getRewardSum = makeGetRewardSum(ctx);
const [
dealerRewardSumm,
dealerBrokerRewardSumm,

Some files were not shown because too many files have changed in this diff Show More