Skip to content
Open
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
4 changes: 4 additions & 0 deletions modulo6/case4-doghero/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
package-lock.json
build
.env
35 changes: 35 additions & 0 deletions modulo6/case4-doghero/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# DOG HERO
## Documentação
[Postman](https://documenter.getpostman.com/view/19296393/UzBqq65M)

[Heroku](https://doghero-vsux.herokuapp.com)
## Descrição

O dog Hero é um case de projeto back-end para conclusão do bootcamp Labenu, onde é feita uma API para passeios de cachorros. Nessa API pode-se cadastrar passeios, iniciar um passeio, finalizar o passeio, mostrar quais passeios estão acontecendo no momento e retornar todos os passeios


## Instalação



```bash
NPM install
```


## Desenvolvedor

<table>
<tr>

<td align="center">
<a href="https://github.com/Vsux17">
<img src="https://avatars.githubusercontent.com/u/94612208?v=4" width="100px;" alt="foto victor github"/><br>
<sub>
<b>Victor Xavier</b>
</sub>
</a>
</td>
</tr>
</table>

37 changes: 37 additions & 0 deletions modulo6/case4-doghero/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "case4-doghero",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start:dev": "ts-node-dev ./src/index.ts",
"start": "tsc && node ./build/index.js",
"build": "tsc",
"dev": "ts-node-dev ./src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/knex": "^0.16.1",
"dotenv": "^16.0.1",
"knex": "^2.1.0",
"mysql": "^2.18.1",
"ts-node-dev": "^2.0.0",
"typescript": "^4.7.3"
},
"dependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express-serve-static-core": "^4.17.28",
"@types/jsonwebtoken": "^8.5.8",
"@types/uuid": "^8.3.4",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.18.1",
"jsonwebtoken": "^8.5.1",
"uuid": "^8.3.2"
},
"description": ""
}
203 changes: 203 additions & 0 deletions modulo6/case4-doghero/src/Business/DogWalkingBusiness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { CalculatePrice } from './../Services/CalculatePrice';
import { IdGenerator } from './../Services/IdGeneretor';
import { CreateWalkInputDTO, Duration, FinishWalkInputDTO, StartWalkInputDTO, STATUS, Walk } from "../Model/Walk";
import { FormataHoras } from "../Services/formatHours";
import { dogWalkingRepository } from "./DogWalkingRepository";

export default class DogWalkingBusiness {
private idGenerator: IdGenerator;
private dogWalkingData: dogWalkingRepository
private calculatePrice: CalculatePrice
private formatHours: FormataHoras

constructor(
dogWalkingDataImplementation: dogWalkingRepository
) {
this.dogWalkingData = dogWalkingDataImplementation
this.idGenerator = new IdGenerator()
this.calculatePrice = new CalculatePrice()
this.formatHours = new FormataHoras()
}

create = async (input: CreateWalkInputDTO) => {
const {
date_schedule,
duration,
latitude,
longitude,
pets,
date_start,
date_end
} = input

if (!date_schedule || !duration || !latitude || !longitude || !pets || !date_start || !date_end) {
throw new Error("Insira todos os campos!")
}

if (duration !== Duration.HORA && duration !== Duration.MEIAHORA) {
throw new Error("Tempo de duração é inválido!")
}

if (date_start === date_end) {
throw new Error("O horário de início não pode ser igual ao de término")
}

const horaInicio = this.formatHours.FormataStringHora(date_start)
const horaTermino = this.formatHours.FormataStringHora(date_end)

if (horaInicio > horaTermino) {
throw new Error("O horário de início não pode ser maior que o horário de término")
}

if (date_end.length !== 8 || date_start.length !== 8) {
throw new Error("Insira um horário válido")
}

const id: string = this.idGenerator.generate()
const status = STATUS.INICIO
const preco = this.calculatePrice.calculatePrice(pets, duration)

const walk = new Walk(
id,
status,
date_schedule,
preco as number,
duration,
latitude,
longitude,
pets,
date_start,
date_end
)

await this.dogWalkingData.insert(walk)
}

startWalk = async (input: StartWalkInputDTO) => {
const { id, date_start } = input

if (!id || !date_start) {
throw new Error("Insira todos os campos!")
}

if (date_start.length !== 8) {
throw new Error("Insira um horário válido")
}

const walkId = await this.dogWalkingData.getWalkById(id)
const status = walkId.status

if (status !== STATUS.INICIO) {
throw new Error("Esse passeio já foi iniciado ou já foi finalizado")
}

if (!walkId) {
throw new Error("Esse passeio não existe!")
}

if (walkId) {
await this.dogWalkingData.start_walk(date_start, id)
}
}

finishWalk = async (input: FinishWalkInputDTO) => {
const { id, date_end } = input

if (!id || !date_end) {
throw new Error("Insira todos os campos!")
}

if (date_end.length !== 8) {
throw new Error("Insira um horário válido")
}

const walkId = await this.dogWalkingData.getWalkById(id)
const status = walkId.status
const duration = Number(walkId.duration)
const horarioInicio = walkId.date_start

const horarioInicioFormatado = this.formatHours.FormataStringHora(horarioInicio)
const horarioTerminoFormatado = this.formatHours.FormataStringHora(date_end)

if (status !== STATUS.ANDAMENTO) {
throw new Error("Esse passeio ainda não foi iniciado!")
}

if (duration === 30 && (horarioTerminoFormatado - horarioInicioFormatado) < (30 * 60)) {
throw new Error("Esse passeio não teve a duração mínima!")
}

if (duration === 60 && (horarioTerminoFormatado - horarioInicioFormatado) < (60 * 60)) {
throw new Error("Esse passeio não teve a duração mínima!")
}

if (horarioTerminoFormatado < horarioInicioFormatado) {
throw new Error("Não há como finalizar a corrida antes do horário de início!")
}

if (!walkId) {
throw new Error("Esse passeio não existe!")
}

if (walkId) {
await this.dogWalkingData.finish_walk(date_end, id)
}
}

show = async (input: string) => {
const walkId = input

if (!walkId) {
throw new Error("Insira todos os campos!")
}

const verifyWalkId = await this.dogWalkingData.getWalkById(walkId)

if (!verifyWalkId) {
throw new Error("Esse passeio não existe!")
}

const status = verifyWalkId.status

if (status !== STATUS.FINALIZADO) {
throw new Error("Esse passeio ainda não foi encerrado!")
}

const tempoInicio = verifyWalkId.date_start
const tempoTermino = verifyWalkId.date_end

const tempoInicioFormatado = this.formatHours.FormataStringHora(tempoInicio)
const tempoTerminoFormatado = this.formatHours.FormataStringHora(tempoTermino)

const diferenca = this.formatHours.diferenca(tempoTerminoFormatado, tempoInicioFormatado)
const diferencaFormatada = this.formatHours.segundosParaHora(diferenca)

return diferencaFormatada

}

index = async (page: number | any, walksPerPage: number | any) => {
const pageInput = page
const walksPerPageInput = walksPerPage

if (pageInput === 0) {
throw new Error("A página não pode ser igual a 0")
}

if ((pageInput || pageInput === "") && !walksPerPageInput) {
throw new Error("Insira todos os campos")
}

if (!pageInput && (walksPerPageInput || walksPerPageInput === "")) {
throw new Error("Insira todos os campos")
}

if (pageInput && walksPerPageInput) {
const result = await this.dogWalkingData.getAllWalksPaged(pageInput, walksPerPageInput)
return result
} else {
const result = await this.dogWalkingData.getAllWalks()
return result
}
}
}
10 changes: 10 additions & 0 deletions modulo6/case4-doghero/src/Business/DogWalkingRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Walk } from "../Model/Walk";

export interface dogWalkingRepository {
insert(walk: Walk): Promise<Walk>
start_walk(start_walk: string, id: string): Promise<undefined>
finish_walk(finish_walk: string, id: string): Promise<undefined>
getWalkById(id: string): Promise<void | any>
getAllWalks(): Promise<Walk[]>
getAllWalksPaged(page: number, walksPerPage: number): Promise<Walk[]>
}
Loading