Compare commits

..

6 Commits

Author SHA1 Message Date
vchikalkin
60f4069aea docker: add api & redis 2024-02-17 17:38:46 +03:00
vchikalkin
d7ba323355 apps/web: fix getCurrentISODate in hooks/init 2024-02-17 17:09:37 +03:00
vchikalkin
49715531d9 apps/web: use dates w/ zero time 2024-02-17 16:57:15 +03:00
vchikalkin
fba7c240b1 apps: simple proxy with cache for graphql requests 2024-02-17 16:33:50 +03:00
vchikalkin
1539183662 apps/cache: use fastify 2024-02-17 11:52:59 +03:00
vchikalkin
6f2778794d apps: add cache 2024-02-17 11:50:46 +03:00
227 changed files with 20177 additions and 32618 deletions

3
.dockerignore Normal file
View File

@ -0,0 +1,3 @@
.git
README.md
node_modules

2
.gitignore vendored
View File

@ -68,5 +68,3 @@ yarn-error.log*
.turbo
# End of https://www.toptal.com/developers/gitignore/api/turbo
.pnpm

104
README.md
View File

@ -1,28 +1,59 @@
# Turborepo starter
# Turborepo Docker starter
This is an official starter Turborepo.
This is an official Docker starter Turborepo.
## What's inside?
This turborepo uses [Yarn](https://classic.yarnpkg.com/lang/en/) as a package manager. It includes the following packages/apps:
### Apps and Packages
- `web`: a [Next.js](https://nextjs.org/) app
- `api`: an [Express](https://expressjs.com/) server
- `ui`: ui: a React component library
- `eslint-config-custom`: `eslint` configurations for client side applications (includes `eslint-config-next` and `eslint-config-prettier`)
- `eslint-config-custom-server`: `eslint` configurations for server side applications (includes `eslint-config-next` and `eslint-config-prettier`)
- `scripts`: Jest configurations
- `logger`: Isomorphic logger (a small wrapper around console.log)
- `tsconfig`: tsconfig.json;s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
## Using this example
Run the following command:
```sh
npx create-turbo@latest
npx degit vercel/turbo/examples/with-docker with-docker
cd with-docker
yarn install
git init . && git add . && git commit -m "Init"
```
## What's inside?
### Docker
This Turborepo includes the following packages/apps:
This repo is configured to be built with Docker, and Docker compose. To build all apps in this repo:
### Apps and Packages
```
# Create a network, which allows containers to communicate
# with each other, by using their container name as a hostname
docker network create app_network
- `docs`: a [Next.js](https://nextjs.org/) app
- `web`: another [Next.js](https://nextjs.org/) app
- `@repo/ui`: a stub React component library shared by both `web` and `docs` applications
- `@repo/eslint-config`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
- `@repo/tsconfig`: `tsconfig.json`s used throughout the monorepo
# Build prod using new BuildKit engine
COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose -f docker-compose.yml build --parallel
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
# Start prod in detached mode
docker-compose -f docker-compose.yml up -d
```
Open http://localhost:3000.
To shutdown all running containers:
```
# Stop all running containers
docker kill $(docker ps -q) && docker rm $(docker ps -a -q)
```
### Utilities
@ -30,52 +61,5 @@ This Turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Jest](https://jestjs.io) test runner for all things JavaScript
- [Prettier](https://prettier.io) for code formatting
### Build
To build all apps and packages, run the following command:
```
cd my-turborepo
pnpm build
```
### Develop
To develop all apps and packages, run the following command:
```
cd my-turborepo
pnpm dev
```
### Remote Caching
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
```
cd my-turborepo
npx turbo login
```
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
```
npx turbo link
```
## Useful Links
Learn more about the power of Turborepo:
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)

View File

@ -1,7 +1,6 @@
.git
Dockerfile
.dockerignore
node_modules
*.log
npm-debug.log
dist
README.md

View File

@ -2,21 +2,17 @@
# Make sure you update both files!
FROM node:alpine AS builder
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@1.12.4 dotenv-cli
RUN yarn global add turbo
COPY . .
RUN turbo prune --scope=api --docker
# Add lockfile and package.json's of isolated subworkspace
FROM node:alpine AS installer
RUN corepack enable && corepack prepare pnpm@latest --activate
ENV PNPM_HOME=/usr/local/bin
RUN apk add --no-cache libc6-compat
RUN apk update
WORKDIR /app
@ -24,14 +20,14 @@ WORKDIR /app
# First install dependencies (as they change less often)
COPY .gitignore .gitignore
COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
COPY --from=builder /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml
RUN pnpm install
COPY --from=builder /app/out/yarn.lock ./yarn.lock
RUN yarn install
# Build the project and its dependencies
COPY --from=builder /app/out/full/ .
COPY turbo.json turbo.json
RUN pnpm dotenv -e .env turbo run build --filter=api...
# COPY .env .env
RUN yarn turbo run build --filter=api...
FROM node:alpine AS runner
WORKDIR /app
@ -42,4 +38,4 @@ RUN adduser --system --uid 1001 nestjs
USER nestjs
COPY --from=installer /app .
CMD node apps/api/dist/main.js
CMD node apps/api/dist/main.js

View File

@ -29,33 +29,33 @@
## Installation
```bash
$ pnpm install
$ yarn install
```
## Running the app
```bash
# development
$ pnpm run start
$ yarn run start
# watch mode
$ pnpm run start:dev
$ yarn run start:dev
# production mode
$ pnpm run start:prod
$ yarn run start:prod
```
## Test
```bash
# unit tests
$ pnpm run test
$ yarn run test
# e2e tests
$ pnpm run test:e2e
$ yarn run test:e2e
# test coverage
$ pnpm run test:cov
$ yarn run test:cov
```
## Support

View File

@ -40,19 +40,18 @@
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/supertest": "^6.0.0",
"@vchikalkin/eslint-config-awesome": "^1.1.6",
"eslint": "^8.52.0",
"@vchikalkin/eslint-config-awesome": "^1.1.5",
"eslint": "^8.51.0",
"fastify": "^4.26.1",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"shared": "workspace:*",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "29.1.1",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.3.3"
"typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [

View File

@ -1,3 +0,0 @@
import { seconds } from 'src/utils/time';
export const DEFAULT_CACHE_TTL = seconds().fromMinutes(15);

View File

@ -1,15 +1,10 @@
import { DEFAULT_CACHE_TTL } from '../constants';
import { z } from 'zod';
const envSchema = z.object({
CACHE_TTL: z
.string()
.transform((val) => Number.parseInt(val, 10))
.default(DEFAULT_CACHE_TTL.toString()),
PORT: z
.string()
.transform((val) => Number.parseInt(val, 10))
.default('3001'),
.default('900'),
REDIS_HOST: z.string(),
REDIS_PORT: z
.string()

View File

@ -1,5 +1,4 @@
import { AppModule } from './app.module';
import { env } from './config/env';
import { NestFactory } from '@nestjs/core';
import type { NestFastifyApplication } from '@nestjs/platform-fastify';
import { FastifyAdapter } from '@nestjs/platform-fastify';
@ -9,7 +8,6 @@ async function bootstrap() {
AppModule,
new FastifyAdapter(),
);
await app.listen(env.PORT, '0.0.0.0');
await app.listen(3001);
}
bootstrap();

View File

@ -1,64 +0,0 @@
import { seconds } from 'src/utils/time';
export const queryTTL: Record<string, number | false> = {
GetAddProductType: seconds().fromHours(12),
GetAddproductTypes: seconds().fromHours(12),
GetAgent: seconds().fromHours(12),
GetBrand: seconds().fromHours(3),
GetBrands: seconds().fromHours(3),
GetCoefficients: seconds().fromHours(12),
GetConfiguration: seconds().fromHours(3),
GetConfigurations: seconds().fromMinutes(15),
GetCurrencyChanges: seconds().fromHours(1),
GetDealer: seconds().fromHours(1),
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),
GetImportProgram: seconds().fromHours(12),
GetInsNSIBTypes: seconds().fromHours(12),
GetInsuranceCompanies: seconds().fromHours(12),
GetInsuranceCompany: seconds().fromHours(12),
GetLead: false,
GetLeadUrl: seconds().fromHours(12),
GetLeads: false,
GetLeaseObjectType: seconds().fromHours(24),
GetLeaseObjectTypes: seconds().fromHours(24),
GetLeasingWithoutKaskoTypes: seconds().fromHours(12),
GetModel: seconds().fromHours(3),
GetModels: seconds().fromMinutes(15),
GetOpportunities: false,
GetOpportunity: false,
GetOpportunityUrl: seconds().fromHours(12),
GetOsagoAddproductTypes: seconds().fromHours(12),
GetProduct: seconds().fromHours(12),
GetProducts: seconds().fromHours(12),
GetQuote: false,
GetQuoteData: false,
GetQuoteUrl: seconds().fromHours(12),
GetQuotes: false,
GetRate: seconds().fromHours(12),
GetRates: seconds().fromHours(12),
GetRegion: seconds().fromHours(24),
GetRegions: seconds().fromHours(24),
GetRegistrationTypes: seconds().fromHours(12),
GetRewardCondition: seconds().fromHours(1),
GetRewardConditions: seconds().fromHours(1),
GetRoles: seconds().fromHours(12),
GetSotCoefficientType: seconds().fromHours(12),
GetSubsidies: seconds().fromHours(12),
GetSubsidy: seconds().fromHours(12),
GetSystemUser: seconds().fromHours(12),
GetTarif: seconds().fromHours(12),
GetTarifs: seconds().fromHours(12),
GetTechnicalCards: seconds().fromHours(12),
GetTelematicTypes: seconds().fromHours(12),
GetTown: seconds().fromHours(24),
GetTowns: seconds().fromHours(24),
GetTrackerTypes: seconds().fromHours(12),
GetTransactionCurrencies: seconds().fromHours(12),
GetTransactionCurrency: seconds().fromHours(12),
};

View File

@ -1,33 +1,13 @@
import { queryTTL } from './lib/config';
import type { GQLRequest, GQLResponse } from './types';
import type { GQLRequest } from './types';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
All,
Controller,
Delete,
Get,
HttpException,
HttpStatus,
Inject,
Query,
Req,
Res,
} from '@nestjs/common';
import type { Cache } from 'cache-manager';
import { All, Controller, Inject, Req, Res } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { FastifyReply, FastifyRequest } from 'fastify';
import type { QueryItem } from 'shared/types/cache';
import { env } from 'src/config/env';
type RedisStore = Omit<Cache, 'set'> & {
set: (key: string, value: unknown, { ttl }: { ttl: number }) => Promise<void>;
};
@Controller('proxy')
export class ProxyController {
constructor(
@Inject(CACHE_MANAGER) private readonly cacheManager: RedisStore,
) {}
constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {}
@All('/graphql')
public async graphql(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
const { operationName, query, variables } = req.body as GQLRequest;
@ -35,7 +15,9 @@ export class ProxyController {
const key = `${operationName} ${JSON.stringify(variables)}`;
const cached = await this.cacheManager.get(key);
if (cached) return reply.send(cached);
if (cached) {
return reply.send(cached);
}
const response = await fetch(env.URL_CRM_GRAPHQL_DIRECT, {
body: JSON.stringify({ operationName, query, variables }),
@ -47,81 +29,9 @@ export class ProxyController {
method: req.method,
});
const data = (await response.json()) as GQLResponse;
if (!response.ok || data?.error || data?.errors?.length)
throw new HttpException(
response.statusText,
response.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
const ttl = queryTTL[operationName];
if (data && ttl !== false)
await this.cacheManager.set(key, data, { ttl: ttl || env.CACHE_TTL });
const data = await response.json();
if (data) await this.cacheManager.set(key, data);
return reply.send(data);
}
@Get('/get-queries')
public async getQueriesList(@Res() reply: FastifyReply) {
const res = await this.getAllQueries();
return reply.send(res);
}
private async getAllQueries() {
const list = await this.cacheManager.store.keys('*');
return (Object.keys(queryTTL) as Array<keyof typeof queryTTL>).reduce(
(acc, queryName) => {
const queries = list.filter((x) => x.split(' ').at(0) === queryName);
if (queries.length) {
const ttl = queryTTL[queryName];
acc[queryName] = { queries, ttl };
}
return acc;
},
{} as Record<string, QueryItem>,
);
}
@Delete('/delete-query')
public async deleteQuery(
@Query('queryKey') queryKey: string,
@Res() reply: FastifyReply,
) {
try {
await this.cacheManager.del(queryKey);
return reply.send('ok');
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Delete('/reset')
public async reset(@Res() reply: FastifyReply) {
try {
await this.cacheManager.reset();
return reply.send('ok');
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get('/get-query')
public async getQueryValue(
@Query('queryKey') queryKey: string,
@Res() reply: FastifyReply,
) {
try {
const value = await this.cacheManager.get(queryKey);
return reply.send(value);
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -3,9 +3,3 @@ export type GQLRequest = {
query: string;
variables: string;
};
export type GQLResponse = {
data: unknown;
error?: unknown;
errors?: unknown[];
};

View File

@ -1,13 +0,0 @@
export function seconds() {
return {
fromDays(days: number) {
return days * 24 * 60 * 60;
},
fromHours(hours: number) {
return hours * 60 * 60;
},
fromMinutes(minutes: number) {
return minutes * 60;
},
};
}

View File

@ -1,8 +0,0 @@
.git
Dockerfile
.dockerignore
node_modules
*.log
dist
.next
README.md

View File

@ -1,14 +1,11 @@
const { createConfig } = require('@vchikalkin/eslint-config-awesome');
module.exports = createConfig('next-typescript', {
module.exports = {
extends: [
'@vchikalkin/eslint-config-awesome/next-typescript/config',
'@vchikalkin/eslint-config-awesome/next-typescript/rules',
],
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: __dirname,
},
rules: {
'import/no-duplicates': 'off',
'react/forbid-component-props': 'off',
'import/consistent-type-specifier-style': 'off',
},
ignorePatterns: ['*.config.js', '.eslintrc.js'],
});
root: true,
};

4
apps/web/.gitignore vendored
View File

@ -1,4 +0,0 @@
# Sentry Config File
.sentryclirc
/styles/antd.min.css

View File

@ -1,6 +1,6 @@
overwrite: true
schema: './graphql/crm.schema.graphql'
documents: [./**/!(*.schema).graphql]
documents: ['./**/!(*.{d,types}).{ts,tsx}', './**/.{js,jsx}', ./**/!(*.schema).graphql]
generates:
./graphql/crm.types.ts:
plugins:
@ -16,7 +16,7 @@ generates:
object: true
defaultValue: true
scalars:
UUID: string
Uuid: string
Decimal: number
DateTime: string
# exclude: './graphql/crm.schema.graphql'

View File

@ -1,19 +0,0 @@
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,77 +0,0 @@
import * as cacheApi from '@/api/cache/query';
import { min } from '@/styles/mq';
import { useQuery } from '@tanstack/react-query';
import { memo, useState } from 'react';
import styled from 'styled-components';
import { Button, Collapse } from 'ui/elements';
import { Flex } from 'ui/grid';
type QueryProps = {
readonly onDeleteQuery: () => Promise<void>;
readonly queryKey: string;
};
const StyledPre = styled.pre`
max-height: 300px;
overflow-y: auto;
${min('desktop')} {
max-height: 800px;
}
`;
export const Query = memo(({ onDeleteQuery, queryKey }: QueryProps) => {
const { data, refetch } = useQuery({
enabled: false,
queryFn: ({ signal }) => signal && cacheApi.getQueryValue(queryKey, { signal }),
queryKey: ['admin', 'cache', 'query', queryKey],
refetchOnWindowFocus: false,
});
const [activeKey, setActiveKey] = useState<string | undefined>(undefined);
const [deletePending, setDeletePending] = useState(false);
const content = (
<>
<StyledPre>{JSON.stringify(data, null, 2)}</StyledPre>
<Flex justifyContent="flex-end">
<Button
type="primary"
danger
disabled={deletePending}
onClick={() => {
setDeletePending(true);
onDeleteQuery().finally(() => {
setDeletePending(false);
});
}}
>
Удалить
</Button>
</Flex>
</>
);
return (
<Collapse
bordered={false}
activeKey={activeKey}
items={[
{
children: data ? content : 'Загрузка...',
key: queryKey,
label: queryKey,
},
]}
onChange={() => {
if (activeKey) {
setActiveKey(undefined);
} else {
setActiveKey(queryKey);
refetch();
}
}}
/>
);
});

View File

@ -1,22 +0,0 @@
import { Query } from './Query';
import * as cacheApi from '@/api/cache/query';
import { useState } from 'react';
import type { QueryItem } from 'shared/types/cache';
type QueryListProps = QueryItem;
export const QueryList = ({ queries }: QueryListProps) => {
const [deletedQueries, setDeletedQueries] = useState<QueryItem['queries']>([]);
function handleDeleteQuery(queryKey: string) {
return cacheApi
.deleteQuery(queryKey)
.then(() => setDeletedQueries([...deletedQueries, queryKey]));
}
const activeQueries = queries.filter((queryKey) => !deletedQueries.includes(queryKey));
return activeQueries.map((queryKey) => (
<Query key={queryKey} queryKey={queryKey} onDeleteQuery={() => handleDeleteQuery(queryKey)} />
));
};

View File

@ -1,24 +0,0 @@
import { useState } from 'react';
import { Button } from 'ui/elements';
import { ReloadOutlined } from 'ui/elements/icons';
export function ReloadButton({ onClick }: { readonly onClick: () => Promise<unknown> }) {
const [pending, setPending] = useState(false);
return (
<Button
loading={pending}
onClick={() => {
setPending(true);
onClick().finally(() => {
setTimeout(() => {
setPending(false);
}, 1000);
});
}}
icon={<ReloadOutlined rev="" />}
>
Обновить
</Button>
);
}

View File

@ -1,70 +0,0 @@
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 { Button, Collapse, Divider, Input } from 'ui/elements';
const Wrapper = styled(Background)`
padding: 4px 6px;
width: 100vw;
${min('tablet')} {
min-height: 790px;
}
${min('laptop')} {
padding: 4px 18px 10px;
width: 1280px;
}
`;
const Flex = styled.div`
display: flex;
flex-direction: column;
gap: 10px;
`;
const ButtonWrapper = styled.div`
display: flex;
justify-content: flex-end;
`;
export function Cache() {
const { filteredQueries, refetch, setFilterString } = useFilteredQueries();
function handleDeleteQuery() {
return reset().then(() => refetch());
}
if (!filteredQueries) {
return <div>Загрузка...</div>;
}
return (
<Wrapper>
<Divider>Управление кэшем</Divider>
<Flex>
<Input
placeholder="Поиск по запросу"
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>
</Wrapper>
);
}

View File

@ -1,30 +0,0 @@
import { filterQueries } from './utils';
import * as cacheApi from '@/api/cache/query';
import type { ResponseQueries } from '@/api/cache/types';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { useDebounce } from 'use-debounce';
export function useFilteredQueries() {
const { data: queries, refetch } = useQuery({
enabled: false,
queryFn: ({ signal }) => signal && cacheApi.getQueries({ signal }),
queryKey: ['admin', 'cache', 'queries'],
refetchOnWindowFocus: false,
});
const [filteredQueries, setFilteredQueries] = useState<ResponseQueries | undefined>(queries);
const [filterString, setFilterString] = useState('');
const [debouncedFilterString] = useDebounce(filterString, 350);
useEffect(() => {
if (!debouncedFilterString) {
setFilteredQueries(queries);
}
if (queries && debouncedFilterString) {
setFilteredQueries(filterQueries(queries, debouncedFilterString));
}
}, [debouncedFilterString, queries]);
return { filteredQueries, queries, refetch, setFilterString };
}

View File

@ -1,23 +0,0 @@
import type { ResponseQueries } from '@/api/cache/types';
export function filterQueries(queriesObj: ResponseQueries, searchStr: string): ResponseQueries {
const filteredObj: ResponseQueries = {};
for (const key in queriesObj) {
if (key.includes(searchStr)) {
filteredObj[key] = queriesObj[key];
} else {
const queries: string[] = [];
queriesObj[key].queries.forEach((queryKey) => {
if (queryKey.toLowerCase().includes(searchStr.toLowerCase())) {
queries.push(queryKey);
}
});
if (queries.length) {
filteredObj[key] = { ...queriesObj[key], queries };
}
}
}
return filteredObj;
}

View File

@ -1,17 +0,0 @@
import { min } from '@/styles/mq';
import type { PropsWithChildren } from 'react';
import styled from 'styled-components';
const Flex = styled.div`
display: flex;
flex-direction: column;
${min('laptop')} {
flex-direction: row;
justify-content: center;
}
`;
export function Layout({ children }: PropsWithChildren) {
return <Flex>{children}</Flex>;
}

View File

@ -1,2 +0,0 @@
export * from './Cache';
export * from './Layout';

View File

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

View File

@ -12,6 +12,5 @@ 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

@ -7,16 +7,16 @@ import { Table } from 'ui/elements';
export const PolicyTable = observer(
({
onSelectRow,
storeSelector,
onSelectRow,
...props
}: {
columns: typeof columns;
onSelectRow: (row: Row) => void;
storeSelector: StoreSelector;
}) => {
const { $process, $tables } = useStore();
const { getRows, getSelectedRow, setSelectedKey } = storeSelector($tables.elt);
const { $tables, $process } = useStore();
const { getRows, setSelectedKey, getSelectedRow } = storeSelector($tables.elt);
return (
<Table
@ -37,12 +37,7 @@ export const PolicyTable = observer(
$process.add('ELT');
setSelectedKey(record.key);
onSelectRow(record);
message.success({
content: 'Выбранный расчет ЭЛТ применен',
duration: 1,
key: record.key,
onClick: () => message.destroy(record.key),
});
message.success({ content: 'Выбранный расчет ЭЛТ применен', key: record.key });
$process.delete('ELT');
}
},

View File

@ -1,41 +1,126 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { resetRow } from './lib/tools';
import { makeEltKaskoRequest } from './lib/make-request';
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 { trpcClient } from '@/trpc/client';
import { defaultRow } from '@/stores/tables/elt/default-values';
import { useApolloClient } from '@apollo/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 { $tables, $calculation } = store;
const apolloClient = useApolloClient();
const { init } = helper({ apolloClient, store });
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 handleOnClick = useCallback(async () => {
$tables.elt.kasko.abortController?.abort();
$tables.elt.kasko.abortController = new AbortController();
function handleOnClick() {
calculateKasko.mutate({
calculation: {
values: store.$calculation.$values.getValues(),
},
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,
skCalcId,
totalFranchise = 0,
requestId,
paymentPeriods,
} = res;
let { error } = res;
if (totalFranchise > MAX_FRANCHISE) {
error ||= `Франшиза по страховке превышает максимально допустимое значение: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_FRANCHISE)}`;
}
if (kaskoSum > MAX_INSURANCE) {
error ||= `Сумма по страховке превышает максимально допустимое значение по стоимости КАСКО: ${Intl.NumberFormat(
'ru',
{
currency: 'RUB',
style: 'currency',
}
).format(MAX_INSURANCE)}`;
}
if (kaskoSum < 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: values.leasingPeriod <= 16 ? kaskoSum : paymentPeriods?.[0]?.kaskoSum || 0,
totalFranchise,
});
}
})
.catch((error) => {
const _err = error as Error;
$tables.elt.kasko.setRow({
...initialData,
key,
message: _err.message || String(error),
status: 'error',
});
});
}
});
}
}, [$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

@ -1,42 +1,98 @@
/* eslint-disable no-negated-condition */
/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { resetRow } from './lib/tools';
import { makeEltOsagoRequest } from './lib/make-request';
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 { trpcClient } from '@/trpc/client';
import { defaultRow } from '@/stores/tables/elt/default-values';
import { useApolloClient } from '@apollo/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 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 handleOnClick = useCallback(async () => {
$tables.elt.osago.abortController?.abort();
$tables.elt.osago.abortController = new AbortController();
async function handleOnClick() {
calculateOsago.mutate({
calculation: {
values: store.$calculation.$values.getValues(),
},
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);
makeEltOsagoRequest({ apolloClient, store }, row)
.then((payload) =>
getEltOsago(payload, { signal: $tables.elt.osago.abortController.signal })
)
.then((res) => {
if (res) {
const { numCalc, premiumSum = 0, message, 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,
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',
});
});
}
});
}
}, [$tables.elt.osago, $tables.insurance, apolloClient, init, store]);
function handleOnSelectRow(row: Row) {
$tables.insurance.row('osago').column('insuranceCompany').setValue(row.key);

View File

@ -1,7 +1,10 @@
import type { Row } from '../types';
import type { RowSchema } from '@/config/schema/elt';
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

@ -1,59 +1,10 @@
/* 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 { getCurrentDateString } from '@/utils/date';
import dayjs from 'dayjs';
import { first, sort } from 'radash';
export async function ownOsagoRequest(
{ store, apolloClient }: Pick<ProcessContext, 'apolloClient' | 'store'>,
row: Row
): Promise<NonNullable<CRMTypes.GetOsagoAddproductTypesQuery['evo_addproduct_types']>[number]> {
const currentDate = getCurrentDateString();
const {
data: { evo_addproduct_types },
} = await apolloClient.query({
query: CRMTypes.GetOsagoAddproductTypesDocument,
variables: { currentDate },
});
if (!evo_addproduct_types) return null;
const { leaseObjectCategory, leaseObjectMotorPower, countSeats, maxMass } =
store.$calculation.$values.getValues([
'leaseObjectCategory',
'leaseObjectMotorPower',
'countSeats',
'maxMass',
]);
const filteredTypes = evo_addproduct_types.filter(
(type) =>
type?.evo_accountid === row.key &&
type.evo_visible_calc &&
type.evo_category === leaseObjectCategory &&
type.evo_min_power !== null &&
type.evo_max_power !== null &&
type.evo_min_power <= leaseObjectMotorPower &&
type.evo_max_power >= leaseObjectMotorPower &&
type.evo_min_seats_count !== null &&
type.evo_max_seats_count !== null &&
type.evo_min_seats_count <= countSeats &&
type.evo_max_seats_count >= countSeats &&
type.evo_min_mass !== null &&
type.evo_max_mass !== null &&
type.evo_min_mass <= maxMass &&
type.evo_max_mass >= maxMass
);
const sortedTypes = sort(filteredTypes, (type) => dayjs(type?.createdon).date());
return first(sortedTypes) || null;
}
const getSpecified = (value: unknown) => value !== null && value !== undefined;
@ -243,11 +194,11 @@ export async function makeEltOsagoRequest(
country: 'Россия',
house: '52',
korpus: '5',
flat: '337',
house: '8',
region: 'Москва',
resident: 1,
street: 'Космодамианская наб',
street: 'ул. Котляковская',
};
const owner = {
@ -255,7 +206,7 @@ export async function makeEltOsagoRequest(
email: 'client@evoleasing.ru',
factAddress: address,
inn: '9724016636',
kpp: '770501001',
kpp: '772401001',
ogrn: '1207700245037',
opf: 1,
opfSpecified: true,
@ -471,8 +422,7 @@ export async function makeEltKaskoRequest(
let selfIgnitionSpecified = false;
if (
leaseObjectCategory === 100_000_002 ||
(evo_leasingobject_type?.evo_id &&
['6', '8', '9', '10'].includes(evo_leasingobject_type?.evo_id))
(evo_leasingobject_type?.evo_id && ['6', '9', '10'].includes(evo_leasingobject_type?.evo_id))
) {
notConfirmedGlassesDamages = 3;
notConfirmedGlassesDamagesSpecified = true;
@ -573,7 +523,6 @@ 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();
@ -618,26 +567,10 @@ export async function makeEltKaskoRequest(
}
}
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;
}
}
const classification =
leaseObjectCategory && [100_000_002, 100_000_003, 100_000_004].includes(leaseObjectCategory)
? '11635'
: '0';
let INN = '';
const leadid = $calculation.element('selectLead').getValue();

View File

@ -1,12 +0,0 @@
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,14 +1,13 @@
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']],
[['tbxMileage', 'tbxInsFranchise', 'selectLegalClientTown']],
[['selectGPSBrand', 'cbxWithTrailer', 'selectInsNSIB']],
[['selectGPSModel', 'cbxInsDecentral', 'selectLeasingWithoutKasko']],
[['selectEngineType', 'tbxInsFranchise', 'selectLegalClientTown']],
[['selectLeaseObjectCategory', 'tbxMileage']],
[['tbxLeaseObjectMotorPower', 'cbxWithTrailer', 'selectGPSBrand']],
[['tbxEngineVolume', 'cbxInsDecentral', 'selectGPSModel']],
[['selectLeasingWithoutKasko', 'selectInsNSIB']],
];
export const mobileRows = transformRowsForMobile(rows);

View File

@ -1,15 +1,15 @@
import renderFormRows from '../../lib/render-rows';
import { id, mobileRows, rows, title } from './config';
import { id, 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">
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
{renderedRows}
<InsuranceTable />
<FinGAPTable />
</Flex>

View File

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

View File

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

View File

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

View File

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

View File

@ -8,9 +8,7 @@ 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';
@ -46,23 +44,22 @@ const ComponentWrapper = styled.div`
}
`;
export const Form = memo(() => {
const { $process } = useStore();
const filteredTabs =
$process.has('Unlimited') === false ? formTabs.filter((x) => x.id !== 'unlimited') : formTabs;
function Form({ prune }) {
return (
<Wrapper>
<Tabs type="card" tabBarGutter="5px">
{filteredTabs.map(({ Component, id, title }) => (
<Tabs.TabPane tab={title} key={id}>
<ComponentWrapper>
<Component />
</ComponentWrapper>
</Tabs.TabPane>
))}
{formTabs
.filter((tab) => !prune?.includes(tab.id))
.map(({ id, title, Component }) => (
<Tabs.TabPane tab={title} key={id}>
<ComponentWrapper>
<Component />
</ComponentWrapper>
</Tabs.TabPane>
))}
</Tabs>
</Wrapper>
);
});
}
export default Form;

View File

@ -1,32 +0,0 @@
/**
*
* @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

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

View File

@ -3,7 +3,6 @@ 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)`
@ -18,7 +17,7 @@ const Wrapper = styled(Background)`
}
`;
export const Settings = memo(() => {
export default function Settings() {
const { $process } = useStore();
const mainRows = $process.has('Unlimited')
@ -34,4 +33,4 @@ export const Settings = memo(() => {
{paramsRows}
</Wrapper>
);
});
}

View File

@ -1,19 +0,0 @@
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,7 +136,6 @@ const components = wrapComponentsMap({
cbxPartialVAT: e.Switch,
cbxFloatingRate: e.Switch,
cbxQuotePriceWithFullVAT: e.Switch,
cbxQuoteShowAcceptLimit: e.Switch,
/** Readonly Elements */
labelLeaseObjectRisk: e.Text,

View File

@ -332,7 +332,7 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
const RenderedComponent = observer(() => {
const { $calculation } = useStore();
const { max, min } = $calculation.$values.getValue('irrInfo');
const { min, max } = $calculation.$values.getValue('irrInfo');
return (
<Container>
@ -370,7 +370,7 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
<Element
{...props}
id={elementName}
addonBefore={isFetching ? <LoadingOutlined spin rev="" /> : null}
addonBefore={isFetching && <LoadingOutlined spin rev="" />}
/>
</Container>
</Tooltip>

View File

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

View File

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

View File

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

View File

@ -0,0 +1,2 @@
export { default as Form } from './Form';
export { default as Settings } from './Settings';

View File

@ -1,101 +0,0 @@
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,20 +0,0 @@
import getColors from '@/styles/colors';
import styled from 'styled-components';
import { Result } from 'ui/elements';
import { LoadingOutlined } from 'ui/elements/icons';
const colors = getColors();
const Title = styled.span`
font-size: 1.25rem;
color: rgba(0, 0, 0, 0.88);
`;
export function Loading() {
return (
<Result
icon={<LoadingOutlined style={{ color: colors.COLOR_PRIMARY, fontSize: '60px' }} />}
title={<Title>Загрузка...</Title>}
/>
);
}

View File

@ -1,7 +1,4 @@
/* 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';
@ -10,61 +7,23 @@ import { message as antdMessage, notification as antdNotification } from 'ui/ele
export let message: Readonly<MessageInstance>;
export let notification: Readonly<NotificationInstance>;
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();
export function Notification({ children }: { children: ReactNode }) {
const [messageApi, messageContextHolder] = antdMessage.useMessage({
duration: device?.isMobile ? 1.5 : 1.2,
maxCount: 3,
top: 70,
});
const [notificationApi, notificationContextHolder] = antdNotification.useNotification({
maxCount: 3,
placement: 'bottomRight',
stack: { threshold: 1 },
});
message = messageApi;
notification = createWrapper(notificationApi, messageApi);
notification = notificationApi;
return (
<>
{messageContextHolder}
<Media greaterThanOrEqual="laptop">{notificationContextHolder}</Media>
{notificationContextHolder}
{children}
</>
);

View File

@ -1,3 +0,0 @@
export * from './Error';
export * from './Loading';
export * from './Notification';

View File

@ -10,7 +10,7 @@ const UserText = styled.span`
padding: 0;
text-transform: uppercase;
color: #fff;
font-size: 0.55rem;
font-size: 0.5rem;
font-family: 'Montserrat';
font-weight: 500;
line-height: 1;
@ -45,7 +45,13 @@ const Logout = styled.a`
function Auth() {
return (
<Flex flexDirection="column" alignItems="flex-end" justifyContent="flex-start" height="100%">
<Flex
flexDirection="column"
alignItems="flex-end"
alignSelf={['flex-start']}
justifyContent="space-between"
height="100%"
>
<User />
<Logout href="/logout">Выход</Logout>
</Flex>

View File

@ -7,7 +7,6 @@ import { Flex } from 'ui/grid';
const HeaderContent = styled(Flex)`
flex-direction: row;
justify-content: space-between;
padding: 14px 12px;
background: linear-gradient(
90deg,
@ -16,7 +15,9 @@ const HeaderContent = styled(Flex)`
var(--color-tertiarty) 100%
);
padding: 14px 12px;
${min('laptop')} {
padding: 14px 12px;
padding-left: 20px;
}
`;

View File

@ -5,7 +5,6 @@ import getColors from '@/styles/colors';
import { min } from '@/styles/mq';
import { observer } from 'mobx-react-lite';
import Image from 'next/image';
import Link from 'next/link';
import logo from 'public/assets/images/logo-primary.svg';
import styled from 'styled-components';
import { Tag } from 'ui/elements';
@ -34,9 +33,8 @@ const LogoText = styled.h3`
const TagWrapper = styled.div`
font-family: 'Montserrat';
font-weight: 500;
${min('tablet')} {
margin: 0 5px;
* {
font-size: 0.7rem;
}
`;
@ -44,11 +42,12 @@ const { COLOR_PRIMARY } = getColors();
const UnlimitedTag = observer(() => {
const { $process } = useStore();
if ($process.has('Unlimited')) {
return (
<TagWrapper>
<Tag color={COLOR_PRIMARY}>без ограничений</Tag>
<Tag color={COLOR_PRIMARY} style={{ margin: '0 5px' }}>
без ограничений
</Tag>
</TagWrapper>
);
}
@ -60,11 +59,9 @@ function Logo() {
return (
<Flex flexDirection="column" alignItems="flex-start" justifyContent="space-between">
<ImageWrapper>
<Link prefetch={false} href="/">
<Image priority className={styles.logo} alt="logo" src={logo} layout="responsive" />
</Link>
<Image priority className={styles.logo} alt="logo" src={logo} layout="responsive" />
</ImageWrapper>
<Flex flexDirection={['column', 'row']} alignItems={[undefined, 'center']}>
<Flex justifyContent="space-between" alignItems="center">
<LogoText>Лизинговый Калькулятор</LogoText>
<UnlimitedTag />
</Flex>

View File

@ -1,60 +0,0 @@
import Background from './Background';
import type { MenuProps } from 'antd';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { Menu } from 'ui/elements';
import { AppstoreOutlined, SettingOutlined } from 'ui/elements/icons';
const items: MenuProps['items'] = [
{
children: [
{
// icon: <HomeOutlined />,
key: '/',
label: (
<Link prefetch={false} href="/">
Главная
</Link>
),
},
{
// icon: <PlusSquareOutlined />,
key: '/unlimited',
label: (
<Link prefetch={false} href="/unlimited">
Без ограничений
</Link>
),
},
],
icon: <AppstoreOutlined />,
key: 'home',
label: 'Приложение',
},
{
children: [
{
// icon: <DatabaseOutlined />,
key: '/admin/cache',
label: (
<Link prefetch={false} href="/admin/cache">
Управление кэшем
</Link>
),
},
],
icon: <SettingOutlined />,
key: 'admin',
label: 'Панель управления',
},
];
export function AppMenu() {
const { pathname } = useRouter();
return (
<Background>
<Menu selectedKeys={[pathname]} mode="horizontal" items={items} />
</Background>
);
}

View File

@ -1,64 +0,0 @@
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

@ -2,7 +2,7 @@ import { min } from '@/styles/mq';
import styled from 'styled-components';
import { Box } from 'ui/grid';
export const Layout = styled(Box)`
export const Grid = styled(Box)`
display: flex;
flex-direction: column;
gap: 10px;
@ -17,4 +17,8 @@ export const Layout = styled(Box)`
grid-template-columns: 2fr 1fr 1.5fr;
/* margin: 8px 5%; */
}
${min('desktop-xl')} {
margin: 8px 10%;
}
`;

View File

@ -1,26 +1,11 @@
import Header from './Header';
import { AppMenu } from './Menu';
import { max, min } from '@/styles/mq';
import styled from 'styled-components';
import { Flex } from 'ui/grid';
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%;
}
`;
export default function Layout({ children, user }) {
export default function Layout({ children }) {
return (
<>
<Flex flexDirection="column">
<Header />
{user?.admin ? <AppMenu /> : false}
<Main>{children}</Main>
</>
<main>{children}</main>
</Flex>
);
}

View File

@ -7,7 +7,7 @@ import { observer } from 'mobx-react-lite';
import { Table } from 'ui/elements';
const PaymentsTable = observer(() => {
const { $process, $results } = useStore();
const { $results, $process } = useStore();
const unlimited = $process.has('Unlimited');
const dataSource = toJS($results.payments);
@ -27,8 +27,8 @@ const PaymentsTable = observer(() => {
showSizeChanger: false,
}}
scroll={{
x: dataColumns.length > 5 ? 1000 : undefined,
y: dataSource.length > 16 ? 630 : undefined,
x: dataColumns.length > 4 && 1000,
y: 630,
}}
/>
);

View File

@ -7,7 +7,6 @@ export const titles: Record<keyof ResultValues, string> = {
_resultContractEconomy: 'Экономика',
_resultContractEconomyWithVAT: 'Экономика, с НДС',
_resultPi: 'PI',
_resultPiRepayment: 'PI для досрочки',
_resultSumCredit: 'Сумма кредита',
_resultSumCreditPayment: 'Сумма платежей по кредиту',
_resultVatRecoverable: 'НДС к возмещению',
@ -47,7 +46,6 @@ export const formatters = {
_resultContractEconomy: moneyFormatter,
_resultContractEconomyWithVAT: moneyFormatter,
_resultPi: percentFormatter,
_resultPiRepayment: percentFormatter,
_resultSumCredit: moneyFormatter,
_resultSumCreditPayment: moneyFormatter,
_resultVatRecoverable: moneyFormatter,
@ -76,7 +74,6 @@ export const elements: Array<keyof ResultValues> = [
'_resultContractEconomy',
'_resultContractEconomyWithVAT',
'_resultPi',
'_resultPiRepayment',
'_resultSumCredit',
'_resultSumCreditPayment',
'_resultVatRecoverable',

View File

@ -22,7 +22,7 @@ const Wrapper = styled.div`
`;
const Results = observer(() => {
const { $process, $results } = useStore();
const { $results, $process } = useStore();
const resultsValues = toJS($results.values);
// eslint-disable-next-line no-negated-condition

View File

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

View File

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

View File

@ -2,21 +2,17 @@
# Make sure you update both files!
FROM node:alpine AS builder
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@1.12.4 dotenv-cli
RUN yarn global add turbo
COPY . .
RUN turbo prune --scope=web --docker
# Add lockfile and package.json's of isolated subworkspace
FROM node:alpine AS installer
RUN corepack enable && corepack prepare pnpm@latest --activate
ENV PNPM_HOME=/usr/local/bin
RUN apk add --no-cache libc6-compat
RUN apk update
WORKDIR /app
@ -24,9 +20,8 @@ WORKDIR /app
# First install the dependencies (as they change less often)
COPY .gitignore .gitignore
COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
COPY --from=builder /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml
RUN pnpm install
COPY --from=builder /app/out/yarn.lock ./yarn.lock
RUN yarn install
# Build the project
COPY --from=builder /app/out/full/ .
@ -34,8 +29,6 @@ COPY turbo.json turbo.json
ARG USE_DEV_COLORS
ARG BASE_PATH
ARG SENTRY_DSN
ARG SENTRY_AUTH_TOKEN
ARG SENTRY_ENVIRONMENT
ARG SENTRYCLI_CDNURL
ARG URL_GET_USER_DIRECT
ARG URL_CRM_GRAPHQL_DIRECT
@ -47,10 +40,7 @@ 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...
RUN yarn turbo run build --filter=web...
FROM node:alpine AS runner
WORKDIR /app
@ -69,4 +59,4 @@ COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/public ./apps/web/public
CMD node apps/web/server.js
CMD node apps/web/server.js

View File

@ -1,36 +1,30 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
- [Learn Next.js](https://nextjs.org/learn/foundations/about-nextjs) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_source=github.com&utm_medium=referral&utm_campaign=turborepo-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View File

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

View File

@ -1,42 +0,0 @@
import type { ResponseQueries } from './types';
import getUrls from '@/config/urls';
import { withHandleError } from '@/utils/axios';
import axios from 'axios';
const {
URL_CACHE_GET_QUERIES,
URL_CACHE_DELETE_QUERY,
URL_CACHE_RESET_QUERIES,
URL_CACHE_GET_QUERY,
} = getUrls();
export function getQueries({ signal }: { signal: AbortSignal }) {
return withHandleError(axios.get<ResponseQueries>(URL_CACHE_GET_QUERIES, { signal })).then(
({ data }) => data
);
}
export function deleteQuery(queryKey: string) {
return withHandleError(
axios.delete(URL_CACHE_DELETE_QUERY, {
params: {
queryKey,
},
})
).then(({ data }) => data);
}
export function reset() {
return withHandleError(axios.delete(URL_CACHE_RESET_QUERIES)).then(({ data }) => data);
}
export function getQueryValue(queryKey: string, { signal }: { signal: AbortSignal }) {
return withHandleError(
axios.get<object>(URL_CACHE_GET_QUERY, {
params: {
queryKey,
},
signal,
})
).then(({ data }) => data);
}

View File

@ -1,3 +0,0 @@
import type { QueryItem } from 'shared/types/cache';
export type ResponseQueries = Record<string, QueryItem>;

View File

@ -111,7 +111,6 @@ export const PreparedValuesSchema = z.object({
transTax: z.number(),
transportTaxGr: z.number(),
transportTaxGrYear: z.number(),
typeRepayment: z.number(),
});
export type PreparedValues = z.infer<typeof PreparedValuesSchema>;
@ -400,7 +399,6 @@ const ColumnsSchema = z.object({
values: z.number().array(),
}),
sumRepaymentColumn: z.object({
pi: z.number(),
values: z.number().array(),
}),
sumVATCreditColumn: z.object({

View File

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

View File

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

View File

@ -1,133 +0,0 @@
/* 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';
function isSovkom(account) {
return account.label.toLowerCase().includes('совком');
}
export function createLink(headers) {
const { URL_CRM_GRAPHQL } = getUrls();
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_equipment,
label: `${evo_equipment.label} (${evo_equipment.evo_start_production_year})`,
};
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;
});
}
}
return response;
});
});
const httpLink = new HttpLink({
uri: URL_CRM_GRAPHQL,
});
const authLink = setContext((_, { headers: existingHeaders }) => {
if (process.env.NODE_ENV === 'development') {
const { publicRuntimeConfig } = getConfig();
const { DEV_AUTH_TOKEN } = publicRuntimeConfigSchema.parse(publicRuntimeConfig);
if (DEV_AUTH_TOKEN)
return {
headers: {
...existingHeaders,
authorization: `Bearer ${DEV_AUTH_TOKEN}`,
},
};
}
if (isServer()) {
return {
headers: {
...existingHeaders,
authorization: headers?.authorization,
},
};
}
return {
headers: {
...existingHeaders,
},
};
});
const key = 'APOLLO_GRAPHQL';
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),
});
}
scope.setExtras({
graphQLErrors,
networkError,
operation,
response,
});
});
return from([authLink, errorLink, modifyDataLink, httpLink]);
}

45
apps/web/config/apollo.js Normal file
View File

@ -0,0 +1,45 @@
import getUrls from './urls';
import { ApolloLink, HttpLink } from '@apollo/client';
const { URL_CRM_GRAPHQL } = getUrls();
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((x) => ({
...x,
label: `${x.label} (${x.evo_graph_price} руб.)`,
}));
}
if (Object.keys(response?.data).includes('evo_equipments')) {
response.data.evo_equipments = response.data.evo_equipments.map((x) => ({
...x,
label: `${x.label} (${x.evo_start_production_year})`,
}));
}
if (operation.operationName === 'GetInsuranceCompanies') {
response.data.accounts = response.data.accounts.map((x) => {
const substring = x.label.match(/"(.+)"/u);
return {
...x,
label: substring ? substring[1].replaceAll('"', '').trim() : x.label,
};
});
}
}
return response;
});
});
const httpLink = new HttpLink({
uri: URL_CRM_GRAPHQL,
});
export const link = modifyDataLink.concat(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,10 +183,6 @@ export const selectLeaseObjectUseFor = alphabetical(
label: 'Строительство',
value: 100_000_019,
},
{
label: 'Перевозка опасных и легковоспламеняющихся грузов',
value: 100_000_020,
},
],
(objectUseFor) => objectUseFor.label.toLowerCase(),
'asc'
@ -511,7 +507,6 @@ const defaultOptions: CalculationOptions = {
cbxPartialVAT: [],
cbxFloatingRate: [],
cbxQuotePriceWithFullVAT: [],
cbxQuoteShowAcceptLimit: [],
};
export default defaultOptions;

View File

@ -18,7 +18,6 @@ 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: 4,
countSeats: 0,
creditRate: RATE,
dealer: null,
dealerBroker: null,
@ -144,7 +144,6 @@ const defaultValues: CalculationValues = {
partialVAT: false,
floatingRate: false,
quotePriceWithFullVAT: false,
quoteShowAcceptLimit: true,
};
export default defaultValues;

View File

@ -2,7 +2,6 @@ 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

@ -215,6 +215,7 @@ export const RequestEltOsagoSchema = z.object({
city: z.string(),
cityKladr: z.string(),
country: z.string(),
flat: z.string(),
house: z.string(),
region: z.string(),
resident: z.number(),
@ -230,6 +231,7 @@ export const RequestEltOsagoSchema = z.object({
city: z.string(),
cityKladr: z.string(),
country: z.string(),
flat: z.string(),
house: z.string(),
region: z.string(),
resident: z.number(),
@ -270,12 +272,10 @@ 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')]),
name: z.string(),
numCalc: z.string(),
numCalc: z.number(),
requestId: z.string(),
skCalcId: z.string(),
status: z.string().nullable(),

View File

@ -2,28 +2,19 @@ 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(),
SENTRY_ENVIRONMENT: z.string(),
URL_1C_TRANSTAX_DIRECT: z.string(),
URL_CACHE_DELETE_QUERY_DIRECT: z.string().default('http://api:3001/proxy/delete-query'),
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'),
URL_CORE_CALCULATE_DIRECT: z.string(),
URL_CORE_FINGAP_DIRECT: z.string(),
URL_CRM_CREATEKP_DIRECT: z.string(),
URL_CRM_DOWNLOADKP_BASE: z.string(),
URL_CRM_GRAPHQL_DIRECT: z.string(),
URL_CRM_GRAPHQL_PROXY: z.string().default('http://api:3001/proxy/graphql'),
URL_CRM_GRAPHQL_PROXY: z.string(),
URL_ELT_KASKO_DIRECT: z.string(),
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

@ -4,7 +4,6 @@ export const ResultValuesSchema = z.object({
_resultContractEconomy: z.number(),
_resultContractEconomyWithVAT: z.number(),
_resultPi: z.number(),
_resultPiRepayment: z.number(),
_resultSumCredit: z.number(),
_resultSumCreditPayment: z.number(),
_resultVatRecoverable: z.number(),

View File

@ -2,24 +2,15 @@ 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,
});
const serverRuntimeConfigSchema = envSchema.pick({
BASE_PATH: true,
DEV_AUTH_TOKEN: true,
PASSWORD_1C_TRANSTAX: true,
PORT: true,
SENTRY_DSN: true,
SENTRY_ENVIRONMENT: true,
URL_1C_TRANSTAX_DIRECT: true,
URL_CACHE_DELETE_QUERY_DIRECT: true,
URL_CACHE_GET_QUERIES_DIRECT: true,
URL_CACHE_GET_QUERY_DIRECT: true,
URL_CACHE_RESET_QUERIES_DIRECT: true,
URL_CORE_CALCULATE_DIRECT: true,
URL_CORE_FINGAP_DIRECT: true,
URL_CRM_CREATEKP_DIRECT: true,
@ -28,7 +19,6 @@ 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,7 +129,6 @@ const ValuesSchema = z.object({
withTrailer: z.boolean(),
partialVAT: z.boolean(),
floatingRate: z.boolean(),
quoteShowAcceptLimit: z.boolean(),
/**
* Link Values

View File

@ -22,10 +22,6 @@ function getUrls() {
URL_ELT_KASKO_DIRECT,
URL_ELT_OSAGO_DIRECT,
URL_CRM_GRAPHQL_PROXY,
URL_CACHE_GET_QUERIES_DIRECT,
URL_CACHE_DELETE_QUERY_DIRECT,
URL_CACHE_RESET_QUERIES_DIRECT,
URL_CACHE_GET_QUERY_DIRECT,
} = serverRuntimeConfigSchema.parse(serverRuntimeConfig);
return {
@ -33,10 +29,6 @@ function getUrls() {
PORT,
SENTRY_DSN,
URL_1C_TRANSTAX: URL_1C_TRANSTAX_DIRECT,
URL_CACHE_DELETE_QUERY: URL_CACHE_DELETE_QUERY_DIRECT,
URL_CACHE_GET_QUERIES: URL_CACHE_GET_QUERIES_DIRECT,
URL_CACHE_GET_QUERY: URL_CACHE_GET_QUERY_DIRECT,
URL_CACHE_RESET_QUERIES: URL_CACHE_RESET_QUERIES_DIRECT,
URL_CORE_CALCULATE: URL_CORE_CALCULATE_DIRECT,
URL_CORE_FINGAP: URL_CORE_FINGAP_DIRECT,
URL_CRM_CREATEKP: URL_CRM_CREATEKP_DIRECT,
@ -52,10 +44,6 @@ function getUrls() {
BASE_PATH,
SENTRY_DSN,
URL_1C_TRANSTAX: withBasePath(urls.URL_1C_TRANSTAX_PROXY),
URL_CACHE_DELETE_QUERY: withBasePath(urls.URL_CACHE_DELETE_QUERY_PROXY),
URL_CACHE_GET_QUERIES: withBasePath(urls.URL_CACHE_GET_QUERIES_PROXY),
URL_CACHE_GET_QUERY: withBasePath(urls.URL_CACHE_GET_QUERY_PROXY),
URL_CACHE_RESET_QUERIES: withBasePath(urls.URL_CACHE_RESET_QUERIES_PROXY),
URL_CORE_CALCULATE: withBasePath(urls.URL_CORE_CALCULATE_PROXY),
URL_CORE_FINGAP: withBasePath(urls.URL_CORE_FINGAP_PROXY),
URL_CRM_CREATEKP: withBasePath(urls.URL_CRM_CREATEKP_PROXY),

View File

@ -1,4 +1,3 @@
export const unlimitedRoles = ['Калькулятор без ограничений'];
export const defaultRoles = ['Лизинговый калькулятор', 'МПЛ', 'Управляющий подразделением'];
export const adminRoles = ['Калькулятор без ограничений', 'Системный администратор'];
export const usersSuper = ['akalinina', 'vchikalkin'];

View File

@ -1,3 +0,0 @@
export const PAGE_TITLE = 'Лизинговый калькулятор - Эволюция';
export const PAGE_DESCRIPTION =
'Лизинговый калькулятор - Эволюция - Расчет лизинговых платежей - Создание КП';

View File

@ -1,9 +1,5 @@
module.exports = {
URL_1C_TRANSTAX_PROXY: '/api/1c/transtax',
URL_CACHE_DELETE_QUERY_PROXY: '/api/admin/cache/delete',
URL_CACHE_GET_QUERIES_PROXY: '/api/admin/cache/get-queries',
URL_CACHE_GET_QUERY_PROXY: '/api/admin/cache/get-query',
URL_CACHE_RESET_QUERIES_PROXY: '/api/admin/cache/reset',
URL_CORE_CALCULATE_PROXY: '/api/core/calculate',
URL_CORE_FINGAP_PROXY: '/api/core/fingap',
URL_CRM_CREATEKP_PROXY: '/api/crm/create-kp',

View File

@ -12,5 +12,3 @@ 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

@ -1,34 +0,0 @@
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,33 +17,20 @@ query GetTransactionCurrency($currencyid: UUID!) {
}
query GetCurrencyChanges($currentDate: DateTime) {
evo_currencychanges(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_coursedate", eq: $currentDate } }
]
}
) {
evo_currencychanges(statecode: 0, evo_coursedate_param: { eq: $currentDate }) {
evo_currencychange
evo_ref_transactioncurrency
}
}
query GetLeads($domainname: String) {
systemusers(
filterConditionGroup: {
andFilterConditions: { filterConditionString: { fieldName: "domainname", eq: $domainname } }
}
) {
leads(orderby: { fieldName: "createdon", sortingType: DESC }) {
label: fullname
value: leadid
}
leads(owner_domainname: $domainname) {
label: fullname
value: leadid
}
}
query GetLead($leadid: UUID!) {
query GetLead($leadid: Uuid!) {
lead(leadid: $leadid) {
evo_agent_accountid
evo_double_agent_accountid
@ -61,11 +48,10 @@ query GetLead($leadid: UUID!) {
}
evo_okved
}
link
}
}
query GetOpportunity($opportunityid: UUID!) {
query GetOpportunity($opportunityid: Uuid!) {
opportunity(opportunityid: $opportunityid) {
evo_leadid
accountidData {
@ -75,33 +61,18 @@ query GetOpportunity($opportunityid: UUID!) {
}
evo_okved
}
link
}
}
query GetOpportunities($domainname: String) {
systemusers(
filterConditionGroup: {
andFilterConditions: { filterConditionString: { fieldName: "domainname", eq: $domainname } }
}
) {
opportunities(orderby: { fieldName: "createdon", sortingType: DESC }) {
label: name
value: opportunityid
}
opportunities(owner_domainname: $domainname) {
label: name
value: opportunityid
}
}
query GetQuotes($leadid: UUID!) {
quotes(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionGuid: { fieldName: "evo_leadid", eq: $leadid } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
orderby: { fieldName: "createdon", sortingType: DESC }
) {
query GetQuotes($leadid: Uuid!) {
quotes(evo_leadid: $leadid) {
label: evo_quotename
value: quoteid
evo_recalc_limit
@ -112,8 +83,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
@ -136,31 +107,11 @@ query GetQuote($quoteId: UUID!) {
evo_kasko_payer
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
@ -255,7 +206,7 @@ query GetQuoteData($quoteId: UUID!) {
evo_graphs {
createdon
evo_sumpay_withnds
evo_planpayments(orderby: { fieldName: "evo_plandate", sortingType: ASC }) {
evo_planpayments {
evo_payment_ratio
}
}
@ -308,26 +259,14 @@ query GetQuoteData($quoteId: UUID!) {
evo_supplier_currency_price
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(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
label: evo_name
value: evo_tarifid
@ -350,7 +289,7 @@ query GetTarifs($currentDate: DateTime) {
}
}
query GetTarif($tarifId: UUID!) {
query GetTarif($tarifId: Uuid!) {
evo_tarif(evo_tarifid: $tarifId) {
label: evo_name
value: evo_tarifid
@ -364,8 +303,6 @@ query GetTarif($tarifId: UUID!) {
evo_rates {
evo_datefrom
evo_rateid
evo_type
statecode
}
evo_irr_plan
evo_margin_min
@ -374,13 +311,9 @@ query GetTarif($tarifId: UUID!) {
query GetRates($currentDate: DateTime) {
evo_rates(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
label: evo_name
value: evo_rateid
@ -392,7 +325,7 @@ query GetRates($currentDate: DateTime) {
}
}
query GetRate($rateId: UUID!) {
query GetRate($rateId: Uuid!) {
evo_rate(evo_rateid: $rateId) {
evo_base_rate
evo_credit_period
@ -403,14 +336,10 @@ query GetRate($rateId: UUID!) {
query GetProducts($currentDate: DateTime) {
evo_baseproducts(
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] } }
]
}
statecode: 0
evo_relation: [100000000]
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
label: evo_name
value: evo_baseproductid
@ -421,7 +350,7 @@ query GetProducts($currentDate: DateTime) {
}
}
query GetProduct($productId: UUID!) {
query GetProduct($productId: Uuid!) {
evo_baseproduct(evo_baseproductid: $productId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -447,13 +376,9 @@ query GetProduct($productId: UUID!) {
query GetSubsidies($currentDate: DateTime) {
evo_subsidies(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
label: evo_name
value: evo_subsidyid
@ -461,7 +386,7 @@ query GetSubsidies($currentDate: DateTime) {
}
}
query GetSubsidy($subsidyId: UUID!) {
query GetSubsidy($subsidyId: Uuid!) {
evo_subsidy(evo_subsidyid: $subsidyId) {
evo_leasingobject_types {
evo_leasingobject_typeid
@ -483,7 +408,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
@ -501,7 +426,7 @@ query GetImportProgram($importProgramId: UUID!) {
}
query GetRegions {
evo_regions(orderby: { fieldName: "evo_name", sortingType: ASC }) {
evo_regions {
label: evo_name
value: evo_regionid
evo_fias_id
@ -509,7 +434,7 @@ query GetRegions {
}
}
query GetRegion($regionId: UUID!) {
query GetRegion($regionId: Uuid!) {
evo_region(evo_regionid: $regionId) {
evo_oktmo
accounts {
@ -519,16 +444,8 @@ query GetRegion($regionId: UUID!) {
}
}
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 }
) {
query GetTowns($regionId: Uuid!) {
evo_towns(evo_regionid: $regionId) {
evo_fias_id
label: evo_name
value: evo_townid
@ -536,33 +453,22 @@ 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(
filterConditionGroup: {
andFilterConditions: { filterConditionInt: { fieldName: "statecode", eq: 0 } }
}
) {
evo_gps_brands(statecode: 0) {
label: evo_name
value: evo_gps_brandid
evo_id
}
}
query GetGPSModels($gpsBrandId: UUID!) {
evo_gps_models(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionGuid: { fieldName: "evo_gps_brandid", eq: $gpsBrandId } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
) {
query GetGPSModels($gpsBrandId: Uuid!) {
evo_gps_models(evo_gps_brandid: $gpsBrandId) {
label: evo_name
value: evo_gps_modelid
evo_id
@ -570,18 +476,14 @@ query GetGPSModels($gpsBrandId: UUID!) {
}
query GetLeaseObjectTypes {
evo_leasingobject_types(
filterConditionGroup: {
andFilterConditions: { filterConditionInt: { fieldName: "statecode", eq: 0 } }
}
) {
evo_leasingobject_types(statecode: 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
@ -592,21 +494,11 @@ query GetLeaseObjectType($leaseObjectTypeId: UUID!) {
evo_expluatation_period2
evo_depreciation_rate1
evo_depreciation_rate2
evo_trailer
evo_vehicle_body_type_option
evo_vehicle_body_types {
evo_vehicle_body_typeid
}
}
}
query GetBrands {
evo_brands(
filterConditionGroup: {
andFilterConditions: { filterConditionInt: { fieldName: "statecode", eq: 0 } }
}
orderby: { fieldName: "evo_name", sortingType: ASC }
) {
evo_brands(statecode: 0) {
label: evo_name
value: evo_brandid
evo_brandid
@ -614,7 +506,7 @@ query GetBrands {
}
}
query GetBrand($brandId: UUID!) {
query GetBrand($brandId: Uuid!) {
evo_brand(evo_brandid: $brandId) {
evo_id
evo_importer_reward_perc
@ -624,26 +516,16 @@ query GetBrand($brandId: UUID!) {
}
}
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 }
) {
query GetModels($brandId: Uuid!) {
evo_models(statecode: 0, evo_brandid: $brandId) {
label: evo_name
value: evo_modelid
evo_modelid
evo_vehicle_type
evo_trailer_sign
evo_vehicle_body_typeid
}
}
query GetModel($modelId: UUID!) {
query GetModel($modelId: Uuid!) {
evo_model(evo_modelid: $modelId) {
evo_impairment_groupidData {
evo_name
@ -655,27 +537,18 @@ query GetModel($modelId: UUID!) {
evo_id_elt
}
evo_running_gear
evo_trailer_sign
evo_vehicle_body_typeid
}
}
query GetConfigurations($modelId: UUID!) {
evo_equipments(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionGuid: { fieldName: "evo_modelid", eq: $modelId } }
]
}
) {
query GetConfigurations($modelId: Uuid!) {
evo_equipments(statecode: 0, evo_modelid: $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
@ -684,7 +557,7 @@ query GetConfiguration($configurationId: UUID!) {
}
query GetDealers {
dealers {
dealers: accounts(evo_account_type: [100000001], statecode: 0, evo_legal_form: 100000001) {
label: name
value: accountid
accountid
@ -692,16 +565,16 @@ query GetDealers {
}
}
query GetDealer($dealerId: UUID!) {
dealer(accountid: $dealerId) {
query GetDealer($dealerId: Uuid!) {
dealer: account(accountid: $dealerId) {
evo_return_leasing_dealer
evo_broker_accountid
evo_supplier_financing_accept
}
}
query GetDealerPersons($dealerId: UUID!) {
dealerPersons: dealer_persons(salonaccountid: $dealerId) {
query GetDealerPersons($dealerId: Uuid!) {
dealerPersons: salon_providers(statecode: 0, salonaccountid: $dealerId) {
label: name
value: accountid
accountid
@ -711,46 +584,27 @@ query GetDealerPersons($dealerId: UUID!) {
}
}
query GetDealerPerson($dealerPersonId: UUID!) {
dealer_person(accountid: $dealerPersonId) {
query GetDealerPerson($dealerPersonId: Uuid!) {
account(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(accountid: $agentid) {
query GetAgent($agentid: Uuid!) {
agent: account(accountid: $agentid) {
label: name
value: accountid
evo_inn
}
}
query GetRewardConditions($agentid: UUID!, $currentDate: DateTime) {
query GetRewardConditions($agentid: Uuid!, $currentDate: DateTime) {
evo_reward_conditions(
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 } }
]
}
]
}
evo_agent_accountid: $agentid
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
statecode: 0
evo_agency_agreementid_param: { has: true }
) {
label: evo_name
value: evo_reward_conditionid
@ -759,7 +613,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
@ -774,27 +628,16 @@ query GetRewardCondition($conditionId: UUID!) {
}
query GetSotCoefficientType($evo_id: String) {
evo_sot_coefficient_types(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionString: { fieldName: "evo_id", eq: $evo_id } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
) {
evo_sot_coefficient_type(evo_id: $evo_id) {
evo_sot_coefficient_typeid
}
}
query GetCoefficients($currentDate: DateTime) {
evo_coefficients(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
evo_job_titleid
evo_sot_coefficient_typeid
@ -820,11 +663,7 @@ query GetCoefficients($currentDate: DateTime) {
}
query GetSystemUser($domainname: String) {
systemusers(
filterConditionGroup: {
filterCondition: { filterConditionString: { fieldName: "domainname", eq: $domainname } }
}
) {
systemuser(domainname: $domainname) {
evo_job_titleid
businessunitid
roles {
@ -842,13 +681,9 @@ fragment CoreAddProductTypesFields on evo_addproduct_type {
query GetAddproductTypes($currentDate: DateTime) {
evo_addproduct_types(
filterConditionGroup: {
andFilterConditions: [
{ filterConditionInt: { fieldName: "statecode", eq: 0 } }
{ filterConditionDateTime: { fieldName: "evo_datefrom", lte: $currentDate } }
{ filterConditionDateTime: { fieldName: "evo_dateto", gte: $currentDate } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
...CoreAddProductTypesFields
evo_product_type
@ -862,7 +697,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
@ -886,14 +721,10 @@ query GetAddProductType($addproductTypeId: UUID!) {
query GetRegistrationTypes($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000001
) {
...CoreAddProductTypesFields
evo_leasingobject_types {
@ -909,14 +740,10 @@ query GetRegistrationTypes($currentDate: DateTime) {
query GetTechnicalCards($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000000
) {
...CoreAddProductTypesFields
evo_min_period
@ -930,14 +757,10 @@ query GetTechnicalCards($currentDate: DateTime) {
query GetFuelCards($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000005
) {
...CoreAddProductTypesFields
evo_min_period
@ -950,14 +773,10 @@ query GetFuelCards($currentDate: DateTime) {
query GetTelematicTypes($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000004
) {
...CoreAddProductTypesFields
evo_controls_program
@ -967,14 +786,10 @@ query GetTelematicTypes($currentDate: DateTime) {
query GetTrackerTypes($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000003
) {
...CoreAddProductTypesFields
evo_controls_program
@ -984,14 +799,10 @@ query GetTrackerTypes($currentDate: DateTime) {
query GetInsNSIBTypes($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
evo_product_type: 100000002
) {
...CoreAddProductTypesFields
evo_max_period
@ -1009,14 +820,10 @@ query GetInsNSIBTypes($currentDate: DateTime) {
query GetLeasingWithoutKaskoTypes($currentDate: DateTime) {
evo_addproduct_types(
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 } }
]
}
statecode: 0
evo_product_type: 100000007
evo_datefrom_param: { lte: $currentDate }
evo_dateto_param: { gte: $currentDate }
) {
...CoreAddProductTypesFields
evo_product_type
@ -1036,45 +843,16 @@ query GetLeasingWithoutKaskoTypes($currentDate: DateTime) {
}
}
query GetOsagoAddproductTypes($currentDate: DateTime) {
evo_addproduct_types(
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
evo_accountid
createdon
evo_category
evo_min_power
evo_max_power
evo_min_seats_count
evo_max_seats_count
evo_min_mass
evo_max_mass
evo_graph_price_withoutnds
evo_id
}
}
query GetInsuranceCompany($accountId: UUID!) {
account: insurance(accountid: $accountId) {
query GetInsuranceCompany($accountId: Uuid!) {
account(accountid: $accountId) {
evo_osago_with_kasko
evo_legal_region_calc
accountid
evo_kasko_fact_part
evo_kasko_plan_part
}
}
query GetInsuranceCompanies {
accounts: insurances {
accounts(evo_account_type: [100000002], statecode: 0) {
evo_type_ins_policy
evo_evokasko_access
evo_inn
@ -1083,74 +861,11 @@ query GetInsuranceCompanies {
evo_id_elt_osago
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(
filterConditionGroup: {
andFilterConditions: { filterConditionString: { fieldName: "name", eq: $roleName } }
}
) {
roles(name: $roleName) {
systemusers {
label: fullname
value: domainname

File diff suppressed because it is too large Load Diff

View File

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

@ -1 +0,0 @@
export * from './loading';

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