add more input checks and format

This commit is contained in:
OxSaitama 2023-07-04 14:05:25 +02:00
parent 4e632e27ed
commit afec5a5cea
55 changed files with 298 additions and 288 deletions

View File

@ -24,13 +24,13 @@ export default class UserController extends ApiController {
try { try {
const code = req.params["code"]; const code = req.params["code"];
if (!code) throw new Error("code is required"); if (!code) throw new Error("code is required");
const token = await fetch('https://qual-connexion.idnot.fr/IdPOAuth2/token/idnot_idp_v1', {method: 'POST'}); const token = await fetch("https://qual-connexion.idnot.fr/IdPOAuth2/token/idnot_idp_v1", { method: "POST" });
console.log(token); console.log(token);
//const user = await this.authService.getUserFromIdNotTokens(code!); //const user = await this.authService.getUserFromIdNotTokens(code!);
//success //success
this.httpSuccess(response); this.httpSuccess(response);
} catch (error) { } catch (error) {
console.log(error) console.log(error);
this.httpInternalError(response); this.httpInternalError(response);
return; return;
} }
@ -49,7 +49,6 @@ export default class UserController extends ApiController {
//success //success
this.httpSuccess(response, { accessToken, refreshToken }); this.httpSuccess(response, { accessToken, refreshToken });
} catch (error) { } catch (error) {
console.log(error);
this.httpInternalError(response); this.httpInternalError(response);
return; return;
} }

View File

@ -92,7 +92,7 @@ export default class DocumentTypesController extends ApiController {
const documentTypeEntity = DocumentType.hydrate<DocumentType>(req.body); const documentTypeEntity = DocumentType.hydrate<DocumentType>(req.body);
//validate user //validate user
await validateOrReject(documentTypeEntity, { groups: ["update"] }); await validateOrReject(documentTypeEntity, { groups: ["updateDocumentType"] });
//call service to get prisma entity //call service to get prisma entity
const documentTypeEntityUpdated = await this.documentTypesService.update(uid, documentTypeEntity); const documentTypeEntityUpdated = await this.documentTypesService.update(uid, documentTypeEntity);

View File

@ -9,7 +9,7 @@ import { validateOrReject } from "class-validator";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService"; import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
import authHandler from "@App/middlewares/AuthHandler"; import authHandler from "@App/middlewares/AuthHandler";
import ruleHandler from "@App/middlewares/RulesHandler"; import ruleHandler from "@App/middlewares/RulesHandler";
import fileHandler from "@App/middlewares/FileHandler"; import fileHandler from "@App/middlewares/OfficeMembershipHandlers/FileHandler";
@Controller() @Controller()
@Service() @Service()
@ -93,13 +93,8 @@ export default class FilesController extends ApiController {
const document = await this.documentService.getByUid(fileEntity.document!.uid!); const document = await this.documentService.getByUid(fileEntity.document!.uid!);
if(!document){ document!.document_status = "DEPOSITED";
this.httpNotFoundRequest(response, "document not found"); await this.documentService.update(document!.uid!, document!);
return;
}
document.document_status = "DEPOSITED";
await this.documentService.update(document.uid!, document);
//Hydrate ressource with prisma entity //Hydrate ressource with prisma entity
const fileEntityHydrated = File.hydrate<File>(fileEntityCreated, { const fileEntityHydrated = File.hydrate<File>(fileEntityCreated, {

View File

@ -14,7 +14,6 @@ import FilesController from "./api/super-admin/FilesController";
import RulesController from "./api/super-admin/RulesController"; import RulesController from "./api/super-admin/RulesController";
import RolesController from "./api/super-admin/RolesController"; import RolesController from "./api/super-admin/RolesController";
/** /**
* @description This allow to declare all controllers used in the application * @description This allow to declare all controllers used in the application
*/ */

View File

@ -4,11 +4,11 @@ import { NextFunction, Request, Response } from "express";
import Container from "typedi"; import Container from "typedi";
export default function authHandler(req: Request, response: Response, next: NextFunction) { export default function authHandler(req: Request, response: Response, next: NextFunction) {
const authHeader = req.headers['authorization']; const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(' ')[1]; const token = authHeader && authHeader.split(" ")[1];
if (!token) { if (!token) {
response.sendStatus(HttpCodes.UNAUTHORIZED) response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
@ -18,8 +18,7 @@ export default function authHandler(req: Request, response: Response, next: Next
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
req.body.user = userPayload req.body.user = userPayload;
next(); next();
}); });
} }

View File

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

View File

@ -10,8 +10,9 @@ export default async function deedHandler(req: Request, response: Response, next
const uid = req.path && req.path.split("/")[5]; const uid = req.path && req.path.split("/")[5];
const documentTypes: DocumentType[] = req.body.document_types; const documentTypes: DocumentType[] = req.body.document_types;
if (uid) {
const deedService = Container.get(DeedsService); const deedService = Container.get(DeedsService);
const deed = await deedService.getOneByUidWithOffice(uid!); const deed = await deedService.getOneByUidWithOffice(uid);
if (!deed) { if (!deed) {
response.sendStatus(HttpCodes.NOT_FOUND); response.sendStatus(HttpCodes.NOT_FOUND);
@ -22,6 +23,7 @@ export default async function deedHandler(req: Request, response: Response, next
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
}
if (documentTypes) { if (documentTypes) {
const documentTypeService = Container.get(DocumentTypesService); const documentTypeService = Container.get(DocumentTypesService);

View File

@ -5,6 +5,7 @@ import Container from "typedi";
import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin"; import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService"; import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService"; import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService";
import OfficeFoldersService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService";
export default async function documentHandler(req: Request, response: Response, next: NextFunction) { export default async function documentHandler(req: Request, response: Response, next: NextFunction) {
const officeId = req.body.user.office_Id; const officeId = req.body.user.office_Id;
@ -12,10 +13,18 @@ export default async function documentHandler(req: Request, response: Response,
const documentType: DocumentType = req.body.document_type; const documentType: DocumentType = req.body.document_type;
const folder: OfficeFolder = req.body.folder; const folder: OfficeFolder = req.body.folder;
if (folder && folder.office?.uid != officeId) { if (folder) {
const officeFolderService = Container.get(OfficeFoldersService);
const officeFolderWithOffice = await officeFolderService.getByUidWithOffice(folder.uid!);
if (!officeFolderWithOffice) {
response.sendStatus(HttpCodes.NOT_FOUND);
return;
}
if (officeFolderWithOffice.office?.uid != officeId) {
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
}
if (documentType) { if (documentType) {
const documentTypeService = Container.get(DocumentTypesService); const documentTypeService = Container.get(DocumentTypesService);

View File

@ -1,18 +1,26 @@
import HttpCodes from "@Common/system/controller-pattern/HttpCodes"; import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
import Container from "typedi"; import Container from "typedi";
import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin";
import FilesService from "@Services/common/FilesService/FilesService"; import FilesService from "@Services/common/FilesService/FilesService";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
export default async function fileHandler(req: Request, response: Response, next: NextFunction) { export default async function fileHandler(req: Request, response: Response, next: NextFunction) {
const officeId = req.body.user.office_Id; const officeId = req.body.user.office_Id;
let uid = req.path && req.path.split("/")[5]; let uid = req.path && req.path.split("/")[5];
const folder: OfficeFolder = req.body.document.folder; const document = req.body.document;
if (folder && folder.office?.uid != officeId) { if (document) {
const documentService = Container.get(DocumentsService);
const documentWithOffice = await documentService.getByUidWithOffice(document.uid!);
if (!documentWithOffice) {
response.sendStatus(HttpCodes.NOT_FOUND);
return;
}
if (documentWithOffice.folder.office?.uid != officeId) {
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
}
if (uid === "download") uid = req.path && req.path.split("/")[6]; if (uid === "download") uid = req.path && req.path.split("/")[6];
@ -24,7 +32,6 @@ export default async function fileHandler(req: Request, response: Response, next
response.sendStatus(HttpCodes.NOT_FOUND); response.sendStatus(HttpCodes.NOT_FOUND);
return; return;
} }
if (file.document.folder.office.uid != officeId) { if (file.document.folder.office.uid != officeId) {
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;

View File

@ -32,7 +32,9 @@ export default async function folderHandler(req: Request, response: Response, ne
const officeFolderService = Container.get(OfficeFoldersService); const officeFolderService = Container.get(OfficeFoldersService);
if (officeFolderNumber) { if (officeFolderNumber) {
const officeFoldersWithSameNumber = await officeFolderService.get({ where: { folder_number: officeFolderNumber, office: {uid: officeId}}}); const officeFoldersWithSameNumber = await officeFolderService.get({
where: { folder_number: officeFolderNumber, office: { uid: officeId } },
});
if (officeFoldersWithSameNumber.length) { if (officeFoldersWithSameNumber.length) {
response.sendStatus(HttpCodes.BAD_REQUEST); response.sendStatus(HttpCodes.BAD_REQUEST);
return; return;

View File

@ -3,20 +3,19 @@ import { NextFunction, Request, Response } from "express";
export default async function ruleHandler(req: Request, response: Response, next: NextFunction) { export default async function ruleHandler(req: Request, response: Response, next: NextFunction) {
const rules = req.body.user.rules; const rules = req.body.user.rules;
const service = req.path && req.path.split('/')[4]; const service = req.path && req.path.split("/")[4];
const namespace = req.path && req.path.split('/')[3]; const namespace = req.path && req.path.split("/")[3];
const role = req.body.user.role; const role = req.body.user.role;
if(namespace != 'notary' && role != namespace) { if (namespace != "notary" && role != namespace) {
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
if(!rules.includes(req.method + ' ' + service)) { if (!rules.includes(req.method + " " + service)) {
response.sendStatus(HttpCodes.UNAUTHORIZED); response.sendStatus(HttpCodes.UNAUTHORIZED);
return; return;
} }
next(); next();
} }

View File

@ -86,8 +86,7 @@ export class BackendVariables {
try { try {
await validateOrReject(this, validationOptions); await validateOrReject(this, validationOptions);
} } catch (error) {
catch(error) {
if (process.env["NODE_ENV"] === "development") { if (process.env["NODE_ENV"] === "development") {
throw error; throw error;
} }

View File

@ -1,4 +1,4 @@
import 'module-alias/register'; import "module-alias/register";
import { EFolderStatus, EOfficeStatus, ECivility, ECustomerStatus, PrismaClient, Prisma } from "@prisma/client"; import { EFolderStatus, EOfficeStatus, ECivility, ECustomerStatus, PrismaClient, Prisma } from "@prisma/client";
import User, { import User, {
Address, Address,
@ -17,7 +17,6 @@ import User, {
export default async function main() { export default async function main() {
const prisma = new PrismaClient(); const prisma = new PrismaClient();
const randomString = () => { const randomString = () => {
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result = ""; let result = "";
@ -824,7 +823,6 @@ export default async function main() {
created_at: new Date(), created_at: new Date(),
updated_at: new Date(), updated_at: new Date(),
}, },
]; ];
const roles: Role[] = [ const roles: Role[] = [
@ -851,7 +849,7 @@ export default async function main() {
created_at: new Date(), created_at: new Date(),
updated_at: new Date(), updated_at: new Date(),
rules: rules.slice(0, 11), rules: rules.slice(0, 11),
} },
]; ];
const officeRoles: OfficeRole[] = [ const officeRoles: OfficeRole[] = [
@ -882,7 +880,7 @@ export default async function main() {
updated_at: new Date(), updated_at: new Date(),
office: offices[0]!, office: offices[0]!,
rules: rules.slice(0, 11), rules: rules.slice(0, 11),
} },
]; ];
const users: User[] = [ const users: User[] = [
@ -1385,12 +1383,12 @@ export default async function main() {
office_status: EOfficeStatus.DESACTIVATED, office_status: EOfficeStatus.DESACTIVATED,
}, },
}); });
; office.uid = officeCreated.uid; office.uid = officeCreated.uid;
} }
for (const rule of rules) { for (const rule of rules) {
const ruleCreated = await prisma.rules.create({ const ruleCreated = await prisma.rules.create({
data: { data: {
name: rule.name name: rule.name,
}, },
}); });
rule.uid = ruleCreated.uid; rule.uid = ruleCreated.uid;
@ -1607,8 +1605,8 @@ export default async function main() {
connect: officeFolder.stakeholders?.map((stakeholder) => ({ connect: officeFolder.stakeholders?.map((stakeholder) => ({
uid: stakeholder.uid!, uid: stakeholder.uid!,
})), })),
} },
} },
}); });
officeFolder.uid = officeFolderCreated.uid; officeFolder.uid = officeFolderCreated.uid;
} }

View File

@ -69,8 +69,8 @@ export default class DeedTypesRepository extends BaseRepository {
document_types: { document_types: {
set: deedType.document_types?.map((documentType) => ({ set: deedType.document_types?.map((documentType) => ({
uid: documentType.uid!, uid: documentType.uid!,
})) })),
} },
}, },
}; };

View File

@ -102,7 +102,7 @@ export default class DeedsRepository extends BaseRepository {
include: { include: {
deed_type: { include: { office: true } }, deed_type: { include: { office: true } },
document_types: { include: { office: true } }, document_types: { include: { office: true } },
} },
}); });
} }
} }

View File

@ -61,7 +61,7 @@ export default class DocumentTypesRepository extends BaseRepository {
uid: documentType.office!.uid, uid: documentType.office!.uid,
}, },
}, },
} },
}; };
return this.model.update(updateArgs); return this.model.update(updateArgs);

View File

@ -78,7 +78,7 @@ export default class DocumentsRepository extends BaseRepository {
const batchPayload = await this.model.createMany(createArgs); const batchPayload = await this.model.createMany(createArgs);
const documentsCreated = await this.model.findMany({orderBy: {created_at: 'desc'}, take: batchPayload.count}); const documentsCreated = await this.model.findMany({ orderBy: { created_at: "desc" }, take: batchPayload.count });
const createHistoryArgs: Prisma.DocumentHistoryCreateManyArgs = { const createHistoryArgs: Prisma.DocumentHistoryCreateManyArgs = {
data: documentsCreated.map((document) => ({ data: documentsCreated.map((document) => ({
@ -106,7 +106,7 @@ export default class DocumentsRepository extends BaseRepository {
document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus], document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus],
refused_reason: refusedReason, refused_reason: refusedReason,
}, },
} },
}, },
}); });
} }

View File

@ -39,8 +39,8 @@ export default class FilesRepository extends BaseRepository {
file_path: file.file_path, file_path: file.file_path,
mimetype: file.mimetype, mimetype: file.mimetype,
size: file.size, size: file.size,
key: key key: key,
} },
}; };
return this.model.create({ ...createArgs, include: { document: true } }); return this.model.create({ ...createArgs, include: { document: true } });
} }
@ -58,8 +58,8 @@ export default class FilesRepository extends BaseRepository {
file_path: file.file_path, file_path: file.file_path,
mimetype: file.mimetype, mimetype: file.mimetype,
size: file.size, size: file.size,
key: key key: key,
} },
}; };
return this.model.update({ ...updateArgs, include: { document: true } }); return this.model.update({ ...updateArgs, include: { document: true } });
} }
@ -74,8 +74,8 @@ export default class FilesRepository extends BaseRepository {
}, },
data: { data: {
key: null, key: null,
archived_at: new Date(Date.now()) archived_at: new Date(Date.now()),
} },
}; };
return this.model.update({ ...updateArgs, include: { document: true } }); return this.model.update({ ...updateArgs, include: { document: true } });
} }

View File

@ -48,8 +48,8 @@ export default class OfficeFoldersRepository extends BaseRepository {
connect: officeFolder.stakeholders?.map((stakeholder) => ({ connect: officeFolder.stakeholders?.map((stakeholder) => ({
uid: stakeholder.uid!, uid: stakeholder.uid!,
})), })),
} },
} },
}; };
return this.model.create({ ...createArgs, include: { stakeholders: true } }); return this.model.create({ ...createArgs, include: { stakeholders: true } });

View File

@ -30,7 +30,7 @@ export default class RulesRepository extends BaseRepository {
public async create(rule: Rule): Promise<Rules> { public async create(rule: Rule): Promise<Rules> {
const createArgs: Prisma.RulesCreateArgs = { const createArgs: Prisma.RulesCreateArgs = {
data: { data: {
name: rule.name name: rule.name,
}, },
}; };
@ -46,7 +46,7 @@ export default class RulesRepository extends BaseRepository {
uid: rule.uid, uid: rule.uid,
}, },
data: { data: {
name: rule.name name: rule.name,
}, },
}; };

View File

@ -57,7 +57,7 @@ export default class UsersRepository extends BaseRepository {
email: user.contact!.email, email: user.contact!.email,
phone_number: user.contact?.phone_number, phone_number: user.contact?.phone_number,
cell_phone_number: user.contact!.cell_phone_number, cell_phone_number: user.contact!.cell_phone_number,
civility: ECivility[user.contact?.civility as keyof typeof ECivility] civility: ECivility[user.contact?.civility as keyof typeof ECivility],
}, },
}, },
role: { role: {
@ -130,7 +130,7 @@ export default class UsersRepository extends BaseRepository {
email: user.contact!.email, email: user.contact!.email,
phone_number: user.contact?.phone_number, phone_number: user.contact?.phone_number,
cell_phone_number: user.contact?.cell_phone_number, cell_phone_number: user.contact?.cell_phone_number,
civility: ECivility[user.contact?.civility as keyof typeof ECivility] civility: ECivility[user.contact?.civility as keyof typeof ECivility],
}, },
}, },
}, },

View File

@ -21,10 +21,10 @@ export type OpenIdConfig = {
scopes_supported: string[]; scopes_supported: string[];
issuer: string; issuer: string;
jwks_uri: string; jwks_uri: string;
} };
export default interface OpenIdInterface { export default interface OpenIdInterface {
getOpenIdConfig(): Promise<OpenIdConfig> getOpenIdConfig(): Promise<OpenIdConfig>;
verifyIdToken(signingKey: string): Promise<Payload>; verifyIdToken(signingKey: string): Promise<Payload>;
getSigningKeys(jwksUri: string): Promise<string[]>; getSigningKeys(jwksUri: string): Promise<string[]>;
} }

View File

@ -9,7 +9,6 @@ import errorHandler from "@App/middlewares/ErrorHandler";
import { BackendVariables } from "@Common/config/variables/Variables"; import { BackendVariables } from "@Common/config/variables/Variables";
import multer from "multer"; import multer from "multer";
const storage = multer.memoryStorage(); const storage = multer.memoryStorage();
(async () => { (async () => {
@ -24,7 +23,12 @@ const storage = multer.memoryStorage();
label, label,
port: parseInt(port), port: parseInt(port),
rootUrl, rootUrl,
middlwares: [cors({ origin: "*" }), multer({storage:storage}).single('file'), bodyParser.urlencoded({ extended: true }), bodyParser.json()], middlwares: [
cors({ origin: "*" }),
multer({ storage: storage }).single("file"),
bodyParser.urlencoded({ extended: true }),
bodyParser.json(),
],
errorHandler, errorHandler,
}); });

View File

@ -5,7 +5,6 @@ import crypto from "crypto";
@Service() @Service()
export default class CryptoService extends BaseService { export default class CryptoService extends BaseService {
private static readonly CRYPTO_ALGORITHM = "aes-256-ctr"; private static readonly CRYPTO_ALGORITHM = "aes-256-ctr";
constructor(protected variables: BackendVariables) { constructor(protected variables: BackendVariables) {
@ -13,7 +12,7 @@ export default class CryptoService extends BaseService {
} }
private getKey(key: string) { private getKey(key: string) {
return crypto.createHash('sha256').update(String(key)).digest('base64').slice(0, 32); return crypto.createHash("sha256").update(String(key)).digest("base64").slice(0, 32);
} }
/** /**

View File

@ -10,7 +10,6 @@ import {v4} from "uuid";
import { Files, Prisma } from "@prisma/client"; import { Files, Prisma } from "@prisma/client";
import fetch from "node-fetch"; import fetch from "node-fetch";
@Service() @Service()
export default class FilesService extends BaseService { export default class FilesService extends BaseService {
constructor( constructor(
@ -66,11 +65,12 @@ export default class FilesService extends BaseService {
const key = v4(); const key = v4();
const encryptedFile = await this.cryptoService.encrypt(fileData.buffer, key); const encryptedFile = await this.cryptoService.encrypt(fileData.buffer, key);
const upload = await this.ipfsService.pinFile(Readable.from(encryptedFile), fileData.originalname); const upload = await this.ipfsService.pinFile(Readable.from(encryptedFile), fileData.originalname);
const fileToCreate: File = file; let fileToCreate: File = file;
fileToCreate.file_name = fileData.originalname; fileToCreate.file_name = fileData.originalname;
fileToCreate.file_path = this.variables.PINATA_GATEWAY.concat(upload.IpfsHash); fileToCreate.file_path = this.variables.PINATA_GATEWAY.concat(upload.IpfsHash);
fileToCreate.mimetype = fileData.mimetype; fileToCreate.mimetype = fileData.mimetype;
fileToCreate.size = fileData.size; fileToCreate.size = fileData.size;
fileToCreate.archived_at = null;
return this.filesRepository.create(fileToCreate, key); return this.filesRepository.create(fileToCreate, key);
} }

View File

@ -9,7 +9,7 @@ export default class FilesService extends BaseService {
private ipfsClient: pinataSDK; private ipfsClient: pinataSDK;
constructor(protected variables: BackendVariables) { constructor(protected variables: BackendVariables) {
super(); super();
this.ipfsClient = new pinataSDK({ pinataApiKey: variables.PINATA_API_KEY, pinataSecretApiKey: variables.PINATA_API_SECRET }) this.ipfsClient = new pinataSDK({ pinataApiKey: variables.PINATA_API_KEY, pinataSecretApiKey: variables.PINATA_API_SECRET });
} }
/** /**

View File

@ -20,7 +20,7 @@ export type OpenIdConfig = {
scopes_supported: string[]; scopes_supported: string[];
issuer: string; issuer: string;
jwks_uri: string; jwks_uri: string;
} };
@Service() @Service()
export default class OpenIdService extends BaseService { export default class OpenIdService extends BaseService {

View File

@ -6,9 +6,7 @@ import { Service } from "typedi";
@Service() @Service()
export default class DeedTypesService extends BaseService { export default class DeedTypesService extends BaseService {
constructor( constructor(private deedTypeRepository: DeedTypesRepository) {
private deedTypeRepository: DeedTypesRepository,
) {
super(); super();
} }

View File

@ -7,13 +7,12 @@ import DeedTypesService from "../DeedTypesService/DeedTypesService";
import DeedsRepository from "@Repositories/DeedsRepository"; import DeedsRepository from "@Repositories/DeedsRepository";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
@Service() @Service()
export default class OfficeFoldersService extends BaseService { export default class OfficeFoldersService extends BaseService {
constructor( constructor(
private officeFoldersRepository: OfficeFoldersRepository, private officeFoldersRepository: OfficeFoldersRepository,
private deedTypeService: DeedTypesService, private deedTypeService: DeedTypesService,
private deedRepository: DeedsRepository private deedRepository: DeedsRepository,
) { ) {
super(); super();
} }
@ -32,8 +31,8 @@ export default class OfficeFoldersService extends BaseService {
*/ */
public async create(officeFolderEntity: OfficeFolder): Promise<OfficeFolders> { public async create(officeFolderEntity: OfficeFolder): Promise<OfficeFolders> {
const deedType = await this.deedTypeService.getByUid(officeFolderEntity.deed!.deed_type!.uid!); const deedType = await this.deedTypeService.getByUid(officeFolderEntity.deed!.deed_type!.uid!);
if(!deedType) throw new Error('deed type not found'); if (!deedType) throw new Error("deed type not found");
if(deedType.archived_at) throw new Error('deed type is archived'); if (deedType.archived_at) throw new Error("deed type is archived");
const deed = await this.deedRepository.create(officeFolderEntity.deed!); const deed = await this.deedRepository.create(officeFolderEntity.deed!);
officeFolderEntity.deed!.uid = deed.uid; officeFolderEntity.deed!.uid = deed.uid;
return this.officeFoldersRepository.create(officeFolderEntity); return this.officeFoldersRepository.create(officeFolderEntity);
@ -69,7 +68,7 @@ export default class OfficeFoldersService extends BaseService {
*/ */
public async delete(uid: string): Promise<OfficeFolders> { public async delete(uid: string): Promise<OfficeFolders> {
const officeFolderEntity = await this.officeFoldersRepository.findOneByUid(uid, { customers: true }); const officeFolderEntity = await this.officeFoldersRepository.findOneByUid(uid, { customers: true });
if(!officeFolderEntity) throw new Error('office folder not found'); if (!officeFolderEntity) throw new Error("office folder not found");
const officeFolder = OfficeFolder.hydrate<OfficeFolder>(officeFolderEntity, { strategy: "excludeAll" }); const officeFolder = OfficeFolder.hydrate<OfficeFolder>(officeFolderEntity, { strategy: "excludeAll" });
if (officeFolder.customers?.length) { if (officeFolder.customers?.length) {

View File

@ -151,7 +151,7 @@ describe("test update function", () => {
describe("test get function", () => { describe("test get function", () => {
it("should return an array of Customers", async () => { it("should return an array of Customers", async () => {
const req = {} const req = {};
const customers = await CustomersServiceTest.get(req); const customers = await CustomersServiceTest.get(req);
// verify result typing // verify result typing

View File

@ -279,7 +279,10 @@ describe("test get function", () => {
expect(deedTypesForFirstOffice[0]?.archived_at).toBeNull(); expect(deedTypesForFirstOffice[0]?.archived_at).toBeNull();
expect(deedTypesForFirstOffice[0]?.office_uid).toEqual(office.uid); expect(deedTypesForFirstOffice[0]?.office_uid).toEqual(office.uid);
const deedTypesForSecondOffice = await DeedTypeServiceTest.get({ where: { office: {uid: office_.uid} }, orderBy: { name: "asc" } }); const deedTypesForSecondOffice = await DeedTypeServiceTest.get({
where: { office: { uid: office_.uid } },
orderBy: { name: "asc" },
});
expect(deedTypesForSecondOffice.length).toEqual(2); expect(deedTypesForSecondOffice.length).toEqual(2);

View File

@ -241,7 +241,10 @@ describe("test get function", () => {
}); });
it("should return an array of DocumentTypes per offices", async () => { it("should return an array of DocumentTypes per offices", async () => {
const documentTypesForFirstOffice = await DocumentTypesServiceTest.get({ where: { office: {uid : office.uid }}, orderBy: { name: "asc" } }); const documentTypesForFirstOffice = await DocumentTypesServiceTest.get({
where: { office: { uid: office.uid } },
orderBy: { name: "asc" },
});
expect(documentTypesForFirstOffice.length).toEqual(1); expect(documentTypesForFirstOffice.length).toEqual(1);
@ -252,7 +255,10 @@ describe("test get function", () => {
expect(documentTypesForFirstOffice[0]?.archived_at).toBeNull(); expect(documentTypesForFirstOffice[0]?.archived_at).toBeNull();
expect(documentTypesForFirstOffice[0]?.office_uid).toEqual(office.uid); expect(documentTypesForFirstOffice[0]?.office_uid).toEqual(office.uid);
const documentTypesForSecondOffice = await DocumentTypesServiceTest.get({ where: { office: {uid : office_.uid }}, orderBy: { name: "asc" } }); const documentTypesForSecondOffice = await DocumentTypesServiceTest.get({
where: { office: { uid: office_.uid } },
orderBy: { name: "asc" },
});
expect(documentTypesForSecondOffice.length).toEqual(2); expect(documentTypesForSecondOffice.length).toEqual(2);

View File

@ -1,7 +1,18 @@
import "module-alias/register"; import "module-alias/register";
import "reflect-metadata"; import "reflect-metadata";
import { PrismaClient } from "prisma/prisma-client"; import { PrismaClient } from "prisma/prisma-client";
import { customer, customer_, deedType, documentType, documentType_, office, officeFolder, officeFolder_, user, user_ } from "@Test/config/MockedData"; import {
customer,
customer_,
deedType,
documentType,
documentType_,
office,
officeFolder,
officeFolder_,
user,
user_,
} from "@Test/config/MockedData";
import Container from "typedi"; import Container from "typedi";
import OfficeFoldersRepository from "@Repositories/OfficeFoldersRepository"; import OfficeFoldersRepository from "@Repositories/OfficeFoldersRepository";
import OfficeFolderService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService"; import OfficeFolderService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService";
@ -12,7 +23,11 @@ import DeedsRepository from "@Repositories/DeedsRepository";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
const OfficeFolderServiceTest = new OfficeFolderService(Container.get(OfficeFoldersRepository), Container.get(DeedTypesService), Container.get(DeedsRepository)); const OfficeFolderServiceTest = new OfficeFolderService(
Container.get(OfficeFoldersRepository),
Container.get(DeedTypesService),
Container.get(DeedsRepository),
);
beforeAll(async () => { beforeAll(async () => {
office.uid = (await initOffice(office)).uid; office.uid = (await initOffice(office)).uid;