This commit is contained in:
Hugo Falcao
2022-06-20 20:07:22 -03:00
32 changed files with 1160 additions and 1247 deletions

108
package-lock.json generated
View File

@@ -14,6 +14,7 @@
"@types/express": "^4.17.11",
"@types/jsonwebtoken": "^8.5.1",
"@types/uuid": "^8.3.0",
"axios": "^0.27.2",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.17.1",
@@ -211,6 +212,20 @@
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz",
"integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==",
"dependencies": {
"follow-redirects": "^1.14.9",
"form-data": "^4.0.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -449,6 +464,17 @@
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -511,6 +537,14 @@
"ms": "2.0.0"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
@@ -671,6 +705,38 @@
"node": ">= 0.8"
}
},
"node_modules/follow-redirects": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz",
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -2150,6 +2216,20 @@
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
},
"asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"axios": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz",
"integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==",
"requires": {
"follow-redirects": "^1.14.9",
"form-data": "^4.0.0"
}
},
"balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -2314,6 +2394,14 @@
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"requires": {
"delayed-stream": "~1.0.0"
}
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -2364,6 +2452,11 @@
"ms": "2.0.0"
}
},
"delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
@@ -2495,6 +2588,21 @@
"unpipe": "~1.0.0"
}
},
"follow-redirects": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz",
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA=="
},
"form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
}
},
"forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",

View File

@@ -1,7 +1,6 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class CreateUsers1617210132141 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({

View File

@@ -0,0 +1,61 @@
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class CreateSocialInformationTable1653956028190
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'socialInformation',
columns: [
{
name: 'id_social',
type: 'integer',
isPrimary: true,
isGenerated: true,
generationStrategy: 'increment',
},
{
name: 'user_id',
type: 'uuid',
isNullable: true,
},
{
name: 'phone',
type: 'varchar',
isNullable: true,
},
{
name: 'whatsapp',
type: 'varchar',
isNullable: true,
},
{
name: 'facebook',
type: 'varchar',
isNullable: true,
},
{
name: 'telegram',
type: 'varchar',
isNullable: true,
},
{
name: 'created_at',
type: 'timestamp',
default: 'now()',
},
{
name: 'updated_at',
type: 'timestamp',
default: 'now()',
},
],
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('socials');
}
}

View File

@@ -0,0 +1,23 @@
import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm';
export class AddFKUserIdToSocialInformationTable1653956193180
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createForeignKey(
'socialInformation',
new TableForeignKey({
name: 'SocialInformationUser', // nome da FK, serve para referenciar numa exclusão pelo QueryRunner se necessário
columnNames: ['user_id'], // coluna que vai virar FK
referencedColumnNames: ['id_user'], // coluna PK da primeira tabela
referencedTableName: 'users', // nome da tabela que possui a PK
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey('socialInformation', 'SocialInformationUser');
}
}

View File

@@ -0,0 +1,24 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';
export class AddCpfAndCnpjFieldToUsers1654814986232
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumns('users', [
new TableColumn({
name: 'cpf',
type: 'varchar',
isNullable: true,
}),
new TableColumn({
name: 'cnpj',
type: 'varchar',
isNullable: true,
}),
]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumns('users', ['cnpj', 'cpf']);
}
}

View File

@@ -0,0 +1,74 @@
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class CreateVansTable1655691282002 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'vans',
columns: [
{
name: 'plate',
type: 'varchar',
isPrimary: true,
},
{
name: 'brand',
type: 'varchar',
},
{
name: 'model',
type: 'varchar',
},
{
name: 'seats_number',
type: 'numeric',
},
{
name: 'document_status',
type: 'boolean',
isNullable: true
},
{
name: 'locator_name',
type: 'varchar',
isNullable: true
},
{
name: 'locator_address',
type: 'varchar',
isNullable: true
},
{
name: 'locator_complement',
type: 'varchar',
isNullable: true
},
{
name: 'locator_city',
type: 'varchar',
isNullable: true
},
{
name: 'locator_state',
type: 'varchar',
isNullable: true
},
{
name: 'created_at',
type: 'timestamp',
default: 'now()',
},
{
name: 'updated_at',
type: 'timestamp',
default: 'now()',
},
],
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('vans');
}
}

View File

@@ -0,0 +1,24 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';
export class RemoveCpfAndCnpjFieldsFromUsersTable1655711281662
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumns('users', ['cnpj', 'cpf']);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumns('users', [
new TableColumn({
name: 'cpf',
type: 'varchar',
isNullable: true,
}),
new TableColumn({
name: 'cnpj',
type: 'varchar',
isNullable: true,
}),
]);
}
}

View File

@@ -0,0 +1,24 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';
export class AddDocumentAndDocumentTypeFieldsToUsersTable1655711315251
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumns('users', [
new TableColumn({
name: 'document',
type: 'varchar',
isNullable: true,
}),
new TableColumn({
name: 'document_type',
type: 'varchar',
isNullable: true,
}),
]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumns('users', ['document_type', 'document']);
}
}

View File

@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';
export class AddUserIdFieldToVansTable1655720865095
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
'vans',
new TableColumn({
name: 'user_id',
type: 'uuid',
isNullable: true,
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn('vans', 'user_id');
}
}

View File

@@ -0,0 +1,24 @@
import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm';
export class AddFKUserIdToVansTable1655720873936 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createForeignKey(
'vans',
new TableForeignKey({
name: 'UserIdVan', // nome da FK, serve para referenciar numa exclusão pelo QueryRunner se necessário
columnNames: ['user_id'], // coluna que vai virar FK
referencedColumnNames: ['id_user'], // coluna PK da primeira tabela
referencedTableName: 'users', // nome da tabela que possui a PK
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey(
'vans',
'UserIdVan',
);
}
}

View File

@@ -11,7 +11,7 @@ import {
import User from './User';
@Entity('socials')
@Entity('socialInformation')
class Social {
@PrimaryGeneratedColumn('increment')
id_social: string;
@@ -21,16 +21,16 @@ class Social {
user: User;
@Column()
telegram: string;
phone: string;
@Column()
whatsapp: string;
@Column()
facebook: string;
@Column()
twitter: string;
@Column()
twitch: string;
telegram: string;
@CreateDateColumn()
created_at: Date;

View File

@@ -4,7 +4,9 @@ import {
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
OneToMany,
} from 'typeorm';
import Van from './Van';
@Entity('users')
class User {
@@ -38,6 +40,15 @@ class User {
@Column()
star_rating: number;
@Column()
document_type: string;
@Column()
document: string;
@OneToMany(() => Van, van => van.user)
van: Van[];
@CreateDateColumn()
created_at: Date;

58
src/models/Van.ts Normal file
View File

@@ -0,0 +1,58 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
JoinColumn,
OneToOne,
PrimaryColumn,
OneToMany,
ManyToOne,
} from 'typeorm';
import User from './User';
@Entity('vans')
class Van {
@PrimaryColumn()
plate: string;
@Column()
brand: string;
@Column()
model: string;
@Column()
seats_number: string;
@Column()
document_status: boolean
@Column()
locator_name: string;
@Column()
locator_address: string;
@Column()
locator_complement: string;
@Column()
locator_city: string;
@Column()
locator_state: string;
@ManyToOne(() => User, user => user.van)
@JoinColumn({ name: 'user_id' })
user: User;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
export default Van;

View File

@@ -5,6 +5,7 @@ import sessionsRouter from './sessions.routes';
import transportesRouter from './transportes.routes';
import usersRouter from './users.routes';
import carsRouter from './cars.routes';
import vansRouter from './vans.routes';
const routes = Router();
@@ -13,5 +14,6 @@ routes.use('/sessions', sessionsRouter);
routes.use('/search', searchRoutes);
routes.use('/transportes', transportesRouter);
routes.use('/cars', carsRouter);
routes.use('/vans', vansRouter);
export default routes;

View File

@@ -2,6 +2,8 @@ import { Router } from 'express';
import { getRepository } from 'typeorm';
import User from '../models/User';
import ensureAuthenticated from '../middlewares/ensureAuthenticated';
import CreateUserService from '../services/CreateUserService';
import FindUserService from '../services/FindUserService';
import FindUserSocialService from '../services/FindUserSocialService';
@@ -9,9 +11,8 @@ import UpdateUserSocialService from '../services/UpdateUserSocialService';
import UpdateUserService from '../services/UpdateUserService';
import UpdateUserAvatarService from '../services/UpdateUserAvatarService';
import UpdateUserPasswordService from '../services/UpdateUserPasswordService';
import ensureAuthenticated from '../middlewares/ensureAuthenticated';
import ensureAdmin from '../middlewares/ensureAdmin';
import AuthenticateUserService from '../services/AuthenticateUserService';
import CheckIfUserHasVansService from '../services/CheckIfUserHasVansService';
const usersRouter = Router();
@@ -29,44 +30,45 @@ usersRouter.get('/list', async (request, response) => {
let usersWithoutSensitiveInfo: userWithoutSensitiveInfo[] = [];
users.map(user => {
usersWithoutSensitiveInfo.push({
id_user: user.id_user,
name: user.name,
email: user.email,
avatar_image: user.avatar_image,
});
// users.map(user => {
// usersWithoutSensitiveInfo.push({
// id_user: user.id_user,
// name: user.name,
// email: user.email,
// avatar_image: user.avatar_image,
// });
// });
return response.json({ data: users });
});
return response.json({ data: usersWithoutSensitiveInfo });
});
// TODO, criar middleware ensureIsOwnUser é necessário?
// usar browserAgent, Encrypted Local Storage ou algo do tipo
usersRouter.get('/:id', ensureAuthenticated, async (request, response) => {
const { id } = request.params;
const findUser = new FindUserService();
const findUserService = new FindUserService();
const user = await findUser.execute(id);
const user = await findUserService.execute(id);
// converting ISO 8601 date to normal date
let birth_date = new Date(user.birth_date)
let birth_date = new Date(user.birth_date);
let year = birth_date.getFullYear()
let month = birth_date.getMonth()+1
let date = birth_date.getDate()
let year = birth_date.getFullYear();
let month = birth_date.getMonth() + 1;
let date = birth_date.getDate();
const finalDate = `${date}/${month}/${year}`
const finalDate = `${date}/${month}/${year}`;
const userWithoutPassword = {
id_user: user.id_user,
name: user.name,
lastname: user.lastname,
email: user.email,
phone_number: user.phone_number,
birth_date: finalDate,
avatar_image: user.avatar_image,
bio: user.bio,
document_type: user.document_type,
document: user.document,
// created_at: user.created_at,
// updated_at: user.updated_at,
};
@@ -77,9 +79,9 @@ usersRouter.get('/:id', ensureAuthenticated, async (request, response) => {
usersRouter.post('/', async (request, response) => {
const { name, lastname, email, birth_date, password } = request.body;
const createUser = new CreateUserService();
const createUserService = new CreateUserService();
const user = await createUser.execute({
const user = await createUserService.execute({
name,
lastname,
email,
@@ -98,7 +100,16 @@ usersRouter.post('/', async (request, response) => {
});
usersRouter.patch('/edit', ensureAuthenticated, async (request, response) => {
const { name, lastname, username, bio, email, birth_date } = request.body;
const {
name,
lastname,
bio,
email,
phone_number,
birth_date,
document_type,
document,
} = request.body;
const updateUserService = new UpdateUserService();
@@ -106,16 +117,37 @@ usersRouter.patch('/edit', ensureAuthenticated, async (request, response) => {
id_user: request.user.id_user,
name,
lastname,
username,
bio,
email,
phone_number,
birth_date,
document_type,
document,
});
return response.json({ message: 'User info sucessfully updated.' });
return response.json({ message: 'Perfil atualizado com sucesso.' });
});
usersRouter.patch('/edit/avatar', ensureAuthenticated, async (request, response) => {
usersRouter.get(
'/isDriver/:id_user',
ensureAuthenticated,
async (request, response) => {
const { id_user } = request.params;
const checkIfUserHasVansService = new CheckIfUserHasVansService();
const userHasVans = await checkIfUserHasVansService.execute({
id_user,
});
return response.json({ result: userHasVans });
},
);
usersRouter.patch(
'/edit/avatar',
ensureAuthenticated,
async (request, response) => {
const { avatar_image } = request.body;
const updateUserAvatarService = new UpdateUserAvatarService();
@@ -126,7 +158,8 @@ usersRouter.patch('/edit/avatar', ensureAuthenticated, async (request, response)
});
return response.json({ message: 'Avatar atualizado com sucesso !' });
});
},
);
usersRouter.get(
'/social/:id',
@@ -134,9 +167,9 @@ usersRouter.get(
async (request, response) => {
const { id } = request.params;
const findUserSocial = new FindUserSocialService();
const findUserSocialService = new FindUserSocialService();
const social = await findUserSocial.execute(id);
const social = await findUserSocialService.execute(id);
return response.json({ data: social });
},
@@ -177,4 +210,37 @@ usersRouter.patch(
},
);
usersRouter.get(
'/social/:id_user',
ensureAuthenticated,
async (request, response) => {
const { id_user } = request.params;
const findUserSocialService = new FindUserSocialService();
const social = await findUserSocialService.execute(id_user);
return response.json({ data: social });
},
);
usersRouter.patch('/social', ensureAuthenticated, async (request, response) => {
const { id_user, phone, whatsapp, facebook, telegram } = request.body;
const social_network = {
phone,
whatsapp,
facebook,
telegram,
};
const updateUserSocialService = new UpdateUserSocialService();
const social = await updateUserSocialService.execute({
id_user,
social_network,
});
return response.json({ data: social });
});
export default usersRouter;

142
src/routes/vans.routes.ts Normal file
View File

@@ -0,0 +1,142 @@
import { Router } from 'express';
import { getRepository } from 'typeorm';
import Van from '../models/Van';
import ensureAuthenticated from '../middlewares/ensureAuthenticated';
import FindVanService from '../services/FindVanService';
import CreateVanService from '../services/CreateVanService';
import UpdateVanService from '../services/UpdateVanService';
import UpdateVanPlateService from '../services/UpdateVanPlateService';
import FindVanByUserIdService from '../services/FindVansByUserIdService';
const vansRouter = Router();
vansRouter.get('/list', async (request, response) => {
const vansRepository = getRepository(Van);
const vans = await vansRepository.find();
return response.json({ data: vans });
});
vansRouter.get(
'/plate/:plate',
ensureAuthenticated,
async (request, response) => {
const { plate } = request.params;
const findVanService = new FindVanService();
const van = await findVanService.execute(plate);
return response.json({ data: van });
},
);
vansRouter.get(
'/user/:id_user',
async (request, response) => {
const { id_user } = request.params;
const findVanByUserIdService = new FindVanByUserIdService();
const vans = await findVanByUserIdService.execute(id_user);
return response.json({ data: vans });
},
);
vansRouter.post('/', ensureAuthenticated, async (request, response) => {
const {
plate,
brand,
model,
seats_number,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
} = request.body;
const createVanService = new CreateVanService();
console.log('aaaaaaaaaaaaaaa');
console.log(request.user);
const van = await createVanService.execute({
id_user: request.user.id_user,
plate,
brand,
model,
seats_number,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
});
return response.json({ message: 'Van criada com sucesso.', data: van });
});
vansRouter.patch(
'/edit/:plate',
ensureAuthenticated,
async (request, response) => {
const {
brand,
model,
seats_number,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
} = request.body;
const { plate } = request.params;
const updateVanService = new UpdateVanService();
await updateVanService.execute({
plate,
brand,
model,
seats_number,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
});
return response.json({
message: 'Informações da van atualizadas com sucesso.',
});
},
);
vansRouter.patch(
'/edit/plate/:plate',
ensureAuthenticated,
async (request, response) => {
const { newPlate } = request.body;
const { plate } = request.params;
const updateVanPlateService = new UpdateVanPlateService();
await updateVanPlateService.execute({
oldPlate: plate,
newPlate,
});
return response.json({
message: 'Placa da van atualizada com sucesso.',
});
},
);
export default vansRouter;

View File

@@ -20,8 +20,9 @@ createConnection();
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
if (err instanceof AppError) {
return response.status(err.statusCode).json({
return response.status(202).json({
status: 'error',
httpCode: err.statusCode,
message: err.message,
});
}

View File

@@ -0,0 +1,33 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Van from '../models/Van';
interface Request {
id_user: string;
}
class CheckIfUserHasVansService {
public async execute({ id_user }: Request): Promise<Boolean> {
const usersRepository = getRepository(User);
const vansRepository = getRepository(Van);
const user = await usersRepository.findOne({
where: { id_user },
});
if (!user) {
throw new AppError('O usuário informado não foi encontrado.', 404);
}
const vanExists = await vansRepository.findOne({
where: { user },
});
return !!vanExists
}
}
export default CheckIfUserHasVansService;

View File

@@ -5,7 +5,7 @@ import { hash } from 'bcryptjs';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/Social';
import Social from '../models/SocialInformation';
interface Request {
name: string;
@@ -18,7 +18,7 @@ interface Request {
class CreateUserService {
public async execute({ name, lastname, email, birth_date, password }: Request): Promise<User> {
const usersRepository = getRepository(User);
const socialsRepository = getRepository(Social);
const socialInformationRepository = getRepository(Social);
const checkUserEmailExists = await usersRepository.findOne({
where: { email },
@@ -39,10 +39,6 @@ class CreateUserService {
await usersRepository.save(user);
// já criar registro na tabela Socials para evitar inconsistências
// const social = socialsRepository.create({ user, telegram: "", facebook: "", twitter: "", twitch: "" });
// await socialsRepository.save(social);
return user;
}
}

View File

@@ -0,0 +1,79 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Van from '../models/Van';
interface Request {
id_user: string;
plate: string;
brand: string;
model: string;
seats_number: string;
locator_name: string;
locator_address: string;
locator_complement: string;
locator_city: string;
locator_state: string;
}
class CreateVanService {
public async execute({
id_user,
plate,
brand,
model,
seats_number,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
}: Request): Promise<Van> {
const vansRepository = getRepository(Van);
const usersRepository = getRepository(User);
const user = await usersRepository.findOne({
where: { id_user },
});
if (!user) {
throw new AppError(
'O usuário informado não foi encontrado.',
404,
);
}
const vanExists = await vansRepository.findOne({
where: { plate },
});
if (vanExists) {
throw new AppError(
'Uma van com a placa informada já foi cadastrada.',
409,
);
}
const van = vansRepository.create({
user,
plate,
brand,
model,
seats_number,
document_status: false,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
});
await vansRepository.save(van);
return van;
}
}
export default CreateVanService;

View File

@@ -3,30 +3,35 @@ import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/Social';
import Social from '../models/SocialInformation';
class FindUserSocialService {
public async execute(id_user: string): Promise<Social> {
const usersRepository = getRepository(User);
const socialRepository = getRepository(Social);
const socialInformationRepository = getRepository(Social);
const user = await usersRepository.findOne({
where: { id_user }
});
if (!user) {
// TODO, fazer no front um tratamento para isso
throw new AppError('User does not exist.');
};
const social = await socialRepository.findOne({
let social = await socialInformationRepository.findOne({
where: { user },
});
if (!social) {
// TODO, lembrar
// muito importate colocar o código HTTP de erro
throw new AppError('User does not have social information.', 200);
social = socialInformationRepository.create({
user,
phone: '',
whatsapp: '',
facebook: '',
telegram: '',
});
await socialInformationRepository.save(social);
};
return social;

View File

@@ -0,0 +1,25 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import Van from '../models/Van';
import VanLocator from '../models/VanLocator';
class FindVanLocatorService {
public async execute(id_van: string): Promise<VanLocator> {
const vansRepository = getRepository(Van);
const vansLocatorsRepository = getRepository(VanLocator);
const van = await vansRepository.findOne({
where: { id_van }
});
if (!van) {
throw new AppError('A Van informada não existe.', 404);
};
return van.locator;
}
}
export default FindVanLocatorService;

View File

@@ -0,0 +1,23 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import Van from '../models/Van';
class FindVanService {
public async execute(plate: string): Promise<Van> {
const vansRepository = getRepository(Van);
const van = await vansRepository.findOne({
where: { plate }
});
if (!van) {
throw new AppError('A van informada não existe.');
};
return van;
}
}
export default FindVanService;

View File

@@ -0,0 +1,33 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Van from '../models/Van';
class FindVanByUserIdService {
public async execute(id_user: string): Promise<Van[]> {
const usersRepository = getRepository(User);
const vansRepository = getRepository(Van);
const user = await usersRepository.findOne({
where: { id_user }
});
if (!user) {
throw new AppError('O usuário informado não existe.', 404);
};
const van = await vansRepository.find({
where: { user }
});
if (!van) {
throw new AppError('Não há nenhuma van cadastrada para esse usuário.');
};
return van;
}
}
export default FindVanByUserIdService;

View File

@@ -3,7 +3,7 @@ import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/Social';
import Social from '../models/SocialInformation';
interface Request {
id_user: string;

View File

@@ -4,7 +4,7 @@ import { hash, compare } from 'bcryptjs';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/Social';
import Social from '../models/SocialInformation';
interface Request {
id_user: string;

View File

@@ -3,35 +3,52 @@ import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/Social';
import Social from '../models/SocialInformation';
interface Request {
id_user: string;
name: string;
lastname: string;
username: string;
bio: string;
email: string;
phone_number: string;
birth_date: string;
document_type: string;
document: string;
}
class UpdateUserService {
public async execute({ id_user, name, lastname, username, bio, email, birth_date }: Request): Promise<User> {
public async execute({ id_user, name, lastname, bio, email, phone_number, birth_date, document_type, document }: Request): Promise<User> {
const usersRepository = getRepository(User);
const socialRepository = getRepository(Social);
const user = await usersRepository.findOne({
where: { id_user: id_user }
where: { id_user }
});
if (!user) {
throw new AppError('User does not exist.');
throw new AppError('O usuário informado não existe.', 404);
};
user.name = name
user.lastname = lastname
user.bio = bio
user.email = email
if (name) user.name = name
if (lastname) user.lastname = lastname
if (bio) user.bio = bio
if (email) user.email = email
if (phone_number) {
const phoneAlreadyExists = await usersRepository.findOne({
where: { phone_number }
});
if (phoneAlreadyExists) {
throw new AppError('O telefone informado já está em uso por outra conta!', 409);
}
}
user.phone_number = phone_number
if (document_type) user.document_type = document_type
if (document) user.document = document
// user.birth_date = new Date(birth_date); // TODO, funciona?

View File

@@ -0,0 +1,66 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/SocialInformation';
interface Request {
id_user: string;
social_info_request: {
phone?: string;
whatsapp?: string;
facebook?: string;
telegram?: string;
};
username: string;
}
class UpdateUserSocialService {
public async execute({
id_user,
social_info_request,
username,
}: Request): Promise<Social> {
const usersRepository = getRepository(User);
const socialInformationRepository = getRepository(Social);
const user = await usersRepository.findOne({
where: { id_user },
});
if (!user) {
throw new AppError('User does not exist.', 404);
}
let social = await socialInformationRepository.findOne({
where: { user },
});
if (!social) {
social = socialInformationRepository.create({ user, phone: "", whatsapp: "", facebook: "", telegram: "" });
}
if (social_info_request.phone) {
social.phone = social_info_request.phone
}
if (social_info_request.whatsapp) {
social.whatsapp = social_info_request.whatsapp
}
if (social_info_request.facebook) {
social.facebook = social_info_request.facebook
}
if (social_info_request.telegram) {
social.telegram = social_info_request.telegram
}
await socialInformationRepository.save(social);
return social;
}
}
export default UpdateUserSocialService;

View File

@@ -3,54 +3,51 @@ import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import User from '../models/User';
import Social from '../models/Social';
import Social from '../models/SocialInformation';
interface Request {
id_user: string;
social_network: string;
social_network: {
phone: string;
whatsapp: string;
facebook: string;
telegram: string;
};
}
class UpdateUserSocialService {
public async execute({
id_user,
social_network,
}: Request): Promise<Social> {
public async execute({ id_user, social_network }: Request): Promise<Social> {
const usersRepository = getRepository(User);
const socialRepository = getRepository(Social);
const socialInformationRepository = getRepository(Social);
const user = await usersRepository.findOne({
where: { id_user: id_user },
where: { id_user },
});
if (!user) {
throw new AppError('User does not exist.');
}
const social = await socialRepository.findOne({
where: { user: user },
let social = await socialInformationRepository.findOne({
where: { user },
});
if (!social) throw new AppError('User does not exist.');
switch (social_network) {
case 'telegram':
social.telegram = "";
break;
case 'facebook':
social.facebook = "";
break;
case 'twitter':
social.twitter = "";
break;
case 'twitch':
social.twitch = "";
break;
default:
break;
if (!social) {
social = socialInformationRepository.create({
user,
phone: '',
whatsapp: '',
facebook: '',
telegram: '',
});
}
await socialRepository.save(social);
if (social_network.phone) social.phone = social_network.phone;
if (social_network.whatsapp) social.whatsapp = social_network.whatsapp;
if (social_network.facebook) social.facebook = social_network.facebook;
if (social_network.telegram) social.telegram = social_network.telegram;
await socialInformationRepository.save(social);
return social;
}

View File

@@ -0,0 +1,32 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import Van from '../models/Van';
interface Request {
oldPlate: string;
newPlate: string;
}
class UpdateVanPlateService {
public async execute({ oldPlate, newPlate }: Request): Promise<Van> {
const vansRepository = getRepository(Van);
const van = await vansRepository.findOne({
where: { plate: oldPlate },
});
if (!van) {
throw new AppError('A van informada não existe.');
}
van.plate = newPlate
await vansRepository.save(van);
return van;
}
}
export default UpdateVanPlateService;

View File

@@ -0,0 +1,56 @@
import { getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import Van from '../models/Van';
interface Request {
plate: string;
brand?: string;
model?: string;
seats_number?: string;
locator_name?: string;
locator_address?: string;
locator_complement?: string;
locator_city?: string;
locator_state?: string;
}
class UpdateVanService {
public async execute({
plate,
brand,
model,
seats_number,
locator_name,
locator_address,
locator_complement,
locator_city,
locator_state,
}: Request): Promise<Van> {
const vansRepository = getRepository(Van);
const van = await vansRepository.findOne({
where: { plate },
});
if (!van) {
throw new AppError('A van informada não existe.');
}
if (brand) van.brand = brand
if (model) van.model = model
if (seats_number) van.seats_number = seats_number
if (locator_name) van.locator_name = locator_name
if (locator_address) van.locator_address = locator_address
if (locator_complement) van.locator_complement = locator_complement
if (locator_city) van.locator_city = locator_city
if (locator_state) van.locator_state = locator_state
await vansRepository.save(van);
return van;
}
}
export default UpdateVanService;

1190
yarn.lock

File diff suppressed because it is too large Load Diff