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

Adicionados módulos de transportes e viagens #129

Open
wants to merge 36 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
f44dde7
feat: added prisma schema and migrations
vitor-msp May 15, 2024
d079fcf
feat: added transports module structure
vitor-msp May 15, 2024
82a7acc
feat: added endpoint post transport
vitor-msp May 15, 2024
4046efa
feat: added endpoint put transport
vitor-msp May 15, 2024
07ecfcd
feat: added transport managers module structure
vitor-msp May 15, 2024
6814988
feat: added endpoint post transport managers
vitor-msp May 15, 2024
c87943c
feat: added trips module structure
vitor-msp May 15, 2024
461a79c
fix: changed name format of the some trip fields
vitor-msp May 15, 2024
52fba27
feat: added endpoint post trip
vitor-msp May 15, 2024
cbe39e9
feat: added endpoint put trip
vitor-msp May 15, 2024
2c3aa1a
feat: added field canceled in trips table
vitor-msp May 15, 2024
2a275cd
feat: added endpoint delete trip
vitor-msp May 15, 2024
a597811
feat: added guards
vitor-msp May 15, 2024
64bd391
feat: added user validation in the trips module
vitor-msp May 16, 2024
c023337
refactor: improved error messages
vitor-msp May 16, 2024
325f732
feat: added endpoint get transports
vitor-msp May 16, 2024
e9641e0
feat: added endpoint get transport by id
vitor-msp May 16, 2024
d2a40e8
feat: added endpoint get trip by id
vitor-msp May 16, 2024
9985a85
feat: added endpoint get trips
vitor-msp May 16, 2024
96140c9
feat: changed departure_datetime field in trip to datetime
vitor-msp May 16, 2024
b8f774b
feat: trip search changed to use departure datetime range
vitor-msp May 16, 2024
9118664
feat: added field departure_neighborhood in trips table
vitor-msp May 16, 2024
b485816
feat: added endpoint get trip cities
vitor-msp May 16, 2024
0c24403
feat: added field departure_state in trips table
vitor-msp May 16, 2024
4d49f92
feat: added endpoint get trip states
vitor-msp May 16, 2024
1514c82
feat: added departure_state in the get trips filter
vitor-msp May 16, 2024
0fb9add
Merge pull request #1 from SOS-RS/develop
vitor-msp May 16, 2024
102cc76
Merge branch 'develop' into feat/transports
vitor-msp May 16, 2024
8e5d4a8
fix: changed type of datetime fields
vitor-msp May 17, 2024
c05baea
fix: temporarily set departure_datetime to string
vitor-msp May 17, 2024
8e7c09e
fix: changed type of departure_datetime field
vitor-msp May 17, 2024
9133c56
Merge pull request #2 from SOS-RS/develop
vitor-msp May 17, 2024
276e5c6
Merge branch 'develop' into feat/transports
vitor-msp May 17, 2024
7f52a13
refactor: improved exceptions
vitor-msp May 17, 2024
bbe0332
Merge branch 'develop' into feat/transports
vitor-msp May 19, 2024
c91ec13
Merge branch 'develop' into feat/transports
vitor-msp May 29, 2024
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
47 changes: 47 additions & 0 deletions prisma/migrations/20240515001139_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
-- CreateTable
CREATE TABLE "transports" (
"id" TEXT NOT NULL,
"vehicle_type" TEXT NOT NULL,
"vehicle_registration_plate" TEXT,
"contact" TEXT,
"created_at" VARCHAR(32) NOT NULL,
vitor-msp marked this conversation as resolved.
Show resolved Hide resolved
"updated_at" VARCHAR(32),

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

-- CreateTable
CREATE TABLE "transport_managers" (
"transport_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"created_at" VARCHAR(32) NOT NULL,
"updated_at" VARCHAR(32),

CONSTRAINT "transport_managers_pkey" PRIMARY KEY ("transport_id","user_id")
);

-- CreateTable
CREATE TABLE "trips" (
"id" TEXT NOT NULL,
"transport_id" TEXT NOT NULL,
"shelter_id" TEXT NOT NULL,
"departure_city" TEXT NOT NULL,
"departure_datetime" TIMESTAMP(3) NOT NULL,
"contact" TEXT NOT NULL,
"created_at" VARCHAR(32) NOT NULL,
"updated_at" VARCHAR(32),

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

-- AddForeignKey
ALTER TABLE "transport_managers" ADD CONSTRAINT "transport_managers_transport_id_fkey" FOREIGN KEY ("transport_id") REFERENCES "transports"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "transport_managers" ADD CONSTRAINT "transport_managers_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "trips" ADD CONSTRAINT "trips_transport_id_fkey" FOREIGN KEY ("transport_id") REFERENCES "transports"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "trips" ADD CONSTRAINT "trips_shelter_id_fkey" FOREIGN KEY ("shelter_id") REFERENCES "shelters"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
2 changes: 2 additions & 0 deletions prisma/migrations/20240515003358_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "trips" ALTER COLUMN "departure_datetime" SET DATA TYPE TEXT;
2 changes: 2 additions & 0 deletions prisma/migrations/20240515022401_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "trips" ADD COLUMN "canceled" BOOLEAN NOT NULL DEFAULT false;
2 changes: 2 additions & 0 deletions prisma/migrations/20240515233229_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "AccessLevel" ADD VALUE 'TransportManager';
9 changes: 9 additions & 0 deletions prisma/migrations/20240516172116_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
Warnings:

- Changed the type of `departure_datetime` on the `trips` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.

*/
-- AlterTable
ALTER TABLE "trips" DROP COLUMN "departure_datetime",
ADD COLUMN "departure_datetime" TIMESTAMP(3) NOT NULL;
2 changes: 2 additions & 0 deletions prisma/migrations/20240516184748_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "trips" ADD COLUMN "departure_neighborhood" TEXT;
11 changes: 11 additions & 0 deletions prisma/migrations/20240516195001_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- Added the required column `departure_state` to the `trips` table without a default value. This is not possible if the table is not empty.

*/
-- CreateEnum
CREATE TYPE "State" AS ENUM ('AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO');

-- AlterTable
ALTER TABLE "trips" ADD COLUMN "departure_state" "State" NOT NULL;
11 changes: 11 additions & 0 deletions prisma/migrations/20240516234942_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- ALTER TABLE
ALTER TABLE "transport_managers" ALTER COLUMN "created_at" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("created_at", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;
ALTER TABLE "transport_managers" ALTER COLUMN "updated_at" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("updated_at", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;

-- ALTER TABLE
ALTER TABLE "transports" ALTER COLUMN "created_at" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("created_at", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;
ALTER TABLE "transports" ALTER COLUMN "updated_at" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("updated_at", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;

-- ALTER TABLE
ALTER TABLE "trips" ALTER COLUMN "created_at" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("created_at", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;
ALTER TABLE "trips" ALTER COLUMN "updated_at" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("updated_at", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;
9 changes: 9 additions & 0 deletions prisma/migrations/20240517002749_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- AlterTable
ALTER TABLE "transport_managers" ALTER COLUMN "created_at" SET DEFAULT CURRENT_TIMESTAMP;

-- AlterTable
ALTER TABLE "transports" ALTER COLUMN "created_at" SET DEFAULT CURRENT_TIMESTAMP;

-- AlterTable
ALTER TABLE "trips" ALTER COLUMN "created_at" SET DEFAULT CURRENT_TIMESTAMP,
ALTER COLUMN "departure_datetime" SET DATA TYPE TEXT;
2 changes: 2 additions & 0 deletions prisma/migrations/20240517003522_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- ALTER TABLE
ALTER TABLE "trips" ALTER COLUMN "departure_datetime" TYPE TIMESTAMP(3) WITH TIME ZONE USING TO_TIMESTAMP("departure_datetime", 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')::TIMESTAMP;
85 changes: 82 additions & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,42 @@ datasource db {

enum AccessLevel {
User
TransportManager
Staff
DistributionCenter
Admin
}

enum State {
AC
AL
AP
AM
BA
CE
DF
ES
GO
MA
MT
MS
MG
PA
PB
PR
PE
PI
RJ
RN
RS
RO
RR
SC
SP
SE
TO
}

enum ShelterCategory {
Shelter
DistributionCenter
Expand All @@ -30,9 +61,10 @@ model User {
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

sessions Session[]
shelterManagers ShelterManagers[]
suppliesHistory SupplyHistory[]
sessions Session[]
shelterManagers ShelterManagers[]
transportManagers TransportManager[]
suppliesHistory SupplyHistory[]

@@map("users")
}
Expand Down Expand Up @@ -116,6 +148,7 @@ model Shelter {

shelterManagers ShelterManagers[]
shelterSupplies ShelterSupply[]
trips Trip[]
supplyHistories SupplyHistory[]

@@map("shelters")
Expand Down Expand Up @@ -155,6 +188,52 @@ model Supporters {
@@map("supporters")
}

model Transport {
id String @id @default(uuid())
vehicleType String @map("vehicle_type")
vehicleRegistrationPlate String? @map("vehicle_registration_plate")
contact String?
createdAt DateTime @default(value: now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime? @map("updated_at") @db.Timestamptz()

transportManagers TransportManager[]
trips Trip[]

@@map("transports")
}

model TransportManager {
transportId String @map("transport_id")
userId String @map("user_id")
createdAt DateTime @default(value: now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime? @map("updated_at") @db.Timestamptz()

transport Transport @relation(fields: [transportId], references: [id])
user User @relation(fields: [userId], references: [id])

@@id([transportId, userId])
@@map("transport_managers")
}

model Trip {
id String @id @default(uuid())
transportId String @map("transport_id")
shelterId String @map("shelter_id")
departureNeighborhood String? @map("departure_neighborhood")
departureCity String @map("departure_city")
departureState State @map("departure_state")
departureDatetime DateTime @map("departure_datetime") @db.Timestamptz()
contact String
canceled Boolean @default(value: false)
createdAt DateTime @default(value: now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime? @map("updated_at") @db.Timestamptz()

transport Transport @relation(fields: [transportId], references: [id])
shelter Shelter @relation(fields: [shelterId], references: [id])

@@map("trips")
}

model SupplyHistory {
id String @id @default(uuid())
predecessorId String? @unique @map("predecessor_id")
Expand Down
6 changes: 6 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import { ShelterSupplyModule } from './shelter-supply/shelter-supply.module';
import { PartnersModule } from './partners/partners.module';
import { DashboardModule } from './modules/dashboard/dashboard.module';
import { SupportersModule } from './supporters/supporters.module';
import { TransportsModule } from './transports/transports.module';
import { TransportManagersModule } from './transport-managers/transport-managers.module';
import { TripsModule } from './trips/trips.module';
import { SuppliesHistoryModule } from './supplies-history/supplies-history.module';

@Module({
Expand All @@ -29,6 +32,9 @@ import { SuppliesHistoryModule } from './supplies-history/supplies-history.modul
PartnersModule,
DashboardModule,
SupportersModule,
TransportsModule,
TransportManagersModule,
TripsModule,
SuppliesHistoryModule,
],
controllers: [],
Expand Down
23 changes: 23 additions & 0 deletions src/guards/transport-manager.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ExecutionContext, HttpException, Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AccessLevel } from '@prisma/client';

import { canActivate } from './utils';

@Injectable()
export class TransportManagerGuard extends AuthGuard('jwt') {
constructor() {
super();
}

async canActivate(context: ExecutionContext): Promise<boolean> {
await super.canActivate(context);
const ok = await canActivate(context, [
AccessLevel.TransportManager,
AccessLevel.Staff,
AccessLevel.Admin,
]);
if (ok) return true;
throw new UnauthorizedException('Acesso não autorizado');
}
}
18 changes: 18 additions & 0 deletions src/transport-managers/transport-managers.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TransportManagersController } from './transport-managers.controller';

describe('TransportManagersController', () => {
let controller: TransportManagersController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [TransportManagersController],
}).compile();

controller = module.get<TransportManagersController>(TransportManagersController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
34 changes: 34 additions & 0 deletions src/transport-managers/transport-managers.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {
Body,
Controller,
HttpException,
Logger,
Post,
UseGuards,
} from '@nestjs/common';
import { TransportManagersService } from './transport-managers.service';
import { ApiTags } from '@nestjs/swagger';
import { ServerResponse } from '../utils';
import { StaffGuard } from '@/guards/staff.guard';

@ApiTags('Transport Managers')
@Controller('transport/managers')
export class TransportManagersController {
private logger = new Logger(TransportManagersController.name);

constructor(
private readonly transportManagersService: TransportManagersService,
) {}

@Post('')
@UseGuards(StaffGuard)
async store(@Body() body) {
try {
await this.transportManagersService.store(body);
return new ServerResponse(200, 'Successfully added manager to transport');
} catch (err: any) {
this.logger.error(`Failed to added manager to transport: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}
}
11 changes: 11 additions & 0 deletions src/transport-managers/transport-managers.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { TransportManagersService } from './transport-managers.service';
import { TransportManagersController } from './transport-managers.controller';
import { PrismaModule } from 'src/prisma/prisma.module';

@Module({
imports: [PrismaModule],
providers: [TransportManagersService],
controllers: [TransportManagersController],
})
export class TransportManagersModule {}
18 changes: 18 additions & 0 deletions src/transport-managers/transport-managers.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TransportManagersService } from './transport-managers.service';

describe('TransportManagersService', () => {
let service: TransportManagersService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TransportManagersService],
}).compile();

service = module.get<TransportManagersService>(TransportManagersService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
41 changes: 41 additions & 0 deletions src/transport-managers/transport-managers.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { z } from 'zod';
import { CreateTransportManagerSchema } from './types';

@Injectable()
export class TransportManagersService {
constructor(private readonly prismaService: PrismaService) {}

async store(body: z.infer<typeof CreateTransportManagerSchema>) {
const { transportId, userId } = CreateTransportManagerSchema.parse(body);

let result = await this.prismaService.transport.findFirst({
where: {
id: transportId,
},
select: {
id: true,
},
});
if (!result) throw new NotFoundException('Transporte não encontrado.');

result = await this.prismaService.user.findFirst({
where: {
id: userId,
},
select: {
id: true,
},
});
if (!result) throw new NotFoundException('Usuário não encontrado.');

await this.prismaService.transportManager.create({
data: {
transportId,
userId,
createdAt: new Date().toISOString(),
},
});
}
}
Loading