Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: item_update_logs implementation #161

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
TZ=America/Sao_Paulo

DB_HOST=sos-rs-db
DB_PORT=5432
DB_DATABASE_NAME=sos_rs
DB_USER=root
DB_PASSWORD=root
DATABASE_URL="postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_DATABASE_NAME}_test?schema=public"

SECRET_KEY=batata

HOST=::0.0.0.0
PORT=4000
54 changes: 54 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest.e2e.config.ts",
"pretest:e2e": "dotenv -e .env.test -- npm run migrations:run",
"test:e2e": "dotenv -e .env.test -- jest --config ./test/jest.e2e.config.ts",
"migrations:run": "npx prisma migrate deploy",
"migrations:dev": "npx prisma migrate dev",
"docker:compose": "docker-compose -f docker-compose.dev.yml up"
Expand All @@ -41,6 +42,7 @@
"zod": "^3.23.6"
},
"devDependencies": {
"@faker-js/faker": "^8.4.1",
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
Expand All @@ -51,6 +53,7 @@
"@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"dotenv-cli": "^7.4.2",
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-jest": "^28.5.0",
Expand Down
32 changes: 32 additions & 0 deletions prisma/migrations/20240522040315_create_log_tables/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-- CreateTable
CREATE TABLE "audit_logs" (
"id" TEXT NOT NULL,
"model_name" TEXT NOT NULL,
"model_id" TEXT NOT NULL,
"user_id" TEXT,
"ip" TEXT,
"previous_value" JSONB,
"current_value" JSONB,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "item_updates_log" (
"id" TEXT NOT NULL,
"supply_name" TEXT,
"shelter_name" TEXT,
"ip_address" TEXT,
"previousPriority" INTEGER,
"currentPriority" INTEGER,
"previousQuantity" INTEGER,
"currentQuantity" INTEGER,
"user_id" TEXT,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "item_updates_log_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Warnings:

- You are about to drop the `item_updates_log` table. If the table is not empty, all the data it contains will be lost.

*/
-- DropTable
DROP TABLE "item_updates_log";

-- CreateTable
CREATE TABLE "supplies_history" (
"id" TEXT NOT NULL,
"supply_name" TEXT,
"shelter_name" TEXT,
"ip_address" TEXT,
"previousPriority" INTEGER,
"currentPriority" INTEGER,
"previousQuantity" INTEGER,
"currentQuantity" INTEGER,
"user_id" TEXT,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "supplies_history_pkey" PRIMARY KEY ("id")
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
Warnings:

- You are about to drop the column `currentPriority` on the `supplies_history` table. All the data in the column will be lost.
- You are about to drop the column `currentQuantity` on the `supplies_history` table. All the data in the column will be lost.
- You are about to drop the column `previousPriority` on the `supplies_history` table. All the data in the column will be lost.
- You are about to drop the column `previousQuantity` on the `supplies_history` table. All the data in the column will be lost.

*/
-- AlterTable
ALTER TABLE "supplies_history" RENAME COLUMN "currentPriority" TO "current_priority";
ALTER TABLE "supplies_history" RENAME COLUMN "currentQuantity" TO "current_quantity";
ALTER TABLE "supplies_history" RENAME COLUMN "previousPriority" TO "previous_priority";
ALTER TABLE "supplies_history" RENAME COLUMN "previousQuantity" TO "previous_quantity";
31 changes: 31 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ model User {

sessions Session[]
shelterManagers ShelterManagers[]
audits Audit[]

@@map("users")
}
Expand Down Expand Up @@ -151,3 +152,33 @@ model Supporters {

@@map("supporters")
}

model Audit {
id String @id @default(uuid())
modelName String @map("model_name")
modelId String @map("model_id")
userId String? @map("user_id")
ip String?
previousValue Json? @map("previous_value")
currentValue Json? @map("current_value")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()

user User? @relation(fields: [userId], references: [id])

@@map("audit_logs")
}

model SuppliesHistory {
id String @id @default(uuid())
supplyName String? @map("supply_name")
shelterName String? @map("shelter_name")
ipAddress String? @map("ip_address")
previousPriority Int? @map("previous_priority")
currentPriority Int? @map("current_priority")
previousQuantity Int? @map("previous_quantity")
currentQuantity Int? @map("current_quantity")
userId String? @map("user_id")
updatedAt DateTime @default(now()) @map("updated_at") @db.Timestamptz()

@@map("supplies_history")
}
55 changes: 55 additions & 0 deletions src/decorators/audit.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { getSessionData } from '@/utils/utils';
import { ExecutionContext, createParamDecorator } from '@nestjs/common';
import { Prisma } from '@prisma/client';

/**
* Decorator que recupera o ip / id do usuário atual da requisição e permite passar
* quais propriedades do modelo do prisma
*
* ```ts
* updateFoo(@AuditProperties<'User'>(['phone','name']) auditProperties:any)){
* // ...sua lógica aqui
* // irá registar as alterações nos campos `phone` e `name` na auditoria.
* }
* ```
*/
const AuditProperties: <T extends keyof typeof Prisma.ModelName>(
auditProps: (keyof Prisma.TypeMap['model'][T]['fields'])[],
) => ParameterDecorator = createParamDecorator(
(auditProps, ctx: ExecutionContext) => {
const req = ctx.switchToHttp().getRequest();
const { headers } = req;
const ipAddress = headers['x-real-ip'] || req.ip;
const token = headers.authorization?.split('Bearer ').at(-1);
const { userId } = getSessionData(token);

return {
auditProps,
ipAddress,
userId,
};
},
);

/**
* Decorator que recupera o ip / id do usuário atual da requisição.
*/
const SessionData = createParamDecorator((_, ctx: ExecutionContext) => {
const req = ctx.switchToHttp().getRequest();
const { headers } = req;
const ipAddress = headers['x-real-ip'] || req.ip;
const token = headers.authorization?.split('Bearer ').at(-1);
const { userId } = getSessionData(token);

return {
ipAddress,
userId,
};
});

type SessionData = {
userId?: string;
ipAddress?: string;
};

export { SessionData, AuditProperties };
Loading