Merge branch 'staging' into preprod

This commit is contained in:
Maxime Lalo 2023-05-11 19:12:22 +02:00
commit bdd611b814
116 changed files with 13478 additions and 2817 deletions

View File

@ -43,7 +43,7 @@ jobs:
name: Deploy
command: >
helm upgrade
lecoffre-back devops/ -i -f devops/<<parameters.env>>.values.yaml
lecoffre-back devops/ -i -f devops/values.yaml
-n lecoffre
--create-namespace
--set lecoffreBack.image.repository='rg.fr-par.scw.cloud/lecoffre/back'

7
.env.test Normal file
View File

@ -0,0 +1,7 @@
DATABASE_URL="postgresql://prisma:prisma@localhost:5433/tests"
DATABASE_PORT="5433"
DATABASE_USER="prisma"
DATABASE_PASSWORD="prisma"
DATABASE_NAME="tests"
DATABASE_HOSTNAME="localhost"
DEV_PRISMA_STUDIO_DB_URL="postgresql://prisma:prisma@localhost:5433/tests"

View File

@ -25,7 +25,6 @@ COPY --from=deps leCoffre/package.json package.json
COPY tsconfig.json tsconfig.json
COPY src src
COPY src/common/databases/schema.prisma ./src/common/databases/schema.prisma
RUN npx prisma generate
RUN npm run build
@ -39,8 +38,9 @@ RUN adduser -D lecoffreuser --uid 10000 && chown -R lecoffreuser .
COPY --from=builder --chown=lecoffreuser leCoffre/node_modules ./node_modules
COPY --from=builder --chown=lecoffreuser leCoffre/dist dist
COPY --from=builder --chown=lecoffreuser leCoffre/package.json ./package.json
COPY --from=builder --chown=lecoffreuser leCoffre/src/common/databases ./src/common/databases
USER lecoffreuser
CMD ["npm", "run", "api:start"]
CMD ["npm", "run", "start"]
EXPOSE 3001

View File

@ -4,7 +4,7 @@
### A. Docker Launch application
#### 1) Local RSA Key for docker build
1) Create a file named : `id_rsa` in /src
1) Create a file named : `id_rsa` in /src/.ssh
2) Get the RSA Private key on Keeper who is allowed to read the `leCoffre-ressources repo`
3) You can find Key on Keeper inside the folder **LeCoffre project > SSH Key**
4) Copy past in the `id_rsa` that you created step 1
@ -16,15 +16,11 @@
#### 2) Build images
###### a- Back end
`docker build -t "le-coffre-back" -f Dockerfiles/Dockerfile.api .`
`docker build -t "le-coffre-back" -f Dockerfile .`
###### b- Front end
`docker build -t "le-coffre-front" -f Dockerfiles/Dockerfile.front .`
`docker build -t "le-coffre-front" -f Dockerfile .`
#### 3) Docker Run
`docker run --env-file .env -p 3000:3000 le-coffre-back`
#### 4) Docker Compose
#### 3) Docker Compose
Docker compose allow to launch multiples images
1) **le-coffre-front**
@ -33,4 +29,6 @@ Docker compose allow to launch multiples images
> Launch your docker container with following command :
`docker compose up` -> Logs in terminal
`docker compose up -d`

View File

@ -21,5 +21,5 @@ version: 0.0.1
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
# It is recommended to use it with quotes.
appVersion: 0.4.4
appVersion: 0.5.6

44
devops/values.yaml Normal file
View File

@ -0,0 +1,44 @@
dockerPullSecret: secret/data/minteed-stg/config/dockerpullsecret
namespace: lecoffre
lecoffreBack:
serviceAccountName: lecoffre-back-sa
command: "'sh', '-c', '. /vault/secrets/envs-api && npm run api:start'"
vault:
role : custom_lecoffre-back_injector_rol
server: https://vault-stg.smart-chain.fr
annotations:
vault.hashicorp.com/agent-pre-populate-only: "true"
vault.hashicorp.com/agent-inject: "true"
vault.hashicorp.com/agent-inject-secret-envs-api: secret/data/lecoffre-back-stg/config/envs-api
vault.hashicorp.com/role: custom_lecoffre-back_injector_rol
vault.hashicorp.com/agent-inject-template-envs-api: |
{{ with secret "secret/data/lecoffre-back-stg/config/envs-api" }}
{{ range $k, $v := .Data.data }}
export {{ $k }}="{{ $v }}"
{{ end }}
{{ end }}
imagePullSecrets:
- name: docker-pull-secret
image:
pullPolicy: Always
repository: "rg.fr-par.scw.cloud/lecoffre/back"
resources:
requests:
cpu: 200m
memory: 1Gi
limits:
memory: 2Gi
ingress:
host: api.stg.lecoffre.smart-chain.fr
tls:
hosts:
- api.stg.lecoffre.smart-chain.fr
secretName: api-tls
annotations:
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt-prod
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"

12
docker-compose-test.yml Normal file
View File

@ -0,0 +1,12 @@
version: "3.8"
services:
db:
image: postgres:13
restart: always
container_name: integration-tests-prisma
ports:
- '5433:5432'
environment:
POSTGRES_USER: prisma
POSTGRES_PASSWORD: prisma
POSTGRES_DB: tests

View File

@ -7,17 +7,27 @@ services:
front-end:
image: "le-coffre-front"
ports:
- 3000:${FRONT_PORT}
- ${FRONT_PORT}:${FRONT_PORT}
environment:
- FRONT_PORT
- BACK_API_PROTOCOL
- BACK_API_HOST
- BACK_API_PORT
- BACK_API_ROOT_URL
- BACK_API_VERSION
- FRONT_APP_HOST
- FRONT_APP_PORT
- IDNOT_AUTHORIZE_ENDPOINT
- IDNOT_CLIENT_ID
backend:
image: "le-coffre-back"
ports:
- 3001:${APP_PORT}
- ${APP_PORT}:${APP_PORT}
environment:
- DATABASE_HOSTNAME
- DATABASE_HOST
- DATABASE_PORT
- DATABASE_USER
- DATABASE_USERNAME
- DATABASE_PASSWORD
- DATABASE_NAME
- APP_LABEL
@ -25,17 +35,21 @@ services:
- APP_ROOT_URL
- API_ROOT_URL
- DEV_PRISMA_STUDIO_DB_URL
- IDNOT_CONNEXION_URL
- IDNOT_CLIENT_ID
- IDNOT_CLIENT_SECRET
- IDNOT_REDIRECT_URL
postgres:
image: postgres
image: postgres:11
restart: always
environment:
- DATABASE_HOSTNAME
- DATABASE_PORT
- DATABASE_USER
- DATABASE_PASSWORD
- DATABASE_NAME
- POSTGRES_USER
- POSTGRES_PASSWORD
- POSTGRES_DB
- DATABASE_USERNAME
- DATABASE_PASSWORD
- DATABASE_NAME=${DATABASE_NAME}
ports:
- ${DATABASE_PORT}:5432
volumes:
@ -43,7 +57,11 @@ services:
- ./init-data.sh:/docker-entrypoint-initdb.d/init-data.sh
healthcheck:
test: ["CMD-SHELL", "pg_isready -h localhost -U ${DATABASE_USER} -d ${DATABASE_NAME}"]
test:
[
"CMD-SHELL",
"pg_isready -h localhost -U ${POSTGRES_USER} -d ${POSTGRES_DB}",
]
interval: 5s
timeout: 5s
retries: 10

16
init-data.sh Executable file
View File

@ -0,0 +1,16 @@
#!/bin/bash
set -e;
# Make sure this script doesn't encounter any errors while building the docker container for the first time
# Carriage returns might be a problem (the first line #!/bin/bash will create an error)
# On Windows Docker Desktop i had to use the following command (in linux env):
# $ sed -i -e 's/\r$//' init-data.sh
if [ -n "${DATABASE_USERNAME:-}" ] && [ -n "${DATABASE_PASSWORD:-}" ]; then
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER ${DATABASE_USERNAME} WITH PASSWORD '${DATABASE_PASSWORD}';
ALTER USER ${DATABASE_USERNAME} CREATEDB;
EOSQL
else
echo "SETUP INFO: No Environment variables given!"
fi

19
jest.config.js Normal file
View File

@ -0,0 +1,19 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
"moduleNameMapper": {
"@Services/(.*)": "<rootDir>/src/services/$1",
"@App/(.*)": "<rootDir>/src/app/$1",
"@Api/(.*)": "<rootDir>/src/app/api/$1",
"@Pages/(.*)": "<rootDir>/src/pages/$1",
"@Common/(.*)": "<rootDir>/src/common/$1",
"@Repositories/(.*)": "<rootDir>/src/common/repositories/$1",
"@Entries/(.*)": "<rootDir>/src/common/entries/$1",
"@Config/(.*)": "<rootDir>/src/common/config/$1",
"@Entities/(.*)": "<rootDir>/src/common/entities/$1",
"@System/(.*)": "<rootDir>/src/common/system/$1",
"@ControllerPattern/(.*)": "<rootDir>/src/common/system/controller-pattern/$1",
"@Test/(.*)": "<rootDir>/src/test/$1"
}
};

5712
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,17 +13,21 @@
"@Config": "./dist/common/config",
"@Entities": "./dist/common/entities",
"@System": "./dist/common/system",
"@ControllerPattern": "./dist/common/system/controller-pattern"
"@ControllerPattern": "./dist/common/system/controller-pattern",
"@Test": "./dist/test"
},
"scripts": {
"build-db": "npx prisma migrate dev",
"build": "tsc",
"api:start": "npm run migrate && node ./dist/entries/App.js",
"start": "tsc && npm run api:start",
"start": "node ./dist/entries/App.js",
"api:start": "npm run migrate && npm run start",
"dev": "nodemon -V",
"api:dev": "nodemon -V --exec 'tsc && npm run api:start'",
"build:test": "tsc && mocha ./dist/entries/Test.js",
"format": "prettier --write src",
"migrate": "npx prisma migrate deploy"
"migrate:test": "dotenv -e .env.test -- npx prisma migrate deploy",
"migrate": "npx prisma migrate deploy",
"docker:up:test": "docker-compose -f docker-compose-test.yml up -d",
"docker:down:test": "docker-compose down",
"test": "tsc && npm run docker:up:test && npm run migrate:test && dotenv -e .env.test -- jest -i --verbose ./dist/test/* && npm run docker:down:test"
},
"repository": {
"type": "git",
@ -36,16 +40,17 @@
},
"homepage": "https://github.com/smart-chain-fr/leCoffre-back#readme",
"dependencies": {
"@prisma/client": "^4.9.0",
"axios": "^1.3.3",
"@pinata/sdk": "^2.1.0",
"@prisma/client": "^4.11.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"classnames": "^2.3.2",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"le-coffre-ressources": "github.com:smart-chain-fr/leCoffre-resources.git",
"jsonwebtoken": "^9.0.0",
"le-coffre-resources": "git@github.com:smart-chain-fr/leCoffre-resources.git#v2.47",
"module-alias": "^2.2.2",
"multer": "^1.4.5-lts.1",
"next": "^13.1.5",
"node-cache": "^5.1.2",
"node-schedule": "^2.1.1",
@ -55,19 +60,27 @@
"tslib": "^2.4.1",
"typedi": "^0.10.0",
"typescript": "^4.9.4",
"uuid": "^9.0.0"
"uuid": "^9.0.0",
"uuidv4": "^6.2.13"
},
"devDependencies": {
"@types/cors": "^2.8.13",
"@types/express": "^4.17.16",
"@types/jest": "^29.5.0",
"@types/jsonwebtoken": "^9.0.1",
"@types/multer": "^1.4.7",
"@types/node": "^18.11.18",
"@types/node-schedule": "^2.1.0",
"@types/uuid": "^9.0.0",
"dotenv": "^16.0.3",
"jest": "^29.5.0",
"nodemon": "^2.0.20",
"prettier": "2.8.4",
"prisma": "^4.11.0"
"prisma": "^4.11.0",
"ts-jest": "^29.0.5"
},
"prisma": {
"schema": "src/common/databases/schema.prisma"
"schema": "src/common/databases/schema.prisma",
"seed": "ts-node src/common/databases/seeders/seeder2.ts"
}
}

View File

@ -6,12 +6,9 @@ import ApiController from "@Common/system/controller-pattern/ApiController";
@Controller()
@Service()
export default class HomeController extends ApiController {
@Get("/")
protected async get(req: Request, res: Response) {
// const query = processFindManyQuery(req.query);
this.httpSuccess(res, "Welcome to the home page!");
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import CustomersService from "@Services/CustomersService/CustomersService";
import { Service } from "typedi";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class CustomersController extends ApiController {
constructor(private customersService: CustomersService) {
super();
}
/**
* @description Get all customers
* @returns ICustomer[] list of customers
*/
@Get("/api/customers")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.customersService.get());
}
/**
* @description Create a new customer
* @returns ICustomer created
*/
@Post("/api/customers")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.customersService.create());
}
/**
* @description Modify a specific customer by uid
* @returns ICustomer modified
*/
@Put("/api/customers/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.customersService.put());
}
/**
* @description Get a specific customer by uid
* @returns ICustomer
*/
@Get("/api/customers/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.customersService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DeedTypesService from "@Services/DeedTypesService/DeedTypesService";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class DeedTypesController extends ApiController {
constructor(private deedTypesService: DeedTypesService) {
super();
}
/**
* @description Get all deedtypes
* @returns IDeedtype[] list of deedtypes
*/
@Get("/api/deed-types")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedTypesService.get());
}
/**
* @description Create a new deedtype
* @returns IDeedtype created
*/
@Post("/api/deed-types")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedTypesService.create());
}
/**
* @description Modify a specific deedtype by uid
* @returns IDeedtype modified
*/
@Put("/api/deed-types/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedTypesService.put());
}
/**
* @description Get a specific deedtype by uid
* @returns IDeedtype
*/
@Get("/api/deed-types/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedTypesService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import DeedsService from "@Services/DeedsService/DeedsService";
import { Service } from "typedi";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class DeedsController extends ApiController {
constructor(private deedsService: DeedsService) {
super();
}
/**
* @description Get all deeds
* @returns IDeed[] list of deeds
*/
@Get("/api/deeds")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedsService.get());
}
/**
* @description Create a new deed
* @returns IDeed created
*/
@Post("/api/deeds")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedsService.create());
}
/**
* @description Modify a specific deed by uid
* @returns IDeed modified
*/
@Put("/api/deeds/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedsService.put());
}
/**
* @description Get a specific deed by uid
* @returns IDeed
*/
@Get("/api/deeds/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.deedsService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DocumentTypesService from "@Services/DocumentTypesService/DocumentTypesService";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class DocumentTypesController extends ApiController {
constructor(private documentTypesService: DocumentTypesService) {
super();
}
/**
* @description Get all document-types
* @returns IFolder[] list of document-types
*/
@Get("/api/document-types")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentTypesService.get());
}
/**
* @description Create a new documentType
* @returns IFolder created
*/
@Post("/api/document-types")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentTypesService.create());
}
/**
* @description Modify a specific documentType by uid
* @returns IFolder modified
*/
@Put("/api/document-types/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentTypesService.put());
}
/**
* @description Get a specific documentType by uid
* @returns IFolder
*/
@Get("/api/document-types/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentTypesService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DocumentsService from "@Services/DocumentsService/DocumentsService";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class DocumentsController extends ApiController {
constructor(private documentsService: DocumentsService) {
super();
}
/**
* @description Get all documents
* @returns IDocument[] list of documents
*/
@Get("/api/documents")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentsService.get());
}
/**
* @description Create a new document
* @returns IDocument created
*/
@Post("/api/documents")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentsService.create());
}
/**
* @description Modify a specific document by uid
* @returns IDocument modified
*/
@Put("/api/documents/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentsService.put());
}
/**
* @description Get a specific document by uid
* @returns IDocument
*/
@Get("/api/documents/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.documentsService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import FoldersService from "@Services/FoldersService/FoldersService";
import { Service } from "typedi";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class FolderController extends ApiController {
constructor(private foldersService: FoldersService) {
super();
}
/**
* @description Get all folders
* @returns IFolder[] list of folders
*/
@Get("/api/folders")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.foldersService.get());
}
/**
* @description Create a new folder
* @returns IFolder created
*/
@Post("/api/folders")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.foldersService.create());
}
/**
* @description Modify a specific folder by uid
* @returns IFolder modified
*/
@Put("/api/folders/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.foldersService.put());
}
/**
* @description Get a specific folder by uid
* @returns IFolder
*/
@Get("/api/folders/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.foldersService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import OfficesService from "@Services/OfficesService/OfficesService";
import { Service } from "typedi";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class OfficesController extends ApiController {
constructor(private officesService: OfficesService) {
super();
}
/**
* @description Get all offices
* @returns IOffice[] list of offices
*/
@Get("/api/offices")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.officesService.get());
}
/**
* @description Create a new office
* @returns IOffice created
*/
@Post("/api/offices")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.officesService.create());
}
/**
* @description Modify a specific office by uid
* @returns IOffice modified
*/
@Put("/api/offices/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.officesService.put());
}
/**
* @description Get a specific office by uid
* @returns IOffice
*/
@Get("/api/offices/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.officesService.getByUid("uid"));
}
}

View File

@ -1,81 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import UsersService from "@Services/UsersService/UsersService";
import { Service } from "typedi";
// import { IsNotEmpty, IsString, IsUUID } from "class-validator";
// class Params {
// @IsString()
// @IsNotEmpty()
// @IsUUID()
// public uuid!: string;
// }
@Controller()
@Service()
export default class UsersController extends ApiController {
constructor(private usersService: UsersService) {
super();
}
/**
* @description Get all users
* @returns IUser[] list of users
*/
@Get("/api/users")
protected async get(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.usersService.get());
}
/**
* @description Create a new user
* @returns IUser created
*/
@Post("/api/users")
protected async post(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.usersService.create());
}
/**
* @description Modify a specific user by uid
* @returns IUser modified
*/
@Put("/api/users/:uid")
protected async put(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.usersService.put());
}
/**
* @description Get a specific user by uid
* @returns IUser
*/
@Get("/api/users/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
// TODO
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.usersService.getByUid("uid"));
}
}

View File

@ -0,0 +1,158 @@
import { Response, Request } from "express";
import { Controller, Delete, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DocumentsService from "@Services/customer/DocumentsService/DocumentsService";
import { Documents } from "@prisma/client";
import { Document } from "le-coffre-resources/dist/Customer";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class DocumentsController extends ApiController {
constructor(private documentsService: DocumentsService) {
super();
}
/**
* @description Get all documents
* @returns IDocument[] list of documents
*/
@Get("/api/v1/customer/documents")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity: Documents[] = await this.documentsService.get(query);
//Hydrate ressource with prisma entity
const documents = Document.map<Document>(Document, prismaEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, documents);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new document
* @returns IDocument created
*/
@Post("/api/v1/customer/documents")
protected async post(req: Request, response: Response) {
try {
//init Document resource with request body values
const documentEntity = Document.hydrate<Document>(req.body);
//validate document
await validateOrReject(documentEntity, { groups: ["createDocument"] });
//call service to get prisma entity
const prismaEntityCreated = await this.documentsService.create(documentEntity);
//Hydrate ressource with prisma entity
const documentEntityCreated = Document.hydrate<Document>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, documentEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Update a specific document
*/
@Put("/api/v1/customer/documents/:uid")
protected async update(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init Document resource with request body values
const documentEntity = new Document();
Document.hydrate(documentEntity, req.body);
//validate document
await validateOrReject(documentEntity, { groups: ["createDocument"] });
//call service to get prisma entity
const prismaEntityUpdated: Documents = await this.documentsService.update(uid, documentEntity);
//Hydrate ressource with prisma entity
const document = Document.hydrate<Document>(prismaEntityUpdated, { strategy: "excludeAll" });
//success
this.httpSuccess(response, document);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Delete a specific document
*/
@Delete("/api/v1/customer/documents/:uid")
protected async delete(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//call service to get prisma entity
const documentEntity: Documents = await this.documentsService.delete(uid);
//Hydrate ressource with prisma entity
const document = Document.hydrate<Document>(documentEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, document);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific document by uid
*/
@Get("/api/v1/customer/documents/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let documentEntity: Documents;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
documentEntity = await this.documentsService.getByUid(uid, query);
} else {
//call service to get prisma entity
documentEntity = await this.documentsService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const document = Document.hydrate<Document>(documentEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, document);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,32 @@
import { Response, Request } from "express";
import { Controller,Post } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import AuthService from "@Services/private-services/AuthService/AuthService";
//import User from "le-coffre-resources/dist/Notary";
@Controller()
@Service()
export default class UserInfoController extends ApiController {
constructor(private authService: AuthService) {
super();
}
/**
* @description Get user created from IdNot authentification
* @returns User
*/
@Post("/api/v1/idnot-user/:code")
protected async getUserInfosFromIdnot(req: Request, response: Response) {
try {
const code = req.params["code"];
const user = await this.authService.getUserFromIdNotTokens(code!);
//success
this.httpSuccess(response, user);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -1,18 +0,0 @@
import { type Response, type Request } from "express";
import { Controller, Get } from "@ControllerPattern/index";
import { Service } from "typedi";
import ApiController from "@Common/system/controller-pattern/ApiController";
@Controller()
@Service()
export default class ProjectController extends ApiController {
@Get("/api/projects/users")
protected async get(req: Request, res: Response) {
// const query = processFindManyQuery(req.query);
this.httpSuccess(res, { message: "get" });
}
}

View File

@ -0,0 +1,129 @@
import { Response, Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import CustomersService from "@Services/super-admin/CustomersService/CustomersService";
import { Service } from "typedi";
import { Customer } from "le-coffre-resources/dist/SuperAdmin";
import { Customers } from "@prisma/client";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class CustomersController extends ApiController {
constructor(private customersService: CustomersService) {
super();
}
/**
* @description Get all customers
*/
@Get("/api/v1/super-admin/customers")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const customersEntity = await this.customersService.get(query);
//Hydrate ressource with prisma entity
const customers = Customer.map<Customer>(Customer, customersEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, customers);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new customer
*/
@Post("/api/v1/super-admin/customers")
protected async post(req: Request, response: Response) {
try {
//init IUser resource with request body values
const customerEntity = Customer.hydrate<Customer>(req.body);
//validate user
await validateOrReject(customerEntity, { groups: ["createCustomer"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityCreated = await this.customersService.create(customerEntity);
//Hydrate ressource with prisma entity
const customerEntityCreated = Customer.hydrate<Customer>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, customerEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific customer by uid
*/
@Put("/api/v1/super-admin/customers/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init IUser resource with request body values
const customerEntity = Customer.hydrate<Customer>(req.body);
//validate user
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityUpdated = await this.customersService.update(uid, customerEntity);
//Hydrate ressource with prisma entity
const customerEntityUpdated = Customer.hydrate<Customer>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, customerEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific customer by uid
*/
@Get("/api/v1/super-admin/customers/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let customerEntity: Customers;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
customerEntity = await this.customersService.getByUid(uid, query);
} else {
//call service to get prisma entity
customerEntity = await this.customersService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const customer = Customer.hydrate<Customer>(customerEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, customer);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,134 @@
import { Response, Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DeedTypesService from "@Services/super-admin/DeedTypesService/DeedTypesService";
import { DeedTypes } from "@prisma/client";
import { DeedType } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class DeedTypesController extends ApiController {
constructor(private deedTypesService: DeedTypesService) {
super();
}
/**
* @description Get all deedtypes
* @returns Deedtype[] list of deedtypes
*/
@Get("/api/v1/super-admin/deed-types")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity: DeedTypes[] = await this.deedTypesService.get(query);
//Hydrate ressource with prisma entity
const DeedTypes = DeedType.map<DeedType>(DeedType, prismaEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, DeedTypes);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new deedtype
* @returns Deedtype created
*/
@Post("/api/v1/super-admin/deed-types")
protected async post(req: Request, response: Response) {
try {
//init DeedType resource with request body values
const deedTypeEntity = DeedType.hydrate<DeedType>(req.body);
//validate deed type
await validateOrReject(deedTypeEntity, { groups: ["createDeedType"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityCreated = await this.deedTypesService.create(deedTypeEntity);
//Hydrate ressource with prisma entity
const deedTypeEntityCreated = DeedType.hydrate<DeedType>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, deedTypeEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific deedtype by uid
* @returns Deedtype modified
*/
@Put("/api/v1/super-admin/deed-types/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init DeedType resource with request body values
const deedTypeEntity = DeedType.hydrate<DeedType>(req.body);
//validate deed type
await validateOrReject(deedTypeEntity, { groups: ["updateDeedType"] });
//call service to get prisma entity
const prismaEntityUpdated = await this.deedTypesService.update(uid, deedTypeEntity);
//Hydrate ressource with prisma entity
const deedTypeEntityUpdated = DeedType.hydrate<DeedType>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, deedTypeEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific deedtype by uid
* @returns IDeedtype
*/
@Get("/api/v1/super-admin/deed-types/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let deedTypeEntity: DeedTypes;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
deedTypeEntity = await this.deedTypesService.getByUid(uid, query);
} else {
//call service to get prisma entity
deedTypeEntity = await this.deedTypesService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const deedType = DeedType.hydrate<DeedType>(deedTypeEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, deedType);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,104 @@
import { Response, Request } from "express";
import { Controller, Get, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import DeedsService from "@Services/super-admin/DeedsService/DeedsService";
import { Service } from "typedi";
import { Deeds } from "@prisma/client";
import { Deed } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class DeedsController extends ApiController {
constructor(private deedsService: DeedsService) {
super();
}
/**
* @description Get all deeds
* @returns Deed[] list of deeds
*/
@Get("/api/v1/super-admin/deeds")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity: Deeds[] = await this.deedsService.get(query);
//Hydrate ressource with prisma entity
const deeds = Deed.map<Deed>(Deed, prismaEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, deeds);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific deed by uid
* @returns Deed
*/
@Get("/api/v1/super-admin/deeds/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let deedEntity: Deeds;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
deedEntity = await this.deedsService.getByUid(uid, query);
} else {
//call service to get prisma entity
deedEntity = await this.deedsService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const deed = Deed.hydrate<Deed>(deedEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, deed);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific deed by uid
*/
@Put("/api/v1/super-admin/deeds/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init OfficeFolder resource with request body values
const deedEntity = Deed.hydrate<Deed>(req.body);
//validate folder
await validateOrReject(deedEntity, { groups: ["updateDeed"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityUpdated = await this.deedsService.update(uid, deedEntity);
//Hydrate ressource with prisma entity
const deedEntityUpdated = Deed.hydrate<Deed>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, deedEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,130 @@
import { Response, Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService";
import { DocumentTypes } from "@prisma/client";
import ObjectHydrate from "@Common/helpers/ObjectHydrate";
import { DocumentType } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class DocumentTypesController extends ApiController {
constructor(private documentTypesService: DocumentTypesService) {
super();
}
/**
* @description Get all document-types
*/
@Get("/api/v1/super-admin/document-types")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity: DocumentTypes[] = await this.documentTypesService.get(query);
//Hydrate ressource with prisma entity
const documentTypes = DocumentType.map<DocumentType>(DocumentType, prismaEntity, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, documentTypes);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new documentType
*/
@Post("/api/v1/super-admin/document-types")
protected async post(req: Request, response: Response) {
try {
//init DocumentType resource with request body values
const documentTypeEntity = DocumentType.hydrate<DocumentType>(req.body);
//validate user
await validateOrReject(documentTypeEntity, { groups: ["createDocumentType"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityCreated = await this.documentTypesService.create(documentTypeEntity);
//Hydrate ressource with prisma entity
const userEntityCreated = DocumentType.hydrate<DocumentType>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, userEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific documentType by uid
*/
@Put("/api/v1/super-admin/document-types/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init DocumentType resource with request body values
const documentTypeEntity = DocumentType.hydrate<DocumentType>(req.body);
//validate user
await validateOrReject(documentTypeEntity, { groups: ["update"] });
//call service to get prisma entity
const prismaEntityUpdated = await this.documentTypesService.update(uid, documentTypeEntity);
//Hydrate ressource with prisma entity
const documentTypeEntityUpdated = DocumentType.hydrate<DocumentType>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, documentTypeEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific documentType by uid
*/
@Get("/api/v1/super-admin/document-types/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let documentTypeEntity: DocumentTypes;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
documentTypeEntity = await this.documentTypesService.getByUid(uid, query);
} else {
//call service to get prisma entity
documentTypeEntity = await this.documentTypesService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const user = ObjectHydrate.hydrate<DocumentType>(new DocumentType(), documentTypeEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, user);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,157 @@
import { Response, Request } from "express";
import { Controller, Delete, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
import { Documents } from "@prisma/client";
import { Document } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class DocumentsController extends ApiController {
constructor(private documentsService: DocumentsService) {
super();
}
/**
* @description Get all documents
* @returns IDocument[] list of documents
*/
@Get("/api/v1/super-admin/documents")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity: Documents[] = await this.documentsService.get(query);
//Hydrate ressource with prisma entity
const documents = Document.map<Document>(Document, prismaEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, documents);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new document
* @returns IDocument created
*/
@Post("/api/v1/super-admin/documents")
protected async post(req: Request, response: Response) {
try {
//init Document resource with request body values
const documentEntity = Document.hydrate<Document>(req.body);
//validate document
await validateOrReject(documentEntity, { groups: ["createDocument"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityCreated = await this.documentsService.create(documentEntity);
//Hydrate ressource with prisma entity
const documentEntityCreated = Document.hydrate<Document>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, documentEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Update a specific document
*/
@Put("/api/v1/super-admin/documents/:uid")
protected async update(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init Document resource with request body values
const documentEntity = Document.hydrate<Document>(req.body);
//validate document
await validateOrReject(documentEntity, { groups: ["updateDocument"] });
//call service to get prisma entity
const prismaEntityUpdated: Documents = await this.documentsService.update(uid, documentEntity, req.body.refused_reason);
//Hydrate ressource with prisma entity
const document = Document.hydrate<Document>(prismaEntityUpdated, { strategy: "excludeAll" });
//success
this.httpSuccess(response, document);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Delete a specific document
*/
@Delete("/api/v1/super-admin/documents/:uid")
protected async delete(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//call service to get prisma entity
const documentEntity: Documents = await this.documentsService.delete(uid);
//Hydrate ressource with prisma entity
const document = Document.hydrate<Document>(documentEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, document);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific document by uid
*/
@Get("/api/v1/super-admin/documents/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let documentEntity: Documents;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
documentEntity = await this.documentsService.getByUid(uid, query);
} else {
//call service to get prisma entity
documentEntity = await this.documentsService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const document = Document.hydrate<Document>(documentEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, document);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,178 @@
import { Response, Request } from "express";
import { Controller, Delete, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import FilesService from "@Services/private-services/FilesService/FilesService";
import { Files } from "@prisma/client";
import { File, Document } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
@Controller()
@Service()
export default class FilesController extends ApiController {
constructor(private filesService: FilesService, private documentService: DocumentsService) {
super();
}
/**
* @description Get all Files
* @returns File[] list of Files
*/
@Get("/api/v1/super-admin/files")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity = await this.filesService.get(query);
//Hydrate ressource with prisma entity
const files = File.map<File>(File, prismaEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, files);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific File by uid
*/
@Get("/api/v1/super-admin/files/upload/:uid")
protected async getFileData(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
const file = await this.filesService.updload(uid);
this.httpSuccess(response, file);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new File
* @returns File created
*/
@Post("/api/v1/super-admin/files")
protected async post(req: Request, response: Response) {
try {
//get file
if(!req.file) throw new Error('No file provided')
//init File resource with request body values
const fileEntity = File.hydrate<File>(JSON.parse(req.body["q"]));
//validate File
await validateOrReject(fileEntity, { groups: ["createFile"] });
//call service to get prisma entity
const prismaEntityCreated = await this.filesService.create(fileEntity, req.file);
const document: Document = await this.documentService.getByUid(fileEntity.document!.uid!)
document.document_status = "DEPOSITED";
await this.documentService.update(document.uid!, document);
//Hydrate ressource with prisma entity
const fileEntityCreated = File.hydrate<File>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, fileEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Update a specific file
*/
@Put("/api/v1/super-admin/files/:uid")
protected async update(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init File resource with request body values
const fileEntity = File.hydrate<File>(req.body);
//validate file
await validateOrReject(fileEntity, { groups: ["updateFile"] });
//call service to get prisma entity
const prismaEntityUpdated: Files = await this.filesService.update(uid, fileEntity);
//Hydrate ressource with prisma entity
const file = File.hydrate<File>(prismaEntityUpdated, { strategy: "excludeAll" });
//success
this.httpSuccess(response, file);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Delete a specific File
*/
@Delete("/api/v1/super-admin/files/:uid")
protected async delete(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//call service to get prisma entity
const fileEntity: Files = await this.filesService.delete(uid);
//Hydrate ressource with prisma entity
const file = File.hydrate<File>(fileEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, file);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific File by uid
*/
@Get("/api/v1/super-admin/files/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
const fileEntity = await this.filesService.getByUid(uid);
//Hydrate ressource with prisma entity
const file = File.hydrate<File>(fileEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, file);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,154 @@
import { Response, Request } from "express";
import { Controller, Delete, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import OfficeFoldersService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService";
import { Service } from "typedi";
import { OfficeFolders } from "@prisma/client";
import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class OfficeFoldersController extends ApiController {
constructor(private officeFoldersService: OfficeFoldersService) {
super();
}
/**
* @description Get all folders
*/
@Get("/api/v1/super-admin/folders")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const prismaEntity: OfficeFolders[] = await this.officeFoldersService.get(query);
//Hydrate ressource with prisma entity
const officeFolders = OfficeFolder.map<OfficeFolder>(OfficeFolder, prismaEntity, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, officeFolders);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new folder
*/
@Post("/api/v1/super-admin/folders")
protected async post(req: Request, response: Response) {
try {
//init OfficeFolder resource with request body values
const officeFolderEntity = OfficeFolder.hydrate<OfficeFolder>(req.body);
//validate folder
await validateOrReject(officeFolderEntity, { groups: ["createFolder"] , forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityCreated = await this.officeFoldersService.create(officeFolderEntity);
//Hydrate ressource with prisma entity
const officeFolderEntityCreated = OfficeFolder.hydrate<OfficeFolder>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, officeFolderEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific folder by uid
*/
@Put("/api/v1/super-admin/folders/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init OfficeFolder resource with request body values
const officeFolderEntity = OfficeFolder.hydrate<OfficeFolder>(req.body);
//validate folder
await validateOrReject(officeFolderEntity, { groups: ["updateFolder"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityUpdated = await this.officeFoldersService.update(uid, officeFolderEntity);
//Hydrate ressource with prisma entity
const officeFolderEntityUpdated = OfficeFolder.hydrate<OfficeFolder>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, officeFolderEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific folder by uid
* @returns IFolder
*/
@Get("/api/v1/super-admin/folders/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let officeFolderEntity: OfficeFolders;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
officeFolderEntity = await this.officeFoldersService.getByUid(uid, query);
} else {
//call service to get prisma entity
officeFolderEntity = await this.officeFoldersService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const officeFolder = OfficeFolder.hydrate<OfficeFolder>(officeFolderEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, officeFolder);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
this.httpSuccess(response, await this.officeFoldersService.getByUid("uid"));
}
/**
* @description Delete a specific folder
*/
@Delete("/api/v1/super-admin/folders/:uid")
protected async delete(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//call service to get prisma entity
const officeFoldertEntity: OfficeFolders = await this.officeFoldersService.delete(uid);
//Hydrate ressource with prisma entity
const officeFolder = OfficeFolder.hydrate<OfficeFolder>(officeFoldertEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, officeFolder);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,113 @@
import { Response, Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import OfficesService from "@Services/super-admin/OfficesService/OfficesService";
import { Service } from "typedi";
import { Offices } from "@prisma/client";
import { Office as OfficeResource } from "le-coffre-resources/dist/SuperAdmin";
import { validateOrReject } from "class-validator";
@Controller()
@Service()
export default class OfficesController extends ApiController {
constructor(private officesService: OfficesService) {
super();
}
/**
* @description Get all offices
*/
@Get("/api/v1/super-admin/offices")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const officesEntity: Offices[] = await this.officesService.get(query);
//Hydrate ressource with prisma entity
const offices = OfficeResource.map<OfficeResource>(OfficeResource, officesEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, offices);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new office
*/
@Post("/api/v1/super-admin/offices")
protected async post(req: Request, response: Response) {
try {
//init IUser resource with request body values
const officeEntity = OfficeResource.hydrate<OfficeResource>(req.body);
//validate user
await validateOrReject(officeEntity, { groups: ["createOffice"], forbidUnknownValues: false });
//call service to get prisma entity
const prismaEntityCreated = await this.officesService.create(officeEntity);
//Hydrate ressource with prisma entity
const officeEntityCreated = OfficeResource.hydrate<OfficeResource>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, officeEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific office by uid
*/
@Put("/api/v1/super-admin/offices/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init IUser resource with request body values
const officeEntity = OfficeResource.hydrate<OfficeResource>(req.body);
//validate user
await validateOrReject(officeEntity, { groups: ["update"] });
//call service to get prisma entity
const prismaEntityUpdated = await this.officesService.update(uid, officeEntity);
//Hydrate ressource with prisma entity
const officeEntityUpdated = OfficeResource.hydrate<OfficeResource>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, officeEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific office by uid
*/
@Get("/api/v1/super-admin/offices/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let officeEntity: Offices;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
officeEntity = await this.officesService.getByUid(uid, query);
} else {
//call service to get prisma entity
officeEntity = await this.officesService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const office = OfficeResource.hydrate<OfficeResource>(officeEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, office);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -0,0 +1,130 @@
import { Response, Request } from "express";
import { Controller, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import UsersService from "@Services/super-admin/UsersService/UsersService";
import { Service } from "typedi";
import { validateOrReject } from "class-validator";
import User from "le-coffre-resources/dist/Notary";
import { Users } from "@prisma/client";
@Controller()
@Service()
export default class UsersController extends ApiController {
constructor(private usersService: UsersService) {
super();
}
/**
* @description Get all users
*/
@Get("/api/v1/super-admin/users")
protected async get(req: Request, response: Response) {
try {
//get query
const query = JSON.parse(req.query["q"] as string);
//call service to get prisma entity
const usersEntity = await this.usersService.get(query);
//Hydrate ressource with prisma entity
const users = User.map<User>(User, usersEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, users);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Create a new user
*/
@Post("/api/v1/super-admin/users")
protected async getAddresses(req: Request, response: Response) {
try {
//init IUser resource with request body values
const userEntity = User.hydrate<User>(req.body);
//validate user
await validateOrReject(userEntity, { groups: ["createUser"] });
//call service to get prisma entity
const prismaEntityCreated = await this.usersService.create(userEntity);
//Hydrate ressource with prisma entity
const userEntityCreated = User.hydrate<User>(prismaEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, userEntityCreated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Modify a specific user by uid
*/
@Put("/api/v1/super-admin/users/:uid")
protected async put(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
//init IUser resource with request body values
const userEntity = User.hydrate<User>(req.body);
//validate user
await validateOrReject(userEntity, { groups: ["update"] });
//call service to get prisma entity
const prismaEntityUpdated = await this.usersService.update(uid, userEntity);
//Hydrate ressource with prisma entity
const userEntityUpdated = User.hydrate<User>(prismaEntityUpdated, {
strategy: "excludeAll",
});
//success
this.httpSuccess(response, userEntityUpdated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific user by uid
*/
@Get("/api/v1/super-admin/users/:uid")
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
let userEntity: Users;
//get query
if (req.query["q"]) {
const query = JSON.parse(req.query["q"] as string);
userEntity = await this.usersService.getByUid(uid, query);
} else {
//call service to get prisma entity
userEntity = await this.usersService.getByUid(uid);
}
//Hydrate ressource with prisma entity
const user = User.hydrate<User>(userEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, user);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}

View File

@ -1,13 +1,17 @@
import { Container } from "typedi";
import HomeController from "./HomeController";
import UsersController from "./api/UsersController";
import FoldersController from "./api/FoldersController";
import CustomersController from "./api/CustomersController";
import OfficesController from "./api/OfficesController";
import DeedsController from "./api/DeedsController";
import DeedTypesController from "./api/DeedTypesController";
import DocumentsController from "./api/DocumentsController";
import DocumentTypesController from "./api/DocumentTypesController";
import UsersController from "./api/super-admin/UsersController";
import FoldersController from "./api/super-admin/OfficeFoldersController";
import CustomersController from "./api/super-admin/CustomersController";
import OfficesController from "./api/super-admin/OfficesController";
import DeedsController from "./api/super-admin/DeedsController";
import DeedTypesController from "./api/super-admin/DeedTypesController";
import DocumentsController from "./api/super-admin/DocumentsController";
import DocumentTypesController from "./api/super-admin/DocumentTypesController";
import IdNotUserInfoController from "./api/idnot-user/UserInfoController";
import DocumentsControllerCustomer from "./api/customer/DocumentsController";
import FilesController from "./api/super-admin/FilesController";
/**
* @description This allow to declare all controllers used in the application
@ -23,5 +27,8 @@ export default {
Container.get(DeedTypesController);
Container.get(DocumentsController);
Container.get(DocumentTypesController);
Container.get(IdNotUserInfoController);
Container.get(FilesController);
Container.get(DocumentsControllerCustomer);
},
};

View File

@ -10,7 +10,7 @@ export default function errorHandler(error: any, req: Request, response: Respons
if (error instanceof SyntaxError && errorStatus === 400 && "body" in error) {
response.status(HttpCodes.BAD_REQUEST).send({
body: error["body"],
type: error as any ["type"],
type: error as any["type"],
});
return;
}
@ -22,4 +22,3 @@ export default function errorHandler(error: any, req: Request, response: Respons
next(error);
}

View File

@ -0,0 +1,22 @@
import { NextFunction, Request, Response } from "express";
import multer from "multer";
export default function fileHandler(req: Request, response: Response, next: NextFunction) {
const storage = multer.memoryStorage()
const upload = multer({storage:storage}).single('file');
// Here call the upload middleware of multer
upload(req, response, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
const err = new Error('Multer error');
return next(err)
} else if (err) {
// An unknown error occurred when uploading.
const err = new Error('Server Error')
return next(err)
}
next()
})
}

View File

@ -1,6 +1,6 @@
import { Service } from "typedi";
import { validateOrReject, IsNotEmpty, IsOptional } from "class-validator";
import { IsNotEmpty, IsOptional, validateOrReject } from "class-validator";
import dotenv from "dotenv";
import { Service } from "typedi";
@Service()
export class BackendVariables {
@ -8,10 +8,10 @@ export class BackendVariables {
public readonly DATABASE_PORT!: string;
@IsNotEmpty()
public readonly DATABASE_HOSTNAME!: string;
public readonly DATABASE_HOST!: string;
@IsNotEmpty()
public readonly DATABASE_USER!: string;
public readonly DATABASE_USERNAME!: string;
@IsNotEmpty()
public readonly DATABASE_PASSWORD!: string;
@ -33,21 +33,48 @@ export class BackendVariables {
public readonly NODE_ENV = process.env.NODE_ENV;
@IsNotEmpty()
public readonly IDNOT_CONNEXION_URL!: string;
@IsNotEmpty()
public readonly IDNOT_CLIENT_ID!: string;
@IsNotEmpty()
public readonly IDNOT_CLIENT_SECRET!: string;
@IsNotEmpty()
public readonly IDNOT_REDIRECT_URL!: string;
@IsNotEmpty()
public readonly PINATA_API_KEY!: string;
@IsNotEmpty()
public readonly PINATA_API_SECRET!: string;
@IsNotEmpty()
public readonly PINATA_GATEWAY!: string;
public constructor() {
dotenv.config();
this.DATABASE_PORT = process.env["DATABASE_PORT"]!;
this.DATABASE_HOSTNAME = process.env["DATABASE_HOSTNAME"]!;
this.DATABASE_USER = process.env["DATABASE_USER"]!;
this.DATABASE_HOST = process.env["DATABASE_HOST"]!;
this.DATABASE_USERNAME = process.env["DATABASE_USERNAME"]!;
this.DATABASE_PASSWORD = process.env["DATABASE_PASSWORD"]!;
this.DATABASE_NAME = process.env["DATABASE_NAME"]!;
this.API_ROOT_URL = process.env["API_ROOT_URL"]!;
this.APP_PORT = process.env["APP_PORT"]!;
this.APP_ROOT_URL = process.env["APP_ROOT_URL"]!;
this.APP_LABEL = process.env["APP_LABEL"]!;
this.IDNOT_CONNEXION_URL = process.env["IDNOT_CONNEXION_URL"]!;
this.IDNOT_CLIENT_ID = process.env["IDNOT_CLIENT_ID"]!;
this.IDNOT_CLIENT_SECRET = process.env["IDNOT_CLIENT_SECRET"]!;
this.IDNOT_REDIRECT_URL = process.env["IDNOT_REDIRECT_URL"]!;
this.PINATA_API_KEY = process.env["PINATA_API_KEY"]!;
this.PINATA_API_SECRET = process.env["PINATA_API_SECRET"]!;
this.PINATA_GATEWAY = process.env["PINATA_GATEWAY"]!;
}
public async validate() {
await validateOrReject(this);
return this;
}
}

View File

@ -27,4 +27,3 @@ export default class Database {
return name;
}
}

View File

@ -0,0 +1,449 @@
-- CreateEnum
CREATE TYPE "ECivility" AS ENUM ('MALE', 'FEMALE', 'OTHERS');
-- CreateEnum
CREATE TYPE "EFolderStatus" AS ENUM ('LIVE', 'ARCHIVED');
-- CreateEnum
CREATE TYPE "EOfficeStatus" AS ENUM ('ACTIVATED', 'DESACTIVATED');
-- CreateEnum
CREATE TYPE "ENotificationStatus" AS ENUM ('READ', 'UNREAD');
-- CreateEnum
CREATE TYPE "ECustomerStatus" AS ENUM ('VALIDATED', 'PENDING', 'ERRONED');
-- CreateEnum
CREATE TYPE "EDocumentStatus" AS ENUM ('ASKED', 'DEPOSITED', 'VALIDATED', 'ANCHORED', 'REFUSED');
-- CreateTable
CREATE TABLE "addresses" (
"uid" TEXT NOT NULL,
"address" VARCHAR(255) NOT NULL,
"city" VARCHAR(255) NOT NULL,
"zip_code" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "addresses_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "contacts" (
"uid" TEXT NOT NULL,
"first_name" VARCHAR(255) NOT NULL,
"last_name" VARCHAR(255) NOT NULL,
"email" VARCHAR(255) NOT NULL,
"phone_number" VARCHAR(50),
"cell_phone_number" VARCHAR(50),
"civility" "ECivility" NOT NULL DEFAULT 'MALE',
"address_uid" VARCHAR(255) NOT NULL,
"birthdate" TIMESTAMP(3),
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "contacts_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "users" (
"uid" TEXT NOT NULL,
"idNot" VARCHAR(255) NOT NULL,
"contact_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
"office_uid" VARCHAR(255) NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "offices" (
"uid" TEXT NOT NULL,
"idNot" VARCHAR(255) NOT NULL,
"name" VARCHAR(255) NOT NULL,
"crpcen" VARCHAR(255) NOT NULL,
"address_uid" VARCHAR(255) NOT NULL,
"office_status" "EOfficeStatus" NOT NULL DEFAULT 'DESACTIVATED',
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "offices_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "customers" (
"uid" TEXT NOT NULL,
"status" "ECustomerStatus" NOT NULL DEFAULT 'PENDING',
"contact_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "customers_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "user_has_notifications" (
"uid" TEXT NOT NULL,
"user_uid" VARCHAR(255) NOT NULL,
"notification_uid" VARCHAR(255) NOT NULL,
"notification_status" "ENotificationStatus" NOT NULL DEFAULT 'UNREAD',
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "user_has_notifications_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "notifications" (
"uid" TEXT NOT NULL,
"message" VARCHAR(255) NOT NULL,
"redirection_url" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "notifications_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "office_folders" (
"uid" TEXT NOT NULL,
"folder_number" VARCHAR(255) NOT NULL,
"name" VARCHAR(255) NOT NULL,
"description" VARCHAR(255),
"archived_description" VARCHAR(255),
"status" "EFolderStatus" NOT NULL DEFAULT 'LIVE',
"deed_uid" VARCHAR(255) NOT NULL,
"office_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "office_folders_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "office_folder_has_customers" (
"uid" TEXT NOT NULL,
"customer_uid" VARCHAR(255) NOT NULL,
"office_folder_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "office_folder_has_customers_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "office_folder_has_stakeholder" (
"uid" TEXT NOT NULL,
"office_folder_uid" VARCHAR(255) NOT NULL,
"user_stakeholder_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "office_folder_has_stakeholder_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "documents" (
"uid" TEXT NOT NULL,
"document_status" "EDocumentStatus" NOT NULL DEFAULT 'ASKED',
"document_type_uid" VARCHAR(255) NOT NULL,
"blockchain_anchor_uid" VARCHAR(255),
"folder_uid" VARCHAR(255) NOT NULL,
"depositor_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "documents_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "document_history" (
"uid" TEXT NOT NULL,
"document_status" "EDocumentStatus" NOT NULL DEFAULT 'ASKED',
"refused_reason" VARCHAR(255),
"document_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "document_history_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "files" (
"uid" TEXT NOT NULL,
"document_uid" VARCHAR(255) NOT NULL,
"file_path" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "files_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "blockchain_anchors" (
"uid" TEXT NOT NULL,
"smartSigJobId" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "blockchain_anchors_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "document_types" (
"uid" TEXT NOT NULL,
"name" VARCHAR(255) NOT NULL,
"public_description" VARCHAR(255) NOT NULL,
"private_description" VARCHAR(255),
"office_uid" VARCHAR(255) NOT NULL,
"archived_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "document_types_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "deed_has_document_types" (
"uid" TEXT NOT NULL,
"document_type_uid" VARCHAR(255) NOT NULL,
"deed_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "deed_has_document_types_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "deed" (
"uid" TEXT NOT NULL,
"deed_type_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "deed_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "deed_types" (
"uid" TEXT NOT NULL,
"name" VARCHAR(255) NOT NULL,
"description" VARCHAR(255) NOT NULL,
"archived_at" TIMESTAMP(3),
"office_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "deed_types_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "deed_type_has_document_types" (
"uid" TEXT NOT NULL,
"document_type_uid" VARCHAR(255) NOT NULL,
"deed_type_uid" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "deed_type_has_document_types_pkey" PRIMARY KEY ("uid")
);
-- CreateIndex
CREATE UNIQUE INDEX "addresses_uid_key" ON "addresses"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "contacts_uid_key" ON "contacts"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "contacts_email_key" ON "contacts"("email");
-- CreateIndex
CREATE UNIQUE INDEX "contacts_cell_phone_number_key" ON "contacts"("cell_phone_number");
-- CreateIndex
CREATE UNIQUE INDEX "contacts_address_uid_key" ON "contacts"("address_uid");
-- CreateIndex
CREATE UNIQUE INDEX "users_uid_key" ON "users"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "users_idNot_key" ON "users"("idNot");
-- CreateIndex
CREATE UNIQUE INDEX "users_contact_uid_key" ON "users"("contact_uid");
-- CreateIndex
CREATE UNIQUE INDEX "offices_uid_key" ON "offices"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "offices_idNot_key" ON "offices"("idNot");
-- CreateIndex
CREATE UNIQUE INDEX "offices_crpcen_key" ON "offices"("crpcen");
-- CreateIndex
CREATE UNIQUE INDEX "offices_address_uid_key" ON "offices"("address_uid");
-- CreateIndex
CREATE UNIQUE INDEX "customers_uid_key" ON "customers"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "customers_contact_uid_key" ON "customers"("contact_uid");
-- CreateIndex
CREATE UNIQUE INDEX "user_has_notifications_uid_key" ON "user_has_notifications"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "user_has_notifications_notification_uid_user_uid_key" ON "user_has_notifications"("notification_uid", "user_uid");
-- CreateIndex
CREATE UNIQUE INDEX "notifications_uid_key" ON "notifications"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folders_uid_key" ON "office_folders"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folders_deed_uid_key" ON "office_folders"("deed_uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folders_folder_number_office_uid_key" ON "office_folders"("folder_number", "office_uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folder_has_customers_uid_key" ON "office_folder_has_customers"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folder_has_customers_office_folder_uid_customer_uid_key" ON "office_folder_has_customers"("office_folder_uid", "customer_uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folder_has_stakeholder_uid_key" ON "office_folder_has_stakeholder"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "office_folder_has_stakeholder_office_folder_uid_user_stakeh_key" ON "office_folder_has_stakeholder"("office_folder_uid", "user_stakeholder_uid");
-- CreateIndex
CREATE UNIQUE INDEX "documents_uid_key" ON "documents"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "document_history_uid_key" ON "document_history"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "files_uid_key" ON "files"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "files_file_path_key" ON "files"("file_path");
-- CreateIndex
CREATE UNIQUE INDEX "blockchain_anchors_uid_key" ON "blockchain_anchors"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "blockchain_anchors_smartSigJobId_key" ON "blockchain_anchors"("smartSigJobId");
-- CreateIndex
CREATE UNIQUE INDEX "document_types_uid_key" ON "document_types"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "document_types_name_office_uid_key" ON "document_types"("name", "office_uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_has_document_types_uid_key" ON "deed_has_document_types"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_has_document_types_deed_uid_document_type_uid_key" ON "deed_has_document_types"("deed_uid", "document_type_uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_uid_key" ON "deed"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_types_uid_key" ON "deed_types"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_types_name_office_uid_key" ON "deed_types"("name", "office_uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_type_has_document_types_uid_key" ON "deed_type_has_document_types"("uid");
-- CreateIndex
CREATE UNIQUE INDEX "deed_type_has_document_types_deed_type_uid_document_type_ui_key" ON "deed_type_has_document_types"("deed_type_uid", "document_type_uid");
-- AddForeignKey
ALTER TABLE "contacts" ADD CONSTRAINT "contacts_address_uid_fkey" FOREIGN KEY ("address_uid") REFERENCES "addresses"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "users" ADD CONSTRAINT "users_contact_uid_fkey" FOREIGN KEY ("contact_uid") REFERENCES "contacts"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "users" ADD CONSTRAINT "users_office_uid_fkey" FOREIGN KEY ("office_uid") REFERENCES "offices"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "offices" ADD CONSTRAINT "offices_address_uid_fkey" FOREIGN KEY ("address_uid") REFERENCES "addresses"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "customers" ADD CONSTRAINT "customers_contact_uid_fkey" FOREIGN KEY ("contact_uid") REFERENCES "contacts"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "user_has_notifications" ADD CONSTRAINT "user_has_notifications_user_uid_fkey" FOREIGN KEY ("user_uid") REFERENCES "users"("uid") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "user_has_notifications" ADD CONSTRAINT "user_has_notifications_notification_uid_fkey" FOREIGN KEY ("notification_uid") REFERENCES "notifications"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "office_folders" ADD CONSTRAINT "office_folders_deed_uid_fkey" FOREIGN KEY ("deed_uid") REFERENCES "deed"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "office_folders" ADD CONSTRAINT "office_folders_office_uid_fkey" FOREIGN KEY ("office_uid") REFERENCES "offices"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "office_folder_has_customers" ADD CONSTRAINT "office_folder_has_customers_customer_uid_fkey" FOREIGN KEY ("customer_uid") REFERENCES "customers"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "office_folder_has_customers" ADD CONSTRAINT "office_folder_has_customers_office_folder_uid_fkey" FOREIGN KEY ("office_folder_uid") REFERENCES "office_folders"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "office_folder_has_stakeholder" ADD CONSTRAINT "office_folder_has_stakeholder_office_folder_uid_fkey" FOREIGN KEY ("office_folder_uid") REFERENCES "office_folders"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "office_folder_has_stakeholder" ADD CONSTRAINT "office_folder_has_stakeholder_user_stakeholder_uid_fkey" FOREIGN KEY ("user_stakeholder_uid") REFERENCES "users"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documents" ADD CONSTRAINT "documents_document_type_uid_fkey" FOREIGN KEY ("document_type_uid") REFERENCES "document_types"("uid") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documents" ADD CONSTRAINT "documents_blockchain_anchor_uid_fkey" FOREIGN KEY ("blockchain_anchor_uid") REFERENCES "blockchain_anchors"("uid") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documents" ADD CONSTRAINT "documents_folder_uid_fkey" FOREIGN KEY ("folder_uid") REFERENCES "office_folders"("uid") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documents" ADD CONSTRAINT "documents_depositor_uid_fkey" FOREIGN KEY ("depositor_uid") REFERENCES "customers"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "document_history" ADD CONSTRAINT "document_history_document_uid_fkey" FOREIGN KEY ("document_uid") REFERENCES "documents"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "files" ADD CONSTRAINT "files_document_uid_fkey" FOREIGN KEY ("document_uid") REFERENCES "documents"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "document_types" ADD CONSTRAINT "document_types_office_uid_fkey" FOREIGN KEY ("office_uid") REFERENCES "offices"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "deed_has_document_types" ADD CONSTRAINT "deed_has_document_types_document_type_uid_fkey" FOREIGN KEY ("document_type_uid") REFERENCES "document_types"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "deed_has_document_types" ADD CONSTRAINT "deed_has_document_types_deed_uid_fkey" FOREIGN KEY ("deed_uid") REFERENCES "deed"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "deed" ADD CONSTRAINT "deed_deed_type_uid_fkey" FOREIGN KEY ("deed_type_uid") REFERENCES "deed_types"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "deed_types" ADD CONSTRAINT "deed_types_office_uid_fkey" FOREIGN KEY ("office_uid") REFERENCES "offices"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "deed_type_has_document_types" ADD CONSTRAINT "deed_type_has_document_types_document_type_uid_fkey" FOREIGN KEY ("document_type_uid") REFERENCES "document_types"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "deed_type_has_document_types" ADD CONSTRAINT "deed_type_has_document_types_deed_type_uid_fkey" FOREIGN KEY ("deed_type_uid") REFERENCES "deed_types"("uid") ON DELETE CASCADE ON UPDATE CASCADE;
-- AlterTable
ALTER TABLE "contacts" ALTER COLUMN "cell_phone_number" SET NOT NULL,
ALTER COLUMN "address_uid" DROP NOT NULL;

View File

@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `iv` to the `files` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "files" ADD COLUMN "iv" VARCHAR(255) NOT NULL;

View File

@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `file_name` to the `files` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "files" ADD COLUMN "file_name" VARCHAR(255) NOT NULL;

View File

@ -0,0 +1,9 @@
/*
Warnings:
- You are about to drop the column `iv` on the `files` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "files" DROP COLUMN "iv",
ADD COLUMN "key" VARCHAR(255);

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "files" ADD COLUMN "archived_at" TIMESTAMP(3);

View File

@ -2,6 +2,7 @@
generator client {
provider = "prisma-client-js"
//binaryTargets = ["native"]
}
datasource db {
@ -17,30 +18,31 @@ datasource db {
// id String @unique @default(auto()) @map("_id") @db.ObjectId // @map de la table checker le naming avec le tiret
model Addresses {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
address String @db.VarChar(255)
city String @db.VarChar(255)
zip_code Int
created_at DateTime @default(now())
updated_at DateTime @updatedAt
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
contacts Contacts?
office Office?
office Offices?
@@map("addresses")
}
model Contacts {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
first_name String @db.VarChar(255)
last_name String @db.VarChar(255)
email String @db.VarChar(255)
email String @unique @db.VarChar(255)
phone_number String? @db.VarChar(50)
cell_phone_number String? @db.VarChar(50)
cell_phone_number String @unique @db.VarChar(50)
civility ECivility @default(MALE)
address Addresses @relation(fields: [address_uuid], references: [uuid])
address_uuid String @unique @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
address Addresses? @relation(fields: [address_uid], references: [uid], onDelete: Cascade)
address_uid String? @unique @db.VarChar(255)
birthdate DateTime?
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
users Users?
customers Customers?
@ -48,44 +50,45 @@ model Contacts {
}
model Users {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid()) @map("uid")
idNot String @unique @db.VarChar(255)
contact Contacts @relation(fields: [contact_uuid], references: [uuid])
contact_uuid String @unique @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
office_membership Office @relation(fields: [office_uuid], references: [uuid])
office_uuid String @db.VarChar(255)
contact Contacts @relation(fields: [contact_uid], references: [uid], onDelete: Cascade)
contact_uid String @unique @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
office_membership Offices @relation(fields: [office_uid], references: [uid], onDelete: Cascade)
office_uid String @db.VarChar(255)
user_has_notifications UserHasNotifications[]
office_folder_has_stakeholder OfficeFolderHasStakeholders[]
@@map("users")
}
model Office {
uuid String @id @unique @default(uuid())
model Offices {
uid String @id @unique @default(uuid())
idNot String @unique @db.VarChar(255)
name String @db.VarChar(255)
crpcen String @unique @db.VarChar(255)
address Addresses @relation(fields: [address_uuid], references: [uuid])
address_uuid String @unique @db.VarChar(255)
address Addresses @relation(fields: [address_uid], references: [uid], onDelete: Cascade)
address_uid String @unique @db.VarChar(255)
office_status EOfficeStatus @default(DESACTIVATED)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
deed_types DeedTypes[]
users Users[]
office_folders OfficeFolders[]
document_types DocumentTypes[]
@@map("offices")
}
model Customers {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
status ECustomerStatus @default(PENDING)
contact Contacts @relation(fields: [contact_uuid], references: [uuid])
contact_uuid String @unique @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
contact Contacts @relation(fields: [contact_uid], references: [uid], onDelete: Cascade)
contact_uid String @unique @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
office_folder_has_customers OfficeFolderHasCustomers[]
documents Documents[]
@ -93,86 +96,90 @@ model Customers {
}
model UserHasNotifications {
uuid String @id @unique @default(uuid())
user Users @relation(fields: [user_uuid], references: [uuid])
user_uuid String @db.VarChar(255)
notification Notifications @relation(fields: [notification_uuid], references: [uuid])
notification_uuid String @db.VarChar(255)
uid String @id @unique @default(uuid())
user Users @relation(fields: [user_uid], references: [uid])
user_uid String @db.VarChar(255)
notification Notifications @relation(fields: [notification_uid], references: [uid], onDelete: Cascade)
notification_uid String @db.VarChar(255)
notification_status ENotificationStatus @default(UNREAD)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@unique([notification_uid, user_uid])
@@map("user_has_notifications")
}
model Notifications {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
message String @db.VarChar(255)
redirection_url String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
user_has_notifications UserHasNotifications[]
@@map("notifications")
}
model OfficeFolders {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
folder_number String @db.VarChar(255)
name String @db.VarChar(255)
description String? @db.VarChar(255)
archived_description String? @db.VarChar(255)
status EFolderStatus @default(LIVE)
deed Deed @relation(fields: [deed_uuid], references: [uuid])
deed_uuid String @unique @db.VarChar(255)
office Office @relation(fields: [office_uuid], references: [uuid])
office_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
deed Deeds @relation(fields: [deed_uid], references: [uid], onDelete: Cascade)
deed_uid String @unique @db.VarChar(255)
office Offices @relation(fields: [office_uid], references: [uid], onDelete: Cascade)
office_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
office_folder_has_customers OfficeFolderHasCustomers[]
office_folder_has_stakeholder OfficeFolderHasStakeholders[]
documents Documents[]
@@unique([folder_number, office_uid])
@@map("office_folders")
}
model OfficeFolderHasCustomers {
uuid String @id @unique @default(uuid())
customer Customers @relation(fields: [customer_uuid], references: [uuid])
customer_uuid String @db.VarChar(255)
office_folder OfficeFolders @relation(fields: [office_folder_uuid], references: [uuid])
office_folder_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
uid String @id @unique @default(uuid())
customer Customers @relation(fields: [customer_uid], references: [uid], onDelete: Cascade)
customer_uid String @db.VarChar(255)
office_folder OfficeFolders @relation(fields: [office_folder_uid], references: [uid], onDelete: Cascade)
office_folder_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@unique([office_folder_uid, customer_uid])
@@map("office_folder_has_customers")
}
model OfficeFolderHasStakeholders {
uuid String @id @unique @default(uuid())
office_folder OfficeFolders @relation(fields: [office_folder_uuid], references: [uuid])
office_folder_uuid String @db.VarChar(255)
user_stakeholder Users @relation(fields: [user_stakeholder_uuid], references: [uuid])
user_stakeholder_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
uid String @id @unique @default(uuid())
office_folder OfficeFolders @relation(fields: [office_folder_uid], references: [uid], onDelete: Cascade)
office_folder_uid String @db.VarChar(255)
user_stakeholder Users @relation(fields: [user_stakeholder_uid], references: [uid], onDelete: Cascade)
user_stakeholder_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@unique([office_folder_uid, user_stakeholder_uid])
@@map("office_folder_has_stakeholder")
}
model Documents {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
document_status EDocumentStatus @default(ASKED)
document_type DocumentTypes @relation(fields: [type_uuid], references: [uuid])
type_uuid String @db.VarChar(255)
blockchain_anchor BlockchainAnchors? @relation(fields: [blockchain_anchor_uuid], references: [uuid])
blockchain_anchor_uuid String? @db.VarChar(255)
folder OfficeFolders @relation(fields: [folder_uuid], references: [uuid])
folder_uuid String @db.VarChar(255)
depositor Customers @relation(fields: [depositor_uuid], references: [uuid])
depositor_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
document_type DocumentTypes @relation(fields: [document_type_uid], references: [uid])
document_type_uid String @db.VarChar(255)
blockchain_anchor BlockchainAnchors? @relation(fields: [blockchain_anchor_uid], references: [uid])
blockchain_anchor_uid String? @db.VarChar(255)
folder OfficeFolders @relation(fields: [folder_uid], references: [uid])
folder_uid String @db.VarChar(255)
depositor Customers @relation(fields: [depositor_uid], references: [uid], onDelete: Cascade)
depositor_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
files Files[]
document_history DocumentHistory[]
@ -180,71 +187,78 @@ model Documents {
}
model DocumentHistory {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
document_status EDocumentStatus @default(ASKED)
refused_reason String? @db.VarChar(255)
document Documents @relation(fields: [document_uuid], references: [uuid])
document_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
document Documents @relation(fields: [document_uid], references: [uid], onDelete: Cascade)
document_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@map("document_history")
}
model Files {
uuid String @id @unique @default(uuid())
document Documents @relation(fields: [document_uuid], references: [uuid])
document_uuid String @db.VarChar(255)
file_path String? @unique @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
uid String @id @unique @default(uuid())
document Documents @relation(fields: [document_uid], references: [uid], onDelete: Cascade)
document_uid String @db.VarChar(255)
file_path String @unique @db.VarChar(255)
file_name String @db.VarChar(255)
archived_at DateTime?
key String? @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@map("files")
}
model BlockchainAnchors {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
smartSigJobId String @unique @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
documents Documents[]
@@map("blockchain_anchors")
}
model DocumentTypes {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
name String @db.VarChar(255)
public_description String @db.VarChar(255)
private_description String? @db.VarChar(255)
office Offices @relation(fields: [office_uid], references: [uid], onDelete: Cascade)
office_uid String @db.VarChar(255)
archived_at DateTime?
created_at DateTime @default(now())
updated_at DateTime @updatedAt
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
documents Documents[]
deed_has_document_types DeedHasDocumentTypes[]
deed_type_has_document_types DeedTypeHasDocumentTypes[]
@@unique([name, office_uid])
@@map("document_types")
}
model DeedHasDocumentTypes {
uuid String @id @unique @default(uuid())
document_type DocumentTypes @relation(fields: [document_type_uuid], references: [uuid])
document_type_uuid String @db.VarChar(255)
deed Deed @relation(fields: [deed_uuid], references: [uuid])
deed_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
uid String @id @unique @default(uuid())
document_type DocumentTypes @relation(fields: [document_type_uid], references: [uid], onDelete: Cascade)
document_type_uid String @db.VarChar(255)
deed Deeds @relation(fields: [deed_uid], references: [uid], onDelete: Cascade)
deed_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@unique([deed_uid, document_type_uid])
@@map("deed_has_document_types")
}
model Deed {
uuid String @id @unique @default(uuid())
deed_type DeedTypes @relation(fields: [deed_type_uuid], references: [uuid])
deed_type_uuid String @unique @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
model Deeds {
uid String @id @unique @default(uuid())
deed_type DeedTypes @relation(fields: [deed_type_uid], references: [uid], onDelete: Cascade)
deed_type_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
deed_has_document_types DeedHasDocumentTypes[]
office_folder OfficeFolders?
@ -252,33 +266,34 @@ model Deed {
}
model DeedTypes {
uuid String @id @unique @default(uuid())
uid String @id @unique @default(uuid())
name String @db.VarChar(255)
description String @db.VarChar(255)
archived_at DateTime?
office Office @relation(fields: [office_uuid], references: [uuid])
office_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
deed Deed?
office Offices @relation(fields: [office_uid], references: [uid], onDelete: Cascade)
office_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
deed Deeds[]
deed_type_has_document_types DeedTypeHasDocumentTypes[]
@@unique([name, office_uid])
@@map("deed_types")
}
model DeedTypeHasDocumentTypes {
uuid String @id @unique @default(uuid())
document_type DocumentTypes @relation(fields: [document_type_uuid], references: [uuid])
document_type_uuid String @db.VarChar(255)
deed_type DeedTypes @relation(fields: [deed_type_uuid], references: [uuid])
deed_type_uuid String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
uid String @id @unique @default(uuid())
document_type DocumentTypes @relation(fields: [document_type_uid], references: [uid], onDelete: Cascade)
document_type_uid String @db.VarChar(255)
deed_type DeedTypes @relation(fields: [deed_type_uid], references: [uid], onDelete: Cascade)
deed_type_uid String @db.VarChar(255)
created_at DateTime? @default(now())
updated_at DateTime? @updatedAt
@@unique([deed_type_uid, document_type_uid])
@@map("deed_type_has_document_types")
}
// TODO SE RENSEIGNER SUR LES ENUMS
enum ECivility {
MALE
FEMALE

View File

@ -0,0 +1,605 @@
import {
Addresses,
Contacts,
Customers,
DeedHasDocumentTypes,
DeedTypeHasDocumentTypes,
DeedTypes,
Deeds,
DocumentHistory,
DocumentTypes,
Documents,
EDocumentStatus,
EFolderStatus,
EOfficeStatus,
Files,
OfficeFolderHasCustomers,
OfficeFolders,
Offices,
Users,
ECivility,
ECustomerStatus,
PrismaClient,
} from "@prisma/client";
(async () => {
const prisma = new PrismaClient();
const randomString = () => {
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result = "";
for (let i = 10; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
const uidCustomer1: string = randomString();
const uidCustomer2: string = randomString();
const uidContact1: string = randomString();
const uidContact2: string = randomString();
const uidContact3: string = randomString();
const uidContact4: string = randomString();
const uidAddress1: string = randomString();
const uidAddress2: string = randomString();
const uidAddress3: string = randomString();
const uidAddress4: string = randomString();
const uidOffice1: string = randomString();
const uidOffice2: string = randomString();
const uidUser1: string = randomString();
const uidUser2: string = randomString();
const uidOfficeFolder1: string = randomString();
const uidOfficeFolder2: string = randomString();
const uidOfficeFolder3: string = randomString();
const uidOfficeFolder4: string = randomString();
const uidOfficeFolder5: string = randomString();
const uidDeed1: string = randomString();
const uidDeed2: string = randomString();
const uidDeed3: string = randomString();
const uidDeed4: string = randomString();
const uidDeed5: string = randomString();
const uidDeedType1: string = randomString();
const uidDeedType2: string = randomString();
const uidDocument1: string = randomString();
const uidDocument2: string = randomString();
const uidDocument3: string = randomString();
const uidDocument4: string = randomString();
const uidDocument5: string = randomString();
const uidDocumentType1: string = randomString();
const uidDocumentType2: string = randomString();
const uidDocumentType3: string = randomString();
const uidOfficeFolderHasCustomer1: string = randomString();
const uidOfficeFolderHasCustomer2: string = randomString();
const uidFiles1: string = randomString();
const uidFiles2: string = randomString();
const uidDeedHasDocumentType1: string = randomString();
const uidDeedHasDocumentType2: string = randomString();
const uidDeedTypeHasDocumentType1: string = randomString();
const uidDeedTypeHasDocumentType2: string = randomString();
const uidDocumentHistory1: string = randomString();
const uidDocumentHistory2: string = randomString();
// const existingData = await prisma.contacts.findFirst({ where: { uid: uidContact4 } });
// if (existingData) {
// console.log("Seed data already exists. Skipping seeding process.");
// return;
// }
const customers: Customers[] = [
{
uid: uidCustomer1,
contact_uid: uidContact1,
created_at: new Date(),
updated_at: new Date(),
status: ECustomerStatus.PENDING,
},
{
uid: uidCustomer2,
contact_uid: uidContact2,
created_at: new Date(),
updated_at: new Date(),
status: ECustomerStatus.PENDING,
},
];
const addresses: Addresses[] = [
{
uid: uidAddress1,
address: "123 Main St",
city: "Los Angeles",
zip_code: 90001,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidAddress2,
address: "Rue Pierre Emillion",
city: "Paris",
zip_code: 75003,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidAddress3,
address: "Rue Pierre Charles",
city: "Paris",
zip_code: 75003,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidAddress4,
address: "Rue Pierre Pologne",
city: "Paris",
zip_code: 75003,
created_at: new Date(),
updated_at: new Date(),
},
];
const contacts: Contacts[] = [
{
uid: uidContact1,
address_uid: uidAddress1,
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com",
phone_number: randomString(),
cell_phone_number: randomString(),
birthdate: null,
created_at: new Date(),
updated_at: new Date(),
civility: ECivility.MALE,
},
{
uid: uidContact2,
address_uid: uidAddress2,
first_name: "Jane",
last_name: "Doe",
email: "jane.doe@example.com",
phone_number: randomString(),
cell_phone_number: randomString(),
birthdate: null,
created_at: new Date(),
updated_at: new Date(),
civility: ECivility.FEMALE,
},
{
uid: uidContact3,
address_uid: uidAddress3,
first_name: "Maitre Marcelino",
last_name: "Jack",
email: "Marcelino.Jack@example.com",
phone_number: randomString(),
cell_phone_number: randomString(),
birthdate: null,
created_at: new Date(),
updated_at: new Date(),
civility: ECivility.MALE,
},
{
uid: uidContact4,
address_uid: uidAddress4,
first_name: "Maitre Massi",
last_name: "Jack",
email: "Massi.Jack@example.com",
phone_number: randomString(),
cell_phone_number: randomString(),
birthdate: null,
created_at: new Date(),
updated_at: new Date(),
civility: ECivility.FEMALE,
},
];
const offices: Offices[] = [
{
uid: uidOffice1,
idNot: randomString(),
name: "LA Office",
crpcen: randomString(),
address_uid: uidAddress1,
created_at: new Date(),
updated_at: new Date(),
office_status: EOfficeStatus.ACTIVATED,
},
{
uid: uidOffice2,
idNot: randomString(),
name: "NYC Office",
crpcen: randomString(),
address_uid: uidAddress2,
created_at: new Date(),
updated_at: new Date(),
office_status: EOfficeStatus.DESACTIVATED,
},
];
const users: Users[] = [
{
uid: uidUser1,
created_at: new Date(),
updated_at: new Date(),
idNot: randomString(),
contact_uid: uidContact1,
office_uid: uidOffice1,
},
{
uid: uidUser2,
created_at: new Date(),
updated_at: new Date(),
idNot: randomString(),
contact_uid: uidContact2,
office_uid: uidOffice2,
},
];
const officeFolders: OfficeFolders[] = [
{
uid: uidOfficeFolder1,
folder_number: "0001",
name: "Dossier",
deed_uid: uidDeed1,
status: EFolderStatus.LIVE,
created_at: new Date(),
updated_at: new Date(),
office_uid: uidOffice1,
description: null,
archived_description: null,
},
{
uid: uidOfficeFolder2,
folder_number: "0002",
name: "Dossier",
deed_uid: uidDeed2,
status: EFolderStatus.LIVE,
created_at: new Date(),
updated_at: new Date(),
office_uid: uidOffice2,
description: null,
archived_description: null,
},
{
uid: uidOfficeFolder3,
folder_number: "0003",
name: "Dossier",
deed_uid: uidDeed3,
status: EFolderStatus.LIVE,
created_at: new Date(),
updated_at: new Date(),
office_uid: uidOffice2,
description: null,
archived_description: null,
},
{
uid: uidOfficeFolder4,
folder_number: "0004",
name: "Dossier",
deed_uid: uidDeed4,
status: EFolderStatus.ARCHIVED,
created_at: new Date(),
updated_at: new Date(),
office_uid: uidOffice2,
description: null,
archived_description: null,
},
{
uid: uidOfficeFolder5,
folder_number: "0005",
name: "Dossier",
deed_uid: uidDeed5,
status: EFolderStatus.ARCHIVED,
created_at: new Date(),
updated_at: new Date(),
office_uid: uidOffice2,
description: null,
archived_description: null,
},
];
const deeds: Deeds[] = [
{
uid: uidDeed1,
deed_type_uid: uidDeedType1,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeed2,
deed_type_uid: uidDeedType2,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeed3,
deed_type_uid: uidDeedType2,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeed4,
deed_type_uid: uidDeedType2,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeed5,
deed_type_uid: uidDeedType2,
created_at: new Date(),
updated_at: new Date(),
},
];
const deedTypes: DeedTypes[] = [
{
uid: uidDeedType1,
name: "Acte de mariage",
archived_at: null,
description: "Acte regroupant deux personnes en mariage",
office_uid: uidOffice1,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeedType2,
name: "Vente d'un bien immobilier",
archived_at: null,
description: "Permet de vendre un bien immobilier à une entité ou une personne physique",
office_uid: uidOffice2,
created_at: new Date(),
updated_at: new Date(),
},
];
const documents: Documents[] = [
{
uid: uidDocument1,
blockchain_anchor_uid: null,
depositor_uid: uidCustomer1,
document_status: EDocumentStatus.DEPOSITED,
folder_uid: uidOfficeFolder1,
document_type_uid: uidDocumentType1,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocument2,
blockchain_anchor_uid: null,
depositor_uid: uidCustomer2,
document_status: EDocumentStatus.ASKED,
folder_uid: uidOfficeFolder2,
document_type_uid: uidDocumentType2,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocument3,
blockchain_anchor_uid: null,
depositor_uid: uidCustomer1,
document_status: EDocumentStatus.ASKED,
folder_uid: uidOfficeFolder1,
document_type_uid: uidDocumentType3,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocument4,
blockchain_anchor_uid: null,
depositor_uid: uidCustomer1,
document_status: EDocumentStatus.ASKED,
folder_uid: uidOfficeFolder1,
document_type_uid: uidDocumentType2,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocument5,
blockchain_anchor_uid: null,
depositor_uid: uidCustomer1,
document_status: EDocumentStatus.ASKED,
folder_uid: uidOfficeFolder1,
document_type_uid: uidDocumentType1,
created_at: new Date(),
updated_at: new Date(),
},
];
const documentTypes: DocumentTypes[] = [
{
uid: uidDocumentType1,
archived_at: null,
name: "Acte de naissance",
office_uid: uidOffice1,
private_description: "Ce document est confidentiel, et ne doit pas être divulgué",
public_description: "Acte de naissance est un document officiel qui atteste de la naissance d'une personne",
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocumentType2,
archived_at: null,
name: "Carte d'identité",
office_uid: uidOffice1,
private_description: "Ce document est confidentiel, demander un recto-verso au client",
public_description: "Carte d'identité est un document officiel qui atteste de l'identité d'une personne",
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocumentType3,
archived_at: null,
name: "Autres documents",
office_uid: uidOffice1,
private_description: "Ce document est confidentiel, demander un recto-verso au client",
public_description: "Carte d'identité est un document officiel qui atteste de l'identité d'une personne",
created_at: new Date(),
updated_at: new Date(),
},
];
const officeFolderHasCustomers: OfficeFolderHasCustomers[] = [
{
uid: uidOfficeFolderHasCustomer1,
customer_uid: uidCustomer1,
office_folder_uid: uidOfficeFolder1,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidOfficeFolderHasCustomer2,
customer_uid: uidCustomer2,
office_folder_uid: uidOfficeFolder2,
created_at: new Date(),
updated_at: new Date(),
},
];
const files: Files[] = [
{
uid: uidFiles1,
document_uid: uidDocument1,
file_name: "fileName1",
file_path: "https://www.google1.com",
key: '',
archived_at: null,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidFiles2,
document_uid: uidDocument1,
file_name: "fileName2",
file_path: "https://www.google2.com",
key: '',
archived_at: null,
created_at: new Date(),
updated_at: new Date(),
},
];
const deedHasDocumentTypes: DeedHasDocumentTypes[] = [
{
uid: uidDeedHasDocumentType1,
deed_uid: uidDeed1,
document_type_uid: uidDocumentType1,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeedHasDocumentType2,
deed_uid: uidDeed2,
document_type_uid: uidDocumentType2,
created_at: new Date(),
updated_at: new Date(),
},
];
const deedTypeHasDocumentTypes: DeedTypeHasDocumentTypes[] = [
{
uid: uidDeedTypeHasDocumentType1,
deed_type_uid: uidDeedType1,
document_type_uid: uidDocumentType1,
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDeedTypeHasDocumentType2,
deed_type_uid: uidDeedType2,
document_type_uid: uidDocumentType2,
created_at: new Date(),
updated_at: new Date(),
},
];
const documentHistories: DocumentHistory[] = [
{
uid: uidDocumentHistory1,
document_status: EDocumentStatus.ASKED,
document_uid: uidDocument1,
refused_reason: "",
created_at: new Date(),
updated_at: new Date(),
},
{
uid: uidDocumentHistory2,
document_status: EDocumentStatus.DEPOSITED,
document_uid: uidDocument1,
refused_reason: "Le document n'est pas conforme",
created_at: new Date(),
updated_at: new Date(),
},
];
for (const address of addresses) {
await prisma.addresses.create({ data: address });
}
for (const contact of contacts) {
await prisma.contacts.create({ data: contact });
}
for (const office of offices) {
await prisma.offices.create({ data: office });
}
for (const user of users) {
await prisma.users.create({ data: user });
}
for (const customer of customers) {
await prisma.customers.create({ data: customer });
}
for (const deedType of deedTypes) {
await prisma.deedTypes.create({ data: deedType });
}
for (const deed of deeds) {
await prisma.deeds.create({ data: deed });
}
for (const officeFolder of officeFolders) {
await prisma.officeFolders.create({ data: officeFolder });
}
for (const documentType of documentTypes) {
await prisma.documentTypes.create({ data: documentType });
}
for (const document of documents) {
await prisma.documents.create({ data: document });
}
for (const file of files) {
await prisma.files.create({ data: file });
}
for (const documentHistory of documentHistories) {
await prisma.documentHistory.create({ data: documentHistory });
}
for (const officeFolderHasCustomer of officeFolderHasCustomers) {
await prisma.officeFolderHasCustomers.create({ data: officeFolderHasCustomer });
}
for (const deedHasDocumentType of deedHasDocumentTypes) {
await prisma.deedHasDocumentTypes.create({ data: deedHasDocumentType });
}
for (const deedTypeHasDocumentType of deedTypeHasDocumentTypes) {
await prisma.deedTypeHasDocumentTypes.create({ data: deedTypeHasDocumentType });
}
console.log(">MOCK DATA - Seeding completed!");
})();

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
import { type ClassTransformOptions, plainToClass, plainToClassFromExist } from "class-transformer";
import { type ClassTransformOptions, plainToClassFromExist, plainToInstance } from "class-transformer";
export default abstract class ObjectHydrate {
public static hydrate<T = {}>(object: T, from: Partial<T>, options?: ClassTransformOptions): T {
@ -7,7 +7,17 @@ export default abstract class ObjectHydrate {
public static map<T = {}>(ClassEntity: { new (): T }, fromArray: Partial<T>[], options?: ClassTransformOptions): T[] {
return fromArray.map((from) => {
return plainToClass(ClassEntity, from, options);
return plainToInstance(ClassEntity, from, options);
});
}
// public static fromTypeToRessource<T>(ClassEntity: { new (): T }, from: Record<string, unknown>): T {
// const properties = Object.getOwnPropertyNames(ClassEntity);
// const classInstance = new ClassEntity() as T;
// properties.forEach((property) => {
// if (property in from) {
// classInstance[property] = from[property] as T[keyof T];
// }
// });
// }
}

View File

@ -0,0 +1,42 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Addresses } from "@prisma/client";
@Service()
export default class AddressesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().addresses;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many addresses
*/
public async findMany(query: any): Promise<Addresses[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Find one address
*/
public async findOneByUid(uid: string): Promise<Addresses> {
const addressEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!addressEntity) {
throw new Error("Address not found");
}
return addressEntity;
}
}

View File

@ -0,0 +1,42 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Contacts } from "@prisma/client";
@Service()
export default class ContactsRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().contacts;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many contacts
*/
public async findMany(query: any): Promise<Contacts[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Find unique contact
*/
public async findOneByUid(uid: string): Promise<Contacts> {
const contactEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!contactEntity) {
throw new Error("contact not found");
}
return contactEntity;
}
}

View File

@ -0,0 +1,117 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Contacts, Customers, ECivility, ECustomerStatus, Prisma } from "@prisma/client";
import { Customer } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class CustomersRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().customers;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many customers
*/
public async findMany(query: Prisma.CustomersFindManyArgs): Promise<
(Customers & {
contact: Contacts;
})[]
> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
if (!query.include) return this.model.findMany({ ...query, include: { contact: true } });
return this.model.findMany({ ...query, include: { contact: { include: { address: true } } } });
}
/**
* @description : Create a customer
*/
public async create(customer: Customer): Promise<Customers> {
const createArgs: Prisma.CustomersCreateArgs = {
data: {
status: ECustomerStatus.PENDING,
contact: {
create: {
first_name: customer.contact!.first_name,
last_name: customer.contact!.last_name,
email: customer.contact!.email,
phone_number: customer.contact!.phone_number,
cell_phone_number: customer.contact!.cell_phone_number,
civility: ECivility[customer.contact!.civility as keyof typeof ECivility],
address: {},
},
},
},
};
if (customer.contact!.address) {
createArgs.data.contact!.create!.address = {
create: {
address: customer.contact!.address!.address,
zip_code: customer.contact!.address!.zip_code,
city: customer.contact!.address!.city,
},
};
}
return this.model.create({ ...createArgs, include: { contact: true } });
}
/**
* @description : Update data from a customer
*/
public async update(uid: string, customer: Customer): Promise<Customers> {
const updateArgs: Prisma.CustomersUpdateArgs = {
where: {
uid: uid,
},
data: {
status: ECustomerStatus[customer.status as keyof typeof ECustomerStatus],
contact: {
update: {
first_name: customer.contact!.first_name,
last_name: customer.contact!.last_name,
email: customer.contact!.email,
phone_number: customer.contact!.phone_number,
cell_phone_number: customer.contact!.cell_phone_number,
civility: ECivility[customer.contact!.civility as keyof typeof ECivility],
address: {},
},
},
},
};
if (customer.contact!.address) {
updateArgs.data.contact!.update!.address!.update = {
address: customer.contact!.address!.address,
zip_code: customer.contact!.address!.zip_code,
city: customer.contact!.address!.city,
};
}
return this.model.update({ ...updateArgs, include: { contact: true } });
}
/**
* @description : Find unique customer
*/
public async findOneByUid(uid: string, query?: any): Promise<Customers> {
const findOneArgs: Prisma.CustomersFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const customerEntity = await this.model.findUnique(findOneArgs);
if (!customerEntity) {
throw new Error("Customer not found");
}
return customerEntity;
}
}

View File

@ -0,0 +1,42 @@
import Database from "@Common/databases/database";
import { DeedTypeHasDocumentTypes } from "@prisma/client";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
@Service()
export default class DeedTypeHasDocumentTypesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().deedTypeHasDocumentTypes;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many relations between deed type and a document type
*/
public async findMany(query: any): Promise<DeedTypeHasDocumentTypes[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Find unique relation between deed type and a document type
*/
public async findOneByUid(uid: string): Promise<DeedTypeHasDocumentTypes> {
const deedTypeHasDoculmentTypesEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!deedTypeHasDoculmentTypesEntity) {
throw new Error("deed type not found");
}
return deedTypeHasDoculmentTypesEntity;
}
}

View File

@ -0,0 +1,111 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { DeedTypes, Prisma } from "@prisma/client";
import { DeedType } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class DeedTypesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().deedTypes;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many deed types
*/
public async findMany(query: any): Promise<DeedTypes[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create new deed type
*/
public async create(deedType: DeedType): Promise<DeedTypes> {
const createArgs: Prisma.DeedTypesCreateArgs = {
data: {
name: deedType.name,
description: deedType.description,
office: {
connect: {
uid: deedType.office!.uid,
},
},
},
};
if (deedType.deed_type_has_document_types) {
createArgs.data.deed_type_has_document_types = {
createMany: {
data: deedType.deed_type_has_document_types.map((relation) => ({
document_type_uid: relation.document_type.uid!,
})),
skipDuplicates: true,
},
};
}
return this.model.create(createArgs);
}
/**
* @description : Update data of a deed type
*/
public async update(uid: string, deedType: DeedType): Promise<DeedTypes> {
const updateArgs: Prisma.DeedTypesUpdateArgs = {
where: {
uid: uid,
},
data: {
name: deedType.name,
description: deedType.description,
archived_at: deedType.archived_at,
office: {
connect: {
uid: deedType.office!.uid,
},
},
},
include: {
deed_type_has_document_types: true,
},
};
if (deedType.deed_type_has_document_types) {
updateArgs.data.deed_type_has_document_types = {
deleteMany: { deed_type_uid: uid },
createMany: {
data: deedType.deed_type_has_document_types.map((relation) => ({
document_type_uid: relation.document_type.uid!,
})),
skipDuplicates: true,
},
};
}
return this.model.update(updateArgs);
}
/**
* @description : Find unique deed type
*/
public async findOneByUid(uid: string, query?: any): Promise<DeedTypes> {
const findOneArgs: Prisma.DeedTypesFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const deedTypeEntity = await this.model.findUnique(findOneArgs);
if (!deedTypeEntity) {
throw new Error("deed type not found");
}
return deedTypeEntity;
}
}

View File

@ -0,0 +1,42 @@
import Database from "@Common/databases/database";
import { DeedHasDocumentTypes } from "@prisma/client";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
@Service()
export default class DeedHasDocumentTypesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().deedHasDocumentTypes;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many deeds
*/
public async findMany(query: any): Promise<DeedHasDocumentTypes[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Find unique relation between deed and a document type
*/
public async findOneByUid(uid: string): Promise<DeedHasDocumentTypes> {
const deedHasDocumentTypesEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!deedHasDocumentTypesEntity) {
throw new Error("relation between deed and document type not found");
}
return deedHasDocumentTypesEntity;
}
}

View File

@ -0,0 +1,110 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Deeds, Prisma } from "@prisma/client";
import { Deed } from "le-coffre-resources/dist/Notary";
@Service()
export default class DeedsRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().deeds;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many users
*/
public async findMany(query: any): Promise<Deeds[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create a deed based on a deed type
*/
public async create(deed: Deed): Promise<Deeds> {
const createArgs: Prisma.DeedsCreateArgs = {
data: {
deed_type: {
connect: {
uid: deed.deed_type!.uid,
},
},
},
};
const deedTypeWithDocumentTypes = await this.instanceDb.deedTypes.findUniqueOrThrow({
where: {
uid: deed.deed_type!.uid,
},
include: { deed_type_has_document_types: true },
});
if (deedTypeWithDocumentTypes.archived_at) throw new Error("deed type is archived");
if (deedTypeWithDocumentTypes.deed_type_has_document_types) {
createArgs.data.deed_has_document_types = {
createMany: {
data: deedTypeWithDocumentTypes.deed_type_has_document_types.map((relation) => ({
document_type_uid: relation.document_type_uid,
})),
skipDuplicates: true,
},
};
}
return this.model.create(createArgs);
}
/**
* @description : Update data of a deed type
*/
public async update(uid: string, deed: Deed): Promise<Deeds> {
const updateArgs: Prisma.DeedsUpdateArgs = {
where: {
uid: uid,
},
data: {},
include: {
deed_has_document_types: true,
},
};
if (deed.deed_has_document_types) {
updateArgs.data.deed_has_document_types = {
deleteMany: { deed_uid: uid },
createMany: {
data: deed.deed_has_document_types.map((relation) => ({
document_type_uid: relation.document_type.uid!,
})),
skipDuplicates: true,
},
};
}
return this.model.update(updateArgs);
}
/**
* @description : Find unique deed
*/
public async findOneByUid(uid: string, query?: any): Promise<Deeds> {
const findOneArgs: Prisma.DeedsFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const deedTypeEntity = await this.model.findUnique(findOneArgs);
if (!deedTypeEntity) {
throw new Error("deed not found");
}
return deedTypeEntity;
}
}

View File

@ -0,0 +1,87 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { DocumentTypes, Prisma } from "prisma/prisma-client";
import { DocumentType } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class DocumentTypesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().documentTypes;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many document types
*/
public async findMany(query: any): Promise<DocumentTypes[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create a document type
*/
public async create(documentType: DocumentType): Promise<DocumentTypes> {
return this.model.create({
data: {
name: documentType.name,
public_description: documentType.public_description,
private_description: documentType.private_description,
office: {
connect: {
uid: documentType.office!.uid,
},
},
},
});
}
/**
* @description : update given document type
*/
public async update(uid: string, documentType: DocumentType): Promise<DocumentTypes> {
return this.model.update({
where: {
uid: uid,
},
data: {
name: documentType.name,
public_description: documentType.public_description,
private_description: documentType.private_description,
archived_at: documentType.archived_at,
office: {
connect: {
uid: documentType.office!.uid,
},
},
},
});
}
/**
* @description : find unique document type
*/
public async findOneByUid(uid: string, query?: any): Promise<DocumentTypes> {
const findOneArgs: Prisma.DocumentTypesFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const documentTypeEntity = await this.model.findUnique(findOneArgs);
if (!documentTypeEntity) {
throw new Error("Document Type not found");
}
return documentTypeEntity;
}
}

View File

@ -0,0 +1,128 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Documents, EDocumentStatus, Prisma } from "@prisma/client";
import { Document } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class DocumentsRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().documents;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many documents
*/
public async findMany(query: any): Promise<Documents[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create a document
*/
public async create(document: Document): Promise<Documents> {
const documentCreated = await this.model.create({
data: {
folder: {
connect: {
uid: document.folder!.uid,
},
},
depositor: {
connect: {
uid: document.depositor!.uid,
},
},
document_type: {
connect: {
uid: document.document_type!.uid,
},
},
},
});
await this.instanceDb.documentHistory.create({
data: {
document: {
connect: {
uid: documentCreated.uid,
},
},
},
});
return documentCreated;
}
/**
* @description : Create many documents linked to an office folder
*/
public async createMany(documents: Document[]): Promise<Prisma.BatchPayload> {
return this.model.createMany({
data: documents.map((document) => ({
folder_uid: document.folder!.uid!,
depositor_uid: document.depositor!.uid!,
document_type_uid: document.document_type!.uid!,
})),
skipDuplicates: true,
});
}
/**
* @description : Update data of a document
*/
public async update(uid: string, document: Document, refusedReason?: string): Promise<Documents> {
return this.model.update({
where: {
uid: uid,
},
data: {
document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus],
document_history: {
create: {
document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus],
refused_reason: refusedReason,
},
}
},
});
}
/**
* @description : Delete a document
*/
public async delete(uid: string): Promise<Documents> {
return this.model.delete({
where: {
uid: uid,
},
});
}
/**
* @description : Find unique document
*/
public async findOneByUid(uid: string, query?: any): Promise<Documents> {
const findOneArgs: Prisma.DocumentsFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const documentEntity = await this.model.findUnique(findOneArgs);
if (!documentEntity) {
throw new Error("Document not found");
}
return documentEntity;
}
}

View File

@ -0,0 +1,91 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Files } from "@prisma/client";
import { File } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class FilesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().files;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many files
*/
public async findMany(query: any): Promise<Files[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create a file linked to a document
*/
public async create(file: File, key: string): Promise<Files> {
return this.model.create({
data: {
document: {
connect: {
uid: file.document!.uid,
},
},
file_name: file.file_name,
file_path: file.file_path,
key: key
},
include: { document: true }
});
}
/**
* @description : Update data of a file
*/
public async update(uid: string, file: File): Promise<Files> {
return this.model.update({
where: {
uid: uid,
},
data: {
file_path: file.file_path,
},
});
}
/**
* @description : Delete a file
*/
public async delete(uid: string): Promise<Files> {
return this.model.update({
where: {
uid: uid,
},
data: {
key: null,
archived_at: new Date(Date.now())
}
});
}
/**
* @description : Find unique file
*/
public async findOneByUid(uid: string): Promise<Files> {
const fileEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!fileEntity) {
throw new Error("File not found");
}
return fileEntity;
}
}

View File

@ -0,0 +1,42 @@
import Database from "@Common/databases/database";
import { OfficeFolderHasCustomers } from "@prisma/client";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
@Service()
export default class OfficeFoldersHasCustomerRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().officeFolderHasCustomers;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many relations
*/
public async findMany(query: any): Promise<OfficeFolderHasCustomers[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Find a unique relation between an office folder and customers
*/
public async findOneByUid(uid: string): Promise<OfficeFolderHasCustomers> {
const officeFolderHasCustomersEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!officeFolderHasCustomersEntity) {
throw new Error("relation between office folder and customer not found");
}
return officeFolderHasCustomersEntity;
}
}

View File

@ -0,0 +1,42 @@
import Database from "@Common/databases/database";
import { OfficeFolderHasStakeholders } from "@prisma/client";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
@Service()
export default class OfficeFoldersHasStakeholderRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().officeFolderHasStakeholders;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many relations
*/
public async findMany(query: any): Promise<OfficeFolderHasStakeholders[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Find a unique relation between an office folder and stakeholders
*/
public async findOneByUid(uid: string): Promise<OfficeFolderHasStakeholders> {
const officeFolderHasStakeholdersEntity = await this.model.findUnique({
where: {
uid: uid,
},
});
if (!officeFolderHasStakeholdersEntity) {
throw new Error("relation between office folder and stakeholder not found");
}
return officeFolderHasStakeholdersEntity;
}
}

View File

@ -0,0 +1,153 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { EFolderStatus, OfficeFolders, Prisma } from "@prisma/client";
import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class OfficeFoldersRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().officeFolders;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many office folders
*/
public async findMany(query: any): Promise<OfficeFolders[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create new office folder with stakeholders
*/
public async create(officeFolder: OfficeFolder): Promise<OfficeFolders> {
const createArgs: Prisma.OfficeFoldersCreateArgs = {
data: {
folder_number: officeFolder.folder_number,
name: officeFolder.name,
description: officeFolder.description,
status: EFolderStatus.LIVE,
deed: {
connect: {
uid: officeFolder.deed?.uid
},
},
office: {
connect: {
uid: officeFolder.office!.uid,
},
},
},
include: {
office_folder_has_stakeholder: true,
},
};
if (officeFolder.office_folder_has_stakeholder) {
createArgs.data.office_folder_has_stakeholder = {
createMany: {
data: officeFolder.office_folder_has_stakeholder.map((relation) => ({
user_stakeholder_uid: relation.user_stakeholder.uid!,
})),
skipDuplicates: true,
},
};
}
return this.model.create(createArgs);
}
/**
* @description : Update data of an office folder
*/
public async update(officeFolderuid: string, officeFolder: OfficeFolder): Promise<OfficeFolders> {
const updateArgs: Prisma.OfficeFoldersUpdateArgs = {
where: {
uid: officeFolderuid,
},
data: {
folder_number: officeFolder.folder_number,
name: officeFolder.name,
description: officeFolder.description,
status: EFolderStatus[officeFolder.status as keyof typeof EFolderStatus],
archived_description: officeFolder.archived_description,
},
include: {
office_folder_has_stakeholder: true,
office_folder_has_customers: true,
documents: true,
},
};
if (officeFolder.office_folder_has_stakeholder) {
updateArgs.data.office_folder_has_stakeholder = {
deleteMany: { office_folder_uid: officeFolderuid },
createMany: {
data: officeFolder.office_folder_has_stakeholder.map((relation) => ({
user_stakeholder_uid: relation.user_stakeholder.uid!,
})),
skipDuplicates: true,
},
};
}
if (officeFolder.office_folder_has_customers) {
updateArgs.data.office_folder_has_customers = {
deleteMany: { office_folder_uid: officeFolderuid },
createMany: {
data: officeFolder.office_folder_has_customers.map((relation) => ({
customer_uid: relation.customer.uid!,
})),
skipDuplicates: true,
},
};
}
if (officeFolder.documents) {
updateArgs.data.documents = {
createMany: {
data: officeFolder.documents.map((relation) => ({
document_type_uid: relation.document_type!.uid!,
depositor_uid: relation.depositor!.uid!,
})),
skipDuplicates: true,
},
};
}
return this.model.update(updateArgs);
}
/**
* @description : Find one office folder
*/
public async findOneByUid(uid: string, query?: any): Promise<OfficeFolders> {
const findOneArgs: Prisma.OfficeFoldersFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const officeFolderEntity = await this.model.findUnique(findOneArgs);
if (!officeFolderEntity) {
throw new Error("office folder not found");
}
return officeFolderEntity;
}
/**
* @description : Delete a folder
*/
public async delete(uid: string): Promise<OfficeFolders> {
return this.model.delete({
where: {
uid: uid,
},
});
}
}

View File

@ -0,0 +1,91 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { EOfficeStatus, Offices, Prisma } from "@prisma/client";
import { Office as OfficeRessource } from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class OfficesRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().offices;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many users
*/
public async findMany(query: any): Promise<Offices[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create an office
*/
public async create(office: OfficeRessource): Promise<Offices> {
return this.model.create({
data: {
idNot: office.idNot,
name: office.name,
crpcen: office.crpcen,
address: {
create: {
address: office.address!.address,
zip_code: office.address!.zip_code,
city: office.address!.city,
},
},
office_status: EOfficeStatus.DESACTIVATED,
},
});
}
/**
* @description : Update data from an office
*/
public async update(uid: string, office: OfficeRessource): Promise<Offices> {
return this.model.update({
where: {
uid: uid,
},
data: {
name: office.name,
address: {
create: {
address: office.address!.address,
zip_code: office.address!.zip_code,
city: office.address!.city,
},
},
office_status: EOfficeStatus[office.office_status as keyof typeof EOfficeStatus],
},
});
}
/**
* @description : Find one office
*/
public async findOneByUid(uid: string, query?: any): Promise<Offices> {
const findOneArgs: Prisma.OfficesFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const officeEntity = await this.model.findUnique(findOneArgs);
if (!officeEntity) {
throw new Error("office not found");
}
return officeEntity;
}
}

View File

@ -0,0 +1,158 @@
import Database from "@Common/databases/database";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
import { Addresses, Contacts, ECivility, Offices, Prisma, Users } from "@prisma/client";
import User from "le-coffre-resources/dist/SuperAdmin";
@Service()
export default class UsersRepository extends BaseRepository {
constructor(private database: Database) {
super();
}
protected get model() {
return this.database.getClient().users;
}
protected get instanceDb() {
return this.database.getClient();
}
/**
* @description : Find many users
*/
public async findMany(query: Prisma.UsersFindManyArgs): Promise<Users[]> {
query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows);
return this.model.findMany(query);
}
/**
* @description : Create a user
*/
public async create(user: User): Promise<Users> {
const createArgs: Prisma.UsersCreateArgs = {
data: {
idNot: user.idNot,
office_membership: {
connectOrCreate: {
where: {
idNot: user.office_membership!.idNot,
},
create: {
idNot: user.office_membership!.idNot,
name: user.office_membership!.name,
crpcen: user.office_membership!.crpcen,
address: {
create: {
address: user.office_membership!.address!.address,
zip_code: user.office_membership!.address!.zip_code,
city: user.office_membership!.address!.city,
},
},
},
},
},
contact: {
create: {
first_name: user.contact!.first_name,
last_name: user.contact!.last_name,
email: user.contact!.email,
phone_number: user.contact!.phone_number,
cell_phone_number: user.contact!.cell_phone_number,
civility: ECivility[user.contact!.civility as keyof typeof ECivility],
address: {},
},
},
},
};
if (user.contact!.address) {
createArgs.data.contact!.create!.address!.create = {
address: user.contact!.address.address,
zip_code: user.contact!.address.zip_code,
city: user.contact!.address.city,
};
}
return this.model.create({ ...createArgs, include: { contact: true, office_membership: { include: { address: true } } } });
}
/**
* @description : Update data from a user
*/
public async update(
uid: string,
user: User,
): Promise<
Users & {
contact: Contacts;
office_membership: Offices & {
address: Addresses;
};
}
> {
const updateArgs: Prisma.UsersUpdateArgs = {
where: {
uid: uid,
},
data: {
idNot: user.idNot,
office_membership: {
connectOrCreate: {
where: {
idNot: user.office_membership!.idNot,
},
create: {
idNot: user.office_membership!.idNot,
name: user.office_membership!.name,
crpcen: user.office_membership!.crpcen,
address: {
create: {
address: user.office_membership!.address!.address,
zip_code: user.office_membership!.address!.zip_code,
city: user.office_membership!.address!.city,
},
},
},
},
},
contact: {
update: {
first_name: user.contact!.first_name,
last_name: user.contact!.last_name,
email: user.contact!.email,
phone_number: user.contact!.phone_number,
cell_phone_number: user.contact!.cell_phone_number,
civility: ECivility[user.contact!.civility as keyof typeof ECivility],
address: {},
},
},
},
};
if (user.contact!.address) {
updateArgs.data.contact!.update!.address!.update = {
address: user.contact!.address!.address,
zip_code: user.contact!.address!.zip_code,
city: user.contact!.address!.city,
};
}
return this.model.update({ ...updateArgs, include: { contact: true, office_membership: { include: { address: true } } } });
}
/**
* @description : Find one user
*/
public async findOneByUid(uid: string, query?: any): Promise<Users> {
const findOneArgs: Prisma.UsersFindUniqueArgs = {
where: {
uid: uid,
},
};
if (query) {
findOneArgs.include = query;
}
const userEntity = await this.model.findUnique(findOneArgs);
if (!userEntity) {
throw new Error("User not found");
}
return userEntity;
}
}

View File

@ -1,82 +0,0 @@
// import Database from "@Common/databases/Database";
import { ORMBadQueryError } from "@Common/system/database/exceptions/ORMBadQueryError";
import BaseRepository from "@Repositories/BaseRepository";
import { Service } from "typedi";
export class RequestsByDayMetrics {
date_requested!: Date;
count!: number;
}
export class CountRpcPathUsage {
path!: string;
count!: number;
}
@Service()
export default class _TemplateRepository extends BaseRepository {
// TODO ? -> Injection private database: Database
constructor() {
super();
}
// protected get model() {
// return this.database.getClient().metric;
// }
// protected get instanceDb() {
// return this.database.getClient();
// }
/**
* @description : Find many T
* @arguments : query: Prisma.TFindManyArgs
* @returns : Promise<T[]>
*/
public async findMany() {
try {
// Query
} catch (error) {
throw new ORMBadQueryError((error as Error).message, error as Error);
}
}
/**
* @description : Find many T
* @arguments : t : Partial<T>
* @returns : Promise<T>
*/
public async findOne() {
try {
// Query
} catch (error) {
throw new ORMBadQueryError((error as Error).message, error as Error);
}
}
/**
* @description : Create T
* @arguments : t : Partial<T>
* @returns : Promise<T[]>
*/
public async create() {
try {
// Create a new T
// return T
} catch (error) {
throw new ORMBadQueryError((error as Error).message, error as Error);
}
}
/**
* @description : Create bulk T
* @arguments : t : Partial<T[]>
* @returns : Promise<T[]>
*/
public async createMany() {
try {
// Create many new T
// return T[]
} catch (error) {
throw new ORMBadQueryError((error as Error).message, error as Error);
}
}
}

View File

@ -31,4 +31,3 @@ export default class ExpressServer implements ServerInterface {
return this;
}
}

View File

@ -0,0 +1,39 @@
import express, { Express, Router } from "express";
import { Service } from "typedi";
import ServerInterface, { IConfig } from "./ServerInterface";
@Service()
export default class ExpressServer implements ServerInterface {
public router: Express = express();
private subRouter: Router = express.Router();
public getRouter(): Router {
return this.subRouter;
}
protected getMainRouter(): Express {
return this.router;
}
public init(config: IConfig) {
this.router.use(...config.middlwares);
this.router.use(config.rootUrl, this.subRouter);
if (config.errorHandler) this.router.use(config.errorHandler);
return this;
}
public listen() {
return this.router.listen(3001, () => {
console.table(
[
{
"Entry label": "le coffre API",
Port: 3001,
"Root url": "/api",
},
],
["Entry label", "Port", "Root url"],
);
});
}
}

View File

@ -14,4 +14,3 @@ export default interface ServerInterface {
init(config: IConfig): this;
}

View File

@ -6,4 +6,3 @@ import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
export default abstract class ApiController extends BaseController {}
export { HttpCodes as ResponseStatusCodes };

View File

@ -2,10 +2,8 @@ import { StRoute } from "./StRoute";
import { Response } from "express";
import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
type IResponseData = {} | string | number | boolean | null | unknown;
export default abstract class BaseController {
public expressRoutes!: StRoute[];
public httpCode: typeof HttpCodes = HttpCodes;

View File

@ -34,4 +34,3 @@ function createRoute(controller: any, route: StRoute) {
}
export default Controller;

View File

@ -12,4 +12,3 @@ export default class ErrorCatch {
next(args[args.length - 1] ?? "Unknown Error");
}
}

View File

@ -1,7 +1,12 @@
import BaseController from "./BaseController";
import { StRoute } from "./StRoute";
function MethodsAny(type: StRoute["type"], path: string, frontMiddlewares: StRoute["frontMiddlewares"] = [], backMiddlewares: StRoute["backMiddlewares"] = []) {
function MethodsAny(
type: StRoute["type"],
path: string,
frontMiddlewares: StRoute["frontMiddlewares"] = [],
backMiddlewares: StRoute["backMiddlewares"] = [],
) {
return (target: any, memberName: string, propertyDescriptor: PropertyDescriptor) => {
const func = propertyDescriptor.value;
const constructor: typeof BaseController = target.constructor;
@ -29,4 +34,3 @@ export const Delete = MethodsAny.bind(null, "delete");
* @description Decorator Method PUT
*/
export const Put = MethodsAny.bind(null, "put");

View File

@ -7,4 +7,3 @@ export interface StRoute {
frontMiddlewares: ((requests: Request, response: Response, next: NextFunction) => void)[];
backMiddlewares: ((requests: Request, response: Response, next: NextFunction) => void)[];
}

View File

@ -1,17 +1,19 @@
import dotenv from "dotenv";
import { PrismaClient } from "@prisma/client";
import IDatabaseConfig from "../../config/database/IDatabaseConfig";
import { BackendVariables } from "@Common/config/variables/Variables";
import { PrismaClient } from "@prisma/client";
import dotenv from "dotenv";
import Container from "typedi";
import IDatabaseConfig from "../../config/database/IDatabaseConfig";
dotenv.config();
export default class DbProvider {
protected readonly variables = Container.get(BackendVariables);
protected url = `postgres://${this.variables.DATABASE_USERNAME}:${this.variables.DATABASE_PASSWORD}@${this.variables.DATABASE_HOST}:${this.variables.DATABASE_PORT}/${this.variables.DATABASE_NAME}`;
protected client = new PrismaClient({
datasources: {
db: {
url: `postgres://${this.variables.DATABASE_USER}:${this.variables.DATABASE_PASSWORD}@${this.variables.DATABASE_HOSTNAME}:${this.variables.DATABASE_PORT}/${this.variables.DATABASE_NAME}`,
url: this.url,
},
},
});

View File

@ -8,6 +8,7 @@ import bodyParser from "body-parser";
// import TezosLink from "@Common/databases/TezosLink";
import errorHandler from "@App/middlewares/ErrorHandler";
import { BackendVariables } from "@Common/config/variables/Variables";
import fileHandler from "@App/middlewares/FileHandler";
(async () => {
try {
@ -22,7 +23,7 @@ import { BackendVariables } from "@Common/config/variables/Variables";
label,
port: parseInt(port),
rootUrl,
middlwares: [cors({ origin: "*" }), bodyParser.urlencoded({ extended: true }), bodyParser.json()],
middlwares: [cors({ origin: "*" }), fileHandler, bodyParser.urlencoded({ extended: true }), bodyParser.json()],
errorHandler,
});
@ -31,4 +32,3 @@ import { BackendVariables } from "@Common/config/variables/Variables";
console.error(e);
}
})();

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class AddressesService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all addresses
* @returns : T
* @throws {Error} If addresses cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const address = await this.usersRepository.findOne(uuid);
// if (!address) Promise.reject(new Error("Cannot get address by uuid"));
return { response: "/api/addresses > GET : All addresses > Not implemented yet" };
}
/**
* @description : Create a new address
* @returns : T
* @throws {Error} If address cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const address = await this.projectRepository.create(projectEntity);
// if (!address) Promise.reject(new Error("Cannot create project"));
return { response: "/api/addresses > POST : Create address > Not implemented yet" };
}
/**
* @description : Modify a new address
* @returns : T
* @throws {Error} If address cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const address = await this.projectRepository.create(projectEntity);
// if (!address) Promise.reject(new Error("Cannot create project"));
return { response: "/api/addresses > PUT : Modified address > Not implemented yet" };
}
/**
* @description : Get a address by uid
* @returns : T
* @throws {Error} If address cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uuid: string) {
// const address = await this.usersRepository.findOne(uuid);
// if (!address) Promise.reject(new Error("Cannot get address by uuid"));
return { response: "/api/addresses/:uuid > GET : address by uid > Not implemented yet" };
}
}

View File

@ -1,8 +1,6 @@
export default abstract class BaseService {
/** @TODO place methods in a config file */
public static readonly whitelisted: string[] = ["/chains/main/blocks"];
public static readonly blacklisted: string[] = ["/context/contracts", "/monitor", "/network"];
public static readonly rollingPatterns: string[] = ["/head", "/injection/operation"];
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class ContactsService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all contacts
* @returns : T
* @throws {Error} If contacts cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const contact = await this.usersRepository.findOne(uuid);
// if (!contact) Promise.reject(new Error("Cannot get contact by uuid"));
return { response: "/api/contacts > GET : All contacts > Not implemented yet" };
}
/**
* @description : Create a new contact
* @returns : T
* @throws {Error} If contact cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const contact = await this.projectRepository.create(projectEntity);
// if (!contact) Promise.reject(new Error("Cannot create project"));
return { response: "/api/contacts > POST : Create contact > Not implemented yet" };
}
/**
* @description : Modify a new contact
* @returns : T
* @throws {Error} If contact cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const contact = await this.projectRepository.create(projectEntity);
// if (!contact) Promise.reject(new Error("Cannot create project"));
return { response: "/api/contacts > PUT : Modified contact > Not implemented yet" };
}
/**
* @description : Get a contact by uid
* @returns : T
* @throws {Error} If project cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uuid: string) {
// const contact = await this.usersRepository.findOne(uuid);
// if (!contact) Promise.reject(new Error("Cannot get contact by uuid"));
return { response: "/api/contacts/:uuid > GET : contact by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class CustomersService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all Customers
* @returns : T
* @throws {Error} If Customers cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const customer = await this.customersRepository.findOne(uuid);
// if (!customer) Promise.reject(new Error("Cannot get customer by uuid"));
return { response: "/api/customers > GET : All customers > Not implemented yet" };
}
/**
* @description : Create a new customer
* @returns : T
* @throws {Error} If customer cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const customer = await this.projectRepository.create(projectEntity);
// if (!customer) Promise.reject(new Error("Cannot create project"));
return { response: "/api/customers > POST : Create customer > Not implemented yet" };
}
/**
* @description : Modify a customer
* @returns : T
* @throws {Error} If customer cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const customer = await this.projectRepository.create(projectEntity);
// if (!customer) Promise.reject(new Error("Cannot create project"));
return { response: "/api/customers > PUT : Modified customer > Not implemented yet" };
}
/**
* @description : Get a customer by uid
* @returns : T
* @throws {Error} If customer cannot be get by uid
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const customer = await this.customersRepository.findOne(uid);
// if (!customer) Promise.reject(new Error("Cannot get customer by uid"));
return { response: "/api/customers/:uid > GET : customer by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class DeedTypesService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all deed-types
* @returns : T
* @throws {Error} If deed-types cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const deedtype = await this.customersRepository.findOne(uuid);
// if (!deedtype) Promise.reject(new Error("Cannot get deedtype by uuid"));
return { response: "/api/deed-types > GET : All deed-types > Not implemented yet" };
}
/**
* @description : Create a new deed-type
* @returns : T
* @throws {Error} If deed-type cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/deed-types > POST : Create deed-type > Not implemented yet" };
}
/**
* @description : Modify a deed-type
* @returns : T
* @throws {Error} If deed-type cannot be modifified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/deed-types > PUT : Modified deed-type > Not implemented yet" };
}
/**
* @description : Get a deedtype by uid
* @returns : T
* @throws {Error} If deed-type cannot be get by uid
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const deedtype = await this.customersRepository.findOne(uuid);
// if (!deedtype) Promise.reject(new Error("Cannot get deedtype by uid"));
return { response: "/api/deed-types/:uid > GET : deed-type by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class DeedsService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all deeds
* @returns : T
* @throws {Error} If deeds cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const deed = await this.usersRepository.findOne(uuid);
// if (!deed) Promise.reject(new Error("Cannot get deed by uuid"));
return { response: "/api/deeds > GET : All deeds > Not implemented yet" };
}
/**
* @description : Create a new deed
* @returns : T
* @throws {Error} If deeds cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const deeds = await this.projectRepository.create(projectEntity);
// if (!deeds) Promise.reject(new Error("Cannot create project"));
return { response: "/api/deeds > POST : Create deed > Not implemented yet" };
}
/**
* @description : Modify a new deed
* @returns : T
* @throws {Error} If deeds cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const deeds = await this.projectRepository.create(projectEntity);
// if (!deeds) Promise.reject(new Error("Cannot create project"));
return { response: "/api/deeds > PUT : Modified deed > Not implemented yet" };
}
/**
* @description : Get a deed by uid
* @returns : T
* @throws {Error} If project cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uuid: string) {
// const deed = await this.usersRepository.findOne(uuid);
// if (!deed) Promise.reject(new Error("Cannot get deed by uuid"));
return { response: "/api/deeds/:uuid > GET : deed by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class DocumentTypesService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all document-types
* @returns : T
* @throws {Error} If document-types cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const documentType = await this.foldersRepository.findOne(uuid);
// if (!documentType) Promise.reject(new Error("Cannot get document-type by uuid"));
return { response: "/api/document-types > GET : All document-types > Not implemented yet" };
}
/**
* @description : Create a new document-type
* @returns : T
* @throws {Error} If document-types cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/document-types > POST : Create document-type > Not implemented yet" };
}
/**
* @description : Modify a document-type
* @returns : T
* @throws {Error} If document-type cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const documentType = await this.projectRepository.create(projectEntity);
// if (!documentType) Promise.reject(new Error("Cannot create documentType"));
return { response: "/api/document-types > PUT : Modified document-type > Not implemented yet" };
}
/**
* @description : Get a document-type by uid
* @returns : T
* @throws {Error} If document-type cannot be get bu uid
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const documentType = await this.foldersRepository.findOne(uid);
// if (!documentType) Promise.reject(new Error("Cannot get document-type by uid"));
return { response: "/api/document-types/:uid > GET : document-type by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class DocumentsService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all documents
* @returns : T
* @throws {Error} If documents cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const document = await this.customersRepository.findOne(uuid);
// if (!document) Promise.reject(new Error("Cannot get documents"));
return { response: "/api/documents > GET : All documents > Not implemented yet" };
}
/**
* @description : Create a new document
* @returns : T
* @throws {Error} If document cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const document = await this.projectRepository.create(projectEntity);
// if (!document) Promise.reject(new Error("Cannot create document"));
return { response: "/api/documents > POST : Create document > Not implemented yet" };
}
/**
* @description : Modify a document
* @returns : T
* @throws {Error} If document cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const document = await this.projectRepository.create(projectEntity);
// if (!document) Promise.reject(new Error("Cannot create document"));
return { response: "/api/documents > PUT : Modified document > Not implemented yet" };
}
/**
* @description : Get a document by uid
* @returns : T
* @throws {Error} If document cannot be get by uid
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const document = await this.customersRepository.findOne(uid);
// if (!document) Promise.reject(new Error("Cannot get document by uid"));
return { response: "/api/documents/:uid > GET : document by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class FilesService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all files
* @returns : T
* @throws {Error} If files cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const files = await this.usersRepository.findOne(uuid);
// if (!files) Promise.reject(new Error("Cannot get files"));
return { response: "/api/files > GET : All files > Not implemented yet" };
}
/**
* @description : Create a new file
* @returns : T
* @throws {Error} If file cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const file = await this.projectRepository.create(projectEntity);
// if (!file) Promise.reject(new Error("Cannot create project"));
return { response: "/api/files > POST : Create file > Not implemented yet" };
}
/**
* @description : Modify a new file
* @returns : T
* @throws {Error} If file cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const file = await this.projectRepository.create(projectEntity);
// if (!file) Promise.reject(new Error("Cannot create project"));
return { response: "/api/files > PUT : Modified file > Not implemented yet" };
}
/**
* @description : Get a file by uid
* @returns : T
* @throws {Error} If project cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const file = await this.usersRepository.findOne(uid);
// if (!file) Promise.reject(new Error("Cannot get file by uid"));
return { response: "/api/files/:uid > GET : file by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class FoldersService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all folders
* @returns : T
* @throws {Error} If folders cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const folder = await this.foldersRepository.findOne(uuid);
// if (!folder) Promise.reject(new Error("Cannot get folder by uuid"));
return { response: "/api/folders > GET : All folders > Not implemented yet" };
}
/**
* @description : Create a new folder
* @returns : T
* @throws {Error} If folder cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const folder = await this.projectRepository.create(projectEntity);
// if (!folder) Promise.reject(new Error("Cannot create folder"));
return { response: "/api/folders > POST : Create folder > Not implemented yet" };
}
/**
* @description : Modify a folder
* @returns : T
* @throws {Error} If folder cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const folder = await this.projectRepository.create(projectEntity);
// if (!folder) Promise.reject(new Error("Cannot create folder"));
return { response: "/api/folders > PUT : Modified folder > Not implemented yet" };
}
/**
* @description : Get a folder by uid
* @returns : T
* @throws {Error} If folder cannot be get by uid
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const folder = await this.foldersRepository.findOne(uid);
// if (!folder) Promise.reject(new Error("Cannot get folder by uid"));
return { response: "/api/folders/:uid > GET : folder by uid > Not implemented yet" };
}
}

View File

@ -1,58 +0,0 @@
// import ProjectsRepository from "@Common/repositories/projects/ProjectsRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class OfficesService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all office
* @returns : T
* @throws {Error} If offices cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const office = await this.usersRepository.findOne(uuid);
// if (!office) Promise.reject(new Error("Cannot get office by uuid"));
return { response: "/api/office > GET : All office > Not implemented yet" };
}
/**
* @description : Create a new office
* @returns : T
* @throws {Error} If office cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/office > POST : Create office > Not implemented yet" };
}
/**
* @description : Modify an office
* @returns : T
* @throws {Error} If office cannot be modified
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/office > PUT : Modified office > Not implemented yet" };
}
/**
* @description : Get a office by uid
* @returns : T
* @throws {Error} If office cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const office = await this.usersRepository.findOne(uuid);
// if (!office) Promise.reject(new Error("Cannot get office by uuid"));
return { response: "/api/office/:uid > GET : office by uid > Not implemented yet" };
}
}

View File

@ -1,57 +0,0 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class UsersService extends BaseService {
constructor() {
super();
}
/**
* @description : Get all users
* @returns : T
* @throws {Error} If users cannot be get
* @param : projectEntity: Partial<ProjectEntity>
*/
public async get() {
// const user = await this.usersRepository.findOne(uuid);
// if (!user) Promise.reject(new Error("Cannot get user by uuid"));
return { response: "/api/users > GET : All users > Not implemented yet" };
}
/**
* @description : Create a new user
* @returns : T
* @throws {Error} If user cannot be created
* @param : projectEntity: Partial<ProjectEntity>
*/
public async create() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/users > POST : Create user > Not implemented yet" };
}
/**
* @description : Modify a user
* @returns : T
* @throws {Error} If user cannot be modififed
* @param : projectEntity: Partial<ProjectEntity>
*/
public async put() {
// const project = await this.projectRepository.create(projectEntity);
// if (!project) Promise.reject(new Error("Cannot create project"));
return { response: "/api/users > PUT : Modified user > Not implemented yet" };
}
/**
* @description : Get a user by uid
* @returns : T
* @throws {Error} If user cannot be get bu uid
* @param : projectEntity: Partial<ProjectEntity>
*/
public async getByUid(uid: string) {
// const user = await this.usersRepository.findOne(uuid);
// if (!user) Promise.reject(new Error("Cannot get user by uuid"));
return { response: "/api/users/:uid > GET : user by uid > Not implemented yet" };
}
}

View File

@ -0,0 +1,60 @@
import { Documents, Prisma } from "@prisma/client";
import { Document } from "le-coffre-resources/dist/Customer";
import DocumentsRepository from "@Repositories/DocumentsRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class DocumentsService extends BaseService {
constructor(private documentsRepository: DocumentsRepository) {
super();
}
/**
* @description : Get all documents
* @throws {Error} If documents cannot be get
*/
public async get(query: any) {
return this.documentsRepository.findMany(query);
}
/**
* @description : Create a new document
* @throws {Error} If document cannot be created
*/
public async create(document: Document): Promise<Documents> {
return this.documentsRepository.create(document);
}
/**
* @description : Create new documents
* @throws {Error} If documents or one of them cannot be created
*/
public async createMany(documents: Document[]): Promise<Prisma.BatchPayload> {
return this.documentsRepository.createMany(documents);
}
/**
* @description : Modify a document
* @throws {Error} If document cannot be modified
*/
public async update(uid: string, document: Document): Promise<Documents> {
return this.documentsRepository.update(uid, document);
}
/**
* @description : Delete a document
* @throws {Error} If document cannot be deleted
*/
public async delete(uid: string): Promise<Documents> {
return this.documentsRepository.delete(uid);
}
/**
* @description : Get a document by uid
* @throws {Error} If document cannot be get by uid
*/
public async getByUid(uid: string, query?: any) {
return this.documentsRepository.findOneByUid(uid, query);
}
}

View File

@ -0,0 +1,26 @@
import AddressesRepository from "@Repositories/AddressesRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class AddressesService extends BaseService {
constructor(private addressRepository: AddressesRepository) {
super();
}
/**
* @description : Get all addresses
* @throws {Error} If addresses cannot be get
*/
public async get(query: any) {
return this.addressRepository.findMany(query);
}
/**
* @description : Get a address by uid
* @throws {Error} If address cannot be get
*/
public async getByUid(uid: string) {
return this.addressRepository.findOneByUid(uid);
}
}

View File

@ -0,0 +1,53 @@
import jwt from "jsonwebtoken";
import BaseService from "@Services/BaseService";
import "reflect-metadata";
import { BackendVariables } from "@Common/config/variables/Variables";
import Container, { Service } from "typedi";
type IdNotTokens = {
access_token: string;
id_token: string;
};
@Service()
export default class AuthService extends BaseService {
protected readonly variables = Container.get(BackendVariables);
private constructor() {
super();
}
/**
* @description : Get IdNot id_token and access_token
* @throws {Error} If jwt pair cannot be get
*/
public async getUserFromIdNotTokens(code: string) {
const tokens = await this.getIdNotTokens(code);
return jwt.decode(tokens.id_token);
}
private async getIdNotTokens(code: string): Promise<IdNotTokens> {
const url = new URL(
this.variables.IDNOT_CONNEXION_URL.concat("?") +
new URLSearchParams({
client_id: this.variables.IDNOT_CLIENT_ID,
client_secret: this.variables.IDNOT_CLIENT_SECRET,
redirect_uri: this.variables.IDNOT_REDIRECT_URL,
code: code,
grant_type: "authorization_code",
}),
);
try {
const headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded",
});
const res = await fetch(url, {
method: "POST",
headers: headers,
});
const data = await res.json();
return data as IdNotTokens;
} catch (error) {
throw new Error();
}
}
}

View File

@ -0,0 +1,26 @@
import ContactsRepository from "@Repositories/ContactsRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class ContactsService extends BaseService {
constructor(private contactRepository: ContactsRepository) {
super();
}
/**
* @description : Get all contacts
* @throws {Error} If contacts cannot be get
*/
public async get(query: any) {
return this.contactRepository.findMany(query);
}
/**
* @description : Get a contact by uid
* @throws {Error} If contact cannot be get
*/
public async getByUid(uid: string) {
return this.contactRepository.findOneByUid(uid);
}
}

View File

@ -0,0 +1,48 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
import { BackendVariables } from "@Common/config/variables/Variables";
import crypto from "crypto";
@Service()
export default class CryptoService extends BaseService {
private static readonly CRYPTO_ALGORITHM = "aes-256-ctr";
constructor(protected variables: BackendVariables) {
super();
}
private getKey(key: string) {
return crypto.createHash('sha256').update(String(key)).digest('base64').slice(0, 32);
}
/**
* @description : encrypt data
* @throws {Error} If data cannot be encrypted
*/
public async encrypt(buffer: Buffer, key: string): Promise<Buffer> {
// Create an initialization vector
const iv = crypto.randomBytes(16);
// Create a new cipher using the algorithm, key, and iv
const cipher = crypto.createCipheriv(CryptoService.CRYPTO_ALGORITHM, this.getKey(key), iv);
// Create the new (encrypted) buffer
const result = Buffer.concat([iv, cipher.update(buffer), cipher.final()]);
return result;
}
/**
* @description : decrypt data with an initialization vector
* @throws {Error} If data cannot be decrypted
*/
public async decrypt(encrypted: Buffer, key: string): Promise<Buffer> {
// Get the iv: the first 16 bytes
const iv = encrypted.subarray(0, 16);
// Get the rest
encrypted = encrypted.subarray(16);
// Create a decipher
const decipher = crypto.createDecipheriv(CryptoService.CRYPTO_ALGORITHM, this.getKey(key), iv);
// Actually decrypt it
const result = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return result;
}
}

View File

@ -0,0 +1,88 @@
import FilesRepository from "@Repositories/FilesRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
import { File } from "le-coffre-resources/dist/SuperAdmin";
import CryptoService from "../CryptoService/CryptoService";
import IpfsService from "../IpfsService/IpfsService";
import { BackendVariables } from "@Common/config/variables/Variables";
import { Readable } from "stream";
import { v4 } from "uuid";
@Service()
export default class FilesService extends BaseService {
constructor(
private filesRepository: FilesRepository,
private ipfsService: IpfsService,
private variables: BackendVariables,
private cryptoService: CryptoService,
) {
super();
}
/**
* @description : Get all files
* @throws {Error} If files cannot be ge
*/
public async get(query: any) {
return this.filesRepository.findMany(query);
}
/**
* @description : Get a file by uid
* @throws {Error} If project cannot be created
*/
public async getByUid(uid: string) {
return this.filesRepository.findOneByUid(uid);
}
/**
* @description : view a file
* @throws {Error} If file cannot be deleted
*/
public async updload(uid: string) {
const file = await this.filesRepository.findOneByUid(uid);
if (!file.key) throw new Error("file deleted");
const fileResult = await fetch(file.file_path);
const fileContent = await fileResult.arrayBuffer();
return await this.cryptoService.decrypt(Buffer.from(fileContent), file.key);
}
/**
* @description : Create a new file
* @throws {Error} If file cannot be created
*/
public async create(file: File, fileData: Express.Multer.File) {
const key = v4();
const encryptedFile = await this.cryptoService.encrypt(fileData.buffer, key);
//const encryptedFileName = await this.cryptoService.encrypt(Buffer.from(fileData.originalname, 'utf-8'), key);
const upload = await this.ipfsService.pinFile(Readable.from(encryptedFile), fileData.originalname);
file.file_name = fileData.originalname; //encryptedFileName.toString('utf-8')
file.file_path = this.variables.PINATA_GATEWAY.concat(upload.IpfsHash);
return this.filesRepository.create(file, key);
}
/**
* @description : Modify a new file
* @throws {Error} If file cannot be modified
*/
public async update(uid: string, file: File) {
return this.filesRepository.update(uid, file);
}
/**
* @description : Delete a file
* @throws {Error} If file cannot be deleted
*/
public async delete(uid: string) {
try {
const fileToUnpin = await this.filesRepository.findOneByUid(uid);
const fileHash = fileToUnpin.file_path.substring(this.variables.PINATA_GATEWAY.length);
await this.ipfsService.unpinFile(fileHash);
} catch(error) {
console.error(error);
}
return this.filesRepository.delete(uid);
}
}

View File

@ -0,0 +1,30 @@
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
import pinataSDK from "@pinata/sdk";
import { BackendVariables } from "@Common/config/variables/Variables";
import { Readable } from "stream";
@Service()
export default class FilesService extends BaseService {
private ipfsClient: pinataSDK;
constructor(protected variables: BackendVariables) {
super();
this.ipfsClient = new pinataSDK({ pinataApiKey: variables.PINATA_API_KEY, pinataSecretApiKey: variables.PINATA_API_SECRET })
}
/**
* @description : pin a file
* @throws {Error} If file cannot be pinned
*/
public async pinFile(stream: Readable, fileName: string) {
return this.ipfsClient.pinFileToIPFS(stream, {pinataMetadata : {name: fileName}});
}
/**
* @description : unpin a file
* @throws {Error} If file cannot be unpinned
*/
public async unpinFile(hashToUnpin: string) {
return this.ipfsClient.unpin(hashToUnpin);
}
}

View File

@ -0,0 +1,44 @@
import { Customers, Prisma } from "@prisma/client";
import CustomersRepository from "@Repositories/CustomersRepository";
import BaseService from "@Services/BaseService";
import { Customer } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi";
@Service()
export default class CustomersService extends BaseService {
constructor(private customerRepository: CustomersRepository) {
super();
}
/**
* @description : Get all Customers
* @throws {Error} If Customers cannot be get
*/
public async get(query: Prisma.CustomersFindManyArgs): Promise<Customers[]> {
return this.customerRepository.findMany(query);
}
/**
* @description : Create a new customer
* @throws {Error} If customer cannot be created
*/
public async create(customerEntity: Customer): Promise<Customers> {
return this.customerRepository.create(customerEntity);
}
/**
* @description : Modify a customer
* @throws {Error} If customer cannot be modified
*/
public async update(uid: string, customerEntity: Customer): Promise<Customers> {
return this.customerRepository.update(uid, customerEntity);
}
/**
* @description : Get a customer by uid
* @throws {Error} If customer cannot be get by uid
*/
public async getByUid(uid: string, query?: any): Promise<Customers> {
return this.customerRepository.findOneByUid(uid, query);
}
}

View File

@ -0,0 +1,46 @@
import { DeedTypes } from "@prisma/client";
import DeedTypesRepository from "@Repositories/DeedTypesRepository";
import BaseService from "@Services/BaseService";
import { DeedType } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi";
@Service()
export default class DeedTypesService extends BaseService {
constructor(
private deedTypeRepository: DeedTypesRepository,
) {
super();
}
/**
* @description : Get all deed-types
* @throws {Error} If deed-types cannot be get
*/
public async get(query: any): Promise<DeedTypes[]> {
return this.deedTypeRepository.findMany(query);
}
/**
* @description : Create a new deed-type
* @throws {Error} If deed-type cannot be created
*/
public async create(deedTypeEntity: DeedType): Promise<DeedTypes> {
return this.deedTypeRepository.create(deedTypeEntity);
}
/**
* @description : Modify a deed-type
* @throws {Error} If deed-type cannot be modifified
*/
public async update(uid: string, deedTypeEntity: DeedType): Promise<DeedTypes> {
return this.deedTypeRepository.update(uid, deedTypeEntity);
}
/**
* @description : Get a deedtype by uid
* @throws {Error} If deed-type cannot be get by uid
*/
public async getByUid(uid: string, query?: any) {
return this.deedTypeRepository.findOneByUid(uid, query);
}
}

View File

@ -0,0 +1,44 @@
import { Deeds } from "@prisma/client";
import DeedsRepository from "@Repositories/DeedsRepository";
import BaseService from "@Services/BaseService";
import { Deed } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi";
@Service()
export default class DeedsService extends BaseService {
constructor(private deedRepository: DeedsRepository) {
super();
}
/**
* @description : Get all deeds
* @throws {Error} If deeds cannot be get
*/
public async get(query: any) {
return this.deedRepository.findMany(query);
}
/**
* @description : Create a new deed with document types
* @throws {Error} If deeds cannot be created
*/
public async create(deed: Deed): Promise<Deeds> {
return this.deedRepository.create(deed);
}
/**
* @description : Update data of a deed with document types
* @throws {Error} If deeds cannot be updated with document types or one of them
*/
public async update(deeduid: string, deed: Deed): Promise<Deeds> {
return this.deedRepository.update(deeduid, deed);
}
/**
* @description : Get a deed by uid
* @throws {Error} If deed-type cannot be get by uid
*/
public async getByUid(uid: string, query?: any) {
return this.deedRepository.findOneByUid(uid, query);
}
}

View File

@ -0,0 +1,44 @@
import { DocumentTypes } from "@prisma/client";
import DocumentTypesRepository from "@Repositories/DocumentTypesRepository";
import BaseService from "@Services/BaseService";
import { DocumentType } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi";
@Service()
export default class DocumentTypesService extends BaseService {
constructor(private documentTypeRepository: DocumentTypesRepository) {
super();
}
/**
* @description : Get all document-types
* @throws {Error} If document-types cannot be get
*/
public async get(query: any) {
return this.documentTypeRepository.findMany(query);
}
/**
* @description : Create a new document-type
* @throws {Error} If document-types cannot be created
*/
public async create(documentTypeEntity: DocumentType): Promise<DocumentTypes> {
return this.documentTypeRepository.create(documentTypeEntity);
}
/**
* @description : Modify a document-type
* @throws {Error} If document-type cannot be modified
*/
public async update(uid: string, documentTypeEntity: DocumentType): Promise<DocumentTypes> {
return this.documentTypeRepository.update(uid, documentTypeEntity);
}
/**
* @description : Get a document-type by uid
* @throws {Error} If document-type is not found
*/
public async getByUid(uid: string, query?: any) {
return this.documentTypeRepository.findOneByUid(uid, query);
}
}

View File

@ -0,0 +1,67 @@
import { Documents, Prisma } from "@prisma/client";
import { Document } from "le-coffre-resources/dist/SuperAdmin";
import DocumentsRepository from "@Repositories/DocumentsRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class DocumentsService extends BaseService {
constructor(private documentsRepository: DocumentsRepository) {
super();
}
/**
* @description : Get all documents
* @throws {Error} If documents cannot be get
*/
public async get(query: any) {
return this.documentsRepository.findMany(query);
}
/**
* @description : Create a new document
* @throws {Error} If document cannot be created
*/
public async create(document: Document): Promise<Documents> {
return this.documentsRepository.create(document);
}
/**
* @description : Create new documents
* @throws {Error} If documents or one of them cannot be created
*/
public async createMany(documents: Document[]): Promise<Prisma.BatchPayload> {
return this.documentsRepository.createMany(documents);
}
/**
* @description : Modify a document
* @throws {Error} If document cannot be modified
*/
public async update(uid: string, document: Document, refused_reason?: string): Promise<Documents> {
return this.documentsRepository.update(uid, document, refused_reason);
}
/**
* @description : Delete a document
* @throws {Error} If document cannot be deleted
*/
public async delete(uid: string): Promise<Documents> {
const documentEntity = await this.documentsRepository.findOneByUid(uid, { files: true });
const document = Document.hydrate<Document>(documentEntity, { strategy: "excludeAll" });
if (document.files && document.files.length !== 0) {
throw new Error("Can't delete a document with file");
}
return this.documentsRepository.delete(uid);
}
/**
* @description : Get a document by uid
* @throws {Error} If document cannot be get by uid
*/
public async getByUid(uid: string, query?: any) {
return this.documentsRepository.findOneByUid(uid, query);
}
}

View File

@ -0,0 +1,69 @@
import { OfficeFolders } from ".prisma/client";
import OfficeFoldersRepository from "@Repositories/OfficeFoldersRepository";
import BaseService from "@Services/BaseService";
import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi";
import DeedTypesService from "../DeedTypesService/DeedTypesService";
import DeedsRepository from "@Repositories/DeedsRepository";
@Service()
export default class OfficeFoldersService extends BaseService {
constructor(
private officeFoldersRepository: OfficeFoldersRepository,
private deedTypeService: DeedTypesService,
private deedRepository: DeedsRepository
) {
super();
}
/**
* @description : Get all folders
* @throws {Error} If folders cannot be get
*/
public async get(query: any) {
return this.officeFoldersRepository.findMany(query);
}
/**
* @description : Create a new folder
* @throws {Error} If folder cannot be created
*/
public async create(officeFolderEntity: OfficeFolder): Promise<OfficeFolders> {
const deedType = await this.deedTypeService.getByUid(officeFolderEntity.deed!.deed_type!.uid!);
if(deedType.archived_at) throw new Error('deed type is archived');
const deed = await this.deedRepository.create(officeFolderEntity.deed!);
officeFolderEntity.deed!.uid = deed.uid;
return this.officeFoldersRepository.create(officeFolderEntity);
}
/**
* @description : Modify a folder
* @throws {Error} If folder cannot be modified
*/
public async update(officeFolderuid: string, officeFolderEntity: OfficeFolder): Promise<OfficeFolders> {
return this.officeFoldersRepository.update(officeFolderuid, officeFolderEntity);
}
/**
* @description : Get a folder by uid
* @throws {Error} If folder cannot be get by uid
*/
public async getByUid(uid: string, query?: any) {
return this.officeFoldersRepository.findOneByUid(uid, query);
}
/**
* @description : Delete a folder
* @throws {Error} If document cannot be deleted
*/
public async delete(uid: string): Promise<OfficeFolders> {
const officeFolderEntity = await this.officeFoldersRepository.findOneByUid(uid, { office_folder_has_customers: true });
const officeFolder = OfficeFolder.hydrate<OfficeFolder>(officeFolderEntity, { strategy: "excludeAll" });
if (officeFolder.office_folder_has_customers && officeFolder.office_folder_has_customers.length !== 0) {
throw new Error("This folder is used by customers");
}
return this.officeFoldersRepository.delete(uid);
}
}

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