Compare commits
136 Commits
experiment
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c25ba30d0 | ||
|
|
ba36eb502b | ||
|
|
2c9a2bd30c | ||
|
|
f35acee64b | ||
|
|
a4c02a747f | ||
|
|
66b1e2cdcb | ||
|
|
81eca1c6e0 | ||
|
|
89f2b3b68c | ||
|
|
549bd901da | ||
|
|
6aad2d3aa2 | ||
|
|
09959e3ac3 | ||
|
|
7014462d42 | ||
|
|
62417b88ba | ||
|
|
bf0b5c9907 | ||
|
|
5347c3ef6c | ||
|
|
194292c083 | ||
|
|
7d023dba1e | ||
|
|
9c63cadf29 | ||
|
|
88b7501b4d | ||
|
|
8f53187a3c | ||
|
|
ef8059b3b1 | ||
|
|
8627233a17 | ||
|
|
2ece25dcb6 | ||
|
|
0eccd799c7 | ||
|
|
2e8c333374 | ||
|
|
671b25a087 | ||
|
|
4a314326fb | ||
|
|
d0270a3c9e | ||
|
|
71fc44e7a6 | ||
|
|
d6f5c73b9d | ||
|
|
d7908bb5da | ||
|
|
ed5391076c | ||
|
|
4a190e962a | ||
|
|
4644dbb404 | ||
|
|
5c6b419452 | ||
|
|
048d132da2 | ||
|
|
dd154a3004 | ||
|
|
8dbcf4bb7f | ||
|
|
c0f825a587 | ||
|
|
2b3dd5e7b9 | ||
|
|
5d1aa99d75 | ||
|
|
4be47fced5 | ||
|
|
66fc8ee70e | ||
|
|
09fc6956d8 | ||
|
|
501ed13f8a | ||
|
|
61132928b5 | ||
|
|
21b009c833 | ||
|
|
c616b981f1 | ||
|
|
93d16cf35c | ||
|
|
bd7cf3284b | ||
|
|
a0e6c4ff2f | ||
|
|
88fbb616b5 | ||
|
|
7efea2acc9 | ||
|
|
907f288815 | ||
|
|
2fea400060 | ||
|
|
f695835c61 | ||
|
|
47d47a0bfd | ||
|
|
540d5642a1 | ||
|
|
2ec2a14706 | ||
|
|
f7110497d3 | ||
|
|
c9326697f6 | ||
|
|
c2982cf31b | ||
|
|
8c69b3b9c4 | ||
|
|
24987be78e | ||
|
|
defc625324 | ||
|
|
eee91d5f2d | ||
|
|
a65202c653 | ||
|
|
ffaad142e8 | ||
|
|
9e40e5141c | ||
|
|
79e707a232 | ||
|
|
d374208097 | ||
|
|
557053caa6 | ||
|
|
e258873976 | ||
|
|
59e45ddc63 | ||
|
|
eaf95c6007 | ||
|
|
f3518244ab | ||
|
|
c5683f7edd | ||
|
|
acdacbf18e | ||
|
|
ef88c12e74 | ||
|
|
ab0d455afb | ||
|
|
e0d2836f4a | ||
|
|
4bc5234d09 | ||
|
|
6041082fec | ||
|
|
f426ca7f23 | ||
|
|
5115551b0e | ||
|
|
5ce9484e43 | ||
|
|
8a117e250c | ||
|
|
8089f62c31 | ||
|
|
bd775babf9 | ||
|
|
e222a3093a | ||
|
|
53debf2cff | ||
|
|
c092b8f47c | ||
|
|
6b7c679a0d | ||
|
|
7a00478727 | ||
|
|
677ab1d75b | ||
|
|
126302a10a | ||
|
|
35ce71c149 | ||
|
|
47b57c0c73 | ||
|
|
46c0b305b6 | ||
|
|
eb6f0ef949 | ||
|
|
7ca4e41980 | ||
|
|
662b04be0f | ||
|
|
e2d37712ad | ||
|
|
4c3d305e7f | ||
|
|
1aaa84e31d | ||
|
|
5a290d5be9 | ||
|
|
ac14a86c33 | ||
|
|
175cb63515 | ||
|
|
803b4a1cfb | ||
|
|
709eda1b50 | ||
|
|
bdc6d032aa | ||
|
|
3462395818 | ||
|
|
9308417c4d | ||
|
|
d0f11cbc63 | ||
|
|
eb1eb44769 | ||
|
|
6c300c8688 | ||
|
|
3898fc1bdf | ||
|
|
0c0dc7de53 | ||
|
|
703cee467c | ||
|
|
c154568bb4 | ||
|
|
8dd9627849 | ||
|
|
07c87d583f | ||
|
|
0ff6ba3f74 | ||
|
|
ae0b72aebd | ||
|
|
10f3760c63 | ||
|
|
db29a77d37 | ||
|
|
0936d1cdd7 | ||
|
|
5c039597b3 | ||
|
|
17a9810878 | ||
|
|
438242ac31 | ||
|
|
78064edf81 | ||
|
|
565cabb9bd | ||
|
|
903b32084a | ||
|
|
0f61d4a399 | ||
|
|
7df69f92e8 | ||
|
|
58d7a05591 |
@ -1,3 +0,0 @@
|
||||
.git
|
||||
README.md
|
||||
node_modules
|
||||
14
.env
14
.env
@ -1,14 +0,0 @@
|
||||
####### COMMON #######
|
||||
USE_DEV_COLORS=
|
||||
BASE_PATH=
|
||||
|
||||
####### URLS ########
|
||||
URL_GET_USER_DIRECT=
|
||||
URL_CRM_GRAPHQL_DIRECT=
|
||||
URL_CRM_CREATEKP_DIRECT=
|
||||
URL_CRM_DOWNLOADKP_BASE=
|
||||
URL_CORE_FINGAP_DIRECT=
|
||||
URL_CORE_CALCULATE_DIRECT=
|
||||
URL_1C_TRANSTAX_DIRECT=
|
||||
URL_ELT_OSAGO_DIRECT=
|
||||
URL_ELT_KASKO_DIRECT=
|
||||
@ -8,6 +8,5 @@ coverage
|
||||
.eslintrc.js
|
||||
**/*.config.js
|
||||
**/scripts
|
||||
packages/eslint-config-custom/*
|
||||
**/package.json
|
||||
turbo.json
|
||||
@ -1,10 +1,8 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
// This tells ESLint to load the config from the package `eslint-config-custom`
|
||||
extends: ['custom', 'custom/rules'],
|
||||
settings: {
|
||||
next: {
|
||||
rootDir: ['packages/web/'],
|
||||
rootDir: ['apps/*/'],
|
||||
},
|
||||
react: {
|
||||
version: 'detect',
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -68,3 +68,5 @@ yarn-error.log*
|
||||
.turbo
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/turbo
|
||||
|
||||
.pnpm
|
||||
6
.vscode/settings.json
vendored
6
.vscode/settings.json
vendored
@ -13,9 +13,9 @@
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"editor.formatOnSave": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll": true,
|
||||
"source.fixAll.eslint": true,
|
||||
"source.removeUnusedImports": true
|
||||
"source.fixAll": "explicit",
|
||||
"source.fixAll.eslint": "explicit",
|
||||
"source.removeUnusedImports": "explicit"
|
||||
},
|
||||
"workbench.editor.labelFormat": "short",
|
||||
"eslint.workingDirectories": [{ "directory": "apps/web", "changeProcessCWD": true }],
|
||||
|
||||
104
README.md
104
README.md
@ -1,59 +1,28 @@
|
||||
# Turborepo Docker starter
|
||||
# Turborepo starter
|
||||
|
||||
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/).
|
||||
This is an official starter Turborepo.
|
||||
|
||||
## Using this example
|
||||
|
||||
Run the following command:
|
||||
|
||||
```sh
|
||||
npx degit vercel/turbo/examples/with-docker with-docker
|
||||
cd with-docker
|
||||
yarn install
|
||||
git init . && git add . && git commit -m "Init"
|
||||
npx create-turbo@latest
|
||||
```
|
||||
|
||||
### Docker
|
||||
## What's inside?
|
||||
|
||||
This repo is configured to be built with Docker, and Docker compose. To build all apps in this repo:
|
||||
This Turborepo includes the following packages/apps:
|
||||
|
||||
```
|
||||
# Create a network, which allows containers to communicate
|
||||
# with each other, by using their container name as a hostname
|
||||
docker network create app_network
|
||||
### Apps and Packages
|
||||
|
||||
# Build prod using new BuildKit engine
|
||||
COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose -f docker-compose.yml build --parallel
|
||||
- `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
|
||||
|
||||
# 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)
|
||||
```
|
||||
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
|
||||
|
||||
### Utilities
|
||||
|
||||
@ -61,5 +30,52 @@ 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)
|
||||
|
||||
7
apps/api/.dockerignore
Normal file
7
apps/api/.dockerignore
Normal file
@ -0,0 +1,7 @@
|
||||
.git
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
node_modules
|
||||
*.log
|
||||
dist
|
||||
README.md
|
||||
13
apps/api/.eslintrc.js
Normal file
13
apps/api/.eslintrc.js
Normal file
@ -0,0 +1,13 @@
|
||||
const { createConfig } = require('@vchikalkin/eslint-config-awesome');
|
||||
|
||||
module.exports = createConfig('typescript', {
|
||||
parserOptions: {
|
||||
project: './tsconfig.json',
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
ignorePatterns: ['*.config.js', '.eslintrc.js'],
|
||||
rules: {
|
||||
'import/no-duplicates': 'off',
|
||||
'import/consistent-type-specifier-style': 'off',
|
||||
},
|
||||
});
|
||||
56
apps/api/.gitignore
vendored
Normal file
56
apps/api/.gitignore
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
4
apps/api/.prettierrc
Normal file
4
apps/api/.prettierrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
45
apps/api/Dockerfile
Normal file
45
apps/api/Dockerfile
Normal file
@ -0,0 +1,45 @@
|
||||
# This Dockerfile is copy-pasted into our main docs at /docs/handbook/deploying-with-docker.
|
||||
# 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
|
||||
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
|
||||
|
||||
# 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
|
||||
|
||||
# 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...
|
||||
|
||||
FROM node:alpine AS runner
|
||||
WORKDIR /app
|
||||
|
||||
# Don't run production as root
|
||||
RUN addgroup --system --gid 1001 nestjs
|
||||
RUN adduser --system --uid 1001 nestjs
|
||||
USER nestjs
|
||||
COPY --from=installer /app .
|
||||
|
||||
CMD node apps/api/dist/main.js
|
||||
73
apps/api/README.md
Normal file
73
apps/api/README.md
Normal file
@ -0,0 +1,73 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ pnpm install
|
||||
```
|
||||
|
||||
## Running the app
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ pnpm run start
|
||||
|
||||
# watch mode
|
||||
$ pnpm run start:dev
|
||||
|
||||
# production mode
|
||||
$ pnpm run start:prod
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ pnpm run test
|
||||
|
||||
# e2e tests
|
||||
$ pnpm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ pnpm run test:cov
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](LICENSE).
|
||||
8
apps/api/nest-cli.json
Normal file
8
apps/api/nest-cli.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
74
apps/api/package.json
Normal file
74
apps/api/package.json
Normal file
@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "api",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/cache-manager": "^2.2.1",
|
||||
"@nestjs/common": "^10.0.0",
|
||||
"@nestjs/config": "^3.2.0",
|
||||
"@nestjs/core": "^10.0.0",
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/platform-fastify": "^10.3.3",
|
||||
"cache-manager": "^5.4.0",
|
||||
"cache-manager-ioredis": "^2.1.0",
|
||||
"ioredis": "^5.3.2",
|
||||
"reflect-metadata": "^0.2.0",
|
||||
"rxjs": "^7.8.1",
|
||||
"zod": "^3.22.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.0.0",
|
||||
"@nestjs/schematics": "^10.0.0",
|
||||
"@nestjs/testing": "^10.0.0",
|
||||
"@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",
|
||||
"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-loader": "^9.4.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
16
apps/api/src/app.module.ts
Normal file
16
apps/api/src/app.module.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { ProxyModule } from './proxy/proxy.module';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
}),
|
||||
ProxyModule,
|
||||
],
|
||||
providers: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
|
||||
export class AppModule {}
|
||||
3
apps/api/src/config/constants.ts
Normal file
3
apps/api/src/config/constants.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import { seconds } from 'src/utils/time';
|
||||
|
||||
export const DEFAULT_CACHE_TTL = seconds().fromMinutes(15);
|
||||
3
apps/api/src/config/env.ts
Normal file
3
apps/api/src/config/env.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import envSchema from './schema/env';
|
||||
|
||||
export const env = envSchema.parse(process.env);
|
||||
21
apps/api/src/config/schema/env.ts
Normal file
21
apps/api/src/config/schema/env.ts
Normal file
@ -0,0 +1,21 @@
|
||||
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'),
|
||||
REDIS_HOST: z.string(),
|
||||
REDIS_PORT: z
|
||||
.string()
|
||||
.transform((val) => Number.parseInt(val, 10))
|
||||
.default('6379'),
|
||||
URL_CRM_GRAPHQL_DIRECT: z.string(),
|
||||
});
|
||||
|
||||
export default envSchema;
|
||||
15
apps/api/src/main.ts
Normal file
15
apps/api/src/main.ts
Normal file
@ -0,0 +1,15 @@
|
||||
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';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
|
||||
await app.listen(env.PORT, '0.0.0.0');
|
||||
}
|
||||
bootstrap();
|
||||
64
apps/api/src/proxy/lib/config.ts
Normal file
64
apps/api/src/proxy/lib/config.ts
Normal file
@ -0,0 +1,64 @@
|
||||
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),
|
||||
};
|
||||
127
apps/api/src/proxy/proxy.controller.ts
Normal file
127
apps/api/src/proxy/proxy.controller.ts
Normal file
@ -0,0 +1,127 @@
|
||||
import { queryTTL } from './lib/config';
|
||||
import type { GQLRequest, GQLResponse } 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 { 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,
|
||||
) {}
|
||||
|
||||
@All('/graphql')
|
||||
public async graphql(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
|
||||
const { operationName, query, variables } = req.body as GQLRequest;
|
||||
|
||||
const key = `${operationName} ${JSON.stringify(variables)}`;
|
||||
const cached = await this.cacheManager.get(key);
|
||||
|
||||
if (cached) return reply.send(cached);
|
||||
|
||||
const response = await fetch(env.URL_CRM_GRAPHQL_DIRECT, {
|
||||
body: JSON.stringify({ operationName, query, variables }),
|
||||
headers: {
|
||||
Authorization: req.headers.authorization,
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: req.headers.cookie,
|
||||
},
|
||||
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 });
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
20
apps/api/src/proxy/proxy.module.ts
Normal file
20
apps/api/src/proxy/proxy.module.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { ProxyController } from './proxy.controller';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { Module } from '@nestjs/common';
|
||||
import * as redisStore from 'cache-manager-ioredis';
|
||||
import type { RedisOptions } from 'ioredis';
|
||||
import { env } from 'src/config/env';
|
||||
|
||||
@Module({
|
||||
controllers: [ProxyController],
|
||||
imports: [
|
||||
CacheModule.register<RedisOptions>({
|
||||
host: env.REDIS_HOST,
|
||||
port: env.REDIS_PORT,
|
||||
store: redisStore,
|
||||
ttl: env.CACHE_TTL,
|
||||
}),
|
||||
],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
|
||||
export class ProxyModule {}
|
||||
11
apps/api/src/proxy/types.ts
Normal file
11
apps/api/src/proxy/types.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export type GQLRequest = {
|
||||
operationName: string;
|
||||
query: string;
|
||||
variables: string;
|
||||
};
|
||||
|
||||
export type GQLResponse = {
|
||||
data: unknown;
|
||||
error?: unknown;
|
||||
errors?: unknown[];
|
||||
};
|
||||
13
apps/api/src/utils/time.ts
Normal file
13
apps/api/src/utils/time.ts
Normal file
@ -0,0 +1,13 @@
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
4
apps/api/tsconfig.build.json
Normal file
4
apps/api/tsconfig.build.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
22
apps/api/tsconfig.json
Normal file
22
apps/api/tsconfig.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false
|
||||
},
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
8
apps/web/.dockerignore
Normal file
8
apps/web/.dockerignore
Normal file
@ -0,0 +1,8 @@
|
||||
.git
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
node_modules
|
||||
*.log
|
||||
dist
|
||||
.next
|
||||
README.md
|
||||
@ -1,8 +1,14 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ['custom', 'custom/rules'],
|
||||
const { createConfig } = require('@vchikalkin/eslint-config-awesome');
|
||||
|
||||
module.exports = createConfig('next-typescript', {
|
||||
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'],
|
||||
});
|
||||
|
||||
4
apps/web/.gitignore
vendored
Normal file
4
apps/web/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
|
||||
# Sentry Config File
|
||||
.sentryclirc
|
||||
/styles/antd.min.css
|
||||
@ -1,6 +1,6 @@
|
||||
overwrite: true
|
||||
schema: './graphql/crm.schema.graphql'
|
||||
documents: '**/*.{graphql,js,ts,jsx,tsx}'
|
||||
documents: [./**/!(*.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'
|
||||
|
||||
19
apps/web/@types/errors.ts
Normal file
19
apps/web/@types/errors.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import elementsToValues from '@/Components/Calculation/config/map/values';
|
||||
|
||||
export const ERR_ELT_KASKO = 'ERR_ELT_KASKO';
|
||||
export const ERR_ELT_OSAGO = 'ERR_ELT_OSAGO';
|
||||
export const ERR_FINGAP_TABLE = 'ERR_FINGAP_TABLE';
|
||||
export const ERR_INSURANCE_TABLE = 'ERR_INSURANCE_TABLE';
|
||||
export const ERR_PAYMENTS_TABLE = 'ERR_PAYMENTS_TABLE';
|
||||
|
||||
export const ERROR_TABLE_KEYS = [
|
||||
ERR_ELT_KASKO,
|
||||
ERR_ELT_OSAGO,
|
||||
ERR_FINGAP_TABLE,
|
||||
ERR_INSURANCE_TABLE,
|
||||
ERR_PAYMENTS_TABLE,
|
||||
];
|
||||
|
||||
export const ERROR_ELEMENTS_KEYS = Object.keys(elementsToValues);
|
||||
|
||||
export const ERROR_KEYS = [...ERROR_ELEMENTS_KEYS, ...ERROR_TABLE_KEYS];
|
||||
77
apps/web/Components/Admin/Cache/Query.tsx
Normal file
77
apps/web/Components/Admin/Cache/Query.tsx
Normal file
@ -0,0 +1,77 @@
|
||||
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();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
});
|
||||
22
apps/web/Components/Admin/Cache/QueryList.tsx
Normal file
22
apps/web/Components/Admin/Cache/QueryList.tsx
Normal file
@ -0,0 +1,22 @@
|
||||
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)} />
|
||||
));
|
||||
};
|
||||
24
apps/web/Components/Admin/Cache/ReloadButton.tsx
Normal file
24
apps/web/Components/Admin/Cache/ReloadButton.tsx
Normal file
@ -0,0 +1,24 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
70
apps/web/Components/Admin/Cache/index.tsx
Normal file
70
apps/web/Components/Admin/Cache/index.tsx
Normal file
@ -0,0 +1,70 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
30
apps/web/Components/Admin/Cache/lib/hooks.tsx
Normal file
30
apps/web/Components/Admin/Cache/lib/hooks.tsx
Normal file
@ -0,0 +1,30 @@
|
||||
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 };
|
||||
}
|
||||
23
apps/web/Components/Admin/Cache/lib/utils.tsx
Normal file
23
apps/web/Components/Admin/Cache/lib/utils.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
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;
|
||||
}
|
||||
17
apps/web/Components/Admin/Layout.tsx
Normal file
17
apps/web/Components/Admin/Layout.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
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>;
|
||||
}
|
||||
2
apps/web/Components/Admin/index.ts
Normal file
2
apps/web/Components/Admin/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './Cache';
|
||||
export * from './Layout';
|
||||
@ -7,7 +7,7 @@ export const rows: FormTabRows = [
|
||||
{
|
||||
title: 'Регистрация',
|
||||
},
|
||||
[['radioObjectRegistration', 'radioTypePTS'], { gridTemplateColumns: ['1fr 1fr'] }],
|
||||
[['radioObjectRegistration', 'radioTypePTS'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
|
||||
[['selectRegionRegistration', 'selectTownRegistration', 'selectObjectRegionRegistration']],
|
||||
[['selectObjectCategoryTax', 'selectObjectTypeTax', 'tbxVehicleTaxInYear']],
|
||||
[['tbxLeaseObjectYear', 'tbxLeaseObjectMotorPower', 'tbxVehicleTaxInLeasingPeriod']],
|
||||
|
||||
@ -4,8 +4,14 @@ export const id = 'create-kp';
|
||||
export const title = 'Создание КП';
|
||||
|
||||
export const rows: FormTabRows = [
|
||||
[['cbxPriceWithDiscount', 'cbxFullPriceWithDiscount', 'cbxCostIncrease']],
|
||||
[['cbxInsurance', 'cbxRegistrationQuote', 'cbxTechnicalCardQuote']],
|
||||
[['cbxNSIB', 'cbxQuoteRedemptionGraph', 'cbxShowFinGAP']],
|
||||
[
|
||||
['cbxPriceWithDiscount', 'cbxFullPriceWithDiscount'],
|
||||
{ gridTemplateColumns: ['1fr', '1fr 1fr'] },
|
||||
],
|
||||
[['cbxQuotePriceWithFullVAT', 'cbxCostIncrease'], { gridTemplateColumns: ['1fr', '1fr 1fr'] }],
|
||||
[['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'] }],
|
||||
];
|
||||
|
||||
@ -7,16 +7,16 @@ import { Table } from 'ui/elements';
|
||||
|
||||
export const PolicyTable = observer(
|
||||
({
|
||||
storeSelector,
|
||||
onSelectRow,
|
||||
storeSelector,
|
||||
...props
|
||||
}: {
|
||||
columns: typeof columns;
|
||||
onSelectRow: (row: Row) => void;
|
||||
storeSelector: StoreSelector;
|
||||
}) => {
|
||||
const { $tables, $process } = useStore();
|
||||
const { getRows, setSelectedKey, getSelectedRow } = storeSelector($tables.elt);
|
||||
const { $process, $tables } = useStore();
|
||||
const { getRows, getSelectedRow, setSelectedKey } = storeSelector($tables.elt);
|
||||
|
||||
return (
|
||||
<Table
|
||||
@ -37,7 +37,12 @@ export const PolicyTable = observer(
|
||||
$process.add('ELT');
|
||||
setSelectedKey(record.key);
|
||||
onSelectRow(record);
|
||||
message.success({ content: 'Выбранный расчет ЭЛТ применен', key: record.key });
|
||||
message.success({
|
||||
content: 'Выбранный расчет ЭЛТ применен',
|
||||
duration: 1,
|
||||
key: record.key,
|
||||
onClick: () => message.destroy(record.key),
|
||||
});
|
||||
$process.delete('ELT');
|
||||
}
|
||||
},
|
||||
|
||||
@ -7,7 +7,7 @@ import { Flex } from 'ui/grid';
|
||||
|
||||
export const ReloadButton = observer(
|
||||
({ storeSelector, onClick }: { onClick: () => void; storeSelector: StoreSelector }) => {
|
||||
const { $tables } = useStore();
|
||||
const { $tables, $process } = useStore();
|
||||
const { validation, getRows: rows } = storeSelector($tables.elt);
|
||||
|
||||
const hasErrors = validation.hasErrors;
|
||||
@ -16,7 +16,12 @@ export const ReloadButton = observer(
|
||||
<Flex justifyContent="center">
|
||||
<Button
|
||||
onClick={onClick}
|
||||
disabled={hasErrors}
|
||||
disabled={
|
||||
hasErrors ||
|
||||
$process.has('LoadKP') ||
|
||||
$process.has('Calculate') ||
|
||||
$process.has('CreateKP')
|
||||
}
|
||||
loading={rows.some((x) => x.status === 'fetching')}
|
||||
shape="circle"
|
||||
icon={<ReloadOutlined rev="" />}
|
||||
|
||||
@ -1,16 +1,10 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { PolicyTable, ReloadButton, Validation } from './Components';
|
||||
import { columns } from './lib/config';
|
||||
import { makeEltKaskoRequest } from './lib/make-request';
|
||||
import { resetRow } from './lib/tools';
|
||||
import type { Row, StoreSelector } from './types';
|
||||
import { getEltKasko } from '@/api/elt/query';
|
||||
import { STALE_TIME } from '@/constants/request';
|
||||
import { MAX_FRANCHISE, MAX_INSURANCE, MIN_INSURANCE } from '@/constants/values';
|
||||
import helper from '@/process/elt/lib/helper';
|
||||
import { useStore } from '@/stores/hooks';
|
||||
import { useApolloClient } from '@apollo/client';
|
||||
import type { QueryFunctionContext } from '@tanstack/react-query';
|
||||
import { useQueries } from '@tanstack/react-query';
|
||||
import { trpcClient } from '@/trpc/client';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { Flex } from 'ui/grid';
|
||||
|
||||
@ -18,129 +12,29 @@ const storeSelector: StoreSelector = ({ kasko }) => kasko;
|
||||
|
||||
export const Kasko = observer(() => {
|
||||
const store = useStore();
|
||||
const { $tables, $calculation } = store;
|
||||
const { $calculation, $tables } = store;
|
||||
|
||||
const apolloClient = useApolloClient();
|
||||
|
||||
const { init } = helper({ apolloClient, store });
|
||||
|
||||
const queries = useQueries({
|
||||
queries: $tables.elt.kasko.getRows.map((row) => {
|
||||
const { id, key } = row;
|
||||
|
||||
return {
|
||||
cacheTime: 0,
|
||||
enabled: false,
|
||||
initialData: {
|
||||
...row,
|
||||
error: '',
|
||||
kaskoSum: 0,
|
||||
paymentPeriods: [
|
||||
{
|
||||
kaskoSum: 0,
|
||||
},
|
||||
],
|
||||
sum: 0,
|
||||
},
|
||||
queryFn: async (context: QueryFunctionContext) => {
|
||||
const payload = await makeEltKaskoRequest({ apolloClient, store }, row);
|
||||
const res = await getEltKasko(payload, context);
|
||||
const companyRes = res[id];
|
||||
|
||||
return { ...companyRes, id, key };
|
||||
},
|
||||
queryKey: ['elt', 'kasko', id],
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: STALE_TIME,
|
||||
};
|
||||
}),
|
||||
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);
|
||||
},
|
||||
});
|
||||
|
||||
async function handleOnClick() {
|
||||
const { kasko } = await init();
|
||||
$tables.elt.kasko.setRows(kasko);
|
||||
|
||||
const kaskoCompanyIds = $tables.insurance
|
||||
.row('kasko')
|
||||
.getOptions('insuranceCompany')
|
||||
.map((x) => x.value);
|
||||
const values = $calculation.$values.getValues();
|
||||
|
||||
queries
|
||||
.filter(({ data }) => data?.key && kaskoCompanyIds.includes(data.key))
|
||||
.forEach(({ refetch, data }) => {
|
||||
if (data?.key) $tables.elt.kasko.setRow({ key: data?.key, status: 'fetching' });
|
||||
|
||||
refetch()
|
||||
.then((res) => {
|
||||
if (res.data) {
|
||||
const {
|
||||
key,
|
||||
kaskoSum = 0,
|
||||
message,
|
||||
skCalcId,
|
||||
totalFranchise = 0,
|
||||
requestId,
|
||||
paymentPeriods,
|
||||
} = res.data;
|
||||
let { error } = res.data;
|
||||
|
||||
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?.at(0)?.kaskoSum || 0,
|
||||
totalFranchise,
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (data?.key)
|
||||
$tables.elt.kasko.setRow({
|
||||
key: data?.key,
|
||||
message: error,
|
||||
numCalc: 0,
|
||||
requestId: '',
|
||||
skCalcId: '',
|
||||
status: 'error',
|
||||
sum: 0,
|
||||
totalFranchise: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
function handleOnClick() {
|
||||
calculateKasko.mutate({
|
||||
calculation: {
|
||||
values: store.$calculation.$values.getValues(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function handleOnSelectRow(row: Row) {
|
||||
|
||||
@ -1,16 +1,11 @@
|
||||
/* eslint-disable no-negated-condition */
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { PolicyTable, ReloadButton, Validation } from './Components';
|
||||
import { columns } from './lib/config';
|
||||
import { makeEltOsagoRequest } from './lib/make-request';
|
||||
import { resetRow } from './lib/tools';
|
||||
import type { Row, StoreSelector } from './types';
|
||||
import { getEltOsago } from '@/api/elt/query';
|
||||
import { STALE_TIME } from '@/constants/request';
|
||||
import { MAX_INSURANCE, MIN_INSURANCE } from '@/constants/values';
|
||||
import helper from '@/process/elt/lib/helper';
|
||||
import { useStore } from '@/stores/hooks';
|
||||
import { useApolloClient } from '@apollo/client';
|
||||
import type { QueryFunctionContext } from '@tanstack/react-query';
|
||||
import { useQueries } from '@tanstack/react-query';
|
||||
import { trpcClient } from '@/trpc/client';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { Flex } from 'ui/grid';
|
||||
|
||||
@ -20,94 +15,27 @@ export const Osago = observer(() => {
|
||||
const store = useStore();
|
||||
const { $tables } = store;
|
||||
|
||||
const apolloClient = useApolloClient();
|
||||
|
||||
const { init } = helper({ apolloClient, store });
|
||||
|
||||
const queries = useQueries({
|
||||
queries: $tables.elt.osago.getRows.map((row) => {
|
||||
const { id, key } = row;
|
||||
|
||||
return {
|
||||
cacheTime: 0,
|
||||
enabled: false,
|
||||
initialData: { ...row, error: '', premiumSum: 0 },
|
||||
queryFn: async (context: QueryFunctionContext) => {
|
||||
const payload = await makeEltOsagoRequest({ apolloClient, store }, row);
|
||||
const res = await getEltOsago(payload, context);
|
||||
const companyRes = res[id];
|
||||
|
||||
return { ...companyRes, id, key };
|
||||
},
|
||||
queryKey: ['elt', 'osago', id],
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: STALE_TIME,
|
||||
};
|
||||
}),
|
||||
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);
|
||||
},
|
||||
});
|
||||
|
||||
async function handleOnClick() {
|
||||
const { osago } = await init();
|
||||
$tables.elt.osago.setRows(osago);
|
||||
|
||||
const osagoCompanyIds = $tables.insurance
|
||||
.row('osago')
|
||||
.getOptions('insuranceCompany')
|
||||
.map((x) => x.value);
|
||||
|
||||
queries
|
||||
.filter(({ data }) => data?.key && osagoCompanyIds.includes(data.key))
|
||||
.forEach(({ refetch, data }) => {
|
||||
if (data?.key) $tables.elt.osago.setRow({ key: data?.key, status: 'fetching' });
|
||||
|
||||
refetch()
|
||||
.then((res) => {
|
||||
if (res.data) {
|
||||
const { key, numCalc, premiumSum = 0, message, skCalcId } = res.data;
|
||||
let { error } = res.data;
|
||||
|
||||
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) => {
|
||||
if (data?.key)
|
||||
$tables.elt.osago.setRow({
|
||||
key: data?.key,
|
||||
message: error,
|
||||
numCalc: 0,
|
||||
skCalcId: '',
|
||||
status: 'error',
|
||||
sum: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
calculateOsago.mutate({
|
||||
calculation: {
|
||||
values: store.$calculation.$values.getValues(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function handleOnSelectRow(row: Row) {
|
||||
@ -123,14 +51,12 @@ export const Osago = observer(() => {
|
||||
title: 'Страховая компания ОСАГО',
|
||||
};
|
||||
}
|
||||
|
||||
if (column.key === 'status') {
|
||||
return {
|
||||
...column,
|
||||
title: <ReloadButton storeSelector={storeSelector} onClick={() => handleOnClick()} />,
|
||||
};
|
||||
}
|
||||
|
||||
if (column.key === 'totalFranchise') {
|
||||
return {
|
||||
...column,
|
||||
|
||||
@ -1,10 +1,7 @@
|
||||
import type { RowSchema } from '@/config/schema/elt';
|
||||
import type { Row } from '../types';
|
||||
import type { ColumnsType } from 'antd/lib/table';
|
||||
import { CloseOutlined, LoadingOutlined } from 'ui/elements/icons';
|
||||
import { Flex } from 'ui/grid';
|
||||
import type { z } from 'zod';
|
||||
|
||||
type Row = z.infer<typeof RowSchema>;
|
||||
|
||||
const formatter = Intl.NumberFormat('ru', {
|
||||
currency: 'RUB',
|
||||
|
||||
12
apps/web/Components/Calculation/Form/ELT/lib/tools.ts
Normal file
12
apps/web/Components/Calculation/Form/ELT/lib/tools.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import type { Row } from '@/Components/Calculation/Form/ELT/types';
|
||||
import { defaultRow } from '@/stores/tables/elt/default-values';
|
||||
|
||||
export function resetRow(row: Row): Row {
|
||||
return {
|
||||
...defaultRow,
|
||||
id: row.id,
|
||||
key: row.key,
|
||||
metodCalc: row.metodCalc,
|
||||
name: row.name,
|
||||
};
|
||||
}
|
||||
@ -1,13 +1,14 @@
|
||||
import type { FormTabRows } from '../../lib/render-rows';
|
||||
import { transformRowsForMobile } from '../lib/utils';
|
||||
|
||||
export const id = 'insurance';
|
||||
export const title = 'Страхование';
|
||||
|
||||
export const rows: FormTabRows = [
|
||||
[['tbxLeaseObjectYear', 'selectLeaseObjectUseFor', 'selectLegalClientRegion']],
|
||||
[['selectEngineType', 'tbxInsFranchise', 'selectLegalClientTown']],
|
||||
[['selectLeaseObjectCategory', 'tbxMileage']],
|
||||
[['tbxLeaseObjectMotorPower', 'cbxWithTrailer', 'selectGPSBrand']],
|
||||
[['tbxEngineVolume', 'cbxInsDecentral', 'selectGPSModel']],
|
||||
[['selectLeasingWithoutKasko', 'selectInsNSIB']],
|
||||
[['tbxMileage', 'tbxInsFranchise', 'selectLegalClientTown']],
|
||||
[['selectGPSBrand', 'cbxWithTrailer', 'selectInsNSIB']],
|
||||
[['selectGPSModel', 'cbxInsDecentral', 'selectLeasingWithoutKasko']],
|
||||
];
|
||||
|
||||
export const mobileRows = transformRowsForMobile(rows);
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import renderFormRows from '../../lib/render-rows';
|
||||
import { id, rows, title } from './config';
|
||||
import { id, mobileRows, rows, title } from './config';
|
||||
import FinGAPTable from './FinGAPTable';
|
||||
import InsuranceTable from './InsuranceTable';
|
||||
import { Media } from '@/styles/media';
|
||||
import { Flex } from 'ui/grid';
|
||||
|
||||
function Insurance() {
|
||||
const renderedRows = renderFormRows(rows);
|
||||
|
||||
return (
|
||||
<Flex flexDirection="column">
|
||||
{renderedRows}
|
||||
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
|
||||
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
|
||||
<InsuranceTable />
|
||||
<FinGAPTable />
|
||||
</Flex>
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import type { FormTabRows } from '../../lib/render-rows';
|
||||
import { transformRowsForMobile } from '../lib/utils';
|
||||
|
||||
export const id = 'leasing-object';
|
||||
export const title = 'ПЛ';
|
||||
@ -16,3 +17,5 @@ export const rows: FormTabRows = [
|
||||
[['selectLeaseObjectCategory', 'tbxEngineVolume', 'tbxMileage']],
|
||||
[['tbxMaxMass', 'tbxEngineHours', 'tbxVIN']],
|
||||
];
|
||||
|
||||
export const mobileRows = transformRowsForMobile(rows);
|
||||
|
||||
@ -1,8 +1,14 @@
|
||||
import renderFormRows from '../../lib/render-rows';
|
||||
import { id, rows, title } from './config';
|
||||
import { id, mobileRows, rows, title } from './config';
|
||||
import { Media } from '@/styles/media';
|
||||
|
||||
function LeasingObject() {
|
||||
return renderFormRows(rows);
|
||||
return (
|
||||
<>
|
||||
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
|
||||
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import type { FormTabRows } from '../../lib/render-rows';
|
||||
import { transformRowsForMobile } from '../lib/utils';
|
||||
|
||||
export const id = 'supplier-agent';
|
||||
export const title = 'Поставщик/агент';
|
||||
@ -20,3 +21,5 @@ export const rows: FormTabRows = [
|
||||
[['selectCalcBrokerRewardCondition', 'selectFinDepartmentRewardCondtion'], defaultRowStyle],
|
||||
[['tbxCalcBrokerRewardSum', 'tbxFinDepartmentRewardSumm'], defaultRowStyle],
|
||||
];
|
||||
|
||||
export const mobileRows = transformRowsForMobile(rows);
|
||||
|
||||
@ -1,8 +1,14 @@
|
||||
import renderFormRows from '../../lib/render-rows';
|
||||
import { id, rows, title } from './config';
|
||||
import { id, mobileRows, rows, title } from './config';
|
||||
import { Media } from '@/styles/media';
|
||||
|
||||
function Leasing() {
|
||||
return renderFormRows(rows);
|
||||
return (
|
||||
<>
|
||||
<Media lessThan="laptop">{renderFormRows(mobileRows)}</Media>
|
||||
<Media greaterThanOrEqual="laptop">{renderFormRows(rows)}</Media>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
|
||||
@ -9,5 +9,6 @@ export const rows: FormTabRows = [
|
||||
[['tbxMinPriceChange', 'tbxMaxPriceChange']],
|
||||
[['tbxImporterRewardPerc', 'tbxImporterRewardRub']],
|
||||
[['tbxBonusCoefficient', 'tbxComissionRub', 'tbxComissionPerc']],
|
||||
[['cbxSupplierFinancing']],
|
||||
[['cbxSupplierFinancing', 'cbxPartialVAT', 'cbxFloatingRate']],
|
||||
[['cbxQuotePriceWithFullVAT']],
|
||||
];
|
||||
|
||||
@ -8,7 +8,9 @@ import Payments from './Payments';
|
||||
import SupplierAgent from './SupplierAgent';
|
||||
import Unlimited from './Unlimited';
|
||||
import Background from '@/Components/Layout/Background';
|
||||
import { useStore } from '@/stores/hooks';
|
||||
import { min } from '@/styles/mq';
|
||||
import { memo } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { Tabs } from 'ui/elements';
|
||||
|
||||
@ -44,22 +46,23 @@ const ComponentWrapper = styled.div`
|
||||
}
|
||||
`;
|
||||
|
||||
function Form({ prune }) {
|
||||
export const Form = memo(() => {
|
||||
const { $process } = useStore();
|
||||
|
||||
const filteredTabs =
|
||||
$process.has('Unlimited') === false ? formTabs.filter((x) => x.id !== 'unlimited') : formTabs;
|
||||
|
||||
return (
|
||||
<Wrapper>
|
||||
<Tabs type="card" tabBarGutter="5px">
|
||||
{formTabs
|
||||
.filter((tab) => !prune?.includes(tab.id))
|
||||
.map(({ id, title, Component }) => (
|
||||
<Tabs.TabPane tab={title} key={id}>
|
||||
<ComponentWrapper>
|
||||
<Component />
|
||||
</ComponentWrapper>
|
||||
</Tabs.TabPane>
|
||||
))}
|
||||
{filteredTabs.map(({ Component, id, title }) => (
|
||||
<Tabs.TabPane tab={title} key={id}>
|
||||
<ComponentWrapper>
|
||||
<Component />
|
||||
</ComponentWrapper>
|
||||
</Tabs.TabPane>
|
||||
))}
|
||||
</Tabs>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default Form;
|
||||
});
|
||||
|
||||
32
apps/web/Components/Calculation/Form/lib/utils.js
Normal file
32
apps/web/Components/Calculation/Form/lib/utils.js
Normal file
@ -0,0 +1,32 @@
|
||||
/**
|
||||
*
|
||||
* @param {import('../../lib/render-rows').FormTabRows} rows
|
||||
* @returns {import('../../lib/render-rows').FormTabRows}
|
||||
*/
|
||||
export function transformRowsForMobile(rows) {
|
||||
const mobileRows = [];
|
||||
let columnGroups = {};
|
||||
|
||||
rows.forEach((row) => {
|
||||
if (Array.isArray(row)) {
|
||||
row[0].forEach((item, index) => {
|
||||
if (!columnGroups[index]) {
|
||||
columnGroups[index] = [];
|
||||
}
|
||||
columnGroups[index].push(item);
|
||||
});
|
||||
} else {
|
||||
Object.values(columnGroups).forEach((group) => {
|
||||
mobileRows.push([group, { gridTemplateColumns: '1fr' }]);
|
||||
});
|
||||
columnGroups = {};
|
||||
mobileRows.push(row);
|
||||
}
|
||||
});
|
||||
|
||||
Object.values(columnGroups).forEach((group) => {
|
||||
mobileRows.push([group, { gridTemplateColumns: '1fr' }]);
|
||||
});
|
||||
|
||||
return mobileRows;
|
||||
}
|
||||
@ -2,7 +2,7 @@ import { min } from '@/styles/mq';
|
||||
import styled from 'styled-components';
|
||||
import { Box } from 'ui/grid';
|
||||
|
||||
export const Grid = styled(Box)`
|
||||
export const Layout = styled(Box)`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
@ -17,8 +17,4 @@ export const Grid = styled(Box)`
|
||||
grid-template-columns: 2fr 1fr 1.5fr;
|
||||
/* margin: 8px 5%; */
|
||||
}
|
||||
|
||||
${min('desktop-xl')} {
|
||||
margin: 8px 10%;
|
||||
}
|
||||
`;
|
||||
@ -7,7 +7,7 @@ import { observer } from 'mobx-react-lite';
|
||||
import { Table } from 'ui/elements';
|
||||
|
||||
const PaymentsTable = observer(() => {
|
||||
const { $results, $process } = useStore();
|
||||
const { $process, $results } = useStore();
|
||||
|
||||
const unlimited = $process.has('Unlimited');
|
||||
const dataSource = toJS($results.payments);
|
||||
@ -27,8 +27,8 @@ const PaymentsTable = observer(() => {
|
||||
showSizeChanger: false,
|
||||
}}
|
||||
scroll={{
|
||||
x: dataColumns.length > 4 && 1000,
|
||||
y: 630,
|
||||
x: dataColumns.length > 5 ? 1000 : undefined,
|
||||
y: dataSource.length > 16 ? 630 : undefined,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
@ -7,6 +7,7 @@ export const titles: Record<keyof ResultValues, string> = {
|
||||
_resultContractEconomy: 'Экономика',
|
||||
_resultContractEconomyWithVAT: 'Экономика, с НДС',
|
||||
_resultPi: 'PI',
|
||||
_resultPiRepayment: 'PI для досрочки',
|
||||
_resultSumCredit: 'Сумма кредита',
|
||||
_resultSumCreditPayment: 'Сумма платежей по кредиту',
|
||||
_resultVatRecoverable: 'НДС к возмещению',
|
||||
@ -46,6 +47,7 @@ export const formatters = {
|
||||
_resultContractEconomy: moneyFormatter,
|
||||
_resultContractEconomyWithVAT: moneyFormatter,
|
||||
_resultPi: percentFormatter,
|
||||
_resultPiRepayment: percentFormatter,
|
||||
_resultSumCredit: moneyFormatter,
|
||||
_resultSumCreditPayment: moneyFormatter,
|
||||
_resultVatRecoverable: moneyFormatter,
|
||||
@ -74,6 +76,7 @@ export const elements: Array<keyof ResultValues> = [
|
||||
'_resultContractEconomy',
|
||||
'_resultContractEconomyWithVAT',
|
||||
'_resultPi',
|
||||
'_resultPiRepayment',
|
||||
'_resultSumCredit',
|
||||
'_resultSumCreditPayment',
|
||||
'_resultVatRecoverable',
|
||||
@ -22,7 +22,7 @@ const Wrapper = styled.div`
|
||||
`;
|
||||
|
||||
const Results = observer(() => {
|
||||
const { $results, $process } = useStore();
|
||||
const { $process, $results } = useStore();
|
||||
|
||||
const resultsValues = toJS($results.values);
|
||||
// eslint-disable-next-line no-negated-condition
|
||||
@ -23,73 +23,34 @@ const AlertWrapper = styled(Box)`
|
||||
margin: 0 0 5px 0;
|
||||
`;
|
||||
|
||||
function getAlerts(errors, title, $process) {
|
||||
return errors.map(({ key, message }) => (
|
||||
<AlertWrapper>
|
||||
<Alert
|
||||
key={key}
|
||||
type={$process.has('Unlimited') ? 'warning' : 'error'}
|
||||
showIcon
|
||||
message={Message(title, message)}
|
||||
/>
|
||||
</AlertWrapper>
|
||||
));
|
||||
}
|
||||
|
||||
function getElementsErrors({ $calculation, $process }) {
|
||||
return Object.values($calculation.$validation).map((validation) => {
|
||||
const elementErrors = validation.getErrors();
|
||||
const elementTitle = validation.params.err_title;
|
||||
|
||||
return elementErrors.map(({ key, message }) => (
|
||||
<AlertWrapper>
|
||||
<Alert
|
||||
key={key}
|
||||
type={$process.has('Unlimited') ? 'warning' : 'error'}
|
||||
showIcon
|
||||
message={Message(elementTitle, message)}
|
||||
/>
|
||||
</AlertWrapper>
|
||||
));
|
||||
return getAlerts(elementErrors, elementTitle, $process);
|
||||
});
|
||||
}
|
||||
|
||||
function getPaymentsTableErrors({ $tables, $process }) {
|
||||
const { payments } = $tables;
|
||||
const errors = payments.validation.getErrors();
|
||||
const title = payments.validation.params.err_title;
|
||||
function getTableErrors(tableName, { $process, $tables }) {
|
||||
const table = $tables[tableName];
|
||||
const errors = table.validation.getErrors();
|
||||
const title = table.validation.params.err_title;
|
||||
|
||||
return errors.map(({ key, message }) => (
|
||||
<AlertWrapper>
|
||||
<Alert
|
||||
key={key}
|
||||
type={$process.has('Unlimited') ? 'warning' : 'error'}
|
||||
showIcon
|
||||
message={Message(title, message)}
|
||||
/>
|
||||
</AlertWrapper>
|
||||
));
|
||||
}
|
||||
|
||||
function getInsuranceTableErrors({ $tables, $process }) {
|
||||
const { insurance } = $tables;
|
||||
const errors = insurance.validation.getErrors();
|
||||
const title = insurance.validation.params.err_title;
|
||||
|
||||
return errors.map(({ key, message }) => (
|
||||
<AlertWrapper>
|
||||
<Alert
|
||||
key={key}
|
||||
type={$process.has('Unlimited') ? 'warning' : 'error'}
|
||||
showIcon
|
||||
message={Message(title, message)}
|
||||
/>
|
||||
</AlertWrapper>
|
||||
));
|
||||
}
|
||||
|
||||
function getFingapTableErrors({ $tables, $process }) {
|
||||
const { fingap } = $tables;
|
||||
const errors = fingap.validation.getErrors();
|
||||
const title = fingap.validation.params.err_title;
|
||||
|
||||
return errors.map(({ key, message }) => (
|
||||
<AlertWrapper>
|
||||
<Alert
|
||||
key={key}
|
||||
type={$process.has('Unlimited') ? 'warning' : 'error'}
|
||||
showIcon
|
||||
message={Message(title, message)}
|
||||
/>
|
||||
</AlertWrapper>
|
||||
));
|
||||
return getAlerts(errors, title, $process);
|
||||
}
|
||||
|
||||
const Errors = observer(() => {
|
||||
@ -101,15 +62,16 @@ const Errors = observer(() => {
|
||||
);
|
||||
const hasPaymentsErrors = $tables.payments.validation.hasErrors;
|
||||
const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
|
||||
const hasFingapErrors = $tables.fingap.validation.hasErrors;
|
||||
|
||||
if (!hasElementsErrors && !hasPaymentsErrors && !hasInsuranceErrors) {
|
||||
if (!hasElementsErrors && !hasPaymentsErrors && !hasInsuranceErrors && !hasFingapErrors) {
|
||||
return <Alert type="success" showIcon message="Ошибок нет 🙂" />;
|
||||
}
|
||||
|
||||
const elementsErrors = getElementsErrors(store);
|
||||
const paymentsErrors = getPaymentsTableErrors(store);
|
||||
const insuranceErrors = getInsuranceTableErrors(store);
|
||||
const fingapErrors = getFingapTableErrors(store);
|
||||
const paymentsErrors = getTableErrors('payments', store);
|
||||
const insuranceErrors = getTableErrors('insurance', store);
|
||||
const fingapErrors = getTableErrors('fingap', store);
|
||||
|
||||
const errors = [...elementsErrors, ...paymentsErrors, ...insuranceErrors, ...fingapErrors];
|
||||
|
||||
@ -42,7 +42,7 @@ const Wrapper = styled(Background)`
|
||||
}
|
||||
`;
|
||||
|
||||
const Output = observer(() => {
|
||||
export const Output = observer(({ tabs }) => {
|
||||
const { $results } = useStore();
|
||||
const [activeKey, setActiveKey] = useState(undefined);
|
||||
const { hasErrors } = useErrors();
|
||||
@ -52,15 +52,15 @@ const Output = observer(() => {
|
||||
setActiveKey('payments-table');
|
||||
}
|
||||
|
||||
if (hasErrors) {
|
||||
if (!tabs && hasErrors) {
|
||||
setActiveKey('validation');
|
||||
}
|
||||
}, [$results.payments.length, hasErrors]);
|
||||
}, [$results.payments.length, hasErrors, tabs]);
|
||||
|
||||
return (
|
||||
<Wrapper>
|
||||
<Tabs
|
||||
items={items}
|
||||
items={tabs ? items.filter((x) => x.key !== 'validation') : items}
|
||||
activeKey={activeKey}
|
||||
onChange={(key) => {
|
||||
setActiveKey(key);
|
||||
@ -69,5 +69,3 @@ const Output = observer(() => {
|
||||
</Wrapper>
|
||||
);
|
||||
});
|
||||
|
||||
export default Output;
|
||||
@ -18,8 +18,8 @@ export const mainRows: FormTabRows = [
|
||||
[
|
||||
['btnCreateKP', 'linkDownloadKp'],
|
||||
{
|
||||
gap: [0, '10px'],
|
||||
gridTemplateColumns: ['1fr', '1fr 1fr'],
|
||||
gap: ['10px'],
|
||||
gridTemplateColumns: ['1fr 1fr'],
|
||||
},
|
||||
],
|
||||
];
|
||||
@ -41,8 +41,8 @@ export const unlimitedMainRows: FormTabRows = [
|
||||
[
|
||||
['btnCreateKP', 'linkDownloadKp'],
|
||||
{
|
||||
gap: [0, '10px'],
|
||||
gridTemplateColumns: ['1fr', '1fr 1fr'],
|
||||
gap: ['10px'],
|
||||
gridTemplateColumns: ['1fr 1fr'],
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
@ -3,6 +3,7 @@ import * as config from './config';
|
||||
import Background from '@/Components/Layout/Background';
|
||||
import { useStore } from '@/stores/hooks';
|
||||
import { min } from '@/styles/mq';
|
||||
import { memo } from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
const Wrapper = styled(Background)`
|
||||
@ -17,7 +18,7 @@ const Wrapper = styled(Background)`
|
||||
}
|
||||
`;
|
||||
|
||||
export default function Settings() {
|
||||
export const Settings = memo(() => {
|
||||
const { $process } = useStore();
|
||||
|
||||
const mainRows = $process.has('Unlimited')
|
||||
@ -33,4 +34,4 @@ export default function Settings() {
|
||||
{paramsRows}
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
19
apps/web/Components/Calculation/Validation/index.jsx
Normal file
19
apps/web/Components/Calculation/Validation/index.jsx
Normal file
@ -0,0 +1,19 @@
|
||||
import Validation from '../Output/Validation';
|
||||
import Background from '@/Components/Layout/Background';
|
||||
import { min } from '@/styles/mq';
|
||||
import { memo } from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
const Wrapper = styled(Background)`
|
||||
padding: 4px 10px;
|
||||
|
||||
${min('laptop')} {
|
||||
padding: 4px 18px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Component = memo(() => (
|
||||
<Wrapper>
|
||||
<Validation.Component />
|
||||
</Wrapper>
|
||||
));
|
||||
31
apps/web/Components/Calculation/addons/irr-addon.tsx
Normal file
31
apps/web/Components/Calculation/addons/irr-addon.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
import { useStore } from '@/stores/hooks';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import styled from 'styled-components';
|
||||
import { LoadingOutlined } from 'ui/elements/icons';
|
||||
|
||||
const TextAddon = styled.span`
|
||||
font-size: 14px;
|
||||
`;
|
||||
|
||||
const formatter = Intl.NumberFormat('ru', {
|
||||
minimumFractionDigits: 2,
|
||||
}).format;
|
||||
|
||||
export const IRRAddon = observer(() => {
|
||||
const { $calculation, $process } = useStore();
|
||||
|
||||
if ($process.has('Tarif')) {
|
||||
return (
|
||||
<TextAddon>
|
||||
<LoadingOutlined rev="" />
|
||||
{' Подбирается тариф...'}
|
||||
</TextAddon>
|
||||
);
|
||||
}
|
||||
|
||||
const tarif = $calculation.element('selectTarif').getValue();
|
||||
if (!tarif) return <TextAddon>Тариф не найден</TextAddon>;
|
||||
|
||||
const { min, max } = $calculation.$values.getValue('irrInfo');
|
||||
return <TextAddon>{`${formatter(min)}% - ${formatter(max)}%`}</TextAddon>;
|
||||
});
|
||||
53
apps/web/Components/Calculation/addons/product-addon.tsx
Normal file
53
apps/web/Components/Calculation/addons/product-addon.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
/* eslint-disable react/forbid-component-props */
|
||||
import titles from '../config/elements-titles';
|
||||
import { useStore } from '@/stores/hooks';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { pick } from 'radash';
|
||||
import styled from 'styled-components';
|
||||
import { Tag } from 'ui/elements';
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 5px;
|
||||
`;
|
||||
|
||||
const TagWrapper = styled.div<{ disabled: boolean }>`
|
||||
> span {
|
||||
pointer-events: ${(props) => (props.disabled ? 'none' : 'auto')};
|
||||
opacity: ${(props) => (props.disabled ? '50%' : '')};
|
||||
}
|
||||
`;
|
||||
|
||||
const tagsData = pick(titles, ['cbxPartialVAT', 'cbxFloatingRate']);
|
||||
|
||||
const { CheckableTag } = Tag;
|
||||
|
||||
export const ProductAddon = observer(() => {
|
||||
const { $calculation } = useStore();
|
||||
|
||||
function handleChange(elementName: keyof typeof tagsData, checked: boolean) {
|
||||
$calculation.element(elementName).setValue(checked);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
{(Object.keys(tagsData) as Array<keyof typeof tagsData>).map((elementName) => {
|
||||
const visible = $calculation.$status.getStatus(elementName);
|
||||
|
||||
return (
|
||||
<TagWrapper key={elementName} disabled={visible === 'Disabled'}>
|
||||
<CheckableTag
|
||||
checked={$calculation.element(elementName).getValue()}
|
||||
onChange={(checked) => handleChange(elementName, checked)}
|
||||
key={elementName}
|
||||
style={{ marginInlineEnd: 0 }}
|
||||
>
|
||||
{tagsData[elementName]}
|
||||
</CheckableTag>
|
||||
</TagWrapper>
|
||||
);
|
||||
})}
|
||||
</Container>
|
||||
);
|
||||
});
|
||||
@ -133,6 +133,10 @@ const components = wrapComponentsMap({
|
||||
selectUser: e.Select,
|
||||
cbxSupplierFinancing: e.Switch,
|
||||
tbxPi: e.InputNumber,
|
||||
cbxPartialVAT: e.Switch,
|
||||
cbxFloatingRate: e.Switch,
|
||||
cbxQuotePriceWithFullVAT: e.Switch,
|
||||
cbxQuoteShowAcceptLimit: e.Switch,
|
||||
|
||||
/** Readonly Elements */
|
||||
labelLeaseObjectRisk: e.Text,
|
||||
|
||||
@ -429,7 +429,7 @@ const props: Partial<ElementsProps> = {
|
||||
},
|
||||
tbxMaxPriceChange: {
|
||||
min: 0,
|
||||
max: 100_000_000,
|
||||
max: 1_000_000_000,
|
||||
step: 10_000,
|
||||
parser,
|
||||
formatter,
|
||||
@ -439,7 +439,7 @@ const props: Partial<ElementsProps> = {
|
||||
},
|
||||
tbxMinPriceChange: {
|
||||
min: 0,
|
||||
max: 100_000_000,
|
||||
max: 1_000_000_000,
|
||||
step: 10_000,
|
||||
parser,
|
||||
formatter,
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import { IRRAddon } from '../../addons/irr-addon';
|
||||
import { ProductAddon } from '../../addons/product-addon';
|
||||
import { buildLink } from '../../builders';
|
||||
import components from '../elements-components';
|
||||
import elementsProps from '../elements-props';
|
||||
@ -10,7 +12,6 @@ import { useErrors, useStore } from '@/stores/hooks';
|
||||
import { useIsFetching } from '@tanstack/react-query';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import type { ComponentProps } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { Link, Tooltip } from 'ui/elements';
|
||||
import { LoadingOutlined } from 'ui/elements/icons';
|
||||
|
||||
@ -21,14 +22,6 @@ const defaultLinkProps: ComponentProps<typeof Link> = {
|
||||
type: 'link',
|
||||
};
|
||||
|
||||
const formatter = Intl.NumberFormat('ru', {
|
||||
minimumFractionDigits: 2,
|
||||
}).format;
|
||||
|
||||
const TextAddon = styled.span`
|
||||
font-size: 14px;
|
||||
`;
|
||||
|
||||
const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
|
||||
btnCalculate: {
|
||||
render: () => {
|
||||
@ -54,7 +47,11 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
|
||||
<Element
|
||||
{...props}
|
||||
loading={$process.has('Calculate') || $process.has('CreateKP')}
|
||||
disabled={$process.has('LoadKP') || (!$process.has('Unlimited') && hasErrors)}
|
||||
disabled={
|
||||
$process.has('LoadKP') ||
|
||||
(!$process.has('Unlimited') && hasErrors) ||
|
||||
$process.has('Tarif')
|
||||
}
|
||||
/>
|
||||
</Container>
|
||||
);
|
||||
@ -88,7 +85,11 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
|
||||
<Element
|
||||
{...props}
|
||||
loading={$process.has('Calculate') || $process.has('CreateKP')}
|
||||
disabled={$process.has('LoadKP') || (!$process.has('Unlimited') && hasErrors)}
|
||||
disabled={
|
||||
$process.has('LoadKP') ||
|
||||
(!$process.has('Unlimited') && hasErrors) ||
|
||||
$process.has('Tarif')
|
||||
}
|
||||
/>
|
||||
</Container>
|
||||
);
|
||||
@ -221,6 +222,29 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
|
||||
},
|
||||
},
|
||||
|
||||
selectProduct: {
|
||||
render: () => {
|
||||
const elementName = 'selectProduct';
|
||||
const title = titles.selectProduct;
|
||||
const valueName = map.selectProduct;
|
||||
const Component = components.selectProduct;
|
||||
const props = elementsProps.selectProduct;
|
||||
const { builder } = types.selectProduct();
|
||||
|
||||
const Element = builder(Component, {
|
||||
elementName,
|
||||
valueName,
|
||||
});
|
||||
|
||||
return (
|
||||
<Container key={elementName}>
|
||||
<Head addon={<ProductAddon />} htmlFor={elementName} title={title} />
|
||||
<Element {...props} id={elementName} />
|
||||
</Container>
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
selectQuote: {
|
||||
render: () => {
|
||||
const elementName = 'selectQuote';
|
||||
@ -308,13 +332,11 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
|
||||
|
||||
const RenderedComponent = observer(() => {
|
||||
const { $calculation } = useStore();
|
||||
const { min, max } = $calculation.$values.getValue('irrInfo');
|
||||
|
||||
const addon = <TextAddon>{`${formatter(min)}% - ${formatter(max)}%`}</TextAddon>;
|
||||
const { max, min } = $calculation.$values.getValue('irrInfo');
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Head htmlFor={elementName} title={title} addon={addon} />
|
||||
<Head htmlFor={elementName} title={title} addon={<IRRAddon />} />
|
||||
<Element {...props} min={min > 0 ? min : undefined} max={max > 0 ? max : undefined} />
|
||||
</Container>
|
||||
);
|
||||
@ -348,7 +370,7 @@ const overrideRender: Partial<Record<keyof typeof map, RenderProps>> = {
|
||||
<Element
|
||||
{...props}
|
||||
id={elementName}
|
||||
addonBefore={isFetching && <LoadingOutlined spin rev="" />}
|
||||
addonBefore={isFetching ? <LoadingOutlined spin rev="" /> : null}
|
||||
/>
|
||||
</Container>
|
||||
</Tooltip>
|
||||
|
||||
@ -127,6 +127,10 @@ const titles: Record<ActionElements | ValuesElements, string> = {
|
||||
selectUser: 'Пользователь',
|
||||
cbxSupplierFinancing: 'Финансирование поставщика',
|
||||
tbxPi: 'PI',
|
||||
cbxPartialVAT: 'Частичный НДС',
|
||||
cbxFloatingRate: 'Плавающая ставка',
|
||||
cbxQuotePriceWithFullVAT: 'Отображать Стоимость ПЛ с полным НДС',
|
||||
cbxQuoteShowAcceptLimit: 'Отображать одобренный лимит',
|
||||
|
||||
/** Link Elements */
|
||||
linkDownloadKp: '',
|
||||
|
||||
@ -192,6 +192,10 @@ const types = wrapElementsTypes({
|
||||
selectUser: t.Options,
|
||||
cbxSupplierFinancing: t.Switch,
|
||||
tbxPi: t.Number,
|
||||
cbxPartialVAT: t.Switch,
|
||||
cbxFloatingRate: t.Switch,
|
||||
cbxQuotePriceWithFullVAT: t.Switch,
|
||||
cbxQuoteShowAcceptLimit: t.Switch,
|
||||
|
||||
labelLeaseObjectRisk: t.Readonly,
|
||||
tbxInsKaskoPriceLeasePeriod: t.Readonly,
|
||||
|
||||
@ -130,6 +130,10 @@ const elementsToValues = wrapElementsMap({
|
||||
selectUser: 'user',
|
||||
cbxSupplierFinancing: 'supplierFinancing',
|
||||
tbxPi: 'pi',
|
||||
cbxPartialVAT: 'partialVAT',
|
||||
cbxFloatingRate: 'floatingRate',
|
||||
cbxQuotePriceWithFullVAT: 'quotePriceWithFullVAT',
|
||||
cbxQuoteShowAcceptLimit: 'quoteShowAcceptLimit',
|
||||
|
||||
/** Readonly Elements */
|
||||
labelLeaseObjectRisk: 'leaseObjectRiskName',
|
||||
|
||||
@ -1,2 +0,0 @@
|
||||
export { default as Form } from './Form';
|
||||
export { default as Settings } from './Settings';
|
||||
101
apps/web/Components/Calculation/index.tsx
Normal file
101
apps/web/Components/Calculation/index.tsx
Normal file
@ -0,0 +1,101 @@
|
||||
import { Form } from './Form';
|
||||
import { Layout } from './Layout';
|
||||
import { Output } from './Output';
|
||||
import { Settings } from './Settings';
|
||||
import { Component as Validation } from './Validation';
|
||||
import { Notification } from '@/Components/Common';
|
||||
import { NavigationBar, Tabs } from '@/Components/Layout/Navigation';
|
||||
import { NavigationProvider } from '@/context/navigation';
|
||||
import { useErrors, useResults } from '@/stores/hooks';
|
||||
import { Media } from '@/styles/media';
|
||||
import { getPageTitle } from '@/utils/page';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import Head from 'next/head';
|
||||
import styled from 'styled-components';
|
||||
import { Badge } from 'ui/elements';
|
||||
import {
|
||||
BarChartOutlined,
|
||||
CalculatorOutlined,
|
||||
ProfileOutlined,
|
||||
WarningOutlined,
|
||||
} from 'ui/elements/icons';
|
||||
|
||||
const defaultIconStyle = { fontSize: '1.2rem' };
|
||||
|
||||
const StyledBadge = styled(Badge)`
|
||||
color: unset !important;
|
||||
`;
|
||||
|
||||
export const tabs = [
|
||||
{
|
||||
Component: Settings,
|
||||
Icon: () => <ProfileOutlined style={defaultIconStyle} />,
|
||||
key: 'settings',
|
||||
title: 'Интерес/Расчет',
|
||||
},
|
||||
{
|
||||
Component: Form,
|
||||
Icon: () => <CalculatorOutlined style={defaultIconStyle} />,
|
||||
key: 'form',
|
||||
title: 'Параметры',
|
||||
},
|
||||
{
|
||||
Component: Output,
|
||||
Icon: observer(() => {
|
||||
const { hasResults } = useResults();
|
||||
|
||||
return (
|
||||
<StyledBadge status="success" dot={hasResults}>
|
||||
<BarChartOutlined style={defaultIconStyle} />
|
||||
</StyledBadge>
|
||||
);
|
||||
}),
|
||||
key: 'output',
|
||||
title: 'Результаты',
|
||||
},
|
||||
{
|
||||
Component: Validation,
|
||||
Icon: observer(() => {
|
||||
const { hasErrors } = useErrors();
|
||||
|
||||
return (
|
||||
<StyledBadge status="error" dot={hasErrors}>
|
||||
<WarningOutlined style={defaultIconStyle} />
|
||||
</StyledBadge>
|
||||
);
|
||||
}),
|
||||
key: 'errors',
|
||||
title: 'Ошибки',
|
||||
},
|
||||
];
|
||||
|
||||
type ContentProps = {
|
||||
readonly initHooks: () => void;
|
||||
readonly title: string;
|
||||
};
|
||||
|
||||
export function Content({ initHooks, title }: ContentProps) {
|
||||
initHooks();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle(title)}</title>
|
||||
</Head>
|
||||
<Notification />
|
||||
<Media lessThan="laptop">
|
||||
<NavigationProvider>
|
||||
<Tabs tabs={tabs} />
|
||||
<NavigationBar />
|
||||
</NavigationProvider>
|
||||
</Media>
|
||||
<Media greaterThanOrEqual="laptop">
|
||||
<Layout>
|
||||
<Form />
|
||||
<Settings />
|
||||
<Output />
|
||||
</Layout>
|
||||
</Media>
|
||||
</>
|
||||
);
|
||||
}
|
||||
20
apps/web/Components/Common/Loading.jsx
Normal file
20
apps/web/Components/Common/Loading.jsx
Normal file
@ -0,0 +1,20 @@
|
||||
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>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,7 @@
|
||||
/* eslint-disable import/no-mutable-exports */
|
||||
import { ERROR_KEYS } from '@/@types/errors';
|
||||
import { Media } from '@/styles/media';
|
||||
import { getDevice } from '@/utils/device';
|
||||
import type { MessageInstance } from 'antd/es/message/interface';
|
||||
import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
import type { ReactNode } from 'react';
|
||||
@ -7,23 +10,61 @@ import { message as antdMessage, notification as antdNotification } from 'ui/ele
|
||||
export let message: Readonly<MessageInstance>;
|
||||
export let notification: Readonly<NotificationInstance>;
|
||||
|
||||
export function Notification({ children }: { children: ReactNode }) {
|
||||
function createWrapper<T extends NotificationInstance, M extends MessageInstance>(
|
||||
notificationObj: T,
|
||||
messageObj: M
|
||||
): T {
|
||||
const handler: ProxyHandler<T> = {
|
||||
get(target, prop, receiver) {
|
||||
const notificationMethod = target[prop as keyof T];
|
||||
const messageMethod = messageObj[prop as keyof M];
|
||||
|
||||
if (typeof notificationMethod === 'function' && typeof messageMethod === 'function') {
|
||||
return function (...args: any[]) {
|
||||
const device = getDevice();
|
||||
|
||||
if (device?.isMobile) {
|
||||
if (typeof args[0] === 'object') {
|
||||
if (ERROR_KEYS.includes(args[0].key)) return;
|
||||
args[0].content = args[0].description || args[0].message;
|
||||
}
|
||||
|
||||
messageMethod.apply(messageObj, args);
|
||||
}
|
||||
|
||||
notificationMethod.apply(target, args);
|
||||
};
|
||||
}
|
||||
|
||||
return Reflect.get(target, prop, receiver);
|
||||
},
|
||||
};
|
||||
|
||||
return new Proxy(notificationObj, handler);
|
||||
}
|
||||
|
||||
export function Notification({ children }: { readonly children?: ReactNode }) {
|
||||
const device = getDevice();
|
||||
|
||||
const [messageApi, messageContextHolder] = antdMessage.useMessage({
|
||||
duration: 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 = notificationApi;
|
||||
notification = createWrapper(notificationApi, messageApi);
|
||||
|
||||
return (
|
||||
<>
|
||||
{messageContextHolder}
|
||||
{notificationContextHolder}
|
||||
<Media greaterThanOrEqual="laptop">{notificationContextHolder}</Media>
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
|
||||
3
apps/web/Components/Common/index.ts
Normal file
3
apps/web/Components/Common/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export * from './Error';
|
||||
export * from './Loading';
|
||||
export * from './Notification';
|
||||
@ -10,7 +10,7 @@ const UserText = styled.span`
|
||||
padding: 0;
|
||||
text-transform: uppercase;
|
||||
color: #fff;
|
||||
font-size: 0.5rem;
|
||||
font-size: 0.55rem;
|
||||
font-family: 'Montserrat';
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
@ -45,13 +45,7 @@ const Logout = styled.a`
|
||||
|
||||
function Auth() {
|
||||
return (
|
||||
<Flex
|
||||
flexDirection="column"
|
||||
alignItems="flex-end"
|
||||
alignSelf={['flex-start']}
|
||||
justifyContent="space-between"
|
||||
height="100%"
|
||||
>
|
||||
<Flex flexDirection="column" alignItems="flex-end" justifyContent="flex-start" height="100%">
|
||||
<User />
|
||||
<Logout href="/logout">Выход</Logout>
|
||||
</Flex>
|
||||
|
||||
@ -7,6 +7,7 @@ import { Flex } from 'ui/grid';
|
||||
const HeaderContent = styled(Flex)`
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
padding: 14px 12px;
|
||||
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
@ -15,9 +16,7 @@ const HeaderContent = styled(Flex)`
|
||||
var(--color-tertiarty) 100%
|
||||
);
|
||||
|
||||
padding: 14px 12px;
|
||||
${min('laptop')} {
|
||||
padding: 14px 12px;
|
||||
padding-left: 20px;
|
||||
}
|
||||
`;
|
||||
|
||||
@ -5,6 +5,7 @@ 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';
|
||||
@ -33,8 +34,9 @@ const LogoText = styled.h3`
|
||||
const TagWrapper = styled.div`
|
||||
font-family: 'Montserrat';
|
||||
font-weight: 500;
|
||||
* {
|
||||
font-size: 0.7rem;
|
||||
|
||||
${min('tablet')} {
|
||||
margin: 0 5px;
|
||||
}
|
||||
`;
|
||||
|
||||
@ -42,12 +44,11 @@ const { COLOR_PRIMARY } = getColors();
|
||||
|
||||
const UnlimitedTag = observer(() => {
|
||||
const { $process } = useStore();
|
||||
|
||||
if ($process.has('Unlimited')) {
|
||||
return (
|
||||
<TagWrapper>
|
||||
<Tag color={COLOR_PRIMARY} style={{ margin: '0 5px' }}>
|
||||
без ограничений
|
||||
</Tag>
|
||||
<Tag color={COLOR_PRIMARY}>без ограничений</Tag>
|
||||
</TagWrapper>
|
||||
);
|
||||
}
|
||||
@ -59,9 +60,11 @@ function Logo() {
|
||||
return (
|
||||
<Flex flexDirection="column" alignItems="flex-start" justifyContent="space-between">
|
||||
<ImageWrapper>
|
||||
<Image priority className={styles.logo} alt="logo" src={logo} layout="responsive" />
|
||||
<Link prefetch={false} href="/">
|
||||
<Image priority className={styles.logo} alt="logo" src={logo} layout="responsive" />
|
||||
</Link>
|
||||
</ImageWrapper>
|
||||
<Flex justifyContent="space-between" alignItems="center">
|
||||
<Flex flexDirection={['column', 'row']} alignItems={[undefined, 'center']}>
|
||||
<LogoText>Лизинговый Калькулятор</LogoText>
|
||||
<UnlimitedTag />
|
||||
</Flex>
|
||||
|
||||
60
apps/web/Components/Layout/Menu.tsx
Normal file
60
apps/web/Components/Layout/Menu.tsx
Normal file
@ -0,0 +1,60 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
64
apps/web/Components/Layout/Navigation.jsx
Normal file
64
apps/web/Components/Layout/Navigation.jsx
Normal file
@ -0,0 +1,64 @@
|
||||
import { NavigationContext } from '@/context/navigation';
|
||||
import { useContext, useEffect } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { Flex } from 'ui/grid';
|
||||
|
||||
const Container = styled.div`
|
||||
background-color: white;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 10px;
|
||||
height: 46px;
|
||||
justify-content: space-around;
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
border-top: 1px solid rgba(5, 5, 5, 0.06);
|
||||
z-index: 999999;
|
||||
`;
|
||||
|
||||
const TabButton = styled.button`
|
||||
background: ${({ active }) => (active ? 'var(--color-primary)' : 'white')};
|
||||
color: ${({ active }) => (active ? 'white' : 'black')};
|
||||
border-radius: 2px 2px 0 0;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
font-size: 0.75rem;
|
||||
`;
|
||||
|
||||
export function NavigationBar() {
|
||||
const { currentTab, setCurrentTab, tabsList } = useContext(NavigationContext);
|
||||
|
||||
return (
|
||||
<Container>
|
||||
{tabsList.map(({ Icon, key, title }) => (
|
||||
<TabButton key={key} active={key === currentTab} onClick={() => setCurrentTab(key)}>
|
||||
<Flex flexDirection="column" alignItems="center">
|
||||
<Icon />
|
||||
{title}
|
||||
</Flex>
|
||||
</TabButton>
|
||||
))}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const Display = styled.div`
|
||||
display: ${(props) => (props.visible ? 'block' : 'none')};
|
||||
`;
|
||||
|
||||
export function Tabs({ tabs }) {
|
||||
const { currentTab, setTabsList } = useContext(NavigationContext);
|
||||
|
||||
useEffect(() => {
|
||||
setTabsList(tabs);
|
||||
}, [setTabsList, tabs]);
|
||||
|
||||
return tabs.map(({ Component, key }) => (
|
||||
<Display key={key} visible={key === currentTab}>
|
||||
<Component key={key} tabs />
|
||||
</Display>
|
||||
));
|
||||
}
|
||||
@ -1,11 +1,26 @@
|
||||
import Header from './Header';
|
||||
import { Flex } from 'ui/grid';
|
||||
import { AppMenu } from './Menu';
|
||||
import { max, min } from '@/styles/mq';
|
||||
import styled from 'styled-components';
|
||||
|
||||
export default function Layout({ children }) {
|
||||
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 }) {
|
||||
return (
|
||||
<Flex flexDirection="column">
|
||||
<>
|
||||
<Header />
|
||||
<main>{children}</main>
|
||||
</Flex>
|
||||
{user?.admin ? <AppMenu /> : false}
|
||||
<Main>{children}</Main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,18 +2,21 @@
|
||||
# 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 yarn global add turbo
|
||||
RUN yarn global add dotenv-cli
|
||||
RUN pnpm add -g turbo@1.12.4 dotenv-cli
|
||||
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
|
||||
@ -21,14 +24,33 @@ 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/yarn.lock ./yarn.lock
|
||||
RUN yarn install
|
||||
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
|
||||
|
||||
# Build the project
|
||||
COPY --from=builder /app/out/full/ .
|
||||
COPY turbo.json turbo.json
|
||||
COPY .env .env
|
||||
RUN yarn dotenv -e .env turbo run build --filter=web...
|
||||
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
|
||||
ARG URL_CRM_GRAPHQL_PROXY
|
||||
ARG URL_CRM_CREATEKP_DIRECT
|
||||
ARG URL_CRM_DOWNLOADKP_BASE
|
||||
ARG URL_CORE_FINGAP_DIRECT
|
||||
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...
|
||||
|
||||
FROM node:alpine AS runner
|
||||
WORKDIR /app
|
||||
@ -47,4 +69,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
|
||||
@ -1,30 +1,36 @@
|
||||
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 `pages/index.js`. The page auto-updates as you edit the file.
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
[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.
|
||||
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
|
||||
|
||||
## 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/foundations/about-nextjs) - an interactive Next.js tutorial.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - 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_source=github.com&utm_medium=referral&utm_campaign=turborepo-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_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
import type { RequestTransTax, ResponseTransTax } from './types';
|
||||
import getUrls from '@/config/urls';
|
||||
import { withHandleError } from '@/utils/axios';
|
||||
import type { QueryFunctionContext } from '@tanstack/react-query';
|
||||
import axios from 'axios';
|
||||
|
||||
const { URL_1C_TRANSTAX } = getUrls();
|
||||
|
||||
export async function getTransTax(payload: RequestTransTax, { signal }: QueryFunctionContext) {
|
||||
const { data } = await axios.post<ResponseTransTax>(URL_1C_TRANSTAX, payload, { signal });
|
||||
|
||||
return data;
|
||||
export function getTransTax(payload: RequestTransTax, { signal }: QueryFunctionContext) {
|
||||
return withHandleError(
|
||||
axios.post<ResponseTransTax>(URL_1C_TRANSTAX, payload, { signal }).then(({ data }) => data)
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
export type RequestTransTax = {
|
||||
CalcDate: string;
|
||||
CarCategory: string;
|
||||
OKTMO: string;
|
||||
calcDate: Date;
|
||||
carCategory: string;
|
||||
power: number;
|
||||
year: number;
|
||||
Power: number;
|
||||
Year: number;
|
||||
};
|
||||
export type ResponseTransTax = {
|
||||
error: string;
|
||||
tax: number;
|
||||
Error: string;
|
||||
Tax: number;
|
||||
TaxRate: number;
|
||||
};
|
||||
|
||||
42
apps/web/api/cache/query.ts
vendored
Normal file
42
apps/web/api/cache/query.ts
vendored
Normal file
@ -0,0 +1,42 @@
|
||||
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);
|
||||
}
|
||||
3
apps/web/api/cache/types.ts
vendored
Normal file
3
apps/web/api/cache/types.ts
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
import type { QueryItem } from 'shared/types/cache';
|
||||
|
||||
export type ResponseQueries = Record<string, QueryItem>;
|
||||
@ -1,21 +1,23 @@
|
||||
import type { RequestCalculate, RequestFinGAP, ResponseCalculate, ResponseFinGAP } from './types';
|
||||
import getUrls from '@/config/urls';
|
||||
import { withHandleError } from '@/utils/axios';
|
||||
import type { QueryFunctionContext } from '@tanstack/react-query';
|
||||
import axios from 'axios';
|
||||
|
||||
const { URL_CORE_FINGAP, URL_CORE_CALCULATE } = getUrls();
|
||||
|
||||
export async function calculateFinGAP(payload: RequestFinGAP, { signal }: QueryFunctionContext) {
|
||||
const { data } = await axios.post<ResponseFinGAP>(URL_CORE_FINGAP, payload, {
|
||||
signal,
|
||||
});
|
||||
|
||||
return data;
|
||||
return withHandleError(
|
||||
axios
|
||||
.post<ResponseFinGAP>(URL_CORE_FINGAP, payload, {
|
||||
signal,
|
||||
})
|
||||
.then(({ data }) => data)
|
||||
);
|
||||
}
|
||||
|
||||
export async function calculate(payload: RequestCalculate): Promise<ResponseCalculate> {
|
||||
return await axios
|
||||
.post<ResponseCalculate>(URL_CORE_CALCULATE, payload)
|
||||
.then((response) => response.data)
|
||||
.catch((error) => error.response.data);
|
||||
export async function calculate(payload: RequestCalculate) {
|
||||
return withHandleError(
|
||||
axios.post<ResponseCalculate>(URL_CORE_CALCULATE, payload).then(({ data }) => data)
|
||||
);
|
||||
}
|
||||
|
||||
@ -44,6 +44,7 @@ export const PreparedValuesSchema = z.object({
|
||||
firstPaymentSum: z.number(),
|
||||
firstPaymentWithNdsAbs: z.number(),
|
||||
fuelCardSum: z.number(),
|
||||
fundingRate: z.number(),
|
||||
gpsCostPaymentSum: z.number(),
|
||||
iRR_MSFO_Plan: z.number(),
|
||||
importProgramSum: z.number(),
|
||||
@ -110,6 +111,7 @@ export const PreparedValuesSchema = z.object({
|
||||
transTax: z.number(),
|
||||
transportTaxGr: z.number(),
|
||||
transportTaxGrYear: z.number(),
|
||||
typeRepayment: z.number(),
|
||||
});
|
||||
|
||||
export type PreparedValues = z.infer<typeof PreparedValuesSchema>;
|
||||
@ -398,6 +400,7 @@ const ColumnsSchema = z.object({
|
||||
values: z.number().array(),
|
||||
}),
|
||||
sumRepaymentColumn: z.object({
|
||||
pi: z.number(),
|
||||
values: z.number().array(),
|
||||
}),
|
||||
sumVATCreditColumn: z.object({
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import type { RequestCreateKP, ResponseCreateKP } from './types';
|
||||
import getUrls from '@/config/urls';
|
||||
import { withHandleError } from '@/utils/axios';
|
||||
import axios from 'axios';
|
||||
|
||||
const { URL_CRM_CREATEKP } = getUrls();
|
||||
|
||||
export async function createKP(payload: RequestCreateKP): Promise<ResponseCreateKP> {
|
||||
return await axios
|
||||
.post(URL_CRM_CREATEKP, payload)
|
||||
.then((response) => ({ ...response.data, success: true }))
|
||||
.catch((error) => ({ ...error.response.data, success: false }));
|
||||
export async function createKP(payload: RequestCreateKP) {
|
||||
return withHandleError(
|
||||
axios.post<ResponseCreateKP>(URL_CRM_CREATEKP, payload).then(({ data }) => data)
|
||||
);
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ import ValuesSchema from '@/config/schema/values';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const RequestCreateKPSchema = z.object({
|
||||
__info: z.record(z.any()).optional(),
|
||||
calculation: z
|
||||
.object({
|
||||
calculationValues: ValuesSchema,
|
||||
@ -31,21 +32,13 @@ export const RequestCreateKPSchema = z.object({
|
||||
|
||||
export type RequestCreateKP = z.infer<typeof RequestCreateKPSchema>;
|
||||
|
||||
export const ResponseCreateKPSchema = z.union([
|
||||
z.object({
|
||||
evo_quotename: z.string(),
|
||||
link: z.string(),
|
||||
name: z.string(),
|
||||
offerprintform: z.string(),
|
||||
offerprintformapi: z.string(),
|
||||
quoteid: z.string(),
|
||||
success: z.literal(true),
|
||||
}),
|
||||
z.object({
|
||||
fullMessage: z.string(),
|
||||
message: z.string(),
|
||||
success: z.literal(false),
|
||||
}),
|
||||
]);
|
||||
export const ResponseCreateKPSchema = z.object({
|
||||
evo_quotename: z.string(),
|
||||
link: z.string(),
|
||||
name: z.string(),
|
||||
offerprintform: z.string(),
|
||||
offerprintformapi: z.string(),
|
||||
quoteid: z.string(),
|
||||
});
|
||||
|
||||
export type ResponseCreateKP = z.infer<typeof ResponseCreateKPSchema>;
|
||||
|
||||
@ -1,22 +1,23 @@
|
||||
import type * as ELT from './types';
|
||||
import getUrls from '@/config/urls';
|
||||
import type { QueryFunctionContext } from '@tanstack/react-query';
|
||||
import { TIMEOUT } from '@/constants/request';
|
||||
import { withHandleError } from '@/utils/axios';
|
||||
import axios from 'axios';
|
||||
|
||||
const { URL_ELT_KASKO, URL_ELT_OSAGO } = getUrls();
|
||||
|
||||
export async function getEltOsago(
|
||||
payload: ELT.RequestEltOsago,
|
||||
{ signal }: QueryFunctionContext
|
||||
): Promise<ELT.ResponseEltOsago> {
|
||||
return await axios
|
||||
.post<ELT.ResponseEltOsago>(URL_ELT_OSAGO, payload, { signal })
|
||||
.then((response) => response.data)
|
||||
.catch((error) => error.response.data);
|
||||
export async function getEltOsago(payload: ELT.RequestEltOsago) {
|
||||
return withHandleError(
|
||||
axios
|
||||
.post<ELT.ResponseEltOsago>(URL_ELT_OSAGO, payload, { timeout: TIMEOUT })
|
||||
.then(({ data }) => data)
|
||||
);
|
||||
}
|
||||
|
||||
export async function getEltKasko(payload: ELT.RequestEltKasko, { signal }: QueryFunctionContext) {
|
||||
const { data } = await axios.post<ELT.ResponseEltKasko>(URL_ELT_KASKO, payload, { signal });
|
||||
|
||||
return data;
|
||||
export async function getEltKasko(payload: ELT.RequestEltKasko) {
|
||||
return withHandleError(
|
||||
axios
|
||||
.post<ELT.ResponseEltKasko>(URL_ELT_KASKO, payload, { timeout: TIMEOUT })
|
||||
.then(({ data }) => data)
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import { love } from './tools';
|
||||
import type { User } from './types';
|
||||
import getUrls from '@/config/urls';
|
||||
import { withHandleError } from '@/utils/axios';
|
||||
import type { AxiosRequestConfig } from 'axios';
|
||||
import axios from 'axios';
|
||||
|
||||
const { URL_GET_USER } = getUrls();
|
||||
|
||||
export async function getUser(config?: AxiosRequestConfig) {
|
||||
return await axios.get<User>(URL_GET_USER, config).then((res) => love(res.data));
|
||||
return withHandleError(axios.get<User>(URL_GET_USER, config).then((res) => love(res.data)));
|
||||
}
|
||||
|
||||
@ -1,20 +1,24 @@
|
||||
import { link } from '@/config/apollo';
|
||||
import { createLink } from './link';
|
||||
import { ApolloClient, InMemoryCache } from '@apollo/client';
|
||||
import { isServer } from 'tools/common';
|
||||
|
||||
/** @type {import('@apollo/client').ApolloClient<import('@apollo/client').NormalizedCacheObject>} */
|
||||
let apolloClient;
|
||||
|
||||
function createApolloClient() {
|
||||
function createApolloClient(headers) {
|
||||
return new ApolloClient({
|
||||
cache: new InMemoryCache(),
|
||||
link,
|
||||
link: createLink(headers),
|
||||
ssrMode: isServer(),
|
||||
});
|
||||
}
|
||||
|
||||
export default function initializeApollo(initialState = null) {
|
||||
const _apolloClient = apolloClient ?? createApolloClient();
|
||||
export default function initializeApollo(initialState, headers) {
|
||||
if (isServer() && !headers) {
|
||||
throw new Error('initializeApollo: headers must be provided in server side');
|
||||
}
|
||||
|
||||
const _apolloClient = apolloClient ?? createApolloClient(headers);
|
||||
|
||||
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
|
||||
// gets hydrated here
|
||||
|
||||
133
apps/web/apollo/link.js
Normal file
133
apps/web/apollo/link.js
Normal file
@ -0,0 +1,133 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { message } from '@/Components/Common/Notification';
|
||||
import { publicRuntimeConfigSchema } from '@/config/schema/runtime-config';
|
||||
import getUrls from '@/config/urls';
|
||||
import { ApolloLink, from, HttpLink } from '@apollo/client';
|
||||
import { setContext } from '@apollo/client/link/context';
|
||||
import { onError } from '@apollo/client/link/error';
|
||||
import { getCurrentScope } from '@sentry/nextjs';
|
||||
import getConfig from 'next/config';
|
||||
import { isServer } from 'tools';
|
||||
|
||||
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]);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user