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 28 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;
83 changes: 81 additions & 2 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
}

model User {
id String @id @default(uuid())
name String
Expand All @@ -25,8 +56,9 @@ model User {
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

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

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

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

@@map("shelters")
}
Expand All @@ -133,3 +166,49 @@ model Partners {

@@map("partners")
}

model Transport {
id String @id @default(uuid())
vehicleType String @map("vehicle_type")
vehicleRegistrationPlate String? @map("vehicle_registration_plate")
contact String?
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

transportManagers TransportManager[]
trips Trip[]

@@map("transports")
}

model TransportManager {
transportId String @map("transport_id")
userId String @map("user_id")
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

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")
contact String
canceled Boolean @default(value: false)
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

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

@@map("trips")
}
6 changes: 6 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { SupplyCategoriesModule } from './supply-categories/supply-categories.mo
import { ShelterManagersModule } from './shelter-managers/shelter-managers.module';
import { ShelterSupplyModule } from './shelter-supply/shelter-supply.module';
import { PartnersModule } from './partners/partners.module';
import { TransportsModule } from './transports/transports.module';
import { TransportManagersModule } from './transport-managers/transport-managers.module';
import { TripsModule } from './trips/trips.module';

@Module({
imports: [
Expand All @@ -24,6 +27,9 @@ import { PartnersModule } from './partners/partners.module';
ShelterManagersModule,
ShelterSupplyModule,
PartnersModule,
TransportsModule,
TransportManagersModule,
TripsModule,
],
controllers: [],
providers: [
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 } 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 HttpException('Acesso não autorizado', 401);
vitor-msp marked this conversation as resolved.
Show resolved Hide resolved
}
}
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 } 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 Error('Transporte não encontrado.');
vitor-msp marked this conversation as resolved.
Show resolved Hide resolved

result = await this.prismaService.user.findFirst({
where: {
id: userId,
},
select: {
id: true,
},
});
if (!result) throw new Error('Usuário não encontrado.');
vitor-msp marked this conversation as resolved.
Show resolved Hide resolved

await this.prismaService.transportManager.create({
data: {
transportId,
userId,
createdAt: new Date().toISOString(),
},
});
}
}
15 changes: 15 additions & 0 deletions src/transport-managers/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import z from 'zod';

const TransportManagerSchema = z.object({
transportId: z.string(),
userId: z.string(),
createdAt: z.string(),
updatedAt: z.string().nullable().optional(),
});

const CreateTransportManagerSchema = TransportManagerSchema.omit({
createdAt: true,
updatedAt: true,
});

export { CreateTransportManagerSchema };
Loading