-
Notifications
You must be signed in to change notification settings - Fork 2
Crud expedicoes #540
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
Open
JordanBonfim
wants to merge
16
commits into
532-cadastro-expedicoes
Choose a base branch
from
crud-expedicoes
base: 532-cadastro-expedicoes
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Crud expedicoes #540
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
86c349c
feat(expedicao): adiciona endpoint de cadastro
JordanBonfim ab6192d
feat(expedicao): adiciona endpoint de listagem com filtros
JordanBonfim a50c225
feat(expedicao): adiciona endpoint de busca por id
JordanBonfim c46de0d
feat(expedicao): endpoint de listagem com paginacao
JordanBonfim d5529ee
feat(expedicao): adiciona endpoint de exclusão
JordanBonfim 3467048
feat(expedicao): adiciona endpoint de atualização
JordanBonfim 386cdfc
fix(expedicao): atualiza teste de integracao para o novo formato pagi…
JordanBonfim 7ba74b1
fix(expedicao): corrige problemas de lint
JordanBonfim 9fae20a
fix(expedicao): corrige mapeamento de erros 404 e 500 na busca por id
JordanBonfim a45d40f
fix(expedicao): cria ExpedicaoListItem para o findAll
JordanBonfim 7169c03
fix(expedicao): implementa padrao de order e validacao no controller …
JordanBonfim 83c9384
test(expedicao): cobre paginacao, ordenacao e filtros no findAll
JordanBonfim dd40c2b
fix(exception):tratamento de excecao endpoint de exclusao
JordanBonfim b6aa2fc
fix(expedicao): corrige verificação de erro na exclusão
JordanBonfim 805699c
fix(expedicao): corrige mapeamento de erros no cadastro
JordanBonfim cce955e
fix(expedicao): corrige mapeamento de erros na atualizacao
JordanBonfim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
src/application/expedicao/AtualizaExpedicaoController.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import { AtualizaExpedicaoUseCase } from '@/domain/expedicao/AtualizaExpedicaoUseCase' | ||
| import { | ||
| HttpRequest, HttpResponse, StatusCode | ||
| } from '@/library/http/common' | ||
| import { BadRequestError } from '@/library/http/error/BadRequestError' | ||
| import { HttpError } from '@/library/http/error/HttpError' | ||
| import { InternalServerError } from '@/library/http/error/InternalServerError' | ||
| import { NotFoundError } from '@/library/http/error/NotFoundError' | ||
| import { NextHandler, RequestHandler } from '@/library/http/Server' | ||
|
|
||
| interface Dependencies { | ||
| atualizaExpedicaoUseCase: AtualizaExpedicaoUseCase | ||
| } | ||
|
|
||
| interface CustomHttpRequest extends HttpRequest { | ||
| usuario?: { | ||
| id: number | ||
| tipo_usuario_id: number | ||
| } | ||
| } | ||
|
|
||
| export class AtualizaExpedicaoController implements RequestHandler { | ||
| private readonly atualizaExpedicaoUseCase: AtualizaExpedicaoUseCase | ||
|
|
||
| constructor(dependencies: Dependencies) { | ||
| this.atualizaExpedicaoUseCase = dependencies.atualizaExpedicaoUseCase | ||
| } | ||
|
|
||
| async handle(request: CustomHttpRequest, _next: NextHandler): Promise<HttpResponse | HttpError> { | ||
| try { | ||
| const { expedicaoId } = request.params | ||
| const id = Number(expedicaoId) | ||
|
|
||
| if (!expedicaoId || Number.isNaN(id)) { | ||
| return new BadRequestError({ message: 'O ID da expedição é inválido.' }) | ||
| } | ||
|
|
||
| const { | ||
| descricao, data_inicio, data_fim, cidade_id | ||
| } = request.body as { | ||
| descricao: string | null | ||
| data_inicio: string | ||
| data_fim: string | ||
| cidade_id: number | ||
| } | ||
|
|
||
| const isValidDate = (dateString: string) => { | ||
| if (!/^\d{4}-\d{2}-\d{2}$/.test(dateString)) return false | ||
|
|
||
| const [ | ||
| year, | ||
| month, | ||
| day | ||
| ] = dateString.split('-').map(Number) | ||
| const date = new Date(year, month - 1, day) | ||
|
|
||
| return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day | ||
| } | ||
|
|
||
| if (typeof data_inicio !== 'string' || !isValidDate(data_inicio)) { | ||
| return new BadRequestError({ message: 'A data_inicio é obrigatória e deve ser uma data válida no calendário (formato YYYY-MM-DD).' }) | ||
| } | ||
| if (typeof data_fim !== 'string' || !isValidDate(data_fim)) { | ||
| return new BadRequestError({ message: 'A data_fim é obrigatória e deve ser uma data válida no calendário (formato YYYY-MM-DD).' }) | ||
| } | ||
| if (!Number.isInteger(cidade_id) || cidade_id <= 0) { | ||
| return new BadRequestError({ message: 'O cidade_id é obrigatório e deve ser um número inteiro válido.' }) | ||
| } | ||
| if (descricao !== undefined && descricao !== null && typeof descricao !== 'string') { | ||
| return new BadRequestError({ message: 'A descricao, se informada, deve ser um texto.' }) | ||
| } | ||
|
|
||
| const updated_by = 10 // MOCK TEMPORÁRIO, trocar por request.usuario.id | ||
|
|
||
| const result = await this.atualizaExpedicaoUseCase.execute(id, { | ||
| descricao: descricao ?? null, | ||
| data_inicio, | ||
| data_fim, | ||
| cidade_id, | ||
| updated_by | ||
| }) | ||
|
|
||
| if (result.left()) { | ||
| const error = result.value | ||
|
|
||
| // Não encontrado (404) | ||
| if (error.message === 'Expedição não encontrada') { | ||
| return new NotFoundError({ message: error.message }) | ||
| } | ||
|
|
||
| // Erro de Infraestrutura / Banco de Dados (500) | ||
| if (error.name === 'CollectionError' || error.message.includes('Failed to update')) { | ||
| return new InternalServerError({ message: 'Falha interna ao atualizar expedição' }) | ||
| } | ||
|
|
||
| // Erro de validação da Entidade / Regra de Negócio (400) | ||
| return new BadRequestError({ message: error.message }) | ||
| } | ||
|
|
||
| return { | ||
| statusCode: StatusCode.Ok, | ||
| body: result.value | ||
| } | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : 'Erro inesperado ao atualizar expedição' | ||
| return new InternalServerError({ message: errorMessage }) | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import { BuscaExpedicaoUseCase } from '@/domain/expedicao/BuscaExpedicaoUseCase' | ||
| import { | ||
| HttpRequest, HttpResponse, StatusCode | ||
| } from '@/library/http/common' | ||
| import { BadRequestError } from '@/library/http/error/BadRequestError' | ||
| import { HttpError } from '@/library/http/error/HttpError' | ||
| import { InternalServerError } from '@/library/http/error/InternalServerError' | ||
| import { NotFoundError } from '@/library/http/error/NotFoundError' | ||
| import { NextHandler, RequestHandler } from '@/library/http/Server' | ||
|
|
||
| interface Dependencies { | ||
| buscaExpedicaoUseCase: BuscaExpedicaoUseCase | ||
| } | ||
|
|
||
| interface CustomHttpRequest extends HttpRequest { | ||
| params: Record<string, string | undefined> | ||
| } | ||
|
|
||
| export class BuscaExpedicaoController implements RequestHandler { | ||
| private readonly buscaExpedicaoUseCase: BuscaExpedicaoUseCase | ||
|
|
||
| constructor(dependencies: Dependencies) { | ||
| this.buscaExpedicaoUseCase = dependencies.buscaExpedicaoUseCase | ||
| } | ||
|
|
||
| // Busca expedição por ID | ||
| // GET /v2/expedicoes/:expedicaoId | ||
| async handle(request: CustomHttpRequest, _next: NextHandler): Promise<HttpResponse | HttpError> { | ||
| try { | ||
| const { expedicaoId } = request.params | ||
|
|
||
| // validação id | ||
| if (expedicaoId === undefined || expedicaoId === null || expedicaoId === '' || !/^\d+$/.test(expedicaoId)) { | ||
| return new BadRequestError({ message: 'expedicaoId inválido' }) | ||
| } | ||
|
|
||
| const result = await this.buscaExpedicaoUseCase.execute({ id: Number(expedicaoId) }) | ||
|
|
||
| // Falha na infra ou exceção de regra de negócio | ||
| if (result.left()) { | ||
|
JordanBonfim marked this conversation as resolved.
|
||
| return new InternalServerError({ message: result.value.message }) | ||
| } | ||
|
|
||
| // sucesso na querry, mas a expedição não encontrada | ||
| if (!result.value) { | ||
| return new NotFoundError({ message: 'Expedição não encontrada' }) | ||
| } | ||
|
|
||
| // sucesso | ||
| return { | ||
| statusCode: StatusCode.Ok, | ||
| body: result.value | ||
| } | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : 'Erro inesperado ao buscar expedição por ID' | ||
| return new InternalServerError({ message: errorMessage }) | ||
| } | ||
| } | ||
| } | ||
101 changes: 101 additions & 0 deletions
101
src/application/expedicao/CadastraExpedicaoController.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { CadastraExpedicaoUseCase } from '@/domain/expedicao/CadastraExpedicaoUseCase' | ||
| import { | ||
| HttpRequest, HttpResponse, StatusCode | ||
| } from '@/library/http/common' | ||
| import { BadRequestError } from '@/library/http/error/BadRequestError' | ||
| import { HttpError } from '@/library/http/error/HttpError' | ||
| import { InternalServerError } from '@/library/http/error/InternalServerError' | ||
| import { NextHandler, RequestHandler } from '@/library/http/Server' | ||
| // import { TIPOS_USUARIOS } from '@/middlewares/tokens-middleware' | ||
| // import { UnauthorizedError } from '@/library/http/error/UnauthorizedError' | ||
|
|
||
| interface Dependencies { | ||
| cadastraExpedicaoUseCase: CadastraExpedicaoUseCase | ||
| } | ||
|
|
||
| interface CustomHttpRequest extends HttpRequest { | ||
| usuario?: { | ||
| id: number | ||
| tipo_usuario_id: number | ||
| } | ||
| } | ||
|
|
||
| export class CadastraExpedicaoController implements RequestHandler { | ||
| private readonly cadastraExpedicaoUseCase: CadastraExpedicaoUseCase | ||
|
|
||
| constructor(dependencies: Dependencies) { | ||
| this.cadastraExpedicaoUseCase = dependencies.cadastraExpedicaoUseCase | ||
| } | ||
|
|
||
| async handle(request: CustomHttpRequest, _next: NextHandler): Promise<HttpResponse | HttpError> { | ||
| try { | ||
| // TODO: AUTENTICAÇÃO TEMPORARIAMENTE DESABILITADA | ||
| // A infraestrutura de request HTTP autenticada está sendo desenvolvida. | ||
| // Assim que integrada, descomentar a validação abaixo e remover o mock do 'created_by'. | ||
|
|
||
| // if (!request.usuario || ![TIPOS_USUARIOS.CURADOR, TIPOS_USUARIOS.OPERADOR].includes(request.usuario.tipo_usuario_id)) { | ||
| // return new UnauthorizedError({ message: 'Não tem permissão para realizar esta ação' }) | ||
| // } | ||
|
|
||
| const { | ||
| descricao, data_inicio, data_fim, cidade_id, participantes, rotas | ||
| } = request.body as { | ||
| descricao?: string | null | ||
| data_inicio: string | ||
| data_fim: string | ||
| cidade_id: number | ||
| participantes?: number[] | ||
| rotas?: number[] | ||
| } | ||
|
|
||
| // VALIDAÇÃO MANUAL DE DADOS | ||
| if (!data_inicio || Number.isNaN(Date.parse(data_inicio))) { | ||
| return new BadRequestError({ message: 'A data_inicio é obrigatória e deve ser uma data válida (ex: YYYY-MM-DD).' }) | ||
| } | ||
|
|
||
| if (!data_fim || Number.isNaN(Date.parse(data_fim))) { | ||
| return new BadRequestError({ message: 'A data_fim é obrigatória e deve ser uma data válida (ex: YYYY-MM-DD).' }) | ||
| } | ||
|
|
||
| if (!cidade_id || typeof cidade_id !== 'number' || cidade_id <= 0) { | ||
| return new BadRequestError({ message: 'O cidade_id é obrigatório e deve ser um número válido.' }) | ||
| } | ||
|
|
||
| if (descricao !== undefined && descricao !== null && typeof descricao !== 'string') { | ||
| return new BadRequestError({ message: 'A descricao, se informada, deve ser um texto.' }) | ||
| } | ||
|
|
||
| // MOCK TEMPORÁRIO: Substituir pelo request.usuario.id quando a autenticação estiver pronta | ||
| const created_by = 9 // Id válido de usuário para teste | ||
|
|
||
| // EXECUÇÃO DO CASO DE USO | ||
| const result = await this.cadastraExpedicaoUseCase.execute({ | ||
| descricao: descricao ?? null, | ||
| data_inicio, | ||
| data_fim, | ||
| cidade_id, | ||
| created_by, | ||
| participantes: participantes ?? [], | ||
| rotas: rotas ?? [] | ||
| }) | ||
|
|
||
| if (result.left()) { | ||
|
JordanBonfim marked this conversation as resolved.
|
||
| // Se for um erro que sabemos ser de banco/infraestrutura devolve 500 | ||
| if (result.value.name === 'CollectionError' || result.value.message.includes('Failed to create')) { | ||
| return new InternalServerError({ message: 'Falha interna ao cadastrar expedição' }) | ||
| } | ||
|
|
||
| // Se for um erro de validação de domínio (ex: data_fim antes de data_inicio) devolve 400 | ||
| return new BadRequestError({ message: result.value.message }) | ||
| } | ||
|
|
||
| return { | ||
| statusCode: StatusCode.Created, | ||
| body: result.value | ||
| } | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : 'Erro inesperado ao cadastrar expedição' | ||
| return new InternalServerError({ message: errorMessage }) | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import { DeletaExpedicaoUseCase } from '@/domain/expedicao/DeletaExpedicaoUseCase' | ||
| import { | ||
| HttpRequest, HttpResponse, StatusCode | ||
| } from '@/library/http/common' | ||
| import { BadRequestError } from '@/library/http/error/BadRequestError' | ||
| import { HttpError } from '@/library/http/error/HttpError' | ||
| import { InternalServerError } from '@/library/http/error/InternalServerError' | ||
| import { NotFoundError } from '@/library/http/error/NotFoundError' | ||
| import { NextHandler, RequestHandler } from '@/library/http/Server' | ||
|
|
||
| interface Dependencies { | ||
| deletaExpedicaoUseCase: DeletaExpedicaoUseCase | ||
| } | ||
|
|
||
| interface CustomHttpRequest extends HttpRequest { | ||
| params: Record<string, string | undefined> | ||
| } | ||
|
|
||
| export class DeletaExpedicaoController implements RequestHandler { | ||
| private readonly deletaExpedicaoUseCase: DeletaExpedicaoUseCase | ||
|
|
||
| constructor(dependencies: Dependencies) { | ||
| this.deletaExpedicaoUseCase = dependencies.deletaExpedicaoUseCase | ||
| } | ||
|
|
||
| async handle(request: CustomHttpRequest, _next: NextHandler): Promise<HttpResponse | HttpError> { | ||
|
JordanBonfim marked this conversation as resolved.
|
||
| try { | ||
| const { expedicaoId } = request.params | ||
|
|
||
| if (expedicaoId === undefined || expedicaoId === null || expedicaoId === '' || !/^\d+$/.test(expedicaoId)) { | ||
| return new BadRequestError({ message: 'O ID da expedição é inválido.' }) | ||
| } | ||
|
|
||
| const result = await this.deletaExpedicaoUseCase.execute({ id: Number(expedicaoId) }) | ||
|
|
||
| if (result.left()) { | ||
| // Distingue não encontrado (404) de erro no banco (500) | ||
| if (result.value.message === 'Expedição não encontrada') { | ||
| return new NotFoundError({ message: result.value.message }) | ||
| } | ||
| return new InternalServerError({ message: result.value.message }) | ||
| } | ||
|
|
||
| return { | ||
| statusCode: StatusCode.NoContent | ||
| } | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : 'Erro inesperado ao deletar a expedição.' | ||
| return new InternalServerError({ message: errorMessage }) | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.