Skip to content

Commit

Permalink
feat: implementado DELETE 'cancelar-compra' e '/concluir-compra'
Browse files Browse the repository at this point in the history
  • Loading branch information
PauloGoncalvesBH committed May 5, 2020
1 parent 428202c commit 203c9ea
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 67 deletions.
72 changes: 34 additions & 38 deletions src/controllers/carrinhos-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,6 @@ exports.get = async (req, res) => {
}
}

/*
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)
Expand Down Expand Up @@ -73,35 +64,40 @@ exports.post = async (req, res) => {
}
}

/*
user tem que ser dono do carrinho ou adm
somar estoque do produto
*/
exports.cancelarCompra = async (req, res) => {
try {
const carrinhoDoUsuario = await service.getCarrinhoDoUsuario(req.headers.authorization)
const usuarioTemCarrinho = typeof carrinhoDoUsuario[0] !== 'undefined'

if (usuarioTemCarrinho) {
const produtos = carrinhoDoUsuario[0].produtos

// 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 })
// }
// }
produtos.forEach(async (produto) => {
const { idProduto, quantidade } = produto
const { quantidade: quantidadeEmEstoque } = await produtosService.getDadosDoProduto({ _id: idProduto })
await produtosService.updateById(idProduto, { $set: { quantidade: quantidadeEmEstoque + quantidade } })
})

/*
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
*/
await service.deleteById(carrinhoDoUsuario[0]._id)
return res.status(200).send({ message: `${constant.DELETE_SUCESS}. ${constant.ESTOQUE_REABASTECIDO}` })
}

// 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 })
// }
// }
res.status(200).send({ message: constant.SEM_CARRINHO })
} catch (error) {
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
}
}

exports.concluirCompra = async (req, res) => {
try {
const carrinhoDoUsuario = await service.getCarrinhoDoUsuario(req.headers.authorization)
const usuarioTemCarrinho = typeof carrinhoDoUsuario[0] !== 'undefined'
if (usuarioTemCarrinho) {
await service.deleteById(carrinhoDoUsuario[0]._id)
return res.status(200).send({ message: constant.DELETE_SUCESS })
}
res.status(200).send({ message: constant.SEM_CARRINHO })
} catch (error) {
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
}
}
4 changes: 2 additions & 2 deletions src/routes/carrinhos-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ 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)
router.delete('/concluir-compra', authController.checkToken, controller.concluirCompra)
router.delete('/cancelar-compra', authController.checkToken, controller.cancelarCompra)

module.exports = router
49 changes: 24 additions & 25 deletions src/services/carrinhos-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
const Nedb = require('nedb')
const { join } = require('path')

const authService = require('../services/auth-service')
const usuariosService = require('../services/usuarios-service')

const datastore = new Nedb({ filename: join(__dirname, '../data/carrinhos.db'), autoload: true })

exports.getAll = queryString => {
Expand Down Expand Up @@ -33,31 +36,27 @@ exports.criarCarrinho = async body => {
}

exports.extrairProdutosDuplicados = arrayProdutos => {
var sorted_arr = arrayProdutos.slice().sort();
var produtosDuplicados = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1].idProduto === sorted_arr[i].idProduto) {
produtosDuplicados.push(sorted_arr[i].idProduto);
}
var sortedArr = arrayProdutos.slice().sort()
var produtosDuplicados = []
for (var i = 0; i < sortedArr.length - 1; i++) {
if (sortedArr[i + 1].idProduto === sortedArr[i].idProduto) {
produtosDuplicados.push(sortedArr[i].idProduto)
}
}
return produtosDuplicados;
return produtosDuplicados
}

exports.deleteById = async id => {
return new Promise((resolve, reject) => {
datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
if (err) reject(err)
else resolve(quantidadeRegistrosExcluidos)
})
})
}

// 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)
// })
// })
// }
exports.getCarrinhoDoUsuario = async (authorization) => {
const { email, password } = authService.verifyToken(authorization)
const { _id: idUsuario } = await usuariosService.getDadosDoUsuario({ email, password })
return this.getAll({ idUsuario })
}
2 changes: 1 addition & 1 deletion src/utils/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async function tokenValido ({ authorization }) {
return false
}

return await existeUsuario({ email: tokenDecodificado.email, password: tokenDecodificado.password })
return existeUsuario({ email: tokenDecodificado.email, password: tokenDecodificado.password })
}

module.exports = {
Expand Down
4 changes: 3 additions & 1 deletion src/utils/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ module.exports = {
ESTOQUE_INSUFICIENTE: 'Produto não possui quantidade suficiente',
EXCLUIR_USUARIO_COM_CARRINHO: 'Não é permitido excluir usuário com carrinho cadastrado',
EXCLUIR_PRODUTO_COM_CARRINHO: 'Não é permitido excluir produto que faz parte de carrinho',
CARRINHO_COM_PRODUTO_DUPLICADO: 'Não é permitido possuir produto duplicado'
CARRINHO_COM_PRODUTO_DUPLICADO: 'Não é permitido possuir produto duplicado',
SEM_CARRINHO: 'Não foi encontrado carrinho para esse usuário',
ESTOQUE_REABASTECIDO: 'Estoque dos produtos reabastecido'
}

0 comments on commit 203c9ea

Please sign in to comment.