From 3dc043e6c48d732ff0ecaa466e961d5a34638523 Mon Sep 17 00:00:00 2001 From: "Arnaud D. Natali" <79214488+0xSaitama@users.noreply.github.com> Date: Thu, 6 Apr 2023 18:43:13 +0200 Subject: [PATCH] Feature/services test (#17) controllers, repositories, services and associated tests for: Deed types, Deed, Document types, Users and Customers --------- Co-authored-by: Vincent Alamelle Co-authored-by: OxSaitama --- .env.test | 4 + docker-compose-test.yml | 12 + docker-compose.yml | 2 +- jest.config.js | 19 + package-lock.json | 2517 ----------------- package.json | 19 +- src/app/HomeController.ts | 3 - src/app/api/CustomersController.ts | 81 - src/app/api/DeedTypesController.ts | 81 - src/app/api/DeedsController.ts | 81 - src/app/api/DocumentTypesController.ts | 81 - src/app/api/FoldersController.ts | 81 - src/app/api/OfficesController.ts | 81 - src/app/api/UsersController.ts | 81 - src/app/api/projects/UserController.ts | 18 - .../api/super-admin/CustomersController.ts | 131 + .../api/super-admin/DeedTypesController.ts | 132 + src/app/api/super-admin/DeedsController.ts | 56 + .../super-admin/DocumentTypesController.ts | 131 + .../{ => super-admin}/DocumentsController.ts | 55 +- .../super-admin/OfficeFoldersController.ts | 97 + src/app/api/super-admin/OfficesController.ts | 114 + src/app/api/super-admin/UsersController.ts | 132 + src/app/index.ts | 16 +- src/app/middlewares/ErrorHandler.ts | 3 +- src/common/config/database/IDatabaseConfig.ts | 8 +- src/common/config/variables/Variables.ts | 1 - src/common/databases/database.ts | 1 - .../20230321102005_v0/migration.sql | 413 +++ .../migration.sql | 92 + .../20230324130335_20230324_v2/migration.sql | 2 + .../20230324171729_v3/migration.sql | 119 + .../20230328095747_v4/migration.sql | 8 + .../20230329084446_v5/migration.sql | 8 + .../20230329145139_v6/migration.sql | 15 + .../20230330150236_v8/migration.sql | 24 + src/common/databases/schema.prisma | 144 +- src/common/helpers/ObjectHydrate.ts | 26 +- .../repositories/AddressesRepository.ts | 35 + src/common/repositories/ContactRepository.ts | 26 + .../repositories/CustomersRepository.ts | 93 + .../DeedTypesHasDocumentTypesRepository.ts | 112 + .../repositories/DeedTypesRepository.ts | 117 + .../DeedsHasDocumentTypesRepository.ts | 112 + src/common/repositories/DeedsRepository.ts | 90 + .../repositories/DocumentTypesRepository.ts | 77 + .../repositories/DocumentsRepository.ts | 26 + .../repositories/OfficeFoldersRepository.ts | 107 + src/common/repositories/OfficesRepository.ts | 101 + src/common/repositories/UsersRepository.ts | 135 + .../_TemplateRepository.ts | 82 - src/common/system/ExpressServer.ts | 1 - src/common/system/ExpressServerTest.ts | 39 + src/common/system/ServerInterface.ts | 1 - .../controller-pattern/ApiController.ts | 1 - .../controller-pattern/BaseController.ts | 2 - .../system/controller-pattern/Controller.ts | 1 - .../system/controller-pattern/ErrorCatch.ts | 1 - .../system/controller-pattern/HttpCodes.ts | 20 +- .../system/controller-pattern/Methods.ts | 8 +- .../system/controller-pattern/StRoute.ts | 1 - .../exceptions/HttpException.ts | 14 +- src/common/system/database/DbProvider.ts | 68 +- .../database/exceptions/ORMBadQueryError.ts | 2 +- src/common/system/database/index.ts | 2 +- src/entries/App.ts | 3 +- src/services/BaseService.ts | 2 - .../CustomersService/CustomersService.ts | 57 - .../DeedTypesService/DeedTypesService.ts | 57 - src/services/DeedsService/DeedsService.ts | 57 - .../DocumentTypesService.ts | 57 - src/services/FoldersService/FoldersService.ts | 57 - src/services/OfficesService/OfficesService.ts | 58 - src/services/UsersService/UsersService.ts | 57 - .../AddressesService/AddressesService.ts | 28 +- .../ContactsService/ContactsService.ts | 2 +- .../FilesService/FilesService.ts | 2 +- .../NotificationsService.ts | 2 +- .../CustomersService/CustomersService.ts | 44 + .../DeedTypesService/DeedTypesService.ts | 78 + .../super-admin/DeedsService/DeedsService.ts | 89 + .../DocumentTypesService.ts | 45 + .../DocumentsService/DocumentsService.ts | 31 +- .../OfficeFoldersService.ts | 67 + .../OfficesService/OfficesService.ts | 46 + .../super-admin/UsersService/UsersService.ts | 45 + .../super-admin/CustomersService.test.ts | 167 ++ .../services/super-admin/DeedService.test.ts | 264 ++ .../super-admin/DeedTypesService.test.ts | 406 +++ .../super-admin/DocumentTypesService.test.ts | 299 ++ src/test/services/super-admin/MockedData.ts | 162 ++ .../services/super-admin/UsersService.test.ts | 226 ++ tsconfig.json | 7 +- 93 files changed, 4769 insertions(+), 3809 deletions(-) create mode 100644 .env.test create mode 100644 docker-compose-test.yml create mode 100644 jest.config.js delete mode 100644 package-lock.json delete mode 100644 src/app/api/CustomersController.ts delete mode 100644 src/app/api/DeedTypesController.ts delete mode 100644 src/app/api/DeedsController.ts delete mode 100644 src/app/api/DocumentTypesController.ts delete mode 100644 src/app/api/FoldersController.ts delete mode 100644 src/app/api/OfficesController.ts delete mode 100644 src/app/api/UsersController.ts delete mode 100644 src/app/api/projects/UserController.ts create mode 100644 src/app/api/super-admin/CustomersController.ts create mode 100644 src/app/api/super-admin/DeedTypesController.ts create mode 100644 src/app/api/super-admin/DeedsController.ts create mode 100644 src/app/api/super-admin/DocumentTypesController.ts rename src/app/api/{ => super-admin}/DocumentsController.ts (50%) create mode 100644 src/app/api/super-admin/OfficeFoldersController.ts create mode 100644 src/app/api/super-admin/OfficesController.ts create mode 100644 src/app/api/super-admin/UsersController.ts create mode 100644 src/common/databases/migrations/20230321102005_v0/migration.sql create mode 100644 src/common/databases/migrations/20230324125436_20230324102005_v1/migration.sql create mode 100644 src/common/databases/migrations/20230324130335_20230324_v2/migration.sql create mode 100644 src/common/databases/migrations/20230324171729_v3/migration.sql create mode 100644 src/common/databases/migrations/20230328095747_v4/migration.sql create mode 100644 src/common/databases/migrations/20230329084446_v5/migration.sql create mode 100644 src/common/databases/migrations/20230329145139_v6/migration.sql create mode 100644 src/common/databases/migrations/20230330150236_v8/migration.sql create mode 100644 src/common/repositories/AddressesRepository.ts create mode 100644 src/common/repositories/ContactRepository.ts create mode 100644 src/common/repositories/CustomersRepository.ts create mode 100644 src/common/repositories/DeedTypesHasDocumentTypesRepository.ts create mode 100644 src/common/repositories/DeedTypesRepository.ts create mode 100644 src/common/repositories/DeedsHasDocumentTypesRepository.ts create mode 100644 src/common/repositories/DeedsRepository.ts create mode 100644 src/common/repositories/DocumentTypesRepository.ts create mode 100644 src/common/repositories/DocumentsRepository.ts create mode 100644 src/common/repositories/OfficeFoldersRepository.ts create mode 100644 src/common/repositories/OfficesRepository.ts create mode 100644 src/common/repositories/UsersRepository.ts delete mode 100644 src/common/repositories/_TemplateRepository/_TemplateRepository.ts create mode 100644 src/common/system/ExpressServerTest.ts delete mode 100644 src/services/CustomersService/CustomersService.ts delete mode 100644 src/services/DeedTypesService/DeedTypesService.ts delete mode 100644 src/services/DeedsService/DeedsService.ts delete mode 100644 src/services/DocumentTypesService/DocumentTypesService.ts delete mode 100644 src/services/FoldersService/FoldersService.ts delete mode 100644 src/services/OfficesService/OfficesService.ts delete mode 100644 src/services/UsersService/UsersService.ts rename src/services/{ => private-services}/AddressesService/AddressesService.ts (66%) rename src/services/{ => private-services}/ContactsService/ContactsService.ts (99%) rename src/services/{ => private-services}/FilesService/FilesService.ts (99%) rename src/services/{ => private-services}/NotificationsService/NotificationsService.ts (99%) create mode 100644 src/services/super-admin/CustomersService/CustomersService.ts create mode 100644 src/services/super-admin/DeedTypesService/DeedTypesService.ts create mode 100644 src/services/super-admin/DeedsService/DeedsService.ts create mode 100644 src/services/super-admin/DocumentTypesService/DocumentTypesService.ts rename src/services/{ => super-admin}/DocumentsService/DocumentsService.ts (62%) create mode 100644 src/services/super-admin/OfficeFoldersService/OfficeFoldersService.ts create mode 100644 src/services/super-admin/OfficesService/OfficesService.ts create mode 100644 src/services/super-admin/UsersService/UsersService.ts create mode 100644 src/test/services/super-admin/CustomersService.test.ts create mode 100644 src/test/services/super-admin/DeedService.test.ts create mode 100644 src/test/services/super-admin/DeedTypesService.test.ts create mode 100644 src/test/services/super-admin/DocumentTypesService.test.ts create mode 100644 src/test/services/super-admin/MockedData.ts create mode 100644 src/test/services/super-admin/UsersService.test.ts diff --git a/.env.test b/.env.test new file mode 100644 index 00000000..0e84c552 --- /dev/null +++ b/.env.test @@ -0,0 +1,4 @@ +DATABASE_URL="postgresql://prisma:prisma@localhost:5433/tests" +POSTGRES_USER=prisma +POSTGRES_PASSWORD=prisma +POSTGRES_DB: tests \ No newline at end of file diff --git a/docker-compose-test.yml b/docker-compose-test.yml new file mode 100644 index 00000000..f5f56f3b --- /dev/null +++ b/docker-compose-test.yml @@ -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 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 92f5eff6..b5a05009 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -46,4 +46,4 @@ services: test: ["CMD-SHELL", "pg_isready -h localhost -U ${DATABASE_USER} -d ${DATABASE_NAME}"] interval: 5s timeout: 5s - retries: 10 \ No newline at end of file + retries: 10 diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 00000000..6784f0af --- /dev/null +++ b/jest.config.js @@ -0,0 +1,19 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + "moduleNameMapper": { + "@Services/(.*)": "/src/services/$1", + "@App/(.*)": "/src/app/$1", + "@Api/(.*)": "/src/app/api/$1", + "@Pages/(.*)": "/src/pages/$1", + "@Common/(.*)": "/src/common/$1", + "@Repositories/(.*)": "/src/common/repositories/$1", + "@Entries/(.*)": "/src/common/entries/$1", + "@Config/(.*)": "/src/common/config/$1", + "@Entities/(.*)": "/src/common/entities/$1", + "@System/(.*)": "/src/common/system/$1", + "@ControllerPattern/(.*)": "/src/common/system/controller-pattern/$1", + "@Test/(.*)": "/src/test/$1" + } +}; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 1cd68512..00000000 --- a/package-lock.json +++ /dev/null @@ -1,2517 +0,0 @@ -{ - "name": "lecoffre-back", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "lecoffre-back", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@prisma/client": "^4.9.0", - "axios": "^1.3.3", - "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", - "module-alias": "^2.2.2", - "next": "^13.1.5", - "node-cache": "^5.1.2", - "node-schedule": "^2.1.1", - "prisma-query": "^2.0.0", - "reflect-metadata": "^0.1.13", - "ts-node": "^10.9.1", - "tslib": "^2.4.1", - "typedi": "^0.10.0", - "typescript": "^4.9.4", - "uuid": "^9.0.0" - }, - "devDependencies": { - "@types/cors": "^2.8.13", - "@types/express": "^4.17.16", - "@types/node": "^18.11.18", - "@types/node-schedule": "^2.1.0", - "@types/uuid": "^9.0.0", - "nodemon": "^2.0.20", - "prettier": "2.8.4", - "prisma": "^4.11.0" - } - }, - "github.com:smart-chain-fr/leCoffre-resources.git": {}, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.0", - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "node_modules/@next/env": { - "version": "13.2.4", - "license": "MIT" - }, - "node_modules/@next/swc-darwin-arm64": { - "version": "13.2.4", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@prisma/client": { - "version": "4.11.0", - "hasInstallScript": true, - "license": "Apache-2.0", - "dependencies": { - "@prisma/engines-version": "4.11.0-57.8fde8fef4033376662cad983758335009d522acb" - }, - "engines": { - "node": ">=14.17" - }, - "peerDependencies": { - "prisma": "*" - }, - "peerDependenciesMeta": { - "prisma": { - "optional": true - } - } - }, - "node_modules/@prisma/engines": { - "version": "4.11.0", - "devOptional": true, - "hasInstallScript": true, - "license": "Apache-2.0" - }, - "node_modules/@prisma/engines-version": { - "version": "4.11.0-57.8fde8fef4033376662cad983758335009d522acb", - "license": "Apache-2.0" - }, - "node_modules/@swc/helpers": { - "version": "0.4.14", - "license": "MIT", - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@tsconfig/node10": { - "version": "1.0.9", - "license": "MIT" - }, - "node_modules/@tsconfig/node12": { - "version": "1.0.11", - "license": "MIT" - }, - "node_modules/@tsconfig/node14": { - "version": "1.0.3", - "license": "MIT" - }, - "node_modules/@tsconfig/node16": { - "version": "1.0.3", - "license": "MIT" - }, - "node_modules/@types/body-parser": { - "version": "1.19.2", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/connect": "*", - "@types/node": "*" - } - }, - "node_modules/@types/connect": { - "version": "3.4.35", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/cors": { - "version": "2.8.13", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/express": { - "version": "4.17.17", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", - "@types/serve-static": "*" - } - }, - "node_modules/@types/express-serve-static-core": { - "version": "4.17.33", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*" - } - }, - "node_modules/@types/mime": { - "version": "3.0.1", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "18.15.3", - "license": "MIT" - }, - "node_modules/@types/node-schedule": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/qs": { - "version": "6.9.7", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/range-parser": { - "version": "1.2.4", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/serve-static": { - "version": "1.15.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/mime": "*", - "@types/node": "*" - } - }, - "node_modules/@types/uuid": { - "version": "9.0.1", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/validator": { - "version": "13.7.14", - "license": "MIT" - }, - "node_modules/abbrev": { - "version": "1.1.1", - "dev": true, - "license": "ISC" - }, - "node_modules/accepts": { - "version": "1.3.8", - "license": "MIT", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/acorn": { - "version": "8.8.2", - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-walk": { - "version": "8.2.0", - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/arg": { - "version": "4.1.3", - "license": "MIT" - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "license": "MIT" - }, - "node_modules/asynckit": { - "version": "0.4.0", - "license": "MIT" - }, - "node_modules/axios": { - "version": "1.3.4", - "license": "MIT", - "dependencies": { - "follow-redirects": "^1.15.0", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/binary-extensions": { - "version": "2.2.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/body-parser": { - "version": "1.20.1", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/brace-expansion": { - "version": "1.1.11", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.2", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/bytes": { - "version": "3.1.2", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind": { - "version": "1.0.2", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001466", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chokidar": { - "version": "3.5.3", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ], - "license": "MIT", - "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "engines": { - "node": ">= 8.10.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, - "node_modules/class-transformer": { - "version": "0.5.1", - "license": "MIT" - }, - "node_modules/class-validator": { - "version": "0.14.0", - "license": "MIT", - "dependencies": { - "@types/validator": "^13.7.10", - "libphonenumber-js": "^1.10.14", - "validator": "^13.7.0" - } - }, - "node_modules/classnames": { - "version": "2.3.2", - "license": "MIT" - }, - "node_modules/client-only": { - "version": "0.0.1", - "license": "MIT" - }, - "node_modules/clone": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", - "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", - "engines": { - "node": ">=0.8" - } - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "dev": true, - "license": "MIT" - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.5.0", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.6", - "license": "MIT" - }, - "node_modules/cors": { - "version": "2.8.5", - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/create-require": { - "version": "1.1.1", - "license": "MIT" - }, - "node_modules/cron-parser": { - "version": "4.8.1", - "license": "MIT", - "dependencies": { - "luxon": "^3.2.1" - }, - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/debug": { - "version": "2.6.9", - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/diff": { - "version": "4.0.2", - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.3.1" - } - }, - "node_modules/dotenv": { - "version": "16.0.3", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "1.0.2", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "license": "MIT" - }, - "node_modules/etag": { - "version": "1.8.1", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/express": { - "version": "4.18.2", - "license": "MIT", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "1.20.1", - "content-disposition": "0.5.4", - "content-type": "~1.0.4", - "cookie": "0.5.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.2.0", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.7", - "qs": "6.11.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - } - }, - "node_modules/fill-range": { - "version": "7.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/finalhandler": { - "version": "1.2.0", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/follow-redirects": { - "version": "1.15.2", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/form-data": { - "version": "4.0.0", - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fsevents": { - "version": "2.3.2", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.1", - "license": "MIT" - }, - "node_modules/get-intrinsic": { - "version": "1.2.0", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/glob-parent": { - "version": "5.1.2", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/has": { - "version": "1.0.3", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/has-flag": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/has-symbols": { - "version": "1.0.3", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/http-errors": { - "version": "2.0.0", - "license": "MIT", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ignore-by-default": { - "version": "1.0.1", - "dev": true, - "license": "ISC" - }, - "node_modules/inherits": { - "version": "2.0.4", - "license": "ISC" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "license": "MIT", - "peer": true - }, - "node_modules/le-coffre-ressources": { - "resolved": "github.com:smart-chain-fr/leCoffre-resources.git", - "link": true - }, - "node_modules/libphonenumber-js": { - "version": "1.10.24", - "license": "MIT" - }, - "node_modules/long-timeout": { - "version": "0.1.1", - "license": "MIT" - }, - "node_modules/loose-envify": { - "version": "1.4.0", - "license": "MIT", - "peer": true, - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "bin": { - "loose-envify": "cli.js" - } - }, - "node_modules/luxon": { - "version": "3.3.0", - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/make-error": { - "version": "1.3.6", - "license": "ISC" - }, - "node_modules/media-typer": { - "version": "0.3.0", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.1", - "license": "MIT" - }, - "node_modules/methods": { - "version": "1.1.2", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/minimatch": { - "version": "3.1.2", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/module-alias": { - "version": "2.2.2", - "license": "MIT" - }, - "node_modules/ms": { - "version": "2.0.0", - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.4", - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/negotiator": { - "version": "0.6.3", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/next": { - "version": "13.2.4", - "license": "MIT", - "dependencies": { - "@next/env": "13.2.4", - "@swc/helpers": "0.4.14", - "caniuse-lite": "^1.0.30001406", - "postcss": "8.4.14", - "styled-jsx": "5.1.1" - }, - "bin": { - "next": "dist/bin/next" - }, - "engines": { - "node": ">=14.6.0" - }, - "optionalDependencies": { - "@next/swc-android-arm-eabi": "13.2.4", - "@next/swc-android-arm64": "13.2.4", - "@next/swc-darwin-arm64": "13.2.4", - "@next/swc-darwin-x64": "13.2.4", - "@next/swc-freebsd-x64": "13.2.4", - "@next/swc-linux-arm-gnueabihf": "13.2.4", - "@next/swc-linux-arm64-gnu": "13.2.4", - "@next/swc-linux-arm64-musl": "13.2.4", - "@next/swc-linux-x64-gnu": "13.2.4", - "@next/swc-linux-x64-musl": "13.2.4", - "@next/swc-win32-arm64-msvc": "13.2.4", - "@next/swc-win32-ia32-msvc": "13.2.4", - "@next/swc-win32-x64-msvc": "13.2.4" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.4.0", - "fibers": ">= 3.1.0", - "node-sass": "^6.0.0 || ^7.0.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sass": "^1.3.0" - }, - "peerDependenciesMeta": { - "@opentelemetry/api": { - "optional": true - }, - "fibers": { - "optional": true - }, - "node-sass": { - "optional": true - }, - "sass": { - "optional": true - } - } - }, - "node_modules/node-cache": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz", - "integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==", - "dependencies": { - "clone": "2.x" - }, - "engines": { - "node": ">= 8.0.0" - } - }, - "node_modules/node-schedule": { - "version": "2.1.1", - "license": "MIT", - "dependencies": { - "cron-parser": "^4.2.0", - "long-timeout": "0.1.1", - "sorted-array-functions": "^1.3.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/nodemon": { - "version": "2.0.21", - "dev": true, - "license": "MIT", - "dependencies": { - "chokidar": "^3.5.2", - "debug": "^3.2.7", - "ignore-by-default": "^1.0.1", - "minimatch": "^3.1.2", - "pstree.remy": "^1.1.8", - "semver": "^5.7.1", - "simple-update-notifier": "^1.0.7", - "supports-color": "^5.5.0", - "touch": "^3.1.0", - "undefsafe": "^2.0.5" - }, - "bin": { - "nodemon": "bin/nodemon.js" - }, - "engines": { - "node": ">=8.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/nodemon" - } - }, - "node_modules/nodemon/node_modules/debug": { - "version": "3.2.7", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.1" - } - }, - "node_modules/nodemon/node_modules/ms": { - "version": "2.1.3", - "dev": true, - "license": "MIT" - }, - "node_modules/nopt": { - "version": "1.0.10", - "dev": true, - "license": "MIT", - "dependencies": { - "abbrev": "1" - }, - "bin": { - "nopt": "bin/nopt.js" - } - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.12.3", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-to-regexp": { - "version": "0.1.7", - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.0.0", - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.4.14", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.4", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/prettier": { - "version": "2.8.4", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin-prettier.js" - }, - "engines": { - "node": ">=10.13.0" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/prisma": { - "version": "4.11.0", - "devOptional": true, - "hasInstallScript": true, - "license": "Apache-2.0", - "dependencies": { - "@prisma/engines": "4.11.0" - }, - "bin": { - "prisma": "build/index.js", - "prisma2": "build/index.js" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/prisma-query": { - "version": "2.0.0", - "license": "MIT" - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/proxy-from-env": { - "version": "1.1.0", - "license": "MIT" - }, - "node_modules/pstree.remy": { - "version": "1.1.8", - "dev": true, - "license": "MIT" - }, - "node_modules/qs": { - "version": "6.11.0", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.0.4" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.1", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/react": { - "version": "18.2.0", - "license": "MIT", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "18.2.0", - "license": "MIT", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.0" - }, - "peerDependencies": { - "react": "^18.2.0" - } - }, - "node_modules/readdirp": { - "version": "3.6.0", - "dev": true, - "license": "MIT", - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/reflect-metadata": { - "version": "0.1.13", - "license": "Apache-2.0" - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "license": "MIT" - }, - "node_modules/scheduler": { - "version": "0.23.0", - "license": "MIT", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0" - } - }, - "node_modules/semver": { - "version": "5.7.1", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/send": { - "version": "0.18.0", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "license": "MIT" - }, - "node_modules/serve-static": { - "version": "1.15.0", - "license": "MIT", - "dependencies": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.18.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "license": "ISC" - }, - "node_modules/side-channel": { - "version": "1.0.4", - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/simple-update-notifier": { - "version": "1.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "~7.0.0" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/simple-update-notifier/node_modules/semver": { - "version": "7.0.0", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/sorted-array-functions": { - "version": "1.3.0", - "license": "MIT" - }, - "node_modules/source-map-js": { - "version": "1.0.2", - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/statuses": { - "version": "2.0.1", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/styled-jsx": { - "version": "5.1.1", - "license": "MIT", - "dependencies": { - "client-only": "0.0.1" - }, - "engines": { - "node": ">= 12.0.0" - }, - "peerDependencies": { - "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/supports-color": { - "version": "5.5.0", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/touch": { - "version": "3.1.0", - "dev": true, - "license": "ISC", - "dependencies": { - "nopt": "~1.0.10" - }, - "bin": { - "nodetouch": "bin/nodetouch.js" - } - }, - "node_modules/ts-node": { - "version": "10.9.1", - "license": "MIT", - "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } - } - }, - "node_modules/tslib": { - "version": "2.5.0", - "license": "0BSD" - }, - "node_modules/type-is": { - "version": "1.6.18", - "license": "MIT", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/typedi": { - "version": "0.10.0", - "license": "MIT" - }, - "node_modules/typescript": { - "version": "4.9.5", - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=4.2.0" - } - }, - "node_modules/undefsafe": { - "version": "2.0.5", - "dev": true, - "license": "MIT" - }, - "node_modules/unpipe": { - "version": "1.0.0", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "license": "MIT", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/uuid": { - "version": "9.0.0", - "license": "MIT", - "bin": { - "uuid": "dist/bin/uuid" - } - }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "license": "MIT" - }, - "node_modules/validator": { - "version": "13.9.0", - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/yn": { - "version": "3.1.1", - "license": "MIT", - "engines": { - "node": ">=6" - } - } - }, - "dependencies": { - "@cspotcode/source-map-support": { - "version": "0.8.1", - "requires": { - "@jridgewell/trace-mapping": "0.3.9" - } - }, - "@jridgewell/resolve-uri": { - "version": "3.1.0" - }, - "@jridgewell/sourcemap-codec": { - "version": "1.4.14" - }, - "@jridgewell/trace-mapping": { - "version": "0.3.9", - "requires": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "@next/env": { - "version": "13.2.4" - }, - "@next/swc-darwin-arm64": { - "version": "13.2.4", - "optional": true - }, - "@prisma/client": { - "version": "4.11.0", - "requires": { - "@prisma/engines-version": "4.11.0-57.8fde8fef4033376662cad983758335009d522acb" - } - }, - "@prisma/engines": { - "version": "4.11.0", - "devOptional": true - }, - "@prisma/engines-version": { - "version": "4.11.0-57.8fde8fef4033376662cad983758335009d522acb" - }, - "@swc/helpers": { - "version": "0.4.14", - "requires": { - "tslib": "^2.4.0" - } - }, - "@tsconfig/node10": { - "version": "1.0.9" - }, - "@tsconfig/node12": { - "version": "1.0.11" - }, - "@tsconfig/node14": { - "version": "1.0.3" - }, - "@tsconfig/node16": { - "version": "1.0.3" - }, - "@types/body-parser": { - "version": "1.19.2", - "dev": true, - "requires": { - "@types/connect": "*", - "@types/node": "*" - } - }, - "@types/connect": { - "version": "3.4.35", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/cors": { - "version": "2.8.13", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/express": { - "version": "4.17.17", - "dev": true, - "requires": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", - "@types/serve-static": "*" - } - }, - "@types/express-serve-static-core": { - "version": "4.17.33", - "dev": true, - "requires": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*" - } - }, - "@types/mime": { - "version": "3.0.1", - "dev": true - }, - "@types/node": { - "version": "18.15.3" - }, - "@types/node-schedule": { - "version": "2.1.0", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/qs": { - "version": "6.9.7", - "dev": true - }, - "@types/range-parser": { - "version": "1.2.4", - "dev": true - }, - "@types/serve-static": { - "version": "1.15.1", - "dev": true, - "requires": { - "@types/mime": "*", - "@types/node": "*" - } - }, - "@types/uuid": { - "version": "9.0.1", - "dev": true - }, - "@types/validator": { - "version": "13.7.14" - }, - "abbrev": { - "version": "1.1.1", - "dev": true - }, - "accepts": { - "version": "1.3.8", - "requires": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - } - }, - "acorn": { - "version": "8.8.2" - }, - "acorn-walk": { - "version": "8.2.0" - }, - "anymatch": { - "version": "3.1.3", - "dev": true, - "requires": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - } - }, - "arg": { - "version": "4.1.3" - }, - "array-flatten": { - "version": "1.1.1" - }, - "asynckit": { - "version": "0.4.0" - }, - "axios": { - "version": "1.3.4", - "requires": { - "follow-redirects": "^1.15.0", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" - } - }, - "balanced-match": { - "version": "1.0.2", - "dev": true - }, - "binary-extensions": { - "version": "2.2.0", - "dev": true - }, - "body-parser": { - "version": "1.20.1", - "requires": { - "bytes": "3.1.2", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - } - }, - "brace-expansion": { - "version": "1.1.11", - "dev": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "braces": { - "version": "3.0.2", - "dev": true, - "requires": { - "fill-range": "^7.0.1" - } - }, - "bytes": { - "version": "3.1.2" - }, - "call-bind": { - "version": "1.0.2", - "requires": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" - } - }, - "caniuse-lite": { - "version": "1.0.30001466" - }, - "chokidar": { - "version": "3.5.3", - "dev": true, - "requires": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "fsevents": "~2.3.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - } - }, - "class-transformer": { - "version": "0.5.1" - }, - "class-validator": { - "version": "0.14.0", - "requires": { - "@types/validator": "^13.7.10", - "libphonenumber-js": "^1.10.14", - "validator": "^13.7.0" - } - }, - "classnames": { - "version": "2.3.2" - }, - "client-only": { - "version": "0.0.1" - }, - "clone": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", - "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==" - }, - "combined-stream": { - "version": "1.0.8", - "requires": { - "delayed-stream": "~1.0.0" - } - }, - "concat-map": { - "version": "0.0.1", - "dev": true - }, - "content-disposition": { - "version": "0.5.4", - "requires": { - "safe-buffer": "5.2.1" - } - }, - "content-type": { - "version": "1.0.5" - }, - "cookie": { - "version": "0.5.0" - }, - "cookie-signature": { - "version": "1.0.6" - }, - "cors": { - "version": "2.8.5", - "requires": { - "object-assign": "^4", - "vary": "^1" - } - }, - "create-require": { - "version": "1.1.1" - }, - "cron-parser": { - "version": "4.8.1", - "requires": { - "luxon": "^3.2.1" - } - }, - "debug": { - "version": "2.6.9", - "requires": { - "ms": "2.0.0" - } - }, - "delayed-stream": { - "version": "1.0.0" - }, - "depd": { - "version": "2.0.0" - }, - "destroy": { - "version": "1.2.0" - }, - "diff": { - "version": "4.0.2" - }, - "dotenv": { - "version": "16.0.3" - }, - "ee-first": { - "version": "1.1.1" - }, - "encodeurl": { - "version": "1.0.2" - }, - "escape-html": { - "version": "1.0.3" - }, - "etag": { - "version": "1.8.1" - }, - "express": { - "version": "4.18.2", - "requires": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "1.20.1", - "content-disposition": "0.5.4", - "content-type": "~1.0.4", - "cookie": "0.5.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.2.0", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.7", - "qs": "6.11.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - } - }, - "fill-range": { - "version": "7.0.1", - "dev": true, - "requires": { - "to-regex-range": "^5.0.1" - } - }, - "finalhandler": { - "version": "1.2.0", - "requires": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - } - }, - "follow-redirects": { - "version": "1.15.2" - }, - "form-data": { - "version": "4.0.0", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - }, - "forwarded": { - "version": "0.2.0" - }, - "fresh": { - "version": "0.5.2" - }, - "fsevents": { - "version": "2.3.2", - "dev": true, - "optional": true - }, - "function-bind": { - "version": "1.1.1" - }, - "get-intrinsic": { - "version": "1.2.0", - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.3" - } - }, - "glob-parent": { - "version": "5.1.2", - "dev": true, - "requires": { - "is-glob": "^4.0.1" - } - }, - "has": { - "version": "1.0.3", - "requires": { - "function-bind": "^1.1.1" - } - }, - "has-flag": { - "version": "3.0.0", - "dev": true - }, - "has-symbols": { - "version": "1.0.3" - }, - "http-errors": { - "version": "2.0.0", - "requires": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - } - }, - "iconv-lite": { - "version": "0.4.24", - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - }, - "ignore-by-default": { - "version": "1.0.1", - "dev": true - }, - "inherits": { - "version": "2.0.4" - }, - "ipaddr.js": { - "version": "1.9.1" - }, - "is-binary-path": { - "version": "2.1.0", - "dev": true, - "requires": { - "binary-extensions": "^2.0.0" - } - }, - "is-extglob": { - "version": "2.1.1", - "dev": true - }, - "is-glob": { - "version": "4.0.3", - "dev": true, - "requires": { - "is-extglob": "^2.1.1" - } - }, - "is-number": { - "version": "7.0.0", - "dev": true - }, - "js-tokens": { - "version": "4.0.0", - "peer": true - }, - "le-coffre-ressources": { - "version": "file:github.com:smart-chain-fr/leCoffre-resources.git" - }, - "libphonenumber-js": { - "version": "1.10.24" - }, - "long-timeout": { - "version": "0.1.1" - }, - "loose-envify": { - "version": "1.4.0", - "peer": true, - "requires": { - "js-tokens": "^3.0.0 || ^4.0.0" - } - }, - "luxon": { - "version": "3.3.0" - }, - "make-error": { - "version": "1.3.6" - }, - "media-typer": { - "version": "0.3.0" - }, - "merge-descriptors": { - "version": "1.0.1" - }, - "methods": { - "version": "1.1.2" - }, - "mime": { - "version": "1.6.0" - }, - "mime-db": { - "version": "1.52.0" - }, - "mime-types": { - "version": "2.1.35", - "requires": { - "mime-db": "1.52.0" - } - }, - "minimatch": { - "version": "3.1.2", - "dev": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "module-alias": { - "version": "2.2.2" - }, - "ms": { - "version": "2.0.0" - }, - "nanoid": { - "version": "3.3.4" - }, - "negotiator": { - "version": "0.6.3" - }, - "next": { - "version": "13.2.4", - "requires": { - "@next/env": "13.2.4", - "@next/swc-android-arm-eabi": "13.2.4", - "@next/swc-android-arm64": "13.2.4", - "@next/swc-darwin-arm64": "13.2.4", - "@next/swc-darwin-x64": "13.2.4", - "@next/swc-freebsd-x64": "13.2.4", - "@next/swc-linux-arm-gnueabihf": "13.2.4", - "@next/swc-linux-arm64-gnu": "13.2.4", - "@next/swc-linux-arm64-musl": "13.2.4", - "@next/swc-linux-x64-gnu": "13.2.4", - "@next/swc-linux-x64-musl": "13.2.4", - "@next/swc-win32-arm64-msvc": "13.2.4", - "@next/swc-win32-ia32-msvc": "13.2.4", - "@next/swc-win32-x64-msvc": "13.2.4", - "@swc/helpers": "0.4.14", - "caniuse-lite": "^1.0.30001406", - "postcss": "8.4.14", - "styled-jsx": "5.1.1" - } - }, - "node-cache": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz", - "integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==", - "requires": { - "clone": "2.x" - } - }, - "node-schedule": { - "version": "2.1.1", - "requires": { - "cron-parser": "^4.2.0", - "long-timeout": "0.1.1", - "sorted-array-functions": "^1.3.0" - } - }, - "nodemon": { - "version": "2.0.21", - "dev": true, - "requires": { - "chokidar": "^3.5.2", - "debug": "^3.2.7", - "ignore-by-default": "^1.0.1", - "minimatch": "^3.1.2", - "pstree.remy": "^1.1.8", - "semver": "^5.7.1", - "simple-update-notifier": "^1.0.7", - "supports-color": "^5.5.0", - "touch": "^3.1.0", - "undefsafe": "^2.0.5" - }, - "dependencies": { - "debug": { - "version": "3.2.7", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.3", - "dev": true - } - } - }, - "nopt": { - "version": "1.0.10", - "dev": true, - "requires": { - "abbrev": "1" - } - }, - "normalize-path": { - "version": "3.0.0", - "dev": true - }, - "object-assign": { - "version": "4.1.1" - }, - "object-inspect": { - "version": "1.12.3" - }, - "on-finished": { - "version": "2.4.1", - "requires": { - "ee-first": "1.1.1" - } - }, - "parseurl": { - "version": "1.3.3" - }, - "path-to-regexp": { - "version": "0.1.7" - }, - "picocolors": { - "version": "1.0.0" - }, - "picomatch": { - "version": "2.3.1", - "dev": true - }, - "postcss": { - "version": "8.4.14", - "requires": { - "nanoid": "^3.3.4", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - } - }, - "prettier": { - "version": "2.8.4", - "dev": true - }, - "prisma": { - "version": "4.11.0", - "devOptional": true, - "requires": { - "@prisma/engines": "4.11.0" - } - }, - "prisma-query": { - "version": "2.0.0" - }, - "proxy-addr": { - "version": "2.0.7", - "requires": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - } - }, - "proxy-from-env": { - "version": "1.1.0" - }, - "pstree.remy": { - "version": "1.1.8", - "dev": true - }, - "qs": { - "version": "6.11.0", - "requires": { - "side-channel": "^1.0.4" - } - }, - "range-parser": { - "version": "1.2.1" - }, - "raw-body": { - "version": "2.5.1", - "requires": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - } - }, - "react": { - "version": "18.2.0", - "peer": true, - "requires": { - "loose-envify": "^1.1.0" - } - }, - "react-dom": { - "version": "18.2.0", - "peer": true, - "requires": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.0" - } - }, - "readdirp": { - "version": "3.6.0", - "dev": true, - "requires": { - "picomatch": "^2.2.1" - } - }, - "reflect-metadata": { - "version": "0.1.13" - }, - "safe-buffer": { - "version": "5.2.1" - }, - "safer-buffer": { - "version": "2.1.2" - }, - "scheduler": { - "version": "0.23.0", - "peer": true, - "requires": { - "loose-envify": "^1.1.0" - } - }, - "semver": { - "version": "5.7.1", - "dev": true - }, - "send": { - "version": "0.18.0", - "requires": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" - }, - "dependencies": { - "ms": { - "version": "2.1.3" - } - } - }, - "serve-static": { - "version": "1.15.0", - "requires": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.18.0" - } - }, - "setprototypeof": { - "version": "1.2.0" - }, - "side-channel": { - "version": "1.0.4", - "requires": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - } - }, - "simple-update-notifier": { - "version": "1.1.0", - "dev": true, - "requires": { - "semver": "~7.0.0" - }, - "dependencies": { - "semver": { - "version": "7.0.0", - "dev": true - } - } - }, - "sorted-array-functions": { - "version": "1.3.0" - }, - "source-map-js": { - "version": "1.0.2" - }, - "statuses": { - "version": "2.0.1" - }, - "styled-jsx": { - "version": "5.1.1", - "requires": { - "client-only": "0.0.1" - } - }, - "supports-color": { - "version": "5.5.0", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "to-regex-range": { - "version": "5.0.1", - "dev": true, - "requires": { - "is-number": "^7.0.0" - } - }, - "toidentifier": { - "version": "1.0.1" - }, - "touch": { - "version": "3.1.0", - "dev": true, - "requires": { - "nopt": "~1.0.10" - } - }, - "ts-node": { - "version": "10.9.1", - "requires": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - } - }, - "tslib": { - "version": "2.5.0" - }, - "type-is": { - "version": "1.6.18", - "requires": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - } - }, - "typedi": { - "version": "0.10.0" - }, - "typescript": { - "version": "4.9.5" - }, - "undefsafe": { - "version": "2.0.5", - "dev": true - }, - "unpipe": { - "version": "1.0.0" - }, - "utils-merge": { - "version": "1.0.1" - }, - "uuid": { - "version": "9.0.0" - }, - "v8-compile-cache-lib": { - "version": "3.0.1" - }, - "validator": { - "version": "13.9.0" - }, - "vary": { - "version": "1.1.2" - }, - "yn": { - "version": "3.1.1" - } - } -} diff --git a/package.json b/package.json index bc3e47db..0d33fc07 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,8 @@ "@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": "tsc", @@ -23,7 +24,11 @@ "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": "npx prisma migrate deploy", + "docker:up": "docker-compose up -d", + "docker:up:test": "docker-compose -f docker-compose-test.yml up -d", + "docker:down": "docker-compose -f docker-compose-test.yml down", + "test": "tsc && npm run docker:up:test && jest -i --verbose ./dist/test/* && npm run docker:down" }, "repository": { "type": "git", @@ -36,15 +41,14 @@ }, "homepage": "https://github.com/smart-chain-fr/leCoffre-back#readme", "dependencies": { - "@prisma/client": "^4.9.0", - "axios": "^1.3.3", + "@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", + "le-coffre-resources": "git@github.com:smart-chain-fr/leCoffre-resources.git#v2.19", "module-alias": "^2.2.2", "next": "^13.1.5", "node-cache": "^5.1.2", @@ -60,12 +64,15 @@ "devDependencies": { "@types/cors": "^2.8.13", "@types/express": "^4.17.16", + "@types/jest": "^29.5.0", "@types/node": "^18.11.18", "@types/node-schedule": "^2.1.0", "@types/uuid": "^9.0.0", + "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" diff --git a/src/app/HomeController.ts b/src/app/HomeController.ts index ae366a0f..2d84c394 100644 --- a/src/app/HomeController.ts +++ b/src/app/HomeController.ts @@ -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!"); } } - diff --git a/src/app/api/CustomersController.ts b/src/app/api/CustomersController.ts deleted file mode 100644 index 89aa15e5..00000000 --- a/src/app/api/CustomersController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/DeedTypesController.ts b/src/app/api/DeedTypesController.ts deleted file mode 100644 index 400649fa..00000000 --- a/src/app/api/DeedTypesController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/DeedsController.ts b/src/app/api/DeedsController.ts deleted file mode 100644 index 264d943a..00000000 --- a/src/app/api/DeedsController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/DocumentTypesController.ts b/src/app/api/DocumentTypesController.ts deleted file mode 100644 index bea1cd3d..00000000 --- a/src/app/api/DocumentTypesController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/FoldersController.ts b/src/app/api/FoldersController.ts deleted file mode 100644 index 4b5200ab..00000000 --- a/src/app/api/FoldersController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/OfficesController.ts b/src/app/api/OfficesController.ts deleted file mode 100644 index 6cf6140d..00000000 --- a/src/app/api/OfficesController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/UsersController.ts b/src/app/api/UsersController.ts deleted file mode 100644 index fb2f5450..00000000 --- a/src/app/api/UsersController.ts +++ /dev/null @@ -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")); - } -} diff --git a/src/app/api/projects/UserController.ts b/src/app/api/projects/UserController.ts deleted file mode 100644 index e9aff82a..00000000 --- a/src/app/api/projects/UserController.ts +++ /dev/null @@ -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" }); - } - -} - diff --git a/src/app/api/super-admin/CustomersController.ts b/src/app/api/super-admin/CustomersController.ts new file mode 100644 index 00000000..cd24238d --- /dev/null +++ b/src/app/api/super-admin/CustomersController.ts @@ -0,0 +1,131 @@ +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 { processFindManyQuery } from "prisma-query"; +import ObjectHydrate from "@Common/helpers/ObjectHydrate"; +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 + * @returns ICustomer[] list of customers + */ + @Get("/api/v1/super-admin/customers") + protected async get(req: Request, response: Response) { + try { + //get query + const query = processFindManyQuery(req.query); + + //call service to get prisma entity + const customersEntity: Customers[] = await this.customersService.get(query); + + //Hydrate ressource with prisma entity + const customers = ObjectHydrate.map(Customer, customersEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, customers); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Create a new customer + * @returns ICustomer created + */ + @Post("/api/v1/super-admin/customers") + protected async post(req: Request, response: Response) { + try { + //init IUser resource with request body values + const customerEntity = new Customer(); + ObjectHydrate.hydrate(customerEntity, req.body); + + //validate user + await validateOrReject(customerEntity, { groups: ["create"] }); + + //call service to get prisma entity + const prismaEntityCreated = await this.customersService.create(customerEntity); + + //Hydrate ressource with prisma entity + const customerEntityCreated = ObjectHydrate.hydrate(new Customer(), prismaEntityCreated, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, customerEntityCreated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Modify a specific customer by uid + * @returns ICustomer modified + */ + @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 = new Customer(); + ObjectHydrate.hydrate(customerEntity, req.body); + //validate user + await validateOrReject(customerEntity, { groups: ["update"] }); + + //call service to get prisma entity + const prismaEntityUpdated = await this.customersService.update(uid, customerEntity); + + //Hydrate ressource with prisma entity + const customerEntityUpdated = ObjectHydrate.hydrate(new Customer(), prismaEntityUpdated, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, customerEntityUpdated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Get a specific customer by uid + * @returns ICustomer + */ + @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 uuid provided"); + } + + //call service to get prisma entity + const customerEntity: Customers = await this.customersService.getByUid(uid); + + //Hydrate ressource with prisma entity + const customer = ObjectHydrate.hydrate(new Customer(), customerEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, customer); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } +} diff --git a/src/app/api/super-admin/DeedTypesController.ts b/src/app/api/super-admin/DeedTypesController.ts new file mode 100644 index 00000000..9bbfd160 --- /dev/null +++ b/src/app/api/super-admin/DeedTypesController.ts @@ -0,0 +1,132 @@ +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 { processFindManyQuery } from "prisma-query"; +import { DeedTypes } from "@prisma/client"; +import ObjectHydrate from "@Common/helpers/ObjectHydrate"; +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 IDeedtype[] list of deedtypes + */ + @Get("/api/v1/super-admin/deed-types") + protected async get(req: Request, response: Response) { + try { + //get query + const query = processFindManyQuery(req.query); + + //call service to get prisma entity + const prismaEntity: DeedTypes[] = await this.deedTypesService.get(query); + + //Hydrate ressource with prisma entity + const DeedTypes = ObjectHydrate.map(DeedType, prismaEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, DeedTypes); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Create a new deedtype + * @returns IDeedtype 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 = new DeedType(); + ObjectHydrate.hydrate(deedTypeEntity, req.body); + + //validate deed type + await validateOrReject(deedTypeEntity, { groups: ["create"] }); + + //call service to get prisma entity + const prismaEntityCreated = await this.deedTypesService.create(deedTypeEntity); + + //Hydrate ressource with prisma entity + const deedTypeEntityCreated = ObjectHydrate.hydrate(new DeedType(), prismaEntityCreated, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, deedTypeEntityCreated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Modify a specific deedtype by uid + * @returns IDeedtype 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 uuid provided"); + } + //init DeedType resource with request body values + const deedTypeEntity = new DeedType(); + ObjectHydrate.hydrate(deedTypeEntity, req.body); + + //validate deed type + await validateOrReject(deedTypeEntity, { groups: ["update"] }); + + //call service to get prisma entity + const prismaEntityUpdated = await this.deedTypesService.update(uid, deedTypeEntity); + + //Hydrate ressource with prisma entity + const deedTypeEntityUpdated = ObjectHydrate.hydrate(new DeedType(), prismaEntityUpdated, { + strategy: "exposeAll", + }); + + //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 uuid provided"); + } + + //call service to get prisma entity + const userEntity: DeedTypes = await this.deedTypesService.getByUid(uid); + + //Hydrate ressource with prisma entity + const user = ObjectHydrate.hydrate(new DeedType(), userEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, user); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } +} diff --git a/src/app/api/super-admin/DeedsController.ts b/src/app/api/super-admin/DeedsController.ts new file mode 100644 index 00000000..4a82bb3a --- /dev/null +++ b/src/app/api/super-admin/DeedsController.ts @@ -0,0 +1,56 @@ +import { Response, Request } from "express"; +import { Controller, Get } from "@ControllerPattern/index"; +import ApiController from "@Common/system/controller-pattern/ApiController"; +import DeedsService from "@Services/super-admin/DeedsService/DeedsService"; +import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +import { Deeds } from "@prisma/client"; +import Deed from "le-coffre-resources/dist/SuperAdmin"; +import ObjectHydrate from "@Common/helpers/ObjectHydrate"; + +@Controller() +@Service() +export default class DeedsController extends ApiController { + constructor(private deedsService: DeedsService) { + super(); + } + + /** + * @description Get all deeds + * @returns IDeed[] list of deeds + */ + @Get("/api/v1/super-admin/deeds") + protected async get(req: Request, response: Response) { + try { + //get query + const query = processFindManyQuery(req.query); + + //call service to get prisma entity + const prismaEntity: Deeds[] = await this.deedsService.get(query); + + //Hydrate ressource with prisma entity + const deeds = ObjectHydrate.map(Deed, prismaEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, deeds); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Get a specific deed by uid + * @returns IDeed + */ + @Get("/api/v1/super-admin/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")); + } +} diff --git a/src/app/api/super-admin/DocumentTypesController.ts b/src/app/api/super-admin/DocumentTypesController.ts new file mode 100644 index 00000000..7567d216 --- /dev/null +++ b/src/app/api/super-admin/DocumentTypesController.ts @@ -0,0 +1,131 @@ +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 { processFindManyQuery } from "prisma-query"; +import { DocumentTypes } from "@prisma/client"; +import ObjectHydrate from "@Common/helpers/ObjectHydrate"; +import { DocumentType } from "le-coffre-resources/dist/SuperAdmin"; +import { validateOrReject } from "class-validator"; +//import { validateOrReject } from "class-validator"; + +@Controller() +@Service() +export default class DocumentTypesController extends ApiController { + constructor(private documentTypesService: DocumentTypesService) { + super(); + } + + /** + * @description Get all document-types + * @returns DocumentType[] list of document-types + */ + @Get("/api/v1/super-admin/document-types") + protected async get(req: Request, response: Response) { + try { + //get query + const query = processFindManyQuery(req.query); + + //call service to get prisma entity + const prismaEntity: DocumentTypes[] = await this.documentTypesService.get(query); + + //Hydrate ressource with prisma entity + const documentTypes = ObjectHydrate.map(DocumentType, prismaEntity, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, documentTypes); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Create a new documentType + * @returns DocumentType created + */ + @Post("/api/v1/super-admin/document-types") + protected async post(req: Request, response: Response) { + try { + //init DocumentType resource with request body values + const documentTypeEntity = new DocumentType(); + ObjectHydrate.hydrate(documentTypeEntity, req.body); + //validate user + await validateOrReject(documentTypeEntity, { groups: ["create"] }); + //call service to get prisma entity + const prismaEntityCreated = await this.documentTypesService.create(documentTypeEntity); + //Hydrate ressource with prisma entity + const userEntityCreated = ObjectHydrate.hydrate(new DocumentType(), prismaEntityCreated, { + strategy: "exposeAll", + }); + //success + this.httpSuccess(response, userEntityCreated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Modify a specific documentType by uid + * @returns DocumentType modified + */ + @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 uuid provided"); + } + //init DocumentType resource with request body values + const documentTypeEntity = new DocumentType(); + ObjectHydrate.hydrate(documentTypeEntity, 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 = ObjectHydrate.hydrate(new DocumentType(), prismaEntityUpdated, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, documentTypeEntityUpdated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Get a specific documentType by uid + * @returns DocumentType + */ + @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 uuid provided"); + } + + //call service to get prisma entity + const documentTypeEntity: DocumentTypes = await this.documentTypesService.getByUid(uid); + + //Hydrate ressource with prisma entity + const user = ObjectHydrate.hydrate(new DocumentType(), documentTypeEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, user); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } +} diff --git a/src/app/api/DocumentsController.ts b/src/app/api/super-admin/DocumentsController.ts similarity index 50% rename from src/app/api/DocumentsController.ts rename to src/app/api/super-admin/DocumentsController.ts index e23f2191..a7ef7de0 100644 --- a/src/app/api/DocumentsController.ts +++ b/src/app/api/super-admin/DocumentsController.ts @@ -1,16 +1,12 @@ -import { type Response, type Request } from "express"; +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 DocumentsService from "@Services/DocumentsService/DocumentsService"; -// import { IsNotEmpty, IsString, IsUUID } from "class-validator"; - -// class Params { -// @IsString() -// @IsNotEmpty() -// @IsUUID() -// public uuid!: string; -// } +import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService"; +// import { processFindManyQuery } from "prisma-query"; +// import { Documents } from "@prisma/client"; +// import ObjectHydrate from "@Common/helpers/ObjectHydrate"; +// import Document from "le-coffre-resources/dist/SuperAdmin"; @Controller() @Service() @@ -23,22 +19,31 @@ export default class DocumentsController extends ApiController { * @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()); - } + // @Get("/api/super-admin/documents") + // protected async get(req: Request, response: Response) { + // try { + // //get query + // const query = processFindManyQuery(req.query); + + // //call service to get prisma entity + // const prismaEntity: Documents[] = await this.documentsService.get(query); + + // //Hydrate ressource with prisma entity + // const documents = ObjectHydrate.map(Document, prismaEntity, { strategy: "exposeAll" }); + + // //success + // this.httpSuccess(response, documents); + // } catch (error) { + // this.httpBadRequest(response, error); + // return; + // } + // } /** * @description Create a new document * @returns IDocument created */ - @Post("/api/documents") + @Post("/api/v1/super-admin/documents") protected async post(req: Request, response: Response) { try { // TODO @@ -46,14 +51,14 @@ export default class DocumentsController extends ApiController { this.httpBadRequest(response, error); return; } - this.httpSuccess(response, await this.documentsService.create()); + // this.httpSuccess(response, await this.documentsService.create()); } /** * @description Modify a specific document by uid * @returns IDocument modified */ - @Put("/api/documents/:uid") + @Put("/api/v1/super-admin/documents/:uid") protected async put(req: Request, response: Response) { try { // TODO @@ -65,10 +70,10 @@ export default class DocumentsController extends ApiController { } /** - * @description Get a specific document by uid + * @description Get a specific document by uid * @returns IDocument */ - @Get("/api/documents/:uid") + @Get("/api/v1/super-admin/documents/:uid") protected async getOneByUid(req: Request, response: Response) { try { // TODO diff --git a/src/app/api/super-admin/OfficeFoldersController.ts b/src/app/api/super-admin/OfficeFoldersController.ts new file mode 100644 index 00000000..ea27229f --- /dev/null +++ b/src/app/api/super-admin/OfficeFoldersController.ts @@ -0,0 +1,97 @@ +import { Response, Request } from "express"; +import { Controller, 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 { processFindManyQuery } from "prisma-query"; +// import { OfficeFolders } from "@prisma/client"; +// import ObjectHydrate from "@Common/helpers/ObjectHydrate"; +// 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 + * @returns IFolder[] list of folders + */ + @Get("/api/super-admin/folders") + protected async get(req: Request, response: Response) { + try { + //get query + // const query = processFindManyQuery(req.query); + // //call service to get prisma entity + // const prismaEntity: OfficeFolders[] = await this.officeFoldersService.get(query); + // //Hydrate ressource with prisma entity + // const officeFolders = ObjectHydrate.map(OfficeFolder, prismaEntity, { + // strategy: "exposeAll", + // }); + // //success + // this.httpSuccess(response, officeFolders); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Create a new folder + * @returns IFolder created + */ + @Post("/api/super-admin/folders") + protected async post(req: Request, response: Response) { + try { + //init IOfficeFolder resource with request body values + // const officeFolderEntity = new OfficeFolder(); + // ObjectHydrate.hydrate(officeFolderEntity, req.body); + // //validate folder + // await validateOrReject(officeFolderEntity, { groups: ["create"] }); + // //call service to get prisma entity + // const prismaEntityCreated = await this.officeFoldersService.create(officeFolderEntity); + // //Hydrate ressource with prisma entity + // const officeFolderEntityCreated = ObjectHydrate.hydrate(new OfficeFolder(), prismaEntityCreated, { + // strategy: "exposeAll", + // }); + //success + //this.httpSuccess(response, officeFolderEntityCreated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Modify a specific folder by uid + * @returns IFolder modified + */ + @Put("/api/super-admin/folders/:uid") + protected async put(req: Request, response: Response) { + try { + // TODO + } catch (error) { + this.httpBadRequest(response, error); + return; + } + //this.httpSuccess(response, await this.officeFoldersService.update()); + } + + /** + * @description Get a specific folder by uid + * @returns IFolder + */ + @Get("/api/super-admin/folders/:uid") + protected async getOneByUid(req: Request, response: Response) { + try { + // TODO + } catch (error) { + this.httpBadRequest(response, error); + return; + } + this.httpSuccess(response, await this.officeFoldersService.getByUid("uid")); + } +} diff --git a/src/app/api/super-admin/OfficesController.ts b/src/app/api/super-admin/OfficesController.ts new file mode 100644 index 00000000..8604706f --- /dev/null +++ b/src/app/api/super-admin/OfficesController.ts @@ -0,0 +1,114 @@ +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 { processFindManyQuery } from "prisma-query"; +import { Offices } from "@prisma/client"; +import ObjectHydrate from "@Common/helpers/ObjectHydrate"; +import { Office as OfficeRessource } 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 + * @returns IOffice[] list of offices + */ + @Get("/api/v1/super-admin/offices") + protected async get(req: Request, response: Response) { + try { + //get query + const query = processFindManyQuery(req.query); + //call service to get prisma entity + const officesEntity: Offices[] = await this.officesService.get(query); + //Hydrate ressource with prisma entity + const offices = ObjectHydrate.map(OfficeRessource, officesEntity, { strategy: "exposeAll" }); + //success + this.httpSuccess(response, offices); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + /** + * @description Create a new office + * @returns IOffice created + */ + @Post("/api/v1/super-admin/offices") + protected async post(req: Request, response: Response) { + try { + //init IUser resource with request body values + const officeEntity = new OfficeRessource(); + ObjectHydrate.hydrate(officeEntity, req.body); + //validate user + await validateOrReject(officeEntity, { groups: ["create"] }); + //call service to get prisma entity + const prismaEntityCreated = await this.officesService.create(officeEntity); + //Hydrate ressource with prisma entity + const officeEntityCreated = ObjectHydrate.hydrate(new OfficeRessource(), prismaEntityCreated, { + strategy: "exposeAll", + }); + //success + this.httpSuccess(response, officeEntityCreated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + /** + * @description Modify a specific office by uid + * @returns IOffice modified + */ + @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 uuid provided"); + } + //init IUser resource with request body values + const officeEntity = new OfficeRessource(); + ObjectHydrate.hydrate(officeEntity, 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 = ObjectHydrate.hydrate(new OfficeRessource(), prismaEntityUpdated, { + strategy: "exposeAll", + }); + //success + this.httpSuccess(response, officeEntityUpdated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + /** + * @description Get a specific office by uid + * @returns IOffice + */ + @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 uuid provided"); + } + //call service to get prisma entity + const officeEntity: Offices = await this.officesService.getByUid(uid); + //Hydrate ressource with prisma entity + const office = ObjectHydrate.hydrate(new OfficeRessource(), officeEntity, { strategy: "exposeAll" }); + //success + this.httpSuccess(response, office); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } +} diff --git a/src/app/api/super-admin/UsersController.ts b/src/app/api/super-admin/UsersController.ts new file mode 100644 index 00000000..fdf2f2db --- /dev/null +++ b/src/app/api/super-admin/UsersController.ts @@ -0,0 +1,132 @@ +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 ObjectHydrate from "@Common/helpers/ObjectHydrate"; +import { validateOrReject } from "class-validator"; +import User from "le-coffre-resources/dist/SuperAdmin"; +import { processFindManyQuery } from "prisma-query"; +import { Users } from "@prisma/client"; + +@Controller() +@Service() +export default class UsersController extends ApiController { + constructor(private usersService: UsersService) { + super(); + } + + /** + * @description Get all users + * @returns IUser[] list of users + */ + @Get("/api/v1/super-admin/users") + protected async get(req: Request, response: Response) { + try { + //get query + const query = processFindManyQuery(req.query); + + //call service to get prisma entity + const usersEntity: Users[] = await this.usersService.get(query); + + //Hydrate ressource with prisma entity + const users = ObjectHydrate.map(User, usersEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, users); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Get all users + * @returns IUser[] list of users + */ + @Post("/api/v1/super-admin/users") + protected async getAddresses(req: Request, response: Response) { + try { + //init IUser resource with request body values + const userEntity = new User(); + ObjectHydrate.hydrate(userEntity, req.body); + + //validate user + await validateOrReject(userEntity, { groups: ["create"] }); + + //call service to get prisma entity + const prismaEntityCreated = await this.usersService.create(userEntity); + + //Hydrate ressource with prisma entity + const userEntityCreated = ObjectHydrate.hydrate(new User(), prismaEntityCreated, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, userEntityCreated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Modify a specific user by uid + * @returns IUser modified + */ + @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 uuid provided"); + } + //init IUser resource with request body values + const userEntity = new User(); + ObjectHydrate.hydrate(userEntity, 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 = ObjectHydrate.hydrate(new User(), prismaEntityUpdated, { + strategy: "exposeAll", + }); + + //success + this.httpSuccess(response, userEntityUpdated); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } + + /** + * @description Modify a specific user by uid + * @returns IUser modified + */ + @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 uuid provided"); + } + + //call service to get prisma entity + const userEntity: Users = await this.usersService.getByUid(uid); + + //Hydrate ressource with prisma entity + const user = ObjectHydrate.hydrate(new User(), userEntity, { strategy: "exposeAll" }); + + //success + this.httpSuccess(response, user); + } catch (error) { + this.httpBadRequest(response, error); + return; + } + } +} diff --git a/src/app/index.ts b/src/app/index.ts index 303407ef..f9dded35 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1,13 +1,13 @@ 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"; /** * @description This allow to declare all controllers used in the application diff --git a/src/app/middlewares/ErrorHandler.ts b/src/app/middlewares/ErrorHandler.ts index ac0b0f4d..274f5923 100644 --- a/src/app/middlewares/ErrorHandler.ts +++ b/src/app/middlewares/ErrorHandler.ts @@ -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); } - diff --git a/src/common/config/database/IDatabaseConfig.ts b/src/common/config/database/IDatabaseConfig.ts index 24796543..2b03000e 100644 --- a/src/common/config/database/IDatabaseConfig.ts +++ b/src/common/config/database/IDatabaseConfig.ts @@ -1,4 +1,4 @@ -export default interface IDatabaseConfig { - name: string; - url?: string; -} +export default interface IDatabaseConfig { + name: string; + url?: string; +} diff --git a/src/common/config/variables/Variables.ts b/src/common/config/variables/Variables.ts index 482a9dce..2ba6dbde 100644 --- a/src/common/config/variables/Variables.ts +++ b/src/common/config/variables/Variables.ts @@ -50,4 +50,3 @@ export class BackendVariables { return this; } } - diff --git a/src/common/databases/database.ts b/src/common/databases/database.ts index ecd8b810..9d8b85ac 100644 --- a/src/common/databases/database.ts +++ b/src/common/databases/database.ts @@ -27,4 +27,3 @@ export default class Database { return name; } } - diff --git a/src/common/databases/migrations/20230321102005_v0/migration.sql b/src/common/databases/migrations/20230321102005_v0/migration.sql new file mode 100644 index 00000000..0a36da48 --- /dev/null +++ b/src/common/databases/migrations/20230321102005_v0/migration.sql @@ -0,0 +1,413 @@ +-- 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" ( + "uuid" TEXT NOT NULL, + "address" VARCHAR(255) NOT NULL, + "city" VARCHAR(255) NOT NULL, + "zip_code" INTEGER NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "addresses_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "contacts" ( + "uuid" 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_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "contacts_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "users" ( + "uuid" TEXT NOT NULL, + "idNot" VARCHAR(255) NOT NULL, + "contact_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + "office_uuid" VARCHAR(255) NOT NULL, + + CONSTRAINT "users_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "offices" ( + "uuid" TEXT NOT NULL, + "idNot" VARCHAR(255) NOT NULL, + "name" VARCHAR(255) NOT NULL, + "crpcen" VARCHAR(255) NOT NULL, + "address_uuid" VARCHAR(255) NOT NULL, + "office_status" "EOfficeStatus" NOT NULL DEFAULT 'DESACTIVATED', + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "offices_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "customers" ( + "uuid" TEXT NOT NULL, + "status" "ECustomerStatus" NOT NULL DEFAULT 'PENDING', + "contact_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "customers_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "user_has_notifications" ( + "uuid" TEXT NOT NULL, + "user_uuid" VARCHAR(255) NOT NULL, + "notification_uuid" VARCHAR(255) NOT NULL, + "notification_status" "ENotificationStatus" NOT NULL DEFAULT 'UNREAD', + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "user_has_notifications_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "notifications" ( + "uuid" TEXT NOT NULL, + "message" VARCHAR(255) NOT NULL, + "redirection_url" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "notifications_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "office_folders" ( + "uuid" 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_uuid" VARCHAR(255) NOT NULL, + "office_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "office_folders_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "office_folder_has_customers" ( + "uuid" TEXT NOT NULL, + "customer_uuid" VARCHAR(255) NOT NULL, + "office_folder_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "office_folder_has_customers_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "office_folder_has_stakeholder" ( + "uuid" TEXT NOT NULL, + "office_folder_uuid" VARCHAR(255) NOT NULL, + "user_stakeholder_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "office_folder_has_stakeholder_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "documents" ( + "uuid" TEXT NOT NULL, + "document_status" "EDocumentStatus" NOT NULL DEFAULT 'ASKED', + "type_uuid" VARCHAR(255) NOT NULL, + "blockchain_anchor_uuid" VARCHAR(255), + "folder_uuid" VARCHAR(255) NOT NULL, + "depositor_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "documents_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "document_history" ( + "uuid" TEXT NOT NULL, + "document_status" "EDocumentStatus" NOT NULL DEFAULT 'ASKED', + "refused_reason" VARCHAR(255), + "document_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "document_history_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "files" ( + "uuid" TEXT NOT NULL, + "document_uuid" VARCHAR(255) NOT NULL, + "file_path" VARCHAR(255), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "files_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "blockchain_anchors" ( + "uuid" TEXT NOT NULL, + "smartSigJobId" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "blockchain_anchors_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "document_types" ( + "uuid" TEXT NOT NULL, + "name" VARCHAR(255) NOT NULL, + "public_description" VARCHAR(255) NOT NULL, + "private_description" VARCHAR(255), + "archived_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "document_types_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "deed_has_document_types" ( + "uuid" TEXT NOT NULL, + "document_type_uuid" VARCHAR(255) NOT NULL, + "deed_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "deed_has_document_types_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "deed" ( + "uuid" TEXT NOT NULL, + "deed_type_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "deed_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "deed_types" ( + "uuid" TEXT NOT NULL, + "name" VARCHAR(255) NOT NULL, + "description" VARCHAR(255) NOT NULL, + "archived_at" TIMESTAMP(3), + "office_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "deed_types_pkey" PRIMARY KEY ("uuid") +); + +-- CreateTable +CREATE TABLE "deed_type_has_document_types" ( + "uuid" TEXT NOT NULL, + "document_type_uuid" VARCHAR(255) NOT NULL, + "deed_type_uuid" VARCHAR(255) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "deed_type_has_document_types_pkey" PRIMARY KEY ("uuid") +); + +-- CreateIndex +CREATE UNIQUE INDEX "addresses_uuid_key" ON "addresses"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "contacts_uuid_key" ON "contacts"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "contacts_address_uuid_key" ON "contacts"("address_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "users_uuid_key" ON "users"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "users_idNot_key" ON "users"("idNot"); + +-- CreateIndex +CREATE UNIQUE INDEX "users_contact_uuid_key" ON "users"("contact_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "offices_uuid_key" ON "offices"("uuid"); + +-- 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_uuid_key" ON "offices"("address_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "customers_uuid_key" ON "customers"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "customers_contact_uuid_key" ON "customers"("contact_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "user_has_notifications_uuid_key" ON "user_has_notifications"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "notifications_uuid_key" ON "notifications"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "office_folders_uuid_key" ON "office_folders"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "office_folders_deed_uuid_key" ON "office_folders"("deed_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "office_folder_has_customers_uuid_key" ON "office_folder_has_customers"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "office_folder_has_stakeholder_uuid_key" ON "office_folder_has_stakeholder"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "documents_uuid_key" ON "documents"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "document_history_uuid_key" ON "document_history"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "files_uuid_key" ON "files"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "files_file_path_key" ON "files"("file_path"); + +-- CreateIndex +CREATE UNIQUE INDEX "blockchain_anchors_uuid_key" ON "blockchain_anchors"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "blockchain_anchors_smartSigJobId_key" ON "blockchain_anchors"("smartSigJobId"); + +-- CreateIndex +CREATE UNIQUE INDEX "document_types_uuid_key" ON "document_types"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "deed_has_document_types_uuid_key" ON "deed_has_document_types"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "deed_uuid_key" ON "deed"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "deed_deed_type_uuid_key" ON "deed"("deed_type_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "deed_types_uuid_key" ON "deed_types"("uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "deed_type_has_document_types_uuid_key" ON "deed_type_has_document_types"("uuid"); + +-- AddForeignKey +ALTER TABLE "contacts" ADD CONSTRAINT "contacts_address_uuid_fkey" FOREIGN KEY ("address_uuid") REFERENCES "addresses"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "users" ADD CONSTRAINT "users_contact_uuid_fkey" FOREIGN KEY ("contact_uuid") REFERENCES "contacts"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "users" ADD CONSTRAINT "users_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "offices" ADD CONSTRAINT "offices_address_uuid_fkey" FOREIGN KEY ("address_uuid") REFERENCES "addresses"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "customers" ADD CONSTRAINT "customers_contact_uuid_fkey" FOREIGN KEY ("contact_uuid") REFERENCES "contacts"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "user_has_notifications" ADD CONSTRAINT "user_has_notifications_user_uuid_fkey" FOREIGN KEY ("user_uuid") REFERENCES "users"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "user_has_notifications" ADD CONSTRAINT "user_has_notifications_notification_uuid_fkey" FOREIGN KEY ("notification_uuid") REFERENCES "notifications"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folders" ADD CONSTRAINT "office_folders_deed_uuid_fkey" FOREIGN KEY ("deed_uuid") REFERENCES "deed"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folders" ADD CONSTRAINT "office_folders_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_customers" ADD CONSTRAINT "office_folder_has_customers_customer_uuid_fkey" FOREIGN KEY ("customer_uuid") REFERENCES "customers"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_customers" ADD CONSTRAINT "office_folder_has_customers_office_folder_uuid_fkey" FOREIGN KEY ("office_folder_uuid") REFERENCES "office_folders"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_stakeholder" ADD CONSTRAINT "office_folder_has_stakeholder_office_folder_uuid_fkey" FOREIGN KEY ("office_folder_uuid") REFERENCES "office_folders"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_stakeholder" ADD CONSTRAINT "office_folder_has_stakeholder_user_stakeholder_uuid_fkey" FOREIGN KEY ("user_stakeholder_uuid") REFERENCES "users"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "documents" ADD CONSTRAINT "documents_type_uuid_fkey" FOREIGN KEY ("type_uuid") REFERENCES "document_types"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "documents" ADD CONSTRAINT "documents_blockchain_anchor_uuid_fkey" FOREIGN KEY ("blockchain_anchor_uuid") REFERENCES "blockchain_anchors"("uuid") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "documents" ADD CONSTRAINT "documents_folder_uuid_fkey" FOREIGN KEY ("folder_uuid") REFERENCES "office_folders"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "documents" ADD CONSTRAINT "documents_depositor_uuid_fkey" FOREIGN KEY ("depositor_uuid") REFERENCES "customers"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "document_history" ADD CONSTRAINT "document_history_document_uuid_fkey" FOREIGN KEY ("document_uuid") REFERENCES "documents"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "files" ADD CONSTRAINT "files_document_uuid_fkey" FOREIGN KEY ("document_uuid") REFERENCES "documents"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_has_document_types" ADD CONSTRAINT "deed_has_document_types_document_type_uuid_fkey" FOREIGN KEY ("document_type_uuid") REFERENCES "document_types"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_has_document_types" ADD CONSTRAINT "deed_has_document_types_deed_uuid_fkey" FOREIGN KEY ("deed_uuid") REFERENCES "deed"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed" ADD CONSTRAINT "deed_deed_type_uuid_fkey" FOREIGN KEY ("deed_type_uuid") REFERENCES "deed_types"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_types" ADD CONSTRAINT "deed_types_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_type_has_document_types" ADD CONSTRAINT "deed_type_has_document_types_document_type_uuid_fkey" FOREIGN KEY ("document_type_uuid") REFERENCES "document_types"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_type_has_document_types" ADD CONSTRAINT "deed_type_has_document_types_deed_type_uuid_fkey" FOREIGN KEY ("deed_type_uuid") REFERENCES "deed_types"("uuid") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/src/common/databases/migrations/20230324125436_20230324102005_v1/migration.sql b/src/common/databases/migrations/20230324125436_20230324102005_v1/migration.sql new file mode 100644 index 00000000..decf61d6 --- /dev/null +++ b/src/common/databases/migrations/20230324125436_20230324102005_v1/migration.sql @@ -0,0 +1,92 @@ +/* + Warnings: + + - A unique constraint covering the columns `[address]` on the table `addresses` will be added. If there are existing duplicate values, this will fail. + - A unique constraint covering the columns `[email]` on the table `contacts` will be added. If there are existing duplicate values, this will fail. + - A unique constraint covering the columns `[cell_phone_number]` on the table `contacts` will be added. If there are existing duplicate values, this will fail. + +*/ +-- AlterTable +ALTER TABLE "addresses" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "blockchain_anchors" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "contacts" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "customers" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "deed" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "deed_has_document_types" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "deed_type_has_document_types" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "deed_types" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "document_history" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "document_types" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "documents" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "files" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "notifications" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "office_folder_has_customers" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "office_folder_has_stakeholder" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "office_folders" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "offices" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "user_has_notifications" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- AlterTable +ALTER TABLE "users" ALTER COLUMN "created_at" DROP NOT NULL, +ALTER COLUMN "updated_at" DROP NOT NULL; + +-- CreateIndex +CREATE UNIQUE INDEX "addresses_address_key" ON "addresses"("address"); + +-- CreateIndex +CREATE UNIQUE INDEX "contacts_email_key" ON "contacts"("email"); + +-- CreateIndex +CREATE UNIQUE INDEX "contacts_cell_phone_number_key" ON "contacts"("cell_phone_number"); diff --git a/src/common/databases/migrations/20230324130335_20230324_v2/migration.sql b/src/common/databases/migrations/20230324130335_20230324_v2/migration.sql new file mode 100644 index 00000000..9fd68230 --- /dev/null +++ b/src/common/databases/migrations/20230324130335_20230324_v2/migration.sql @@ -0,0 +1,2 @@ +-- DropIndex +DROP INDEX "addresses_address_key"; diff --git a/src/common/databases/migrations/20230324171729_v3/migration.sql b/src/common/databases/migrations/20230324171729_v3/migration.sql new file mode 100644 index 00000000..0c38c4c9 --- /dev/null +++ b/src/common/databases/migrations/20230324171729_v3/migration.sql @@ -0,0 +1,119 @@ +-- DropForeignKey +ALTER TABLE "contacts" DROP CONSTRAINT "contacts_address_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "customers" DROP CONSTRAINT "customers_contact_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "deed" DROP CONSTRAINT "deed_deed_type_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "deed_has_document_types" DROP CONSTRAINT "deed_has_document_types_deed_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "deed_has_document_types" DROP CONSTRAINT "deed_has_document_types_document_type_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "deed_type_has_document_types" DROP CONSTRAINT "deed_type_has_document_types_deed_type_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "deed_type_has_document_types" DROP CONSTRAINT "deed_type_has_document_types_document_type_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "deed_types" DROP CONSTRAINT "deed_types_office_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "document_history" DROP CONSTRAINT "document_history_document_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "documents" DROP CONSTRAINT "documents_depositor_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "files" DROP CONSTRAINT "files_document_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "office_folder_has_customers" DROP CONSTRAINT "office_folder_has_customers_customer_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "office_folder_has_customers" DROP CONSTRAINT "office_folder_has_customers_office_folder_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "office_folder_has_stakeholder" DROP CONSTRAINT "office_folder_has_stakeholder_office_folder_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "office_folder_has_stakeholder" DROP CONSTRAINT "office_folder_has_stakeholder_user_stakeholder_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "office_folders" DROP CONSTRAINT "office_folders_deed_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "office_folders" DROP CONSTRAINT "office_folders_office_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "offices" DROP CONSTRAINT "offices_address_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "user_has_notifications" DROP CONSTRAINT "user_has_notifications_notification_uuid_fkey"; + +-- DropForeignKey +ALTER TABLE "users" DROP CONSTRAINT "users_contact_uuid_fkey"; + +-- AddForeignKey +ALTER TABLE "contacts" ADD CONSTRAINT "contacts_address_uuid_fkey" FOREIGN KEY ("address_uuid") REFERENCES "addresses"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "users" ADD CONSTRAINT "users_contact_uuid_fkey" FOREIGN KEY ("contact_uuid") REFERENCES "contacts"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "offices" ADD CONSTRAINT "offices_address_uuid_fkey" FOREIGN KEY ("address_uuid") REFERENCES "addresses"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "customers" ADD CONSTRAINT "customers_contact_uuid_fkey" FOREIGN KEY ("contact_uuid") REFERENCES "contacts"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "user_has_notifications" ADD CONSTRAINT "user_has_notifications_notification_uuid_fkey" FOREIGN KEY ("notification_uuid") REFERENCES "notifications"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folders" ADD CONSTRAINT "office_folders_deed_uuid_fkey" FOREIGN KEY ("deed_uuid") REFERENCES "deed"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folders" ADD CONSTRAINT "office_folders_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_customers" ADD CONSTRAINT "office_folder_has_customers_customer_uuid_fkey" FOREIGN KEY ("customer_uuid") REFERENCES "customers"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_customers" ADD CONSTRAINT "office_folder_has_customers_office_folder_uuid_fkey" FOREIGN KEY ("office_folder_uuid") REFERENCES "office_folders"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_stakeholder" ADD CONSTRAINT "office_folder_has_stakeholder_office_folder_uuid_fkey" FOREIGN KEY ("office_folder_uuid") REFERENCES "office_folders"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "office_folder_has_stakeholder" ADD CONSTRAINT "office_folder_has_stakeholder_user_stakeholder_uuid_fkey" FOREIGN KEY ("user_stakeholder_uuid") REFERENCES "users"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "documents" ADD CONSTRAINT "documents_depositor_uuid_fkey" FOREIGN KEY ("depositor_uuid") REFERENCES "customers"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "document_history" ADD CONSTRAINT "document_history_document_uuid_fkey" FOREIGN KEY ("document_uuid") REFERENCES "documents"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "files" ADD CONSTRAINT "files_document_uuid_fkey" FOREIGN KEY ("document_uuid") REFERENCES "documents"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_has_document_types" ADD CONSTRAINT "deed_has_document_types_document_type_uuid_fkey" FOREIGN KEY ("document_type_uuid") REFERENCES "document_types"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_has_document_types" ADD CONSTRAINT "deed_has_document_types_deed_uuid_fkey" FOREIGN KEY ("deed_uuid") REFERENCES "deed"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed" ADD CONSTRAINT "deed_deed_type_uuid_fkey" FOREIGN KEY ("deed_type_uuid") REFERENCES "deed_types"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_types" ADD CONSTRAINT "deed_types_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_type_has_document_types" ADD CONSTRAINT "deed_type_has_document_types_document_type_uuid_fkey" FOREIGN KEY ("document_type_uuid") REFERENCES "document_types"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "deed_type_has_document_types" ADD CONSTRAINT "deed_type_has_document_types_deed_type_uuid_fkey" FOREIGN KEY ("deed_type_uuid") REFERENCES "deed_types"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/src/common/databases/migrations/20230328095747_v4/migration.sql b/src/common/databases/migrations/20230328095747_v4/migration.sql new file mode 100644 index 00000000..feb43abb --- /dev/null +++ b/src/common/databases/migrations/20230328095747_v4/migration.sql @@ -0,0 +1,8 @@ +-- DropForeignKey +ALTER TABLE "users" DROP CONSTRAINT "users_office_uuid_fkey"; + +-- DropIndex +DROP INDEX "deed_deed_type_uuid_key"; + +-- AddForeignKey +ALTER TABLE "users" ADD CONSTRAINT "users_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/src/common/databases/migrations/20230329084446_v5/migration.sql b/src/common/databases/migrations/20230329084446_v5/migration.sql new file mode 100644 index 00000000..8671fd3a --- /dev/null +++ b/src/common/databases/migrations/20230329084446_v5/migration.sql @@ -0,0 +1,8 @@ +/* + Warnings: + + - A unique constraint covering the columns `[name,office_uuid]` on the table `deed_types` will be added. If there are existing duplicate values, this will fail. + +*/ +-- CreateIndex +CREATE UNIQUE INDEX "deed_types_name_office_uuid_key" ON "deed_types"("name", "office_uuid"); diff --git a/src/common/databases/migrations/20230329145139_v6/migration.sql b/src/common/databases/migrations/20230329145139_v6/migration.sql new file mode 100644 index 00000000..13597e8e --- /dev/null +++ b/src/common/databases/migrations/20230329145139_v6/migration.sql @@ -0,0 +1,15 @@ +/* + Warnings: + + - A unique constraint covering the columns `[name,office_uuid]` on the table `document_types` will be added. If there are existing duplicate values, this will fail. + - Added the required column `office_uuid` to the `document_types` table without a default value. This is not possible if the table is not empty. + +*/ +-- AlterTable +ALTER TABLE "document_types" ADD COLUMN "office_uuid" VARCHAR(255) NOT NULL; + +-- CreateIndex +CREATE UNIQUE INDEX "document_types_name_office_uuid_key" ON "document_types"("name", "office_uuid"); + +-- AddForeignKey +ALTER TABLE "document_types" ADD CONSTRAINT "document_types_office_uuid_fkey" FOREIGN KEY ("office_uuid") REFERENCES "offices"("uuid") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/src/common/databases/migrations/20230330150236_v8/migration.sql b/src/common/databases/migrations/20230330150236_v8/migration.sql new file mode 100644 index 00000000..5bda5e34 --- /dev/null +++ b/src/common/databases/migrations/20230330150236_v8/migration.sql @@ -0,0 +1,24 @@ +/* + Warnings: + + - A unique constraint covering the columns `[deed_uuid,document_type_uuid]` on the table `deed_has_document_types` will be added. If there are existing duplicate values, this will fail. + - A unique constraint covering the columns `[deed_type_uuid,document_type_uuid]` on the table `deed_type_has_document_types` will be added. If there are existing duplicate values, this will fail. + - A unique constraint covering the columns `[customer_uuid,office_folder_uuid]` on the table `office_folder_has_customers` will be added. If there are existing duplicate values, this will fail. + - A unique constraint covering the columns `[office_folder_uuid,user_stakeholder_uuid]` on the table `office_folder_has_stakeholder` will be added. If there are existing duplicate values, this will fail. + - A unique constraint covering the columns `[notification_uuid,user_uuid]` on the table `user_has_notifications` will be added. If there are existing duplicate values, this will fail. + +*/ +-- CreateIndex +CREATE UNIQUE INDEX "deed_has_document_types_deed_uuid_document_type_uuid_key" ON "deed_has_document_types"("deed_uuid", "document_type_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "deed_type_has_document_types_deed_type_uuid_document_type_u_key" ON "deed_type_has_document_types"("deed_type_uuid", "document_type_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "office_folder_has_customers_customer_uuid_office_folder_uui_key" ON "office_folder_has_customers"("customer_uuid", "office_folder_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "office_folder_has_stakeholder_office_folder_uuid_user_stake_key" ON "office_folder_has_stakeholder"("office_folder_uuid", "user_stakeholder_uuid"); + +-- CreateIndex +CREATE UNIQUE INDEX "user_has_notifications_notification_uuid_user_uuid_key" ON "user_has_notifications"("notification_uuid", "user_uuid"); diff --git a/src/common/databases/schema.prisma b/src/common/databases/schema.prisma index 8d670423..d6e1f3f7 100644 --- a/src/common/databases/schema.prisma +++ b/src/common/databases/schema.prisma @@ -2,6 +2,7 @@ generator client { provider = "prisma-client-js" + //binaryTargets = ["native"] } datasource db { @@ -21,10 +22,10 @@ model Addresses { 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") } @@ -33,14 +34,14 @@ model Contacts { uuid 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 Addresses @relation(fields: [address_uuid], references: [uuid], onDelete: Cascade) address_uuid String @unique @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt users Users? customers Customers? @@ -50,11 +51,11 @@ model Contacts { model Users { uuid String @id @unique @default(uuid()) idNot String @unique @db.VarChar(255) - contact Contacts @relation(fields: [contact_uuid], references: [uuid]) + contact Contacts @relation(fields: [contact_uuid], references: [uuid], onDelete: Cascade) 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]) + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt + office_membership Offices @relation(fields: [office_uuid], references: [uuid], onDelete: Cascade) office_uuid String @db.VarChar(255) user_has_notifications UserHasNotifications[] office_folder_has_stakeholder OfficeFolderHasStakeholders[] @@ -62,19 +63,20 @@ model Users { @@map("users") } -model Office { +model Offices { uuid 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 Addresses @relation(fields: [address_uuid], references: [uuid], onDelete: Cascade) address_uuid 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") } @@ -82,10 +84,10 @@ model Office { model Customers { uuid String @id @unique @default(uuid()) status ECustomerStatus @default(PENDING) - contact Contacts @relation(fields: [contact_uuid], references: [uuid]) + contact Contacts @relation(fields: [contact_uuid], references: [uuid], onDelete: Cascade) contact_uuid String @unique @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt office_folder_has_customers OfficeFolderHasCustomers[] documents Documents[] @@ -96,12 +98,13 @@ 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 Notifications @relation(fields: [notification_uuid], references: [uuid], onDelete: Cascade) notification_uuid 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_uuid, user_uuid]) @@map("user_has_notifications") } @@ -109,8 +112,8 @@ model Notifications { uuid 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") @@ -123,12 +126,12 @@ model OfficeFolders { description String? @db.VarChar(255) archived_description String? @db.VarChar(255) status EFolderStatus @default(LIVE) - deed Deed @relation(fields: [deed_uuid], references: [uuid]) + deed Deeds @relation(fields: [deed_uuid], references: [uuid], onDelete: Cascade) deed_uuid String @unique @db.VarChar(255) - office Office @relation(fields: [office_uuid], references: [uuid]) + office Offices @relation(fields: [office_uuid], references: [uuid], onDelete: Cascade) office_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt office_folder_has_customers OfficeFolderHasCustomers[] office_folder_has_stakeholder OfficeFolderHasStakeholders[] documents Documents[] @@ -138,25 +141,27 @@ model OfficeFolders { model OfficeFolderHasCustomers { uuid String @id @unique @default(uuid()) - customer Customers @relation(fields: [customer_uuid], references: [uuid]) + customer Customers @relation(fields: [customer_uuid], references: [uuid], onDelete: Cascade) customer_uuid String @db.VarChar(255) - office_folder OfficeFolders @relation(fields: [office_folder_uuid], references: [uuid]) + office_folder OfficeFolders @relation(fields: [office_folder_uuid], references: [uuid], onDelete: Cascade) office_folder_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt + @@unique([customer_uuid, office_folder_uuid]) @@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 OfficeFolders @relation(fields: [office_folder_uuid], references: [uuid], onDelete: Cascade) office_folder_uuid String @db.VarChar(255) - user_stakeholder Users @relation(fields: [user_stakeholder_uuid], references: [uuid]) + user_stakeholder Users @relation(fields: [user_stakeholder_uuid], references: [uuid], onDelete: Cascade) user_stakeholder_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt + @@unique([office_folder_uuid, user_stakeholder_uuid]) @@map("office_folder_has_stakeholder") } @@ -169,10 +174,10 @@ model Documents { 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 Customers @relation(fields: [depositor_uuid], references: [uuid], onDelete: Cascade) depositor_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt files Files[] document_history DocumentHistory[] @@ -183,21 +188,21 @@ model DocumentHistory { uuid 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 Documents @relation(fields: [document_uuid], references: [uuid], onDelete: Cascade) document_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + 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 Documents @relation(fields: [document_uuid], references: [uuid], onDelete: Cascade) document_uuid String @db.VarChar(255) file_path String? @unique @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt @@map("files") } @@ -205,8 +210,8 @@ model Files { model BlockchainAnchors { uuid 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") @@ -217,34 +222,38 @@ model DocumentTypes { name String @db.VarChar(255) public_description String @db.VarChar(255) private_description String? @db.VarChar(255) + office Offices @relation(fields: [office_uuid], references: [uuid], onDelete: Cascade) + office_uuid 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_uuid]) @@map("document_types") } model DeedHasDocumentTypes { uuid String @id @unique @default(uuid()) - document_type DocumentTypes @relation(fields: [document_type_uuid], references: [uuid]) + document_type DocumentTypes @relation(fields: [document_type_uuid], references: [uuid], onDelete: Cascade) document_type_uuid String @db.VarChar(255) - deed Deed @relation(fields: [deed_uuid], references: [uuid]) + deed Deeds @relation(fields: [deed_uuid], references: [uuid], onDelete: Cascade) deed_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt + @@unique([deed_uuid, document_type_uuid]) @@map("deed_has_document_types") } -model Deed { +model Deeds { 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 + deed_type DeedTypes @relation(fields: [deed_type_uuid], references: [uuid], onDelete: Cascade) + deed_type_uuid String @db.VarChar(255) + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt deed_has_document_types DeedHasDocumentTypes[] office_folder OfficeFolders? @@ -256,29 +265,30 @@ model DeedTypes { name String @db.VarChar(255) description String @db.VarChar(255) archived_at DateTime? - office Office @relation(fields: [office_uuid], references: [uuid]) + office Offices @relation(fields: [office_uuid], references: [uuid], onDelete: Cascade) office_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt - deed Deed? + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt + deed Deeds[] deed_type_has_document_types DeedTypeHasDocumentTypes[] + @@unique([name, office_uuid]) @@map("deed_types") } model DeedTypeHasDocumentTypes { uuid String @id @unique @default(uuid()) - document_type DocumentTypes @relation(fields: [document_type_uuid], references: [uuid]) + document_type DocumentTypes @relation(fields: [document_type_uuid], references: [uuid], onDelete: Cascade) document_type_uuid String @db.VarChar(255) - deed_type DeedTypes @relation(fields: [deed_type_uuid], references: [uuid]) + deed_type DeedTypes @relation(fields: [deed_type_uuid], references: [uuid], onDelete: Cascade) deed_type_uuid String @db.VarChar(255) - created_at DateTime @default(now()) - updated_at DateTime @updatedAt + created_at DateTime? @default(now()) + updated_at DateTime? @updatedAt + @@unique([deed_type_uuid, document_type_uuid]) @@map("deed_type_has_document_types") } -// TODO SE RENSEIGNER SUR LES ENUMS enum ECivility { MALE FEMALE diff --git a/src/common/helpers/ObjectHydrate.ts b/src/common/helpers/ObjectHydrate.ts index 5e220bd0..d8f3121c 100644 --- a/src/common/helpers/ObjectHydrate.ts +++ b/src/common/helpers/ObjectHydrate.ts @@ -1,13 +1,13 @@ -import { type ClassTransformOptions, plainToClass, plainToClassFromExist } from "class-transformer"; - -export default abstract class ObjectHydrate { - public static hydrate(object: T, from: Partial, options?: ClassTransformOptions): T { - return plainToClassFromExist(object, from, options); - } - - public static map(ClassEntity: { new (): T }, fromArray: Partial[], options?: ClassTransformOptions): T[] { - return fromArray.map((from) => { - return plainToClass(ClassEntity, from, options); - }); - } -} +import { type ClassTransformOptions, plainToClass, plainToClassFromExist } from "class-transformer"; + +export default abstract class ObjectHydrate { + public static hydrate(object: T, from: Partial, options?: ClassTransformOptions): T { + return plainToClassFromExist(object, from, options); + } + + public static map(ClassEntity: { new (): T }, fromArray: Partial[], options?: ClassTransformOptions): T[] { + return fromArray.map((from) => { + return plainToClass(ClassEntity, from, options); + }); + } +} diff --git a/src/common/repositories/AddressesRepository.ts b/src/common/repositories/AddressesRepository.ts new file mode 100644 index 00000000..6b2cf46d --- /dev/null +++ b/src/common/repositories/AddressesRepository.ts @@ -0,0 +1,35 @@ +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 users + */ + public async findMany(query: any): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + public async create(address: Addresses): Promise { + return this.model.create({ + data: { + address: address.address, + city: address.city, + zip_code: address.zip_code, + }, + }); + } +} diff --git a/src/common/repositories/ContactRepository.ts b/src/common/repositories/ContactRepository.ts new file mode 100644 index 00000000..bb0496eb --- /dev/null +++ b/src/common/repositories/ContactRepository.ts @@ -0,0 +1,26 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +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 users + */ + public async findMany(query: ReturnType): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } +} diff --git a/src/common/repositories/CustomersRepository.ts b/src/common/repositories/CustomersRepository.ts new file mode 100644 index 00000000..af434c55 --- /dev/null +++ b/src/common/repositories/CustomersRepository.ts @@ -0,0 +1,93 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { Customers, ECivility, ECustomerStatus } 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: any): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + public async create(customer: Customer): Promise { + return this.model.create({ + 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: { + create: { + address: customer.contact.address.address, + zip_code: customer.contact.address.zip_code, + city: customer.contact.address.city, + }, + }, + }, + }, + }, + }); + } + + public async update(uid: string, customer: Customer): Promise { + return this.model.update({ + where: { + uuid: 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: { + update: { + address: customer.contact.address.address, + zip_code: customer.contact.address.zip_code, + city: customer.contact.address.city, + }, + }, + }, + }, + }, + }); + } + + public async findOneByUid(uid: string): Promise { + const customerEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!customerEntity) { + throw new Error("Customer not found"); + } + + return customerEntity; + } +} diff --git a/src/common/repositories/DeedTypesHasDocumentTypesRepository.ts b/src/common/repositories/DeedTypesHasDocumentTypesRepository.ts new file mode 100644 index 00000000..21141db7 --- /dev/null +++ b/src/common/repositories/DeedTypesHasDocumentTypesRepository.ts @@ -0,0 +1,112 @@ +import Database from "@Common/databases/database"; +import { DeedTypeHasDocumentTypes, Prisma } 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 users + */ + public async findMany(query: any): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async create(deedTypeUuid: string, documentTypesUuid: string): Promise { + return this.model.create({ + data: { + deed_type: { + connect: { + uuid: deedTypeUuid, + }, + }, + document_type: { + connect: { + uuid: documentTypesUuid, + }, + }, + }, + }); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async createMany(deedTypeUuid: string, documentTypesUuid: string[]): Promise { + let relationsToAdd: Prisma.DeedTypeHasDocumentTypesCreateManyInput[] = []; + documentTypesUuid.forEach((item) => { + relationsToAdd.push({ deed_type_uuid: deedTypeUuid, document_type_uuid: item }); + }); + + const numberOfRelationsAdded = ( + await this.model.createMany({ + data: relationsToAdd, + skipDuplicates: true, + }) + ).count; + + return this.findMany({ where: { deed_type_uuid: deedTypeUuid }, take: numberOfRelationsAdded }); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async delete(deedTypeUuid: string, documentTypesUuid: string): Promise { + return this.model.delete({ + where: { + deed_type_uuid_document_type_uuid: { + deed_type_uuid: deedTypeUuid, + document_type_uuid: documentTypesUuid, + }, + }, + }); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async deleteMany(deedTypeUuid: string, documentTypesUuids: string[]): Promise { + let relationsToRemove: any[] = []; + documentTypesUuids.forEach((relationUuid) => { + relationsToRemove.push( + this.model.delete({ + where: { + deed_type_uuid_document_type_uuid: { + deed_type_uuid: deedTypeUuid, + document_type_uuid: relationUuid, + }, + }, + }), + ); + }); + return this.instanceDb.$transaction(relationsToRemove); + } + + public async findOneByUid(uid: string): Promise { + const deedTypeHasDoculmentTypesEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!deedTypeHasDoculmentTypesEntity) { + throw new Error("deed type not found"); + } + + return deedTypeHasDoculmentTypesEntity; + } +} diff --git a/src/common/repositories/DeedTypesRepository.ts b/src/common/repositories/DeedTypesRepository.ts new file mode 100644 index 00000000..eb60b8ed --- /dev/null +++ b/src/common/repositories/DeedTypesRepository.ts @@ -0,0 +1,117 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { DeedTypes } 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 users + */ + public async findMany(query: any): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + /** + * @description : Create new office folder wihtout customers nor stakeholders + */ + public async create(deedType: DeedType): Promise { + return this.model.create({ + data: { + name: deedType.name, + description: deedType.description, + office: { + connect: { + uuid: deedType.office.uid, + }, + }, + }, + }); + } + + /** + * @description : Create new office folder wihtout customers nor stakeholders + */ + public async update(uid: string, deedType: DeedType): Promise { + return this.model.update({ + where: { uuid: uid }, + data: { + name: deedType.name, + description: deedType.description, + archived_at: deedType.archived_at, + office: { + connect: { + uuid: deedType.office.uid, + }, + }, + }, + }); + } + + public async findOneByUid(uid: string): Promise { + const deedTypeEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + include: { + deed_type_has_document_types: true, + }, + }); + + if (!deedTypeEntity) { + throw new Error("deed type not found"); + } + + return deedTypeEntity; + } + + /** + * @description : update relations between document types and given deed type + */ + public async addDocumentType(uid: string, deedTypeHasDocumentTypeUuid: string): Promise { + return this.model.update({ + where: { uuid: uid }, + data: { + deed_type_has_document_types: { + connect: { + uuid: deedTypeHasDocumentTypeUuid, + }, + }, + }, + }); + } + + /** + * @description : update relations between document types and given deed type + */ + public async addDocumentTypes(uid: string, deedTypeHasDocumentTypeUuid: string[]): Promise { + let relationsToAdd: any[] = []; + deedTypeHasDocumentTypeUuid.forEach((relationUuid) => { + relationsToAdd.push( + this.model.update({ + where: { uuid: uid }, + data: { + deed_type_has_document_types: { + connect: { + uuid: relationUuid, + }, + }, + }, + }), + ); + }); + return this.instanceDb.$transaction(relationsToAdd); + } +} diff --git a/src/common/repositories/DeedsHasDocumentTypesRepository.ts b/src/common/repositories/DeedsHasDocumentTypesRepository.ts new file mode 100644 index 00000000..f9b6aa7b --- /dev/null +++ b/src/common/repositories/DeedsHasDocumentTypesRepository.ts @@ -0,0 +1,112 @@ +import Database from "@Common/databases/database"; +import { DeedHasDocumentTypes, Prisma } 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 users + */ + public async findMany(query: any): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async create(deedUuid: string, documentTypesUuid: string): Promise { + return this.model.create({ + data: { + deed: { + connect: { + uuid: deedUuid, + }, + }, + document_type: { + connect: { + uuid: documentTypesUuid, + }, + }, + }, + }); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async createMany(deedUuid: string, documentTypesUuid: string[]): Promise { + let relationsToAdd: Prisma.DeedHasDocumentTypesCreateManyInput[] = []; + documentTypesUuid.forEach((item) => { + relationsToAdd.push({ deed_uuid: deedUuid, document_type_uuid: item }); + }); + + const numberOfRelationsAdded = ( + await this.model.createMany({ + data: relationsToAdd, + skipDuplicates: true, + }) + ).count; + + return this.findMany({ where: { deed_uuid: deedUuid }, take: numberOfRelationsAdded }); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async delete(deedUuid: string, documentTypesUuid: string): Promise { + return this.model.delete({ + where: { + deed_uuid_document_type_uuid: { + deed_uuid: deedUuid, + document_type_uuid: documentTypesUuid, + }, + }, + }); + } + + /** + * @description : Create new relation between deed type and a document type + */ + public async deleteMany(deedUuid: string, documentTypesUuids: string[]): Promise { + let relationsToRemove: any[] = []; + documentTypesUuids.forEach((relationUuid) => { + relationsToRemove.push( + this.model.delete({ + where: { + deed_uuid_document_type_uuid: { + deed_uuid: deedUuid, + document_type_uuid: relationUuid, + }, + }, + }), + ); + }); + return this.instanceDb.$transaction(relationsToRemove); + } + + public async findOneByUid(uid: string): Promise { + const deedHasDoculmentTypesEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!deedHasDoculmentTypesEntity) { + throw new Error("relation between deed and document type not found"); + } + + return deedHasDoculmentTypesEntity; + } +} diff --git a/src/common/repositories/DeedsRepository.ts b/src/common/repositories/DeedsRepository.ts new file mode 100644 index 00000000..494dc60c --- /dev/null +++ b/src/common/repositories/DeedsRepository.ts @@ -0,0 +1,90 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { Deeds } from "@prisma/client"; +import { DeedType } from "le-coffre-resources/dist/Customer"; + +@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 { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + public async create(deedType: DeedType): Promise { + return this.model.create({ + data: { + deed_type: { + connect: { + uuid: deedType.uid, + }, + }, + }, + }); + } + + public async findOneByUid(uid: string): Promise { + const deedTypeEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!deedTypeEntity) { + throw new Error("deed type not found"); + } + + return deedTypeEntity; + } + + /** + * @description : update relations between document types and given deed type + */ + public async addDocumentType(uid: string, deedHasDocumentTypeUuid: string): Promise { + return this.model.update({ + where: { uuid: uid }, + data: { + deed_has_document_types: { + connect: { + uuid: deedHasDocumentTypeUuid, + }, + }, + }, + }); + } + + /** + * @description : update relations between document types and given deed type + */ + public async addDocumentTypes(uid: string, deedHasDocumentTypeUuid: string[]): Promise { + let relationsToAdd: any[] = []; + deedHasDocumentTypeUuid.forEach((relationUuid) => { + relationsToAdd.push( + this.model.update({ + where: { uuid: uid }, + data: { + deed_has_document_types: { + connect: { + uuid: relationUuid, + }, + }, + }, + }), + ); + }); + return this.instanceDb.$transaction(relationsToAdd); + } +} diff --git a/src/common/repositories/DocumentTypesRepository.ts b/src/common/repositories/DocumentTypesRepository.ts new file mode 100644 index 00000000..ca65f0ad --- /dev/null +++ b/src/common/repositories/DocumentTypesRepository.ts @@ -0,0 +1,77 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { DocumentTypes } 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 users + */ + public async findMany(query: any): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } + + public async create(documentType: DocumentType): Promise { + return this.model.create({ + data: { + name: documentType.name, + public_description: documentType.public_description, + private_description: documentType.private_description, + office: { + connect: { + uuid: documentType.office.uid, + }, + }, + }, + }); + } + + /** + * @description : update given deed + */ + public async update(uuid: string, documentType: DocumentType): Promise { + return this.model.update({ + where: { + uuid: uuid, + }, + data: { + name: documentType.name, + public_description: documentType.public_description, + private_description: documentType.private_description, + archived_at: documentType.archived_at, + office: { + connect: { + uuid: documentType.office.uid, + }, + }, + }, + }); + } + + public async findOneByUid(uid: string): Promise { + const documentTypeEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!documentTypeEntity) { + throw new Error("Document Type not found"); + } + + return documentTypeEntity; + } +} diff --git a/src/common/repositories/DocumentsRepository.ts b/src/common/repositories/DocumentsRepository.ts new file mode 100644 index 00000000..1f6b09e5 --- /dev/null +++ b/src/common/repositories/DocumentsRepository.ts @@ -0,0 +1,26 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +import { Documents } from "@prisma/client"; + +@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 users + */ + public async findMany(query: ReturnType): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return this.model.findMany(query); + } +} diff --git a/src/common/repositories/OfficeFoldersRepository.ts b/src/common/repositories/OfficeFoldersRepository.ts new file mode 100644 index 00000000..efb8f5d5 --- /dev/null +++ b/src/common/repositories/OfficeFoldersRepository.ts @@ -0,0 +1,107 @@ +import Database from "@Common/databases/database"; +import { ORMBadQueryError } from "@Common/system/database/exceptions/ORMBadQueryError"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +import { EFolderStatus, OfficeFolders } 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: ReturnType): Promise { + try { + const limit = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + + return await this.model.findMany({ ...query, take: limit }); + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } + + /** + * @description : Create new office folder wihtout customers nor stakeholders + */ + public async create(officeFolder: OfficeFolder): Promise { + try { + const officeFolderEntityCreated = (await this.model.create({ + data: { + folder_number: officeFolder.folder_number, + name: officeFolder.name, + description: officeFolder.description, + status: EFolderStatus.LIVE, + deed: { + create: { + deed_type: { + connect: { + uuid: officeFolder.deed.deed_type.uid, + }, + }, + }, + }, + office: { + connect: { + idNot: officeFolder.office.idNot, + }, + }, + }, + })) as OfficeFolders; + + return officeFolderEntityCreated; + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } + + public async update( + officeFolder: OfficeFolder, + officeFolderHasStakeholders_uuid?: string, + officeFolderHasCustomers_uuid?: string, + document_uuid?: string, + ): Promise { + try { + const officeFolderEntityUpdated = (await this.model.update({ + where: { + uuid: officeFolder.uid, + }, + data: { + folder_number: officeFolder.folder_number, + name: officeFolder.name, + description: officeFolder.description, + status: EFolderStatus.LIVE, + office_folder_has_stakeholder: { + connect: { + uuid: officeFolderHasStakeholders_uuid, + }, + }, + office_folder_has_customers: { + connect: { + uuid: officeFolderHasCustomers_uuid, + }, + }, + documents: { + connect: { + uuid: document_uuid, + }, + }, + }, + })) as OfficeFolders; + + return officeFolderEntityUpdated; + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } +} diff --git a/src/common/repositories/OfficesRepository.ts b/src/common/repositories/OfficesRepository.ts new file mode 100644 index 00000000..5a9302e6 --- /dev/null +++ b/src/common/repositories/OfficesRepository.ts @@ -0,0 +1,101 @@ +import Database from "@Common/databases/database"; +import { ORMBadQueryError } from "@Common/system/database/exceptions/ORMBadQueryError"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +import { EOfficeStatus, Offices } 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: ReturnType): Promise { + try { + const limit = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + + return await this.model.findMany({ ...query, take: limit }); + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } + + public async create(office: OfficeRessource): Promise { + try { + const officeEntityCreated = (await 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, + }, + })) as Offices; + + return officeEntityCreated; + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } + + public async update(uid: string, office: OfficeRessource): Promise { + try { + const officeEntityUpdated = (await this.model.update({ + where: { + uuid: 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], + }, + })) as Offices; + return officeEntityUpdated; + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } + + public async findOneByUid(uid: string): Promise { + try { + const officeEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!officeEntity) { + throw new Error("User not found"); + } + + return officeEntity; + + //return await this.model.find({ ...query, take: limit }); + } catch (error) { + throw new ORMBadQueryError((error as Error).message, error as Error); + } + } +} diff --git a/src/common/repositories/UsersRepository.ts b/src/common/repositories/UsersRepository.ts new file mode 100644 index 00000000..2c7ef00e --- /dev/null +++ b/src/common/repositories/UsersRepository.ts @@ -0,0 +1,135 @@ +import Database from "@Common/databases/database"; +import BaseRepository from "@Repositories/BaseRepository"; +import { Service } from "typedi"; +import { ECivility, Users } from "@prisma/client"; +import User from "le-coffre-resources/dist/SuperAdmin"; +import { processFindManyQuery } from "prisma-query"; + +@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: ReturnType): Promise { + query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); + return await this.model.findMany(query); + } + + public async create(user: User): Promise { + return this.model.create({ + 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: { + create: { + address: user.contact.address.address, + zip_code: user.contact.address.zip_code, + city: user.contact.address.city, + }, + }, + }, + }, + }, + }); + } + + public async update(uid: string, user: User): Promise { + return this.model.update({ + where: { + uuid: 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: { + update: { + address: user.contact.address.address, + zip_code: user.contact.address.zip_code, + city: user.contact.address.city, + }, + }, + }, + }, + }, + }); + } + + /** + * @description : Find one user + */ + public async findOneByUid(uid: string): Promise { + const userEntity = await this.model.findUnique({ + where: { + uuid: uid, + }, + }); + + if (!userEntity) { + throw new Error("User not found"); + } + + return userEntity; + } +} diff --git a/src/common/repositories/_TemplateRepository/_TemplateRepository.ts b/src/common/repositories/_TemplateRepository/_TemplateRepository.ts deleted file mode 100644 index 8ea415db..00000000 --- a/src/common/repositories/_TemplateRepository/_TemplateRepository.ts +++ /dev/null @@ -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 - */ - public async findMany() { - try { - // Query - } catch (error) { - throw new ORMBadQueryError((error as Error).message, error as Error); - } - } - - /** - * @description : Find many T - * @arguments : t : Partial - * @returns : Promise - */ - public async findOne() { - try { - // Query - } catch (error) { - throw new ORMBadQueryError((error as Error).message, error as Error); - } - } - - /** - * @description : Create T - * @arguments : t : Partial - * @returns : Promise - */ - 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 - * @returns : Promise - */ - public async createMany() { - try { - // Create many new T - // return T[] - } catch (error) { - throw new ORMBadQueryError((error as Error).message, error as Error); - } - } -} diff --git a/src/common/system/ExpressServer.ts b/src/common/system/ExpressServer.ts index 8f381907..ec8e217b 100644 --- a/src/common/system/ExpressServer.ts +++ b/src/common/system/ExpressServer.ts @@ -31,4 +31,3 @@ export default class ExpressServer implements ServerInterface { return this; } } - diff --git a/src/common/system/ExpressServerTest.ts b/src/common/system/ExpressServerTest.ts new file mode 100644 index 00000000..abf20b60 --- /dev/null +++ b/src/common/system/ExpressServerTest.ts @@ -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"], + ); + }); + } +} diff --git a/src/common/system/ServerInterface.ts b/src/common/system/ServerInterface.ts index 15ea57f2..e3962a03 100644 --- a/src/common/system/ServerInterface.ts +++ b/src/common/system/ServerInterface.ts @@ -14,4 +14,3 @@ export default interface ServerInterface { init(config: IConfig): this; } - diff --git a/src/common/system/controller-pattern/ApiController.ts b/src/common/system/controller-pattern/ApiController.ts index f1159f3e..3f8458c7 100644 --- a/src/common/system/controller-pattern/ApiController.ts +++ b/src/common/system/controller-pattern/ApiController.ts @@ -6,4 +6,3 @@ import HttpCodes from "@Common/system/controller-pattern/HttpCodes"; export default abstract class ApiController extends BaseController {} export { HttpCodes as ResponseStatusCodes }; - diff --git a/src/common/system/controller-pattern/BaseController.ts b/src/common/system/controller-pattern/BaseController.ts index 516b7e66..3b128b1f 100644 --- a/src/common/system/controller-pattern/BaseController.ts +++ b/src/common/system/controller-pattern/BaseController.ts @@ -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; diff --git a/src/common/system/controller-pattern/Controller.ts b/src/common/system/controller-pattern/Controller.ts index 9a5c8d2e..91d5789f 100644 --- a/src/common/system/controller-pattern/Controller.ts +++ b/src/common/system/controller-pattern/Controller.ts @@ -34,4 +34,3 @@ function createRoute(controller: any, route: StRoute) { } export default Controller; - diff --git a/src/common/system/controller-pattern/ErrorCatch.ts b/src/common/system/controller-pattern/ErrorCatch.ts index d6bed57c..8dc0aea4 100644 --- a/src/common/system/controller-pattern/ErrorCatch.ts +++ b/src/common/system/controller-pattern/ErrorCatch.ts @@ -12,4 +12,3 @@ export default class ErrorCatch { next(args[args.length - 1] ?? "Unknown Error"); } } - diff --git a/src/common/system/controller-pattern/HttpCodes.ts b/src/common/system/controller-pattern/HttpCodes.ts index 433b5525..8ca2500b 100644 --- a/src/common/system/controller-pattern/HttpCodes.ts +++ b/src/common/system/controller-pattern/HttpCodes.ts @@ -1,10 +1,10 @@ -enum HttpCodes { - SUCCESS = 200, - CREATED = 201, - BAD_REQUEST = 400, - INTERNAL_ERROR = 500, - UNKNOWN_ERROR = 520, - NOT_IMPLEMENTED = 501, - NOT_FOUND = 404, -} -export default HttpCodes; +enum HttpCodes { + SUCCESS = 200, + CREATED = 201, + BAD_REQUEST = 400, + INTERNAL_ERROR = 500, + UNKNOWN_ERROR = 520, + NOT_IMPLEMENTED = 501, + NOT_FOUND = 404, +} +export default HttpCodes; diff --git a/src/common/system/controller-pattern/Methods.ts b/src/common/system/controller-pattern/Methods.ts index b0dd3729..43c0f6f0 100644 --- a/src/common/system/controller-pattern/Methods.ts +++ b/src/common/system/controller-pattern/Methods.ts @@ -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"); - diff --git a/src/common/system/controller-pattern/StRoute.ts b/src/common/system/controller-pattern/StRoute.ts index f216112f..fe6ae78d 100644 --- a/src/common/system/controller-pattern/StRoute.ts +++ b/src/common/system/controller-pattern/StRoute.ts @@ -7,4 +7,3 @@ export interface StRoute { frontMiddlewares: ((requests: Request, response: Response, next: NextFunction) => void)[]; backMiddlewares: ((requests: Request, response: Response, next: NextFunction) => void)[]; } - diff --git a/src/common/system/controller-pattern/exceptions/HttpException.ts b/src/common/system/controller-pattern/exceptions/HttpException.ts index ceb49fa7..62a485b7 100644 --- a/src/common/system/controller-pattern/exceptions/HttpException.ts +++ b/src/common/system/controller-pattern/exceptions/HttpException.ts @@ -1,7 +1,7 @@ -import HttpCodes from "../HttpCodes"; - -export default class HttpException extends Error { - constructor(message: string, public httpCode: HttpCodes = HttpCodes.UNKNOWN_ERROR) { - super(message); - } -} +import HttpCodes from "../HttpCodes"; + +export default class HttpException extends Error { + constructor(message: string, public httpCode: HttpCodes = HttpCodes.UNKNOWN_ERROR) { + super(message); + } +} diff --git a/src/common/system/database/DbProvider.ts b/src/common/system/database/DbProvider.ts index 0037217b..1c5f9d69 100644 --- a/src/common/system/database/DbProvider.ts +++ b/src/common/system/database/DbProvider.ts @@ -1,34 +1,34 @@ -import dotenv from "dotenv"; -import { PrismaClient } from "@prisma/client"; -import IDatabaseConfig from "../../config/database/IDatabaseConfig"; -import { BackendVariables } from "@Common/config/variables/Variables"; -import Container from "typedi"; - -dotenv.config(); - -export default class DbProvider { - protected readonly variables = Container.get(BackendVariables); - 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}`, - }, - }, - }); - - constructor(protected config: IDatabaseConfig) {} - - public async connect(): Promise { - await this.client.$connect(); - console.info(`⚡️[Prisma]: Connected to ${this.config.name}`); // A Logger middleware is to be added here - } - - public getClient() { - return this.client; - } - - public async disconnect(): Promise { - await this.client.$disconnect(); - console.info(`⚡️[Prisma]: Disconnected from ${this.config.name}`); // A Logger middleware is to be added here - } -} +import dotenv from "dotenv"; +import { PrismaClient } from "@prisma/client"; +import IDatabaseConfig from "../../config/database/IDatabaseConfig"; +import { BackendVariables } from "@Common/config/variables/Variables"; +import Container from "typedi"; + +dotenv.config(); + +export default class DbProvider { + protected readonly variables = Container.get(BackendVariables); + 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}`, + }, + }, + }); + + constructor(protected config: IDatabaseConfig) {} + + public async connect(): Promise { + await this.client.$connect(); + console.info(`⚡️[Prisma]: Connected to ${this.config.name}`); // A Logger middleware is to be added here + } + + public getClient() { + return this.client; + } + + public async disconnect(): Promise { + await this.client.$disconnect(); + console.info(`⚡️[Prisma]: Disconnected from ${this.config.name}`); // A Logger middleware is to be added here + } +} diff --git a/src/common/system/database/exceptions/ORMBadQueryError.ts b/src/common/system/database/exceptions/ORMBadQueryError.ts index b61c4d15..89255e6a 100644 --- a/src/common/system/database/exceptions/ORMBadQueryError.ts +++ b/src/common/system/database/exceptions/ORMBadQueryError.ts @@ -2,4 +2,4 @@ export class ORMBadQueryError extends Error { constructor(message: string, public error: Error) { super(message); } -} \ No newline at end of file +} diff --git a/src/common/system/database/index.ts b/src/common/system/database/index.ts index 6f728469..943586b8 100644 --- a/src/common/system/database/index.ts +++ b/src/common/system/database/index.ts @@ -2,4 +2,4 @@ import IDatabaseConfig from "@Common/config/database/IDatabaseConfig"; import DbProvider from "./DbProvider"; export type { IDatabaseConfig }; -export default DbProvider; \ No newline at end of file +export default DbProvider; diff --git a/src/entries/App.ts b/src/entries/App.ts index 5db0695d..b520f7a0 100644 --- a/src/entries/App.ts +++ b/src/entries/App.ts @@ -16,7 +16,7 @@ import { BackendVariables } from "@Common/config/variables/Variables"; const port = variables.APP_PORT; const rootUrl = variables.APP_ROOT_URL; const label = variables.APP_LABEL ?? "Unknown Service"; - + // Container.get(TezosLink).connect(); Container.get(ExpressServer).init({ label, @@ -31,4 +31,3 @@ import { BackendVariables } from "@Common/config/variables/Variables"; console.error(e); } })(); - diff --git a/src/services/BaseService.ts b/src/services/BaseService.ts index 91aae64f..0ff263c1 100644 --- a/src/services/BaseService.ts +++ b/src/services/BaseService.ts @@ -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"]; } - diff --git a/src/services/CustomersService/CustomersService.ts b/src/services/CustomersService/CustomersService.ts deleted file mode 100644 index 89b01607..00000000 --- a/src/services/CustomersService/CustomersService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/DeedTypesService/DeedTypesService.ts b/src/services/DeedTypesService/DeedTypesService.ts deleted file mode 100644 index a85eea94..00000000 --- a/src/services/DeedTypesService/DeedTypesService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/DeedsService/DeedsService.ts b/src/services/DeedsService/DeedsService.ts deleted file mode 100644 index 09ca10fe..00000000 --- a/src/services/DeedsService/DeedsService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/DocumentTypesService/DocumentTypesService.ts b/src/services/DocumentTypesService/DocumentTypesService.ts deleted file mode 100644 index 202074db..00000000 --- a/src/services/DocumentTypesService/DocumentTypesService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/FoldersService/FoldersService.ts b/src/services/FoldersService/FoldersService.ts deleted file mode 100644 index 633f64b9..00000000 --- a/src/services/FoldersService/FoldersService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/OfficesService/OfficesService.ts b/src/services/OfficesService/OfficesService.ts deleted file mode 100644 index 2b6d2ba8..00000000 --- a/src/services/OfficesService/OfficesService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/UsersService/UsersService.ts b/src/services/UsersService/UsersService.ts deleted file mode 100644 index a1b12d29..00000000 --- a/src/services/UsersService/UsersService.ts +++ /dev/null @@ -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 - */ - 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 - */ - 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 - */ - 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 - */ - 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" }; - } -} diff --git a/src/services/AddressesService/AddressesService.ts b/src/services/private-services/AddressesService/AddressesService.ts similarity index 66% rename from src/services/AddressesService/AddressesService.ts rename to src/services/private-services/AddressesService/AddressesService.ts index 8295b1a0..a9c04087 100644 --- a/src/services/AddressesService/AddressesService.ts +++ b/src/services/private-services/AddressesService/AddressesService.ts @@ -1,5 +1,9 @@ +// import { Addresses } from "@prisma/client"; +import { Addresses } from "@prisma/client"; +import AddressesRepository from "@Repositories/AddressesRepository"; import BaseService from "@Services/BaseService"; -import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +import Container, { Service } from "typedi"; @Service() export default class AddressesService extends BaseService { @@ -13,22 +17,26 @@ export default class AddressesService extends BaseService { * @throws {Error} If addresses cannot be get * @param : projectEntity: Partial */ - 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" }; + public async get(query: ReturnType) { + //init repo + const repo = Container.get(AddressesRepository); + + //call service to return prisma entity + return await repo.findMany(query); } - + /** * @description : Create a new address * @returns : T * @throws {Error} If address cannot be created * @param : projectEntity: Partial */ - 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" }; + public async create(address: Addresses): Promise { + //init repo + const repo = Container.get(AddressesRepository); + + // call service to return prisma entity + return await repo.create(address); } /** diff --git a/src/services/ContactsService/ContactsService.ts b/src/services/private-services/ContactsService/ContactsService.ts similarity index 99% rename from src/services/ContactsService/ContactsService.ts rename to src/services/private-services/ContactsService/ContactsService.ts index 02cde913..7976931c 100644 --- a/src/services/ContactsService/ContactsService.ts +++ b/src/services/private-services/ContactsService/ContactsService.ts @@ -18,7 +18,7 @@ export default class ContactsService extends BaseService { // 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 diff --git a/src/services/FilesService/FilesService.ts b/src/services/private-services/FilesService/FilesService.ts similarity index 99% rename from src/services/FilesService/FilesService.ts rename to src/services/private-services/FilesService/FilesService.ts index c4c1f6f8..3245f019 100644 --- a/src/services/FilesService/FilesService.ts +++ b/src/services/private-services/FilesService/FilesService.ts @@ -18,7 +18,7 @@ export default class FilesService extends BaseService { // 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 diff --git a/src/services/NotificationsService/NotificationsService.ts b/src/services/private-services/NotificationsService/NotificationsService.ts similarity index 99% rename from src/services/NotificationsService/NotificationsService.ts rename to src/services/private-services/NotificationsService/NotificationsService.ts index 790e0bab..4187e937 100644 --- a/src/services/NotificationsService/NotificationsService.ts +++ b/src/services/private-services/NotificationsService/NotificationsService.ts @@ -18,7 +18,7 @@ export default class NotificationsService extends BaseService { // if (!notifications) Promise.reject(new Error("Cannot get notifications")); return { response: "/api/notifications > GET : All notifications > Not implemented yet" }; } - + /** * @description : Create a new notification * @returns : T diff --git a/src/services/super-admin/CustomersService/CustomersService.ts b/src/services/super-admin/CustomersService/CustomersService.ts new file mode 100644 index 00000000..f096654e --- /dev/null +++ b/src/services/super-admin/CustomersService/CustomersService.ts @@ -0,0 +1,44 @@ +import { Customers } 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: any) { + return this.customerRepository.findMany(query); + } + + /** + * @description : Create a new customer + * @throws {Error} If customer cannot be created + */ + public async create(customerEntity: Customer): Promise { + return this.customerRepository.create(customerEntity); + } + + /** + * @description : Modify a customer + * @throws {Error} If customer cannot be modified + */ + public async update(uid: string, customerEntity: Customer): Promise { + 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): Promise { + return this.customerRepository.findOneByUid(uid); + } +} diff --git a/src/services/super-admin/DeedTypesService/DeedTypesService.ts b/src/services/super-admin/DeedTypesService/DeedTypesService.ts new file mode 100644 index 00000000..1a92eb9b --- /dev/null +++ b/src/services/super-admin/DeedTypesService/DeedTypesService.ts @@ -0,0 +1,78 @@ +import { DeedTypes } from "@prisma/client"; +import DeedTypeHasDocumentTypesRepository from "@Repositories/DeedTypesHasDocumentTypesRepository"; +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, + private deedTypeHasDocumentTypesRepository: DeedTypeHasDocumentTypesRepository, + ) { + super(); + } + + /** + * @description : Get all deed-types + * @throws {Error} If deed-types cannot be get + */ + public async get(query: any): Promise { + return this.deedTypeRepository.findMany(query); + } + + /** + * @description : Create a new deed-type + * @throws {Error} If deed-type cannot be created + * @param : deedTypesEntity: Partial + */ + public async create(deedTypeEntity: DeedType): Promise { + 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 { + 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) { + return this.deedTypeRepository.findOneByUid(uid); + } + + public async addDocumentTypes(deedTypeUuid: string, documentTypesUuidToAdd: string[]): Promise { + const relationsToDocumentTypes = await this.deedTypeHasDocumentTypesRepository.createMany(deedTypeUuid, documentTypesUuidToAdd); + + let deedTypeHasDocumentUuids: string[] = []; + relationsToDocumentTypes.forEach((item) => { + deedTypeHasDocumentUuids.push(item.uuid); + }); + + return this.deedTypeRepository.addDocumentTypes(deedTypeUuid, deedTypeHasDocumentUuids); + } + + public async addDocumentType(deedTypeUuid: string, documentTypesUuidToAdd: string): Promise { + const deedTypeHasDocumentType = await this.deedTypeHasDocumentTypesRepository.create(deedTypeUuid, documentTypesUuidToAdd); + + return this.deedTypeRepository.addDocumentType(deedTypeUuid, deedTypeHasDocumentType.uuid); + } + + public async removeDocumentType(deedTypeUuid: string, documentTypesUuidToRemove: string): Promise { + await this.deedTypeHasDocumentTypesRepository.delete(deedTypeUuid, documentTypesUuidToRemove); + + return this.get({ where: { uuid: deedTypeUuid }, include: { deed_type_has_document_types: true } }); + } + + public async removeDocumentTypes(deedTypeUuid: string, documentTypesUuidToRemove: string[]): Promise { + await this.deedTypeHasDocumentTypesRepository.deleteMany(deedTypeUuid, documentTypesUuidToRemove); + + return this.get({ where: { uuid: deedTypeUuid }, include: { deed_type_has_document_types: true } }); + } +} diff --git a/src/services/super-admin/DeedsService/DeedsService.ts b/src/services/super-admin/DeedsService/DeedsService.ts new file mode 100644 index 00000000..dbbdb171 --- /dev/null +++ b/src/services/super-admin/DeedsService/DeedsService.ts @@ -0,0 +1,89 @@ +import { Deeds } from "@prisma/client"; +import DeedHasDocumentTypesRepository from "@Repositories/DeedsHasDocumentTypesRepository"; +import DeedsRepository from "@Repositories/DeedsRepository"; +import DeedTypesHasDocumentTypesRepository from "@Repositories/DeedTypesHasDocumentTypesRepository"; +import DeedTypesRepository from "@Repositories/DeedTypesRepository"; +import BaseService from "@Services/BaseService"; +import { DeedType } from "le-coffre-resources/dist/Customer"; +import Container, { Service } from "typedi"; + +@Service() +export default class DeedsService extends BaseService { + constructor(private deedRepository: DeedsRepository, private deedHasDocumentTypesRepository: DeedHasDocumentTypesRepository) { + 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(deedType: DeedType): Promise { + let documentTypesToAdd: string[] = []; + const deedTypeHasDocumentTypesRepository = Container.get(DeedTypesHasDocumentTypesRepository); + const deedTypesRepository = Container.get(DeedTypesRepository); + + if ((await deedTypesRepository.findOneByUid(deedType.uid)).archived_at != null) throw new Error("deed type is archived"); + + const deedTypeHasDocumentTypes = await deedTypeHasDocumentTypesRepository.findMany({ where: { deed_type_uuid: deedType.uid } }); + deedTypeHasDocumentTypes.forEach((relation) => { + documentTypesToAdd.push(relation.document_type_uuid); + }); + + const deed = await this.deedRepository.create(deedType); + const relations = await this.deedHasDocumentTypesRepository.createMany(deed.uuid, documentTypesToAdd); + + let relationsToAdd: string[] = []; + relations.forEach((relation) => { + documentTypesToAdd.push(relation.uuid); + }); + + await this.deedRepository.addDocumentTypes(deed.uuid, relationsToAdd); + + return this.getByUid(deed.uuid); + } + + /** + * @description : Get a deed by uid + * @throws {Error} If deed-type cannot be get by uid + */ + public async getByUid(uid: string) { + return this.deedRepository.findOneByUid(uid); + } + + public async addDocumentTypes(deedTypeUuid: string, documentTypesUuidToAdd: string[]): Promise { + const relationsToDocumentTypes = await this.deedHasDocumentTypesRepository.createMany(deedTypeUuid, documentTypesUuidToAdd); + + let deedTypeHasDocumentUuids: string[] = []; + relationsToDocumentTypes.forEach((item) => { + deedTypeHasDocumentUuids.push(item.uuid); + }); + + return this.deedRepository.addDocumentTypes(deedTypeUuid, deedTypeHasDocumentUuids); + } + + public async addDocumentType(deedTypeUuid: string, documentTypesUuidToAdd: string): Promise { + const deedTypeHasDocumentType = await this.deedHasDocumentTypesRepository.create(deedTypeUuid, documentTypesUuidToAdd); + + return this.deedRepository.addDocumentType(deedTypeUuid, deedTypeHasDocumentType.uuid); + } + + public async removeDocumentType(deedTypeUuid: string, documentTypesUuidToRemove: string): Promise { + await this.deedHasDocumentTypesRepository.delete(deedTypeUuid, documentTypesUuidToRemove); + + return await this.get({ where: { uuid: deedTypeUuid }, include: { deed_has_document_types: true } }); + } + + public async removeDocumentTypes(deedTypeUuid: string, documentTypesUuidToRemove: string[]): Promise { + await this.deedHasDocumentTypesRepository.deleteMany(deedTypeUuid, documentTypesUuidToRemove); + + return await this.get({ where: { uuid: deedTypeUuid }, include: { deed_has_document_types: true } }); + } +} diff --git a/src/services/super-admin/DocumentTypesService/DocumentTypesService.ts b/src/services/super-admin/DocumentTypesService/DocumentTypesService.ts new file mode 100644 index 00000000..a3308ab5 --- /dev/null +++ b/src/services/super-admin/DocumentTypesService/DocumentTypesService.ts @@ -0,0 +1,45 @@ +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 { + 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 { + return this.documentTypeRepository.update(uid, documentTypeEntity); + } + + /** + * @description : Get a document-type by uid + * @returns : T + * @throws {Error} If document-type is not found + */ + public async getByUid(uid: string) { + return this.documentTypeRepository.findOneByUid(uid); + } +} diff --git a/src/services/DocumentsService/DocumentsService.ts b/src/services/super-admin/DocumentsService/DocumentsService.ts similarity index 62% rename from src/services/DocumentsService/DocumentsService.ts rename to src/services/super-admin/DocumentsService/DocumentsService.ts index 790f7843..cf19570f 100644 --- a/src/services/DocumentsService/DocumentsService.ts +++ b/src/services/super-admin/DocumentsService/DocumentsService.ts @@ -1,5 +1,8 @@ +import DocumentTypesRepository from "@Repositories/DocumentTypesRepository"; +//import { DocumentTypes } from "prisma/prisma-client"; import BaseService from "@Services/BaseService"; -import { Service } from "typedi"; +import { processFindManyQuery } from "prisma-query"; +import Container, { Service } from "typedi"; @Service() export default class DocumentsService extends BaseService { @@ -9,14 +12,16 @@ export default class DocumentsService extends BaseService { /** * @description : Get all documents - * @returns : T + * @returns : Document[] * @throws {Error} If documents cannot be get - * @param : projectEntity: Partial + * @param : ReturnType */ - 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" }; + public async get(query: ReturnType) { + //init repo + const repo = Container.get(DocumentTypesRepository); + + //call service to return prisma entity + return await repo.findMany(query); } /** @@ -25,11 +30,13 @@ export default class DocumentsService extends BaseService { * @throws {Error} If document cannot be created * @param : projectEntity: Partial */ - 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" }; - } + // public async create(documentTypeEntity: DocumentTypes): Promise { + // //init repo + // const repo = Container.get(DocumentTypesRepository); + + // // call service to return prisma entity + // return await repo.create(documentTypeEntity); + // } /** * @description : Modify a document diff --git a/src/services/super-admin/OfficeFoldersService/OfficeFoldersService.ts b/src/services/super-admin/OfficeFoldersService/OfficeFoldersService.ts new file mode 100644 index 00000000..c630756a --- /dev/null +++ b/src/services/super-admin/OfficeFoldersService/OfficeFoldersService.ts @@ -0,0 +1,67 @@ +import { OfficeFolders } from ".prisma/client"; +import OfficeFoldersRepository from "@Repositories/OfficeFoldersRepository"; +import BaseService from "@Services/BaseService"; +import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin"; +import { processFindManyQuery } from "prisma-query"; +import Container, { Service } from "typedi"; + +@Service() +export default class OfficeFoldersService extends BaseService { + constructor() { + super(); + } + + /** + * @description : Get all folders + * @returns : OfficeFolders[] + * @throws {Error} If folders cannot be get + * @param : query: ReturnType + */ + public async get(query: ReturnType) { + //init repo + const repo = Container.get(OfficeFoldersRepository); + + //call service to return prisma entity + return await repo.findMany(query); + } + + /** + * @description : Create a new folder + * @returns : T + * @throws {Error} If folder cannot be created + * @param : projectEntity: Partial + */ + public async create(officeFolderEntity: OfficeFolder): Promise { + //init repo + const repo = Container.get(OfficeFoldersRepository); + + // call service to return prisma entity + return await repo.create(officeFolderEntity); + } + + /** + * @description : Modify a folder + * @returns : T + * @throws {Error} If folder cannot be modified + * @param : projectEntity: Partial + */ + public async update(officeFolderEntity: OfficeFolder): Promise { + //init repo + const repo = Container.get(OfficeFoldersRepository); + + // call service to return prisma entity + return await repo.update(officeFolderEntity); + } + + /** + * @description : Get a folder by uid + * @returns : T + * @throws {Error} If folder cannot be get by uid + * @param : projectEntity: Partial + */ + 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" }; + } +} diff --git a/src/services/super-admin/OfficesService/OfficesService.ts b/src/services/super-admin/OfficesService/OfficesService.ts new file mode 100644 index 00000000..c9512c84 --- /dev/null +++ b/src/services/super-admin/OfficesService/OfficesService.ts @@ -0,0 +1,46 @@ +// import ProjectsRepository from "@Common/repositories/projects/ProjectsRepository"; +import { Offices } from "@prisma/client"; +import OfficesRepository from "@Repositories/OfficesRepository"; +import BaseService from "@Services/BaseService"; +import { Office as OfficeRessource } from "le-coffre-resources/dist/SuperAdmin"; +import { processFindManyQuery } from "prisma-query"; +import { Service } from "typedi"; + +@Service() +export default class OfficesService extends BaseService { + constructor(private officeRepository: OfficesRepository) { + super(); + } + + /** + * @description : Get all offices + * @throws {Error} If offices cannot be get + */ + public async get(query: ReturnType): Promise { + return this.officeRepository.findMany(query); + } + + /** + * @description : Create a new office + * @throws {Error} If office cannot be created + */ + public async create(officeEntity: OfficeRessource): Promise { + return this.officeRepository.create(officeEntity); + } + + /** + * @description : Modify an office + * @throws {Error} If office cannot be modified + */ + public async update(uid: string, officeEntity: OfficeRessource): Promise { + return this.officeRepository.update(uid, officeEntity); + } + + /** + * @description : Get a office by uid + * @throws {Error} If office cannot be get + */ + public async getByUid(uid: string): Promise { + return this.officeRepository.findOneByUid(uid); + } +} diff --git a/src/services/super-admin/UsersService/UsersService.ts b/src/services/super-admin/UsersService/UsersService.ts new file mode 100644 index 00000000..62e11871 --- /dev/null +++ b/src/services/super-admin/UsersService/UsersService.ts @@ -0,0 +1,45 @@ +import BaseService from "@Services/BaseService"; +import "reflect-metadata"; +import { Service } from "typedi"; +import UsersRepository from "@Repositories/UsersRepository"; +import User from "le-coffre-resources/dist/SuperAdmin"; +import { Users } from "@prisma/client"; + +@Service() +export default class UsersService extends BaseService { + constructor(private userRepository: UsersRepository) { + super(); + } + + /** + * @description : Get all users + * @throws {Error} If users cannot be get + */ + public get(query: any): Promise { + return this.userRepository.findMany(query); + } + + /** + * @description : Create a user + * @throws {Error} If user couldn't be created + */ + public create(userEntity: User): Promise { + return this.userRepository.create(userEntity); + } + + /** + * @description : Modify a user + * @throws {Error} If user modification failed + */ + public update(uuid: string, userEntity: User): Promise { + return this.userRepository.update(uuid, userEntity); + } + + /** + * @description : Get a user by uid + * @throws {Error} If user cannot be get by uid + */ + public getByUid(uid: string): Promise { + return this.userRepository.findOneByUid(uid); + } +} diff --git a/src/test/services/super-admin/CustomersService.test.ts b/src/test/services/super-admin/CustomersService.test.ts new file mode 100644 index 00000000..d2b5b74b --- /dev/null +++ b/src/test/services/super-admin/CustomersService.test.ts @@ -0,0 +1,167 @@ +import "module-alias/register"; +import "reflect-metadata"; +import { Customer } from "le-coffre-resources/dist/SuperAdmin"; +import CustomersService from "@Services/super-admin/CustomersService/CustomersService"; +import { processFindManyQuery } from "prisma-query"; +import { PrismaClient } from "@prisma/client"; +import { customer, customer_, userContact, userContact_ } from "./MockedData"; +import Container from "typedi"; +import CustomersRepository from "@Repositories/CustomersRepository"; + +const prisma = new PrismaClient(); + +const CustomersServiceTest = new CustomersService(Container.get(CustomersRepository)); + +afterAll(async () => { + /* + * Clean database after all tests execution. + * Due to cascade deletion, if addresses are deleted, all items following tables are dropped: contacts, customers, offices + */ + const deleteAddresses = prisma.addresses.deleteMany(); + await prisma.$transaction([deleteAddresses]); + await prisma.$disconnect(); +}); + +describe("test create function", () => { + it("should create a new customer", async () => { + const customerCreated = await CustomersServiceTest.create(customer); + + expect(customerCreated?.status).toEqual("PENDING"); + + // verify if customer contact is created in db + const contactCreated = await prisma.contacts.findUnique({ where: { uuid: customerCreated.contact_uuid } }); + expect(contactCreated?.first_name).toEqual(customer.contact.first_name); + expect(contactCreated?.last_name).toEqual(customer.contact.last_name); + expect(contactCreated?.cell_phone_number).toEqual(customer.contact.cell_phone_number); + expect(contactCreated?.phone_number).toEqual(customer.contact.phone_number); + expect(contactCreated?.civility).toEqual(customer.contact.civility); + expect(contactCreated?.email).toEqual(customer.contact.email); + + // verify if customer address is created in db + const addressForContactCreated = await prisma.addresses.findUnique({ where: { uuid: contactCreated?.address_uuid } }); + expect(addressForContactCreated?.address).toEqual(customer.contact.address.address); + expect(addressForContactCreated?.zip_code).toEqual(customer.contact.address.zip_code); + expect(addressForContactCreated?.city).toEqual(customer.contact.address.city); + }); + + it("should not create an customer already created", async () => { + // try to create the same customer + async function duplicateCustomer() { + await CustomersServiceTest.create(customer); + } + await expect(duplicateCustomer).rejects.toThrow(); + }); + + it("should not create an new customer with an email already created", async () => { + let newCustomer: Customer = JSON.parse(JSON.stringify(customer_)); + newCustomer.contact.email = userContact.email; + + // try to create a new customer with already used email + async function createCustomerWithDuplicateEmail() { + await CustomersServiceTest.create(newCustomer); + } + await expect(createCustomerWithDuplicateEmail).rejects.toThrow(); + }); + + it("should not create an customer with an phone number already created", async () => { + let newCustomer: Customer = JSON.parse(JSON.stringify(customer_)); + newCustomer.contact.cell_phone_number = userContact.cell_phone_number; + + // try to create a new customer with already used cellphone number + async function duplicateCustomer() { + await CustomersServiceTest.create(newCustomer); + } + await expect(duplicateCustomer).rejects.toThrow(); + }); + + it("should create an new customer if unique attributes differ from existing customers", async () => { + let newCustomer: Customer = JSON.parse(JSON.stringify(customer)); + newCustomer.contact.email = userContact_.email; + newCustomer.contact.cell_phone_number = userContact_.cell_phone_number; + + const customerCreated = await CustomersServiceTest.create(newCustomer); + + expect(customerCreated?.status).toEqual("PENDING"); + + // verify if customer_ contact is created in db + const contactCreated = await prisma.contacts.findUnique({ where: { uuid: customerCreated.contact_uuid } }); + expect(contactCreated?.first_name).toEqual(customer.contact.first_name); + expect(contactCreated?.last_name).toEqual(customer.contact.last_name); + expect(contactCreated?.cell_phone_number).toEqual(customer_.contact.cell_phone_number); + expect(contactCreated?.phone_number).toEqual(customer.contact.phone_number); + expect(contactCreated?.civility).toEqual(customer.contact.civility); + expect(contactCreated?.email).toEqual(customer_.contact.email); + + // verify if customer_ address is created in db + const addressForContactCreated = await prisma.addresses.findUnique({ where: { uuid: contactCreated?.address_uuid } }); + expect(addressForContactCreated?.address).toEqual(customer.contact.address.address); + expect(addressForContactCreated?.zip_code).toEqual(customer.contact.address.zip_code); + expect(addressForContactCreated?.city).toEqual(customer.contact.address.city); + }); +}); + +describe("test update function", () => { + it("should update an customer's data", async () => { + const customerCreated = await prisma.customers.findFirstOrThrow({ where: { contact: { email: customer_.contact.email } } }); + + // update the last customer created with his own new office and own contact + const updatedCustomer = await CustomersServiceTest.update(customerCreated.uuid, customer_); + + expect(updatedCustomer?.status).toEqual("ERRONED"); + + // verify if customer_ contact is created in db + const existingContact = await prisma.contacts.findUnique({ where: { uuid: updatedCustomer.contact_uuid } }); + expect(existingContact?.first_name).toEqual(customer_.contact.first_name); + expect(existingContact?.last_name).toEqual(customer_.contact.last_name); + expect(existingContact?.cell_phone_number).toEqual(customer_.contact.cell_phone_number); + expect(existingContact?.phone_number).toEqual(customer_.contact.phone_number); + expect(existingContact?.civility).toEqual(customer_.contact.civility); + expect(existingContact?.email).toEqual(customer_.contact.email); + + // verify if customer_ address is created in db + const addressForExistingContact = await prisma.addresses.findUnique({ where: { uuid: existingContact?.address_uuid } }); + expect(addressForExistingContact?.address).toEqual(customer_.contact.address.address); + expect(addressForExistingContact?.zip_code).toEqual(customer_.contact.address.zip_code); + expect(addressForExistingContact?.city).toEqual(customer_.contact.address.city); + }); + + it("should not update an customer with an email already used", async () => { + const customerUid = (await prisma.customers.findFirstOrThrow({ where: { contact: { email: customer_.contact.email } } })).uuid; + let updatedCustomer: Customer = JSON.parse(JSON.stringify(customer_)); + updatedCustomer.contact.email = userContact.email; + + // try to create a new customer with already used email + async function updateCustomerWithDuplicateEmail() { + await CustomersServiceTest.update(customerUid, updatedCustomer); + } + await expect(updateCustomerWithDuplicateEmail).rejects.toThrow(); + }); + + it("should not update an customer with an phone number already used", async () => { + const customerUid = (await prisma.customers.findFirstOrThrow({ where: { contact: { email: customer_.contact.email } } })).uuid; + let updatedCustomer: Customer = JSON.parse(JSON.stringify(customer_)); + updatedCustomer.contact.cell_phone_number = userContact.cell_phone_number; + + // try to create a new customer with already used email + async function updateCustomerWithDuplicateEmail() { + await CustomersServiceTest.update(customerUid, updatedCustomer); + } + await expect(updateCustomerWithDuplicateEmail).rejects.toThrow(); + }); +}); + +describe("test get function", () => { + it("should return an array of Customers", async () => { + const req = processFindManyQuery({}); + const customers = await CustomersServiceTest.get(req); + + // verify result typing + expect(customers).toBeInstanceOf(Array); + expect(customers.length).toEqual(2); + + // verify result content + const customersCreated = await prisma.customers.findMany(); + expect(customers).toContainEqual(customersCreated[0]); + expect(customers).toContainEqual(customersCreated[1]); + }); +}); diff --git a/src/test/services/super-admin/DeedService.test.ts b/src/test/services/super-admin/DeedService.test.ts new file mode 100644 index 00000000..be5b0775 --- /dev/null +++ b/src/test/services/super-admin/DeedService.test.ts @@ -0,0 +1,264 @@ +import "module-alias/register"; +import "reflect-metadata"; +import { Deed, DeedType } from "le-coffre-resources/dist/SuperAdmin"; +import DeedService from "@Services/super-admin/DeedsService/DeedsService"; +import { PrismaClient, Offices, DocumentTypes, DeedTypes, DeedTypeHasDocumentTypes } from "prisma/prisma-client"; +import { deedType, documentType, documentType_, office } from "./MockedData"; +import DeedsRepository from "@Repositories/DeedsRepository"; +import Container from "typedi"; +import DeedHasDocumentTypesRepository from "@Repositories/DeedsHasDocumentTypesRepository"; + +const prisma = new PrismaClient(); + +const DeedServiceTest = new DeedService(Container.get(DeedsRepository), Container.get(DeedHasDocumentTypesRepository)); + +let office1: Offices; + +let documentType1: DocumentTypes; +let documentType2: DocumentTypes; + +let deedType1: DeedTypes; + +let deedType1HasDocumentType1: DeedTypeHasDocumentTypes; + +beforeAll(async () => { + office1 = await prisma.offices.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, + }, + }, + }, + }); + + documentType1 = await prisma.documentTypes.create({ + data: { + name: documentType.name, + public_description: documentType.public_description, + private_description: documentType.private_description, + archived_at: null, + office_uuid: office1.uuid, + }, + }); + + documentType2 = await prisma.documentTypes.create({ + data: { + name: documentType_.name, + public_description: documentType_.public_description, + private_description: documentType_.private_description, + archived_at: null, + office_uuid: office1.uuid, + }, + }); + + deedType1 = await prisma.deedTypes.create({ + data: { + name: deedType.name, + description: deedType.description, + archived_at: null, + office_uuid: office1.uuid, + }, + }); + + deedType1HasDocumentType1 = await prisma.deedTypeHasDocumentTypes.create({ + data: { + deed_type_uuid: deedType1.uuid, + document_type_uuid: documentType1.uuid, + }, + }); + + await prisma.deedTypes.update({ + where: { uuid: deedType1.uuid }, + data: { + deed_type_has_document_types: { + connect: { + uuid: deedType1HasDocumentType1.uuid, + }, + }, + }, + }); +}); + +afterAll(async () => { + const deleteDeedTypes = prisma.deedTypes.deleteMany(); + const deleteOffices = prisma.offices.deleteMany(); + await prisma.$transaction([deleteDeedTypes, deleteOffices]); + await prisma.$disconnect(); +}); + +describe("test create function", () => { + it("should not create a new deed if deed type is unknown", async () => { + // try to create a new deed with unknown deed type + async function createDeedWithUnknownDeedType() { + await DeedServiceTest.create(deedType); + } + await expect(createDeedWithUnknownDeedType).rejects.toThrow(); + }); + + it("should create a new deed based on existing deed type", async () => { + let deedTypeWithUid: DeedType = JSON.parse(JSON.stringify(deedType)); + deedTypeWithUid.uid = deedType1.uuid; + const deedCreated = await DeedServiceTest.create(deedTypeWithUid); + + expect(deedCreated.deed_type_uuid).toEqual(deedType1.uuid); + }); + + it("should have by default the same document types as its deed type ", async () => { + const deedWithDocumentTypes = await prisma.deeds.findFirstOrThrow({ include: { deed_has_document_types: true } }); + expect(deedWithDocumentTypes.deed_has_document_types.length).toEqual(1); + expect(deedWithDocumentTypes.deed_has_document_types[0]?.document_type_uuid).toEqual(documentType1.uuid); + }); + + it("should create a the same deed based on existing deed type", async () => { + let deedTypeWithUid: DeedType = JSON.parse(JSON.stringify(deedType)); + deedTypeWithUid.uid = deedType1.uuid; + const deedCreated = await DeedServiceTest.create(deedTypeWithUid); + + expect(deedCreated.deed_type_uuid).toEqual(deedType1.uuid); + }); + + it("should not create a new deed based on archivated deed type", async () => { + let deedTypeArchivated: DeedType = JSON.parse(JSON.stringify(deedType)); + deedTypeArchivated.uid = deedType1.uuid; + + await prisma.deedTypes.update({ + where: { uuid: deedType1.uuid }, + data: { + archived_at: new Date(Date.now()), + }, + }); + + // try to create a new deed with archivated deed type + async function createDeedWithArchivatedDeedType() { + await DeedServiceTest.create(deedTypeArchivated); + } + await expect(createDeedWithArchivatedDeedType).rejects.toThrow("deed type is archived"); + }); +}); + +describe("test addDocumentTypes function", () => { + it("should add document types to a deed", async () => { + const deedUid = (await prisma.deeds.findFirstOrThrow({ where: { deed_type_uuid: deedType1.uuid } })).uuid; + const documentsToAdd = [documentType1.uuid, documentType2.uuid]; + await DeedServiceTest.addDocumentTypes(deedUid, documentsToAdd); + + const deed = await prisma.deeds.findFirstOrThrow({ + where: { + uuid: deedUid, + }, + include: { + deed_has_document_types: true, + }, + }); + expect(deed.deed_has_document_types.length).toEqual(2); + }); + + it("should not add document types to a deed type that already has those document types ", async () => { + const deedUid = (await prisma.deeds.findFirstOrThrow({ where: { deed_type_uuid: deedType1.uuid } })).uuid; + let deedHasDocumentTypes = await prisma.deedHasDocumentTypes.findMany({ where: { deed_uuid: deedUid } }); + expect(deedHasDocumentTypes.length).toEqual(2); + + const documentsToAdd = [documentType1.uuid, documentType2.uuid]; + //we expect deedTypeHasDocumentTypes service to skip duplicates without throwing error + await DeedServiceTest.addDocumentTypes(deedUid, documentsToAdd); + + deedHasDocumentTypes = await prisma.deedHasDocumentTypes.findMany({ where: { deed_uuid: deedUid } }); + expect(deedHasDocumentTypes.length).toEqual(2); + }); +}); +describe("test removeDocumentTypes function", () => { + it("should remove document types from a deed type", async () => { + const deedUid = (await prisma.deeds.findFirstOrThrow({ where: { deed_type_uuid: deedType1.uuid } })).uuid; + const documentsToRemove = [documentType1.uuid]; + await DeedServiceTest.removeDocumentTypes(deedUid, documentsToRemove); + + const deedWithDocumentTypeRelations = await prisma.deeds.findFirstOrThrow({ + where: { + uuid: deedUid, + }, + include: { + deed_has_document_types: true, + }, + }); + expect(deedWithDocumentTypeRelations.deed_has_document_types.length).toEqual(1); + expect(deedWithDocumentTypeRelations.deed_has_document_types[0]?.document_type_uuid).toEqual(documentType2.uuid); + }); + it("should not remove document types from a deed type is they were not linked", async () => { + let deedWithOneDocumentType = await prisma.deeds.findFirstOrThrow({ + where: { deed_type_uuid: deedType1.uuid }, + include: { + deed_has_document_types: true, + }, + }); + expect(deedWithOneDocumentType.deed_has_document_types.length).toEqual(1); + + const documentsToRemove = [documentType1.uuid]; + + async function removeDocumentTypeNotLinkedToDeedType() { + await DeedServiceTest.removeDocumentTypes(deedWithOneDocumentType.uuid, documentsToRemove); + } + await expect(removeDocumentTypeNotLinkedToDeedType).rejects.toThrow(); + }); +}); +describe("test removeDocumentType function", () => { + it("should remove only one document type from a deed type", async () => { + let deedWithOneDocumentType = await prisma.deeds.findFirstOrThrow({ + where: { deed_type_uuid: deedType1.uuid }, + include: { + deed_has_document_types: true, + }, + }); + expect(deedWithOneDocumentType.deed_has_document_types.length).toEqual(1); + + const documentToRemove = documentType2.uuid; + await DeedServiceTest.removeDocumentType(deedWithOneDocumentType.uuid, documentToRemove); + + deedWithOneDocumentType = await prisma.deeds.findFirstOrThrow({ + where: { + uuid: deedWithOneDocumentType.uuid, + }, + include: { + deed_has_document_types: true, + }, + }); + expect(deedWithOneDocumentType.deed_has_document_types.length).toEqual(0); + }); +}); +describe("test addDocumentType function", () => { + it("should add only one document type to a deed type", async () => { + const deedUid = (await prisma.deeds.findFirstOrThrow({ where: { deed_type_uuid: deedType1.uuid } })).uuid; + const documentToAdd = documentType1.uuid; + await DeedServiceTest.addDocumentType(deedUid, documentToAdd); + + const deed = await prisma.deeds.findFirstOrThrow({ + where: { + uuid: deedUid, + }, + include: { + deed_has_document_types: true, + }, + }); + expect(deed.deed_has_document_types.length).toEqual(1); + expect(deed.deed_has_document_types[0]?.document_type_uuid).toEqual(documentType1.uuid); + }); +}); + +describe("test get function", () => { + it("should return an array of Deeds", async () => { + const deeds = await DeedServiceTest.get({}); + + // verify result typing + expect(deeds).toBeInstanceOf(Array); + expect(deeds.length).toEqual(2); + + // verify result content + expect(deeds[0]?.deed_type_uuid).toEqual(deedType1.uuid); + expect(deeds[1]?.deed_type_uuid).toEqual(deedType1.uuid); + }); +}); diff --git a/src/test/services/super-admin/DeedTypesService.test.ts b/src/test/services/super-admin/DeedTypesService.test.ts new file mode 100644 index 00000000..54d30f2f --- /dev/null +++ b/src/test/services/super-admin/DeedTypesService.test.ts @@ -0,0 +1,406 @@ +import "module-alias/register"; +import "reflect-metadata"; +import { DeedType } from "le-coffre-resources/dist/SuperAdmin"; +import DeedTypeService from "@Services/super-admin/DeedTypesService/DeedTypesService"; +import { PrismaClient, Offices, DocumentTypes } from "prisma/prisma-client"; +import { deedType, deedType_, documentType, documentType_, office, office_ } from "./MockedData"; +import DeedTypesRepository from "@Repositories/DeedTypesRepository"; +import Container from "typedi"; +import DeedTypeHasDocumentTypesRepository from "@Repositories/DeedTypesHasDocumentTypesRepository"; + +const prisma = new PrismaClient(); + +const DeedTypeServiceTest = new DeedTypeService(Container.get(DeedTypesRepository), Container.get(DeedTypeHasDocumentTypesRepository)); + +let office1: Offices; +let office2: Offices; + +let documentType1: DocumentTypes; +let documentType2: DocumentTypes; + +beforeAll(async () => { + office1 = await prisma.offices.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, + }, + }, + }, + }); + + office2 = await prisma.offices.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, + }, + }, + }, + }); + + documentType1 = await prisma.documentTypes.create({ + data: { + name: documentType.name, + public_description: documentType.public_description, + private_description: documentType.private_description, + archived_at: null, + office_uuid: office1.uuid, + }, + }); + + documentType2 = await prisma.documentTypes.create({ + data: { + name: documentType_.name, + public_description: documentType_.public_description, + private_description: documentType_.private_description, + archived_at: null, + office_uuid: office1.uuid, + }, + }); +}); + +afterAll(async () => { + const deleteDeedTypes = prisma.deedTypes.deleteMany(); + const deleteOffices = prisma.offices.deleteMany(); + await prisma.$transaction([deleteDeedTypes, deleteOffices]); + await prisma.$disconnect(); +}); + +describe("test create function", () => { + it("should not create a new deed type if office is unknown", async () => { + // try to create a new deed type with unknown office + async function createDeedTypeWithUnknownOffice() { + await DeedTypeServiceTest.create(deedType); + } + await expect(createDeedTypeWithUnknownOffice).rejects.toThrow(); + }); + + it("should create a new deed type", async () => { + let deedTypeWithOfficeUid: DeedType = JSON.parse(JSON.stringify(deedType)); + deedTypeWithOfficeUid.office.uid = office1.uuid; + const deedTypeCreated = await DeedTypeServiceTest.create(deedTypeWithOfficeUid); + + expect(deedTypeCreated.name).toEqual(deedType.name); + expect(deedTypeCreated.description).toEqual(deedType.description); + expect(deedTypeCreated.archived_at).toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office1.uuid); + }); + + it("should not create a new deed type with a name already used for a given office", async () => { + let deedTypeWithSameNameAndOffice: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeWithSameNameAndOffice.office.uid = office1.uuid; + deedTypeWithSameNameAndOffice.name = deedType.name; + + async function createDeedTypeWithSameNameAndOffice() { + await DeedTypeServiceTest.create(deedTypeWithSameNameAndOffice); + } + await expect(createDeedTypeWithSameNameAndOffice).rejects.toThrow(); + }); + + it("should create the same deed type for a different office", async () => { + let deedTypeDuplicatedForNewOffice: DeedType = JSON.parse(JSON.stringify(deedType)); + deedTypeDuplicatedForNewOffice.office.uid = office2.uuid; + + const deedTypeCreated = await DeedTypeServiceTest.create(deedTypeDuplicatedForNewOffice); + + expect(deedTypeCreated.name).toEqual(deedType.name); + expect(deedTypeCreated.description).toEqual(deedType.description); + expect(deedTypeCreated.archived_at).toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office2.uuid); + }); + + it("should create the a new deed type version with a different name for a given office", async () => { + let deedTypeWithSameDescription: DeedType = JSON.parse(JSON.stringify(deedType)); + deedTypeWithSameDescription.office.uid = office1.uuid; + deedTypeWithSameDescription.name = deedType_.name; + + const deedTypeCreated = await DeedTypeServiceTest.create(deedTypeWithSameDescription); + + expect(deedTypeCreated.name).toEqual(deedType_.name); + expect(deedTypeCreated.description).toEqual(deedType.description); + expect(deedTypeCreated.archived_at).toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office1.uuid); + }); +}); + +describe("test update function", () => { + it("should update a deed type data", async () => { + const deedTypeCreated = await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType_.name, office_uuid: office1.uuid } }); + + expect(deedTypeCreated.name).toEqual(deedType_.name); + expect(deedTypeCreated.description).toEqual(deedType.description); + expect(deedTypeCreated.archived_at).toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office1.uuid); + + let deedTypeWithNewDescription: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeWithNewDescription.office.uid = office1.uuid; + + // update the last deed type created with his the right description + const deedTypeUpdated = await DeedTypeServiceTest.update(deedTypeCreated.uuid, deedTypeWithNewDescription); + + expect(deedTypeUpdated.name).toEqual(deedType_.name); + expect(deedTypeUpdated.description).toEqual(deedType_.description); + expect(deedTypeUpdated.archived_at).toBeNull(); + expect(deedTypeUpdated.office_uuid).toEqual(office1.uuid); + }); + + it("should not update a deed type name with an already used name for given office", async () => { + const deedTypeUid = (await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType_.name, office_uuid: office1.uuid } })).uuid; + let deedTypeWithSameNameAndOffice: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeWithSameNameAndOffice.office.uid = office1.uuid; + deedTypeWithSameNameAndOffice.name = deedType.name; + + // update the last deed type created with his the right description + async function updateDocumentTypeWithSameName() { + await DeedTypeServiceTest.update(deedTypeUid, deedTypeWithSameNameAndOffice); + } + await expect(updateDocumentTypeWithSameName).rejects.toThrow(); + }); + + it("should not update a deed type office membership if the office already have this document type", async () => { + const deedTypeUid = (await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType_.name, office_uuid: office1.uuid } })).uuid; + let deedTypeWithSameNameAndOffice: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeWithSameNameAndOffice.office.uid = office1.uuid; + deedTypeWithSameNameAndOffice.name = deedType.name; + + // try to duplicate deed type in a given office + async function updateDocumentTypeWithduplicatedName() { + await DeedTypeServiceTest.update(deedTypeUid, deedTypeWithSameNameAndOffice); + } + await expect(updateDocumentTypeWithduplicatedName).rejects.toThrow(); + }); + + it("should update a deed type office membership", async () => { + const deedTypeCreated = await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType_.name, office_uuid: office1.uuid } }); + + expect(deedTypeCreated.name).toEqual(deedType_.name); + expect(deedTypeCreated.description).toEqual(deedType_.description); + expect(deedTypeCreated.archived_at).toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office1.uuid); + + let deedTypeTransferedToNewOffice: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeTransferedToNewOffice.office.uid = office2.uuid; + + // update the last deed type updated with a new office membership + const deedTypeUpdated = await DeedTypeServiceTest.update(deedTypeCreated.uuid, deedTypeTransferedToNewOffice); + + expect(deedTypeUpdated.name).toEqual(deedType_.name); + expect(deedTypeUpdated.description).toEqual(deedType_.description); + expect(deedTypeUpdated.archived_at).toBeNull(); + expect(deedTypeUpdated.office_uuid).toEqual(office2.uuid); + }); + + it("should archivate a deed type", async () => { + const deedTypeCreated = await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType_.name, office_uuid: office2.uuid } }); + + expect(deedTypeCreated.name).toEqual(deedType_.name); + expect(deedTypeCreated.description).toEqual(deedType_.description); + expect(deedTypeCreated.archived_at).toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office2.uuid); + + let deedTypeArchivated: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeArchivated.office.uid = office2.uuid; + const currentDate = new Date(Date.now()); + deedTypeArchivated.archived_at = currentDate; + + // archivate a deed type by giving a non null date for archivated_at attribute + const deedTypeUpdated = await DeedTypeServiceTest.update(deedTypeCreated.uuid, deedTypeArchivated); + + expect(deedTypeUpdated.name).toEqual(deedType_.name); + expect(deedTypeUpdated.description).toEqual(deedType_.description); + expect(deedTypeUpdated.archived_at).toEqual(currentDate); + expect(deedTypeUpdated.office_uuid).toEqual(office2.uuid); + }); + + it("should unarchivate a deed type", async () => { + const deedTypeCreated = await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType_.name, office_uuid: office2.uuid } }); + + expect(deedTypeCreated.name).toEqual(deedType_.name); + expect(deedTypeCreated.description).toEqual(deedType_.description); + expect(deedTypeCreated.archived_at).not.toBeNull(); + expect(deedTypeCreated.office_uuid).toEqual(office2.uuid); + + let deedTypeUnarchivated: DeedType = JSON.parse(JSON.stringify(deedType_)); + deedTypeUnarchivated.office.uid = office2.uuid; + + // unarchivate a deed type by giving a null date for archivated_at attribute + const deedTypeUpdated = await DeedTypeServiceTest.update(deedTypeCreated.uuid, deedTypeUnarchivated); + + expect(deedTypeUpdated.name).toEqual(deedType_.name); + expect(deedTypeUpdated.description).toEqual(deedType_.description); + expect(deedTypeUpdated.archived_at).toBeNull(); + expect(deedTypeUpdated.office_uuid).toEqual(office2.uuid); + }); +}); + +describe("test addDocumentTypes function", () => { + it("should add document types to a deed type", async () => { + const deedTypeUid = (await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType.name, office_uuid: office1.uuid } })).uuid; + const documentsToAdd = [documentType1.uuid, documentType2.uuid]; + await DeedTypeServiceTest.addDocumentTypes(deedTypeUid, documentsToAdd); + + const deedTypes = await prisma.deedTypes.findFirstOrThrow({ + where: { + uuid: deedTypeUid, + }, + include: { + deed_type_has_document_types: true, + }, + }); + expect(deedTypes.deed_type_has_document_types.length).toEqual(2); + }); + + it("should not add document types to a deed type that already has those document types ", async () => { + const deedTypeUid = (await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType.name, office_uuid: office1.uuid } })).uuid; + let deedTypeHasDocumentTypes = await prisma.deedTypeHasDocumentTypes.findMany({ where: { deed_type_uuid: deedTypeUid } }); + expect(deedTypeHasDocumentTypes.length).toEqual(2); + + const documentsToAdd = [documentType1.uuid, documentType2.uuid]; + //we expect deedTypeHasDocumentTypes service to skip duplicates without throwing error + await DeedTypeServiceTest.addDocumentTypes(deedTypeUid, documentsToAdd); + + deedTypeHasDocumentTypes = await prisma.deedTypeHasDocumentTypes.findMany({ where: { deed_type_uuid: deedTypeUid } }); + expect(deedTypeHasDocumentTypes.length).toEqual(2); + }); +}); +describe("test removeDocumentTypes function", () => { + it("should remove document types from a deed type", async () => { + const deedTypeUid = (await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType.name, office_uuid: office1.uuid } })).uuid; + const documentsToRemove = [documentType1.uuid]; + await DeedTypeServiceTest.removeDocumentTypes(deedTypeUid, documentsToRemove); + + const deedTypeWithDocumentTypeRelations = await prisma.deedTypes.findFirstOrThrow({ + where: { + uuid: deedTypeUid, + }, + include: { + deed_type_has_document_types: true, + }, + }); + expect(deedTypeWithDocumentTypeRelations.deed_type_has_document_types.length).toEqual(1); + expect(deedTypeWithDocumentTypeRelations.deed_type_has_document_types[0]?.document_type_uuid).toEqual(documentType2.uuid); + }); + it("should not remove document types from a deed type is they were not linked", async () => { + let deedTypeWithOneDocumentType = await prisma.deedTypes.findFirstOrThrow({ + where: { name: deedType.name, office_uuid: office1.uuid }, + include: { + deed_type_has_document_types: true, + }, + }); + expect(deedTypeWithOneDocumentType.deed_type_has_document_types.length).toEqual(1); + + const documentsToRemove = [documentType1.uuid]; + + // try to duplicate deed type in a given office + async function removeDocumentTypeNotLinkedToDeedType() { + await DeedTypeServiceTest.removeDocumentTypes(deedTypeWithOneDocumentType.uuid, documentsToRemove); + } + await expect(removeDocumentTypeNotLinkedToDeedType).rejects.toThrow(); + }); +}); +describe("test removeDocumentType function", () => { + it("should remove only one document type from a deed type", async () => { + let deedTypeWithOneDocumentType = await prisma.deedTypes.findFirstOrThrow({ + where: { name: deedType.name, office_uuid: office1.uuid }, + include: { + deed_type_has_document_types: true, + }, + }); + expect(deedTypeWithOneDocumentType.deed_type_has_document_types.length).toEqual(1); + + const documentToRemove = documentType2.uuid; + await DeedTypeServiceTest.removeDocumentType(deedTypeWithOneDocumentType.uuid, documentToRemove); + + deedTypeWithOneDocumentType = await prisma.deedTypes.findFirstOrThrow({ + where: { + uuid: deedTypeWithOneDocumentType.uuid, + }, + include: { + deed_type_has_document_types: true, + }, + }); + expect(deedTypeWithOneDocumentType.deed_type_has_document_types.length).toEqual(0); + }); +}); +describe("test addDocumentType function", () => { + it("should add only one document type to a deed type", async () => { + const deedTypeUid = (await prisma.deedTypes.findFirstOrThrow({ where: { name: deedType.name, office_uuid: office1.uuid } })).uuid; + const documentToAdd = documentType1.uuid; + await DeedTypeServiceTest.addDocumentType(deedTypeUid, documentToAdd); + + const deedTypes = await prisma.deedTypes.findFirstOrThrow({ + where: { + uuid: deedTypeUid, + }, + include: { + deed_type_has_document_types: true, + }, + }); + expect(deedTypes.deed_type_has_document_types.length).toEqual(1); + expect(deedTypes.deed_type_has_document_types[0]?.document_type_uuid).toEqual(documentType1.uuid); + }); +}); + +describe("test get function", () => { + it("should return an array of DeedTypes", async () => { + const deedTypes = await DeedTypeServiceTest.get({ orderBy: [{ name: "asc" }, { created_at: "asc" }] }); + + // verify result typing + expect(deedTypes).toBeInstanceOf(Array); + expect(deedTypes.length).toEqual(3); + + // verify result content + expect(deedTypes[0]?.name).toEqual(deedType_.name); + expect(deedTypes[0]?.description).toEqual(deedType_.description); + expect(deedTypes[0]?.archived_at).toBeNull(); + expect(deedTypes[0]?.office_uuid).toEqual(office2.uuid); + + expect(deedTypes[1]?.name).toEqual(deedType.name); + expect(deedTypes[1]?.description).toEqual(deedType.description); + expect(deedTypes[1]?.archived_at).toBeNull(); + expect(deedTypes[1]?.office_uuid).toEqual(office1.uuid); + + expect(deedTypes[2]?.name).toEqual(deedType.name); + expect(deedTypes[2]?.description).toEqual(deedType.description); + expect(deedTypes[2]?.archived_at).toBeNull(); + expect(deedTypes[2]?.office_uuid).toEqual(office2.uuid); + }); + + it("should return an array of DeedTypes per offices", async () => { + const deedTypesForFirstOffice = await DeedTypeServiceTest.get({ where: { office: office1 }, orderBy: { name: "asc" } }); + + expect(deedTypesForFirstOffice.length).toEqual(1); + + // verify result content + expect(deedTypesForFirstOffice[0]?.name).toEqual(deedType.name); + expect(deedTypesForFirstOffice[0]?.description).toEqual(deedType.description); + expect(deedTypesForFirstOffice[0]?.archived_at).toBeNull(); + expect(deedTypesForFirstOffice[0]?.office_uuid).toEqual(office1.uuid); + + const deedTypesForSecondOffice = await DeedTypeServiceTest.get({ where: { office: office2 }, orderBy: { name: "asc" } }); + + expect(deedTypesForSecondOffice.length).toEqual(2); + + // verify result content + expect(deedTypesForSecondOffice[0]?.name).toEqual(deedType_.name); + expect(deedTypesForSecondOffice[0]?.description).toEqual(deedType_.description); + expect(deedTypesForSecondOffice[0]?.archived_at).toBeNull(); + expect(deedTypesForSecondOffice[0]?.office_uuid).toEqual(office2.uuid); + + expect(deedTypesForSecondOffice[1]?.name).toEqual(deedType.name); + expect(deedTypesForSecondOffice[1]?.description).toEqual(deedType.description); + expect(deedTypesForSecondOffice[1]?.archived_at).toBeNull(); + expect(deedTypesForSecondOffice[1]?.office_uuid).toEqual(office2.uuid); + }); +}); diff --git a/src/test/services/super-admin/DocumentTypesService.test.ts b/src/test/services/super-admin/DocumentTypesService.test.ts new file mode 100644 index 00000000..51460c70 --- /dev/null +++ b/src/test/services/super-admin/DocumentTypesService.test.ts @@ -0,0 +1,299 @@ +import "module-alias/register"; +import "reflect-metadata"; +import { DocumentType } from "le-coffre-resources/dist/SuperAdmin"; +import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService"; +import { PrismaClient, Offices } from "prisma/prisma-client"; +import { documentType, documentType_, office, office_ } from "./MockedData"; +import DocumentTypesRepository from "@Repositories/DocumentTypesRepository"; +import Container from "typedi"; + +const prisma = new PrismaClient(); + +const DocumentTypesServiceTest = new DocumentTypesService(Container.get(DocumentTypesRepository)); + +let office1: Offices; +let office2: Offices; + +beforeAll(async () => { + office1 = await prisma.offices.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, + }, + }, + }, + }); + + office2 = await prisma.offices.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, + }, + }, + }, + }); +}); + +afterAll(async () => { + const deleteDocumentTypes = prisma.documentTypes.deleteMany(); + const deleteOffices = prisma.offices.deleteMany(); + await prisma.$transaction([deleteDocumentTypes, deleteOffices]); + await prisma.$disconnect(); +}); + +describe("test create function", () => { + it("should not create a new document type if office is unknown", async () => { + // try to create a new document type with unknown office + async function createDocumentTypeWithUnknownOffice() { + await DocumentTypesServiceTest.create(documentType); + } + await expect(createDocumentTypeWithUnknownOffice).rejects.toThrow(); + }); + + it("should create a new document type", async () => { + let documentTypeWithOfficeUid: DocumentType = JSON.parse(JSON.stringify(documentType)); + documentTypeWithOfficeUid.office.uid = office1.uuid; + const documentTypeCreated = await DocumentTypesServiceTest.create(documentTypeWithOfficeUid); + + expect(documentTypeCreated.name).toEqual(documentType.name); + expect(documentTypeCreated.public_description).toEqual(documentType.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType.private_description); + expect(documentTypeCreated.archived_at).toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office1.uuid); + }); + + it("should not create a new document type with a name already used for a given office", async () => { + let documentTypeWithSameNameAndOffice: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeWithSameNameAndOffice.office.uid = office1.uuid; + documentTypeWithSameNameAndOffice.name = documentType.name; + + async function createDocumentTypeWithSameNameAndOffice() { + await DocumentTypesServiceTest.create(documentTypeWithSameNameAndOffice); + } + await expect(createDocumentTypeWithSameNameAndOffice).rejects.toThrow(); + }); + + it("should create the same document type for a different office", async () => { + let documentTypeDuplicatedForNewOffice: DocumentType = JSON.parse(JSON.stringify(documentType)); + documentTypeDuplicatedForNewOffice.office.uid = office2.uuid; + + const documentTypeCreated = await DocumentTypesServiceTest.create(documentTypeDuplicatedForNewOffice); + + expect(documentTypeCreated.name).toEqual(documentType.name); + expect(documentTypeCreated.public_description).toEqual(documentType.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType.private_description); + expect(documentTypeCreated.archived_at).toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office2.uuid); + }); + + it("should create a new document type version with a different name for a given office", async () => { + let documentTypeWithSameDescription: DocumentType = JSON.parse(JSON.stringify(documentType)); + documentTypeWithSameDescription.office.uid = office1.uuid; + documentTypeWithSameDescription.name = documentType_.name; + + const documentTypeCreated = await DocumentTypesServiceTest.create(documentTypeWithSameDescription); + + expect(documentTypeCreated.name).toEqual(documentType_.name); + expect(documentTypeCreated.public_description).toEqual(documentType.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType.private_description); + expect(documentTypeCreated.archived_at).toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office1.uuid); + }); +}); + +describe("test update function", () => { + it("should update a document type", async () => { + const documentTypeCreated = await prisma.documentTypes.findFirstOrThrow({ + where: { name: documentType_.name, office_uuid: office1.uuid }, + }); + expect(documentTypeCreated.name).toEqual(documentType_.name); + expect(documentTypeCreated.public_description).toEqual(documentType.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType.private_description); + expect(documentTypeCreated.archived_at).toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office1.uuid); + + let documentTypeWithNewDescription: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeWithNewDescription.office.uid = office1.uuid; + + // update the last document type created with his the right descriptions + const documentTypeUpdated = await DocumentTypesServiceTest.update(documentTypeCreated.uuid, documentTypeWithNewDescription); + expect(documentTypeUpdated.name).toEqual(documentType_.name); + expect(documentTypeUpdated.public_description).toEqual(documentType_.public_description); + expect(documentTypeUpdated.private_description).toEqual(documentType_.private_description); + expect(documentTypeUpdated.archived_at).toBeNull(); + expect(documentTypeUpdated.office_uuid).toEqual(office1.uuid); + }); + + it("should not update a document type name with an already used name for given office", async () => { + const documentTypeUid = ( + await prisma.documentTypes.findFirstOrThrow({ where: { name: documentType_.name, office_uuid: office1.uuid } }) + ).uuid; + let documentTypeWithSameNameAndOffice: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeWithSameNameAndOffice.office.uid = office1.uuid; + documentTypeWithSameNameAndOffice.name = documentType.name; + + // update the last document type created with his the right description + async function updateDocumentTypeWithSameName() { + await DocumentTypesServiceTest.update(documentTypeUid, documentTypeWithSameNameAndOffice); + } + await expect(updateDocumentTypeWithSameName).rejects.toThrow(); + }); + + it("should not update a document type office membership if the office already has this document type", async () => { + const documentTypeUid = ( + await prisma.documentTypes.findFirstOrThrow({ where: { name: documentType_.name, office_uuid: office1.uuid } }) + ).uuid; + let documentTypeWithSameNameAndOffice: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeWithSameNameAndOffice.office.uid = office1.uuid; + documentTypeWithSameNameAndOffice.name = documentType.name; + + // try to duplicate document type in a given office + async function updateDocumentTypeWithduplicatedName() { + await DocumentTypesServiceTest.update(documentTypeUid, documentTypeWithSameNameAndOffice); + } + await expect(updateDocumentTypeWithduplicatedName).rejects.toThrow(); + }); + + it("should update a document type office membership", async () => { + const documentTypeCreated = await prisma.documentTypes.findFirstOrThrow({ + where: { name: documentType_.name, office_uuid: office1.uuid }, + }); + + expect(documentTypeCreated.name).toEqual(documentType_.name); + expect(documentTypeCreated.public_description).toEqual(documentType_.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType_.private_description); + expect(documentTypeCreated.archived_at).toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office1.uuid); + + let documentTypeTransferedToNewOffice: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeTransferedToNewOffice.office.uid = office2.uuid; + + // update the last document type updated with a new office membership + const documentTypeUpdated = await DocumentTypesServiceTest.update(documentTypeCreated.uuid, documentTypeTransferedToNewOffice); + + expect(documentTypeUpdated.name).toEqual(documentType_.name); + expect(documentTypeUpdated.public_description).toEqual(documentType_.public_description); + expect(documentTypeUpdated.private_description).toEqual(documentType_.private_description); + expect(documentTypeUpdated.archived_at).toBeNull(); + expect(documentTypeUpdated.office_uuid).toEqual(office2.uuid); + }); + + it("should archivate a document type", async () => { + const documentTypeCreated = await prisma.documentTypes.findFirstOrThrow({ + where: { name: documentType_.name, office_uuid: office2.uuid }, + }); + + expect(documentTypeCreated.name).toEqual(documentType_.name); + expect(documentTypeCreated.public_description).toEqual(documentType_.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType_.private_description); + expect(documentTypeCreated.archived_at).toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office2.uuid); + + let documentTypeArchivated: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeArchivated.office.uid = office2.uuid; + const currentDate = new Date(Date.now()); + documentTypeArchivated.archived_at = currentDate; + // archivate a document type by giving a non null date for archivated_at attribute + const documentTypeUpdated = await DocumentTypesServiceTest.update(documentTypeCreated.uuid, documentTypeArchivated); + expect(documentTypeUpdated.name).toEqual(documentType_.name); + expect(documentTypeUpdated.public_description).toEqual(documentType_.public_description); + expect(documentTypeUpdated.private_description).toEqual(documentType_.private_description); + expect(documentTypeUpdated.archived_at).toEqual(currentDate); + expect(documentTypeUpdated.office_uuid).toEqual(office2.uuid); + }); + + it("should unarchivate a document type", async () => { + const documentTypeCreated = await prisma.documentTypes.findFirstOrThrow({ + where: { name: documentType_.name, office_uuid: office2.uuid }, + }); + + expect(documentTypeCreated.name).toEqual(documentType_.name); + expect(documentTypeCreated.public_description).toEqual(documentType_.public_description); + expect(documentTypeCreated.private_description).toEqual(documentType_.private_description); + expect(documentTypeCreated.archived_at).not.toBeNull(); + expect(documentTypeCreated.office_uuid).toEqual(office2.uuid); + + let documentTypeUnarchivated: DocumentType = JSON.parse(JSON.stringify(documentType_)); + documentTypeUnarchivated.office.uid = office2.uuid; + + // unarchivate a document type by giving a null date for archivated_at attribute + const documentTypeUpdated = await DocumentTypesServiceTest.update(documentTypeCreated.uuid, documentTypeUnarchivated); + + expect(documentTypeUpdated.name).toEqual(documentType_.name); + expect(documentTypeUpdated.public_description).toEqual(documentType_.public_description); + expect(documentTypeUpdated.private_description).toEqual(documentType_.private_description); + expect(documentTypeUpdated.archived_at).toBeNull(); + expect(documentTypeUpdated.office_uuid).toEqual(office2.uuid); + }); +}); + +describe("test get function", () => { + it("should return an array of DocumentTypes", async () => { + const documentTypes = await DocumentTypesServiceTest.get({ orderBy: [{ name: "asc" }, { created_at: "asc" }] }); + + // verify result typing + expect(documentTypes).toBeInstanceOf(Array); + expect(documentTypes.length).toEqual(3); + + // verify result content + expect(documentTypes[0]?.name).toEqual(documentType_.name); + expect(documentTypes[0]?.public_description).toEqual(documentType_.public_description); + expect(documentTypes[0]?.private_description).toEqual(documentType_.private_description); + expect(documentTypes[0]?.archived_at).toBeNull(); + expect(documentTypes[0]?.office_uuid).toEqual(office2.uuid); + + expect(documentTypes[1]?.name).toEqual(documentType.name); + expect(documentTypes[1]?.public_description).toEqual(documentType.public_description); + expect(documentTypes[1]?.private_description).toEqual(documentType.private_description); + expect(documentTypes[1]?.archived_at).toBeNull(); + expect(documentTypes[1]?.office_uuid).toEqual(office1.uuid); + + expect(documentTypes[2]?.name).toEqual(documentType.name); + expect(documentTypes[2]?.public_description).toEqual(documentType.public_description); + expect(documentTypes[2]?.private_description).toEqual(documentType.private_description); + expect(documentTypes[2]?.archived_at).toBeNull(); + expect(documentTypes[2]?.office_uuid).toEqual(office2.uuid); + }); + + it("should return an array of DocumentTypes per offices", async () => { + const documentTypesForFirstOffice = await DocumentTypesServiceTest.get({ where: { office: office1 }, orderBy: { name: "asc" } }); + + expect(documentTypesForFirstOffice.length).toEqual(1); + + // verify result content + expect(documentTypesForFirstOffice[0]?.name).toEqual(documentType.name); + expect(documentTypesForFirstOffice[0]?.public_description).toEqual(documentType.public_description); + expect(documentTypesForFirstOffice[0]?.private_description).toEqual(documentType.private_description); + expect(documentTypesForFirstOffice[0]?.archived_at).toBeNull(); + expect(documentTypesForFirstOffice[0]?.office_uuid).toEqual(office1.uuid); + + const documentTypesForSecondOffice = await DocumentTypesServiceTest.get({ where: { office: office2 }, orderBy: { name: "asc" } }); + + expect(documentTypesForSecondOffice.length).toEqual(2); + + // verify result content + expect(documentTypesForSecondOffice[0]?.name).toEqual(documentType_.name); + expect(documentTypesForSecondOffice[0]?.public_description).toEqual(documentType_.public_description); + expect(documentTypesForSecondOffice[0]?.private_description).toEqual(documentType_.private_description); + expect(documentTypesForSecondOffice[0]?.archived_at).toBeNull(); + expect(documentTypesForSecondOffice[0]?.office_uuid).toEqual(office2.uuid); + + expect(documentTypesForSecondOffice[1]?.name).toEqual(documentType.name); + expect(documentTypesForSecondOffice[1]?.public_description).toEqual(documentType.public_description); + expect(documentTypesForSecondOffice[1]?.private_description).toEqual(documentType.private_description); + expect(documentTypesForSecondOffice[1]?.archived_at).toBeNull(); + expect(documentTypesForSecondOffice[1]?.office_uuid).toEqual(office2.uuid); + }); +}); diff --git a/src/test/services/super-admin/MockedData.ts b/src/test/services/super-admin/MockedData.ts new file mode 100644 index 00000000..df44244d --- /dev/null +++ b/src/test/services/super-admin/MockedData.ts @@ -0,0 +1,162 @@ +import { EOfficeStatus } from "le-coffre-resources/dist/Customer/Office"; +import User, { Address, Contact, Office, DeedType, DocumentType, Customer } from "le-coffre-resources/dist/SuperAdmin"; + +export const userAddress: Address = { + uid: "", + address: "1 avenue des champs élysées", + zip_code: 75008, + city: "paris", + created_at: null, + updated_at: null, +}; + +export const userAddress_: Address = { + uid: "", + address: "1 rue Victor Hugo", + zip_code: 75001, + city: "paris", + created_at: null, + updated_at: null, +}; + +export const userContact: Contact = { + uid: "", + first_name: "Philippe", + last_name: "le Bel", + address: userAddress, + email: "philippe.lebel@notaires.fr", + phone_number: "+33101020304", + cell_phone_number: "+33605060708", + civility: "MALE", + created_at: null, + updated_at: null, +}; + +export const userContact_: Contact = { + uid: "", + first_name: "Saint", + last_name: "Louise", + address: userAddress_, + email: "saint.louise@notaires.fr", + phone_number: "+33105060708", + cell_phone_number: "+33601020304", + civility: "FEMALE", + created_at: null, + updated_at: null, +}; + +export const officeAddress: Address = { + uid: "", + address: "1 rue Rivoli", + zip_code: 75001, + city: "paris", + created_at: null, + updated_at: null, +}; + +export const officeAddress_: Address = { + uid: "", + address: "1 rue de la paix", + zip_code: 75008, + city: "paris", + created_at: null, + updated_at: null, +}; + +export const office: Office = { + uid: "", + idNot: "123456789", + name: "first office", + crpcen: "0123456789CRPCEN", + office_status: EOfficeStatus.ACTIVATED, + address: officeAddress, + created_at: null, + updated_at: null, +}; + +export const office_: Office = { + uid: "", + idNot: "789101112", + name: "second office", + crpcen: "987654321CRPCEN", + office_status: EOfficeStatus.DESACTIVATED, + address: officeAddress_, + created_at: null, + updated_at: null, +}; + +export const user: User = { + uid: "", + idNot: "123456_123456789", + contact: userContact, + office_membership: office, + created_at: null, + updated_at: null, +}; + +export const user_: User = { + uid: "", + idNot: "654321_789101112", + contact: userContact_, + office_membership: office_, + created_at: null, + updated_at: null, +}; + +export const deedType: DeedType = { + uid: "", + name: "Wedding", + description: "we assume wedding involve two people", + archived_at: null, + office: office, + created_at: null, + updated_at: null, +}; + +export const deedType_: DeedType = { + uid: "", + name: "Inheritance", + description: "we assume inheritance involve two people", + archived_at: null, + office: office, + created_at: null, + updated_at: null, +}; + +export const documentType: DocumentType = { + uid: "", + name: "Identity card", + public_description: "your ID card delivered by your country of residence", + private_description: "verify if this ID card is legit", + archived_at: null, + office: office, + created_at: null, + updated_at: null, +}; + +export const documentType_: DocumentType = { + uid: "", + name: "Electricity bill", + public_description: "an electricity bill payed within the last 3 months", + private_description: "verify if this electricity company is legit", + archived_at: null, + office: office, + created_at: null, + updated_at: null, +}; + +export const customer: Customer = { + uid: "", + contact: userContact, + status: "PENDING", + created_at: null, + updated_at: null, +}; + +export const customer_: Customer = { + uid: "", + contact: userContact_, + status: "ERRONED", + created_at: null, + updated_at: null, +}; diff --git a/src/test/services/super-admin/UsersService.test.ts b/src/test/services/super-admin/UsersService.test.ts new file mode 100644 index 00000000..f58b4c8c --- /dev/null +++ b/src/test/services/super-admin/UsersService.test.ts @@ -0,0 +1,226 @@ +import "module-alias/register"; +import "reflect-metadata"; +import User from "le-coffre-resources/dist/SuperAdmin"; +import UsersService from "@Services/super-admin/UsersService/UsersService"; +import { processFindManyQuery } from "prisma-query"; +import { PrismaClient } from "@prisma/client"; +import { user, userContact, userContact_, user_ } from "./MockedData"; +import UsersRepository from "@Repositories/UsersRepository"; +import Container from "typedi"; + +const prisma = new PrismaClient(); + +const UsersServiceTest = new UsersService(Container.get(UsersRepository)); + +afterAll(async () => { + /* + * Clean database after all tests execution. + * Due to cascade deletion, if addresses are deleted, all items following tables are dropped: contacts, users, offices + */ + const deleteAddresses = prisma.addresses.deleteMany(); + await prisma.$transaction([deleteAddresses]); + await prisma.$disconnect(); +}); + +describe("test create function", () => { + it("should create a new user", async () => { + const userCreated = await UsersServiceTest.create(user); + + expect(userCreated?.idNot).toEqual(user.idNot); + + // verify if user contact is created in db + const contactCreated = await prisma.contacts.findUnique({ where: { uuid: userCreated.contact_uuid } }); + expect(contactCreated?.first_name).toEqual(user.contact.first_name); + expect(contactCreated?.last_name).toEqual(user.contact.last_name); + expect(contactCreated?.cell_phone_number).toEqual(user.contact.cell_phone_number); + expect(contactCreated?.phone_number).toEqual(user.contact.phone_number); + expect(contactCreated?.civility).toEqual(user.contact.civility); + expect(contactCreated?.email).toEqual(user.contact.email); + + // verify if user address is created in db + const addressForContactCreated = await prisma.addresses.findUnique({ where: { uuid: contactCreated?.address_uuid } }); + expect(addressForContactCreated?.address).toEqual(user.contact.address.address); + expect(addressForContactCreated?.zip_code).toEqual(user.contact.address.zip_code); + expect(addressForContactCreated?.city).toEqual(user.contact.address.city); + + // verify if user office is created in db + const officeCreated = await prisma.offices.findUnique({ where: { uuid: userCreated.office_uuid } }); + expect(officeCreated?.idNot).toEqual(user.office_membership.idNot); + expect(officeCreated?.name).toEqual(user.office_membership.name); + expect(officeCreated?.crpcen).toEqual(user.office_membership.crpcen); + expect(officeCreated?.office_status).toEqual("DESACTIVATED"); + + // verify if user office's address is created in db + const addressForOfficeCreated = await prisma.addresses.findUnique({ where: { uuid: officeCreated?.address_uuid } }); + expect(addressForOfficeCreated?.address).toEqual(user.office_membership.address.address); + expect(addressForOfficeCreated?.zip_code).toEqual(user.office_membership.address.zip_code); + expect(addressForOfficeCreated?.city).toEqual(user.office_membership.address.city); + }); + + it("should not create an user already created", async () => { + // try to create the same user + async function duplicateUser() { + await UsersServiceTest.create(user); + } + await expect(duplicateUser).rejects.toThrow(); + }); + + it("should not create an new user with an email already created", async () => { + let newUser: User = JSON.parse(JSON.stringify(user_)); + newUser.contact.email = userContact.email; + + // try to create a new user with already used email + async function createUserWithDuplicateEmail() { + await UsersServiceTest.create(newUser); + } + await expect(createUserWithDuplicateEmail).rejects.toThrow(); + }); + + it("should not create an user with an phone number already created", async () => { + let newUser: User = JSON.parse(JSON.stringify(user_)); + newUser.contact.cell_phone_number = userContact.cell_phone_number; + + // try to create a new user with already used cellphone number + async function duplicateUser() { + await UsersServiceTest.create(newUser); + } + await expect(duplicateUser).rejects.toThrow(); + }); + + it("should create an new user if unique attributes differ from existing users", async () => { + let newUser: User = JSON.parse(JSON.stringify(user)); + newUser.idNot = user_.idNot; + newUser.contact.email = userContact_.email; + newUser.contact.cell_phone_number = userContact_.cell_phone_number; + + const userCreated = await UsersServiceTest.create(newUser); + + expect(userCreated?.idNot).toEqual(user_.idNot); + + // verify if user_ contact is created in db + const contactCreated = await prisma.contacts.findUnique({ where: { uuid: userCreated.contact_uuid } }); + expect(contactCreated?.first_name).toEqual(user.contact.first_name); + expect(contactCreated?.last_name).toEqual(user.contact.last_name); + expect(contactCreated?.cell_phone_number).toEqual(user_.contact.cell_phone_number); + expect(contactCreated?.phone_number).toEqual(user.contact.phone_number); + expect(contactCreated?.civility).toEqual(user.contact.civility); + expect(contactCreated?.email).toEqual(user_.contact.email); + + // verify if user_ address is created in db + const addressForContactCreated = await prisma.addresses.findUnique({ where: { uuid: contactCreated?.address_uuid } }); + expect(addressForContactCreated?.address).toEqual(user.contact.address.address); + expect(addressForContactCreated?.zip_code).toEqual(user.contact.address.zip_code); + expect(addressForContactCreated?.city).toEqual(user.contact.address.city); + + // verify if user joined the existing office + const officeJoined = await prisma.offices.findUnique({ where: { uuid: userCreated.office_uuid } }); + expect(officeJoined?.idNot).toEqual(user.office_membership.idNot); + expect(officeJoined?.name).toEqual(user.office_membership.name); + expect(officeJoined?.crpcen).toEqual(user.office_membership.crpcen); + expect(officeJoined?.office_status).toEqual("DESACTIVATED"); + }); +}); + +describe("test update function", () => { + it("should update an user's data", async () => { + const userCreated = await prisma.users.findFirstOrThrow({ where: { idNot: user_.idNot } }); + + const officeJoined = await prisma.offices.findUnique({ where: { uuid: userCreated.office_uuid } }); + expect(officeJoined?.idNot).toEqual(user.office_membership.idNot); + expect(officeJoined?.name).toEqual(user.office_membership.name); + expect(officeJoined?.crpcen).toEqual(user.office_membership.crpcen); + expect(officeJoined?.office_status).toEqual("DESACTIVATED"); + + // update the last user created with his own new office and own contact + const updatedUser = await UsersServiceTest.update(userCreated.uuid, user_); + + expect(updatedUser?.idNot).toEqual(user_.idNot); + + // verify if user_ contact is created in db + const existingContact = await prisma.contacts.findUnique({ where: { uuid: updatedUser.contact_uuid } }); + expect(existingContact?.first_name).toEqual(user_.contact.first_name); + expect(existingContact?.last_name).toEqual(user_.contact.last_name); + expect(existingContact?.cell_phone_number).toEqual(user_.contact.cell_phone_number); + expect(existingContact?.phone_number).toEqual(user_.contact.phone_number); + expect(existingContact?.civility).toEqual(user_.contact.civility); + expect(existingContact?.email).toEqual(user_.contact.email); + + // verify if user_ address is created in db + const addressForExistingContact = await prisma.addresses.findUnique({ where: { uuid: existingContact?.address_uuid } }); + expect(addressForExistingContact?.address).toEqual(user_.contact.address.address); + expect(addressForExistingContact?.zip_code).toEqual(user_.contact.address.zip_code); + expect(addressForExistingContact?.city).toEqual(user_.contact.address.city); + + // verify if user_ joined the new office + const officeCreated = await prisma.offices.findUnique({ where: { uuid: updatedUser.office_uuid } }); + expect(officeCreated?.idNot).toEqual(user_.office_membership.idNot); + expect(officeCreated?.name).toEqual(user_.office_membership.name); + expect(officeCreated?.crpcen).toEqual(user_.office_membership.crpcen); + expect(officeCreated?.office_status).toEqual("DESACTIVATED"); + + // verify is user_ office's address is created in db + const addressForOfficeCreated = await prisma.addresses.findUnique({ where: { uuid: officeCreated?.address_uuid } }); + expect(addressForOfficeCreated?.address).toEqual(user_.office_membership.address.address); + expect(addressForOfficeCreated?.zip_code).toEqual(user_.office_membership.address.zip_code); + expect(addressForOfficeCreated?.city).toEqual(user_.office_membership.address.city); + }); + + it("should not update an user with an email already used", async () => { + const userUid = (await prisma.users.findFirstOrThrow({ where: { idNot: user_.idNot } })).uuid; + let updatedUser: User = JSON.parse(JSON.stringify(user_)); + updatedUser.contact.email = userContact.email; + + // try to create a new user with already used email + async function updateUserWithDuplicateEmail() { + await UsersServiceTest.update(userUid, updatedUser); + } + await expect(updateUserWithDuplicateEmail).rejects.toThrow(); + }); + + it("should not update an user with an phone number already used", async () => { + const userUid = (await prisma.users.findFirstOrThrow({ where: { idNot: user_.idNot } })).uuid; + let updatedUser: User = JSON.parse(JSON.stringify(user_)); + updatedUser.contact.cell_phone_number = userContact.cell_phone_number; + + // try to create a new user with already used email + async function updateUserWithDuplicateEmail() { + await UsersServiceTest.update(userUid, updatedUser); + } + await expect(updateUserWithDuplicateEmail).rejects.toThrow(); + }); +}); + +describe("test get function", () => { + it("should return an array of Users", async () => { + const req = processFindManyQuery({}); + const users = await UsersServiceTest.get(req); + + // verify result typing + expect(users).toBeInstanceOf(Array); + expect(users.length).toEqual(2); + + // verify result content + const usersCreated = await prisma.users.findMany(); + expect(users).toContainEqual(usersCreated[0]); + expect(users).toContainEqual(usersCreated[1]); + }); + + it("should return an array of Users per offices", async () => { + const officesCreated = await prisma.offices.findMany(); + const reqForFirstOffice = { where: { office_uuid: officesCreated[0]?.uuid } }; + const usersForFirstOffice = await UsersServiceTest.get(reqForFirstOffice); + + expect(usersForFirstOffice.length).toEqual(1); + + // verify result content + expect(usersForFirstOffice[0]?.idNot).toEqual(user.idNot); + + const reqForSecondOffice = { where: { office_uuid: officesCreated[1]?.uuid } }; + const usersForSecondOffice = await UsersServiceTest.get(reqForSecondOffice); + + expect(usersForSecondOffice.length).toEqual(1); + + // verify result content + expect(usersForSecondOffice[0]?.idNot).toEqual(user_.idNot); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 0d461c21..0a55fb94 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -67,7 +67,10 @@ ], "@ControllerPattern/*": [ "src/common/system/controller-pattern/*" - ] + ], + "@Test/*":[ + "src/test/*" + ], }, // "rootDirs": [], // "typeRoots": [], @@ -91,7 +94,7 @@ "include": [ "**/*.ts", "**/*.tsx", - "src/app/api/UsersController.ts" + "src/app/api/admin/UsersController.ts" ], "exclude": [ "node_modules"