merge branch dyn-4250_migrate-to-new-graphql

This commit is contained in:
vchikalkin 2024-07-15 11:04:47 +03:00
parent d7908bb5da
commit d6f5c73b9d
74 changed files with 14632 additions and 8812 deletions

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

@ -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

@ -4,7 +4,7 @@ import type { Row } from '../types';
import type { RequestEltKasko, RequestEltOsago } from '@/api/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';
@ -12,7 +12,7 @@ export async function makeOwnOsagoRequest(
{ 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 },

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

@ -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

@ -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

@ -1,20 +1,20 @@
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) {
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,121 @@
/* 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();
export function createLink(headers) {
const { URL_CRM_GRAPHQL } = getUrls();
const modifyDataLink = new ApolloLink((operation, forward) => {
const context = operation?.getContext();
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 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.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

@ -11,6 +11,7 @@ const envSchema = z.object({
URL_CACHE_GET_QUERIES_DIRECT: z.string().default('http://api:3001/proxy/get-queries'),
URL_CACHE_GET_QUERY_DIRECT: z.string().default('http://api:3001/proxy/get-query'),
URL_CACHE_RESET_QUERIES_DIRECT: z.string().default('http://api:3001/proxy/reset'),
DEV_AUTH_TOKEN: z.string().optional(),
URL_CORE_CALCULATE_DIRECT: z.string(),
URL_CORE_FINGAP_DIRECT: z.string(),
URL_CRM_CREATEKP_DIRECT: z.string(),

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,7 @@ const publicRuntimeConfigSchema = envSchema.pick({
const serverRuntimeConfigSchema = envSchema.pick({
BASE_PATH: true,
DEV_AUTH_TOKEN: true,
PORT: true,
SENTRY_DSN: true,
SENTRY_ENVIRONMENT: true,

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
@ -132,8 +159,8 @@ query GetQuote($quoteId: Uuid!) {
}
}
query GetQuoteData($quoteId: Uuid!) {
quote(quoteId: $quoteId) {
query GetQuoteData($quoteId: UUID!) {
quote(quoteid: $quoteId) {
evo_addproduct_types {
evo_product_type
evo_addproduct_typeid
@ -288,9 +315,13 @@ query GetQuoteData($quoteId: Uuid!) {
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
@ -313,7 +344,7 @@ query GetTarifs($currentDate: DateTime) {
}
}
query GetTarif($tarifId: Uuid!) {
query GetTarif($tarifId: UUID!) {
evo_tarif(evo_tarifid: $tarifId) {
label: evo_name
value: evo_tarifid
@ -336,9 +367,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
@ -350,7 +385,7 @@ query GetRates($currentDate: DateTime) {
}
}
query GetRate($rateId: Uuid!) {
query GetRate($rateId: UUID!) {
evo_rate(evo_rateid: $rateId) {
evo_base_rate
evo_credit_period
@ -361,10 +396,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
@ -375,7 +414,7 @@ query GetProducts($currentDate: DateTime) {
}
}
query GetProduct($productId: Uuid!) {
query GetProduct($productId: UUID!) {
evo_baseproduct(evo_baseproductid: $productId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -401,9 +440,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
@ -411,7 +454,7 @@ query GetSubsidies($currentDate: DateTime) {
}
}
query GetSubsidy($subsidyId: Uuid!) {
query GetSubsidy($subsidyId: UUID!) {
evo_subsidy(evo_subsidyid: $subsidyId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -433,7 +476,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
@ -451,7 +494,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
@ -459,7 +502,7 @@ query GetRegions {
}
}
query GetRegion($regionId: Uuid!) {
query GetRegion($regionId: UUID!) {
evo_region(evo_regionid: $regionId) {
evo_oktmo
accounts {
@ -469,8 +512,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
@ -478,22 +529,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
@ -501,14 +563,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
@ -528,7 +594,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
@ -536,7 +607,7 @@ query GetBrands {
}
}
query GetBrand($brandId: Uuid!) {
query GetBrand($brandId: UUID!) {
evo_brand(evo_brandid: $brandId) {
evo_id
evo_importer_reward_perc
@ -546,8 +617,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
@ -557,7 +636,7 @@ query GetModels($brandId: Uuid!) {
}
}
query GetModel($modelId: Uuid!) {
query GetModel($modelId: UUID!) {
evo_model(evo_modelid: $modelId) {
evo_impairment_groupidData {
evo_name
@ -574,15 +653,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
@ -591,7 +677,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
@ -599,16 +685,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
@ -618,27 +704,43 @@ 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
}
}
query GetAgent($agentid: Uuid!) {
agent: account(accountid: $agentid) {
query GetAgent($agentid: UUID!) {
agent(accountid: $agentid) {
label: name
value: accountid
}
}
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
@ -647,7 +749,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
@ -662,16 +764,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
@ -697,7 +810,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 {
@ -715,9 +832,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
@ -731,7 +852,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
@ -755,10 +876,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 {
@ -774,10 +899,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
@ -791,10 +920,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
@ -807,10 +940,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
@ -820,10 +957,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
@ -833,10 +974,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
@ -854,10 +999,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
@ -879,10 +1028,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
@ -900,8 +1053,8 @@ 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
@ -909,7 +1062,7 @@ query GetInsuranceCompany($accountId: Uuid!) {
}
query GetInsuranceCompanies {
accounts(evo_account_type: [100000002], statecode: 0) {
accounts: insurances {
evo_type_ins_policy
evo_evokasko_access
evo_inn
@ -923,7 +1076,11 @@ query GetInsuranceCompanies {
}
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

View File

@ -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",
@ -56,7 +57,7 @@
"@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

@ -4,13 +4,14 @@ 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 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';
@ -54,11 +55,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

@ -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,7 +4,7 @@ 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';
@ -21,7 +21,7 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
return;
}
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -126,7 +126,7 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
reaction(
() => $calculation.$values.getValues(['leasingPeriod', 'leaseObjectType']),
async ({ leasingPeriod, leaseObjectType }) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -210,7 +210,7 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
leasingPeriod,
plPriceRub,
}) => {
const currentDate = getCurrentISODate();
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
@ -323,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

@ -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,9 +12,10 @@ 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)
@ -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;

View File

@ -4,7 +4,7 @@ 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';
@ -99,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 },
@ -157,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

@ -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,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,7 +6,7 @@ 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';
@ -250,7 +250,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

@ -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

@ -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

@ -86,7 +86,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
if (dealerPersonId && quoteId && productId) {
const {
data: { account: dealerPerson },
data: { dealer_person },
} = await apolloClient.query({
query: CRMTypes.GetDealerPersonDocument,
variables: { dealerPersonId },
@ -101,7 +101,7 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
const maxCondition1 =
leaseObjectUsed === false &&
dealerPerson?.evo_supplier_type !== 100_000_001 &&
dealer_person?.evo_supplier_type !== 100_000_001 &&
quote?.evo_max_price_change &&
!partialVAT &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
@ -109,14 +109,14 @@ export function createValidationSchema({ apolloClient }: ValidationContext) {
const maxCondition2 =
leaseObjectUsed === false &&
dealerPerson?.evo_supplier_type !== 100_000_001 &&
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 || dealerPerson?.evo_supplier_type === 100_000_001) &&
(leaseObjectUsed === true || dealer_person?.evo_supplier_type === 100_000_001) &&
quote?.evo_supplier_currency_price &&
plPriceRub - discountRub + addEquipmentPrice - importProgramSum >
quote.evo_supplier_currency_price -

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,

View File

@ -3,8 +3,8 @@ import type { GetQuoteInputData, GetQuoteProcessData } from '../../load-kp/types
import getSums from './get-sums';
import defaultValues from '@/config/default-values';
export async function getKPData({ quote }: GetQuoteInputData): Promise<GetQuoteProcessData> {
const sums = await getSums(quote);
export async function getKPData({ quote, ctx }: GetQuoteInputData): Promise<GetQuoteProcessData> {
const sums = await getSums(quote, ctx);
return {
values: {

View File

@ -1,7 +1,7 @@
import type { AgentsFields, AgentsRewardConditionsFields, AgentsSumFields } from './types';
import * as CRMTypes from '@/graphql/crm.types';
import type RootStore from '@/stores/root';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import { disposableReaction } from '@/utils/mobx';
import type { ApolloClient } from '@apollo/client';
@ -41,7 +41,7 @@ export function fillAgentRewardReaction(
query: CRMTypes.GetRewardConditionsDocument,
variables: {
agentid,
currentDate: getCurrentISODate(),
currentDate: getCurrentDateString(),
},
});

View File

@ -75,21 +75,21 @@ export function common({ store, apolloClient }: ProcessContext) {
}
const {
data: { dealer },
data: { dealer_person },
} = await apolloClient.query({
query: CRMTypes.GetDealerDocument,
query: CRMTypes.GetDealerPersonDocument,
variables: {
dealerId: dealerPersonId,
dealerPersonId,
},
});
if (dealer?.evo_broker_accountid) {
if (dealer_person?.evo_broker_accountid) {
const {
data: { agent: dealerBroker },
} = await apolloClient.query<CRMTypes.GetAgentQuery, CRMTypes.GetAgentQueryVariables>({
query: CRMTypes.GetAgentDocument,
variables: {
agentid: dealer?.evo_broker_accountid,
agentid: dealer_person?.evo_broker_accountid,
},
});

View File

@ -4,7 +4,7 @@ import type { ValidationContext } from '../types';
import type { Elements } from '@/Components/Calculation/config/map/values';
import ValuesSchema from '@/config/schema/values';
import * as CRMTypes from '@/graphql/crm.types';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import { normalizeOptions } from '@/utils/entity';
import type { RefinementCtx } from 'zod';
import { z } from 'zod';
@ -29,7 +29,7 @@ function helper({ apolloClient, ctx }: ValidationContext & { ctx: RefinementCtx
query: CRMTypes.GetRewardConditionsDocument,
variables: {
agentid,
currentDate: getCurrentISODate(),
currentDate: getCurrentDateString(),
},
});

View File

@ -1,9 +1,16 @@
const run = require('tools/scripts');
const PATH_CRM_GRAPHQL_SCHEMA = './graphql/crm.schema.graphql';
const { URL_CRM_GRAPHQL_DIRECT, DEV_AUTH_TOKEN } = process.env;
function downloadSchema() {
const { URL_CRM_GRAPHQL_DIRECT } = process.env;
const PATH_CRM_GRAPHQL_SCHEMA = './graphql/crm.schema.graphql';
const command1 = ['gql-sdl', URL_CRM_GRAPHQL_DIRECT, '-o', PATH_CRM_GRAPHQL_SCHEMA].join(' ');
const command1 = [
'gql-sdl',
URL_CRM_GRAPHQL_DIRECT,
`-H "Authorization: Bearer ${DEV_AUTH_TOKEN}"`,
'-o',
PATH_CRM_GRAPHQL_SCHEMA,
].join(' ');
run(command1, 'Download GraphQL Schema...');
}

View File

@ -4,7 +4,7 @@ import type { inferAsyncReturnType } from '@trpc/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
export async function createContext({ req }: CreateNextContextOptions) {
const { cookie = '' } = req.headers;
const { cookie = '', authorization } = req.headers;
const user = await getUser({
headers: {
@ -16,6 +16,7 @@ export async function createContext({ req }: CreateNextContextOptions) {
scope.setUser(user);
return {
headers: { authorization },
user,
};
}

View File

@ -15,10 +15,10 @@ export const userMiddleware = t.middleware(async ({ ctx, next }) => {
});
}
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, ctx.headers);
const {
data: { systemuser },
data: { systemusers },
} = await apolloClient.query({
query: CRMTypes.GetSystemUserDocument,
variables: {
@ -26,6 +26,8 @@ export const userMiddleware = t.middleware(async ({ ctx, next }) => {
},
});
const systemuser = systemusers?.at(0);
const unlimited = systemuser?.roles?.some((x) => x?.name && unlimitedRoles.includes(x.name));
return next({

View File

@ -17,7 +17,7 @@ export const calculateRouter = router({
.input(CalculateInputSchema)
.output(CalculateOutputSchema)
.mutation(async ({ input, ctx }) => {
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, ctx.headers);
const queryClient = new QueryClient();
try {

View File

@ -5,7 +5,7 @@ import { ESN, NSIB_MAX, VAT } from '@/constants/values';
import * as CRMTypes from '@/graphql/crm.types';
import helper from '@/process/calculate/lib/helper';
import { createCurrencyUtility } from '@/utils/currency';
import { getCurrentISODate } from '@/utils/date';
import { getCurrentDateString } from '@/utils/date';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { min, sum } from 'radash';
@ -76,7 +76,7 @@ export async function createRequestData({
const currentDate = dayjs().utc(false);
let systemuser: CRMTypes.GetSystemUserQuery['systemuser'] = null;
let systemuser: NonNullable<CRMTypes.GetSystemUserQuery['systemusers']>[number] = null;
if (user?.domainName) {
const { data } = await apolloClient.query({
@ -85,7 +85,7 @@ export async function createRequestData({
domainname: user.domainName,
},
});
if (data.systemuser) systemuser = data.systemuser;
systemuser = data.systemusers?.at(0) ?? null;
}
async function getDeprecation() {
@ -127,7 +127,7 @@ export async function createRequestData({
await apolloClient.query({
query: CRMTypes.GetCoefficientsDocument,
variables: {
currentDate: getCurrentISODate(),
currentDate: getCurrentDateString(),
},
})
).data.evo_coefficients

View File

@ -60,10 +60,12 @@ export const quoteRouter = router({
getQuote: protectedProcedure
.input(GetQuoteInputDataSchema)
.output(GetQuoteOutputDataSchema)
.query(async ({ input }) => {
.query(async ({ input, ctx }) => {
const { quote: quoteId } = input.values;
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, ctx.headers);
const queryClient = new QueryClient();
const {
data: { quote },
} = await apolloClient.query({
@ -88,7 +90,16 @@ export const quoteRouter = router({
addProduct,
createKpProcess,
eltProcess,
].map(({ getKPData }) => getKPData({ ...input, quote }))
].map(({ getKPData }) =>
getKPData({
...input,
quote,
ctx: {
apolloClient,
queryClient,
},
})
)
);
const values = processData.reduce((obj, data) => ({ ...obj, ...data.values }), defaultValues);
@ -112,7 +123,7 @@ export const quoteRouter = router({
.input(CreateQuoteInputDataSchema)
.output(CreateQuoteOutputDataSchema)
.mutation(async ({ input, ctx }) => {
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, ctx.headers);
const queryClient = new QueryClient();
try {

View File

@ -5,6 +5,8 @@ import { KeysSchema, RowSchema } from '@/config/schema/insurance';
import PaymentsSchema from '@/config/schema/payments';
import ValuesSchema from '@/config/schema/values';
import type * as CRMTypes from '@/graphql/crm.types';
import type { ApolloClient, NormalizedCacheObject } from '@apollo/client';
import type { QueryClient } from '@tanstack/react-query';
import { z } from 'zod';
const { quote, recalcWithRevision, lead, opportunity } = ValuesSchema.shape;
@ -22,7 +24,13 @@ export const GetQuoteInputDataSchema = z
})
.strict();
export type GetQuoteContext = {
apolloClient: ApolloClient<NormalizedCacheObject>;
queryClient: QueryClient;
};
export type GetQuoteInputData = z.infer<typeof GetQuoteInputDataSchema> & {
ctx: GetQuoteContext;
quote: CRMTypes.GetQuoteDataQuery['quote'];
};

View File

@ -6,9 +6,9 @@ import configuratorHelper from '@/process/configurator/lib/helper';
import { createTRPCError } from '@/utils/trpc';
export const tarifRouter = router({
getTarif: protectedProcedure.input(GetTarifInputSchema).query(async ({ input }) => {
getTarif: protectedProcedure.input(GetTarifInputSchema).query(async ({ input, ctx }) => {
try {
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, ctx.headers);
const { getTarifs } = configuratorHelper({ apolloClient });
return getTarifs(input);

View File

@ -22,3 +22,11 @@ export function useErrors() {
hasErrors: hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors || hasFingapErrors,
};
}
export function useResults() {
const { $results } = useStore();
return {
hasResults: $results.payments.length > 0,
};
}

9
apps/web/styles/media.ts Normal file
View File

@ -0,0 +1,9 @@
import { screens } from '@/config/ui';
import { createMedia } from '@artsy/fresnel';
const AppMedia = createMedia({
breakpoints: { ...screens, min: 0 },
});
export const mediaStyle = AppMedia.createMediaStyle();
export const { Media, MediaContextProvider } = AppMedia;

View File

@ -1,4 +1,4 @@
import { getCurrentISODate } from './date';
import { getCurrentDateString } from './date';
import * as CRMTypes from '@/graphql/crm.types';
import type { ApolloClient } from '@apollo/client';
@ -33,7 +33,7 @@ export function createCurrencyUtility({ apolloClient }: Context) {
fetchPolicy: 'network-only',
query: CRMTypes.GetCurrencyChangesDocument,
variables: {
currentDate: getCurrentISODate(),
currentDate: getCurrentDateString(),
},
});

View File

@ -11,6 +11,10 @@ export function getCurrentISODate() {
return _currentDate().toISOString();
}
export function getCurrentDateString() {
return _currentDate().format('YYYY-MM-DD');
}
export function getCurrentDate() {
return _currentDate().toDate();
}

11
apps/web/utils/device.ts Normal file
View File

@ -0,0 +1,11 @@
import { screens } from '@/config/ui';
export function getDevice() {
if (typeof window === 'undefined') return null;
const isMobile = window.innerWidth < screens.tablet;
return {
isMobile,
};
}

View File

@ -31,7 +31,7 @@ export function makeGetUserType({ apolloClient, queryClient }: MakeGetUserTypePr
);
const {
data: { systemuser },
data: { systemusers },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetSystemUserDocument,
@ -40,6 +40,8 @@ export function makeGetUserType({ apolloClient, queryClient }: MakeGetUserTypePr
},
});
const systemuser = systemusers?.[0];
const roles = systemuser?.roles ? sift(systemuser?.roles)?.map((x) => x?.name) : [];
return {

14
pnpm-lock.yaml generated
View File

@ -126,6 +126,9 @@ importers:
'@apollo/client':
specifier: ^3.9.5
version: 3.9.5(@types/react@18.2.58)(graphql@16.8.1)(react-dom@18.2.0)(react@18.2.0)
'@artsy/fresnel':
specifier: ^7.1.4
version: 7.1.4(react@18.2.0)
'@fontsource/montserrat':
specifier: ^4.5.14
version: 4.5.14
@ -242,7 +245,7 @@ importers:
specifier: ^8.52.0
version: 8.57.0
gql-sdl:
specifier: ^1.0.0
specifier: ^1.1.0
version: 1.1.0
jest:
specifier: ^29.4.3
@ -557,6 +560,15 @@ packages:
- encoding
dev: true
/@artsy/fresnel@7.1.4(react@18.2.0):
resolution: {integrity: sha512-qbUdxzlcI9Q9Ez+HfYDq7hlLoeFKC8EKcCckW+EltWu9SWL3px4QZIkr7NwYEz13q/nLvAlHMnbJ3TpSEEZ1zg==}
engines: {node: '>=12.20.2', yarn: 1.x.x}
peerDependencies:
react: '>=18.0.0'
dependencies:
react: 18.2.0
dev: false
/@babel/code-frame@7.23.5:
resolution: {integrity: sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==}
engines: {node: '>=6.9.0'}