-
-
Notifications
You must be signed in to change notification settings - Fork 83
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(carrinhos): implementação do GET e POST da rota /carrinhos
- Loading branch information
1 parent
3935ded
commit b888561
Showing
14 changed files
with
254 additions
and
8 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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,96 @@ | ||
'use strict' | ||
|
||
const authService = require('../services/auth-service') | ||
const constant = require('../utils/constants') | ||
const produtosService = require('../services/produtos-service') | ||
const service = require('../services/carrinhos-service') | ||
const usuariosService = require('../services/usuarios-service') | ||
|
||
exports.get = async (req, res) => { | ||
try { | ||
const carrinhos = await service.getAll(req.query) | ||
res.status(200).send({ quantidade: carrinhos.length, carrinhos }) | ||
} catch (error) { | ||
res.status(500).send({ message: constant.INTERNAL_ERROR, error }) | ||
} | ||
} | ||
|
||
/* | ||
X 1 carrinho por user | ||
X validar idproduto | ||
X verificar estoque do produto | ||
X subtrair estoque do produto | ||
X pegar e cadastrar idUsuario | ||
X pegar e cadastrar preço do produto | ||
*/ | ||
|
||
exports.post = async (req, res) => { | ||
try { | ||
const { email, password } = authService.verifyToken(req.headers.authorization) | ||
const { _id } = await usuariosService.getDadosDoUsuario({ email, password }) | ||
const usuarioJaPossuiCarrinho = await service.existeCarrinho({ idusuario: _id }) | ||
|
||
if (usuarioJaPossuiCarrinho) { | ||
return res.status(400).send({ message: constant.USUARIO_POSSUI_CARRINHO }) | ||
} | ||
|
||
const produtos = req.body.produtos | ||
for (let index = 0; index < produtos.length; index++) { | ||
const { idproduto, quantidade } = produtos[index] | ||
if (!await produtosService.existeProduto({ _id: idproduto })) { | ||
return res.status(400).send({ message: constant.IDPRODUTO_INVALIDO, item: { index, idproduto, quantidade } }) | ||
} | ||
|
||
const { quantidade: quantidadeEmEstoque, preco } = await produtosService.getDadosDoProduto({ _id: idproduto }) | ||
if (quantidade > quantidadeEmEstoque) { | ||
return res.status(400).send({ message: constant.ESTOQUE_INSUFICIENTE, item: { index, idproduto, quantidade, quantidadeEmEstoque } }) | ||
} | ||
Object.assign(produtos[index], { precounitario: preco }) | ||
} | ||
let precototal = 0 | ||
for (let index = 0; index < produtos.length; index++) { | ||
const { idproduto, quantidade } = produtos[index] | ||
const { quantidade: quantidadeEmEstoque, preco } = await produtosService.getDadosDoProduto({ _id: idproduto }) | ||
const novaQuantidade = quantidadeEmEstoque - quantidade | ||
await produtosService.updateById(idproduto, { $set: { quantidade: novaQuantidade } }) | ||
precototal += preco * quantidade | ||
} | ||
|
||
Object.assign(req.body, { precototal, idusuario: _id }) | ||
|
||
const dadosCadastrados = await service.criarCarrinho(req.body) | ||
res.status(201).send({ message: constant.POST_SUCESS, _id: dadosCadastrados._id }) | ||
} catch (error) { | ||
res.status(500).send({ message: constant.INTERNAL_ERROR, error }) | ||
} | ||
} | ||
|
||
// user tem que ser dono do carrinho | ||
|
||
// exports.delete = async (req, res) => { | ||
// try { | ||
// const quantidadeRegistrosExcluidos = await service.deleteById(req.params.id) | ||
// const message = quantidadeRegistrosExcluidos === 0 ? constant.DELETE_NONE : constant.DELETE_SUCESS | ||
// res.status(200).send({ message }) | ||
// } catch (error) { | ||
// res.status(500).send({ message: constant.INTERNAL_ERROR, error }) | ||
// } | ||
// } | ||
|
||
/* | ||
se user tiver carrinho > edita | ||
se user n tiver carrinho > cadastra | ||
verificar estoque do produto | ||
pegar e cadastrar idUsuario | ||
pegar e cadastrar preço do produto | ||
*/ | ||
|
||
// exports.put = async (req, res) => { | ||
// try { | ||
// const registroCriado = await service.createOrUpdateById(req.params.id, req.body) | ||
// if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) } | ||
// res.status(200).send({ message: constant.PUT_SUCESS }) | ||
// } catch (error) { | ||
// res.status(500).send({ message: constant.INTERNAL_ERROR, error }) | ||
// } | ||
// } |
This file contains 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 @@ | ||
{"produtos":[{"idproduto":"BeeJh5lz3k6kSIzA","quantidade":1,"precounitario":123}],"precototal":123,"idusuario":"oUb7aGkMtSEPf6BZ","_id":"8y7oMpY9tWFXUQWY"} |
This file contains 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 @@ | ||
{"nome":"Logitech MX Vertical","preco":123,"descricao":"Mouse bom","quantidade":383,"_id":"BeeJh5lz3k6kSIzA"} |
This file contains 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 @@ | ||
{"nome":"Paulo","email":"paulo@g.com","password":"teste","administrador":"true","_id":"oUb7aGkMtSEPf6BZ","createdAt":{"$$date":1588459955988},"updatedAt":{"$$date":1588459992115}} |
This file contains 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,37 @@ | ||
'use strict' | ||
|
||
const { Joi } = require('express-validation') | ||
|
||
exports.schemaGet = { | ||
query: Joi.object({ | ||
_id: Joi.any(), | ||
produtos: Joi.any(), | ||
idusuario: Joi.any(), | ||
idproduto: Joi.any(), | ||
quantidade: Joi.any(), | ||
precounitario: Joi.any(), | ||
precototal: Joi.any() | ||
}) | ||
} | ||
|
||
exports.schemaPost = { | ||
body: Joi.object({ | ||
produtos: Joi.array().unique('idproduto').items( | ||
Joi.object({ | ||
idproduto: Joi.string().required(), | ||
quantidade: Joi.number().positive().integer().required() | ||
}).required() | ||
).required() | ||
}) | ||
} | ||
|
||
exports.schemaDelete = { | ||
params: Joi.object({ | ||
id: Joi.string().required() | ||
}) | ||
} | ||
|
||
exports.schemaPut = { | ||
params: this.schemaDelete.params, | ||
body: this.schemaPost.body | ||
} |
This file contains 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,16 @@ | ||
'use strict' | ||
|
||
const express = require('express') | ||
|
||
const authController = require('../controllers/auth-controller') | ||
const controller = require('../controllers/carrinhos-controller') | ||
const model = require('../models/carrinhos-model') | ||
const validateSchema = require('../services/validateSchema-service') | ||
|
||
const router = express.Router() | ||
router.get('/', validateSchema(model.schemaGet), controller.get) | ||
router.post('/', authController.checkToken, validateSchema(model.schemaPost), controller.post) | ||
// router.delete('/:id', authController.checkAdm, validateSchema(model.schemaDelete), controller.delete) | ||
// router.put('/:id', authController.checkAdm, validateSchema(model.schemaPut), controller.put) | ||
|
||
module.exports = router |
This file contains 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
This file contains 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,60 @@ | ||
'use strict' | ||
|
||
const Nedb = require('nedb') | ||
const { join } = require('path') | ||
|
||
const datastore = new Nedb({ filename: join(__dirname, '../data/carrinhos.db'), autoload: true }) | ||
|
||
exports.getAll = queryString => { | ||
return new Promise((resolve, reject) => { | ||
datastore.find(queryString, (err, resultado) => { | ||
if (err) reject(err) | ||
else resolve(resultado) | ||
}) | ||
}) | ||
} | ||
|
||
exports.existeCarrinho = pesquisa => { | ||
return new Promise((resolve, reject) => { | ||
datastore.count(pesquisa, (err, count) => { | ||
if (err) reject(err) | ||
else resolve(count !== 0) | ||
}) | ||
}) | ||
} | ||
|
||
exports.criarCarrinho = async body => { | ||
// body = formatarValores(body) | ||
return new Promise((resolve, reject) => { | ||
datastore.insert(body, (err, novoProduto) => { | ||
if (err) reject(err) | ||
else resolve(novoProduto) | ||
}) | ||
}) | ||
} | ||
|
||
// exports.deleteById = async id => { | ||
// return new Promise((resolve, reject) => { | ||
// datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => { | ||
// if (err) reject(err) | ||
// else resolve(quantidadeRegistrosExcluidos) | ||
// }) | ||
// }) | ||
// } | ||
|
||
// exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => { | ||
// body = formatarValores(body) | ||
// return new Promise((resolve, reject) => { | ||
// datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => { | ||
// if (err) reject(err) | ||
// else resolve(registroCriado) | ||
// }) | ||
// }) | ||
// } | ||
|
||
// function formatarValores (body) { | ||
// body.nome = body.nome.trim() | ||
// body.preco = parseInt(body.preco) | ||
// body.quantidade = parseInt(body.quantidade) | ||
// return body | ||
// } |
This file contains 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
This file contains 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
This file contains 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