112 lines
2.6 KiB
JavaScript
112 lines
2.6 KiB
JavaScript
const router = require("express").Router();
|
|
const ahorro = require("../models/ahorros").Ahorro;
|
|
const itemAhorro = require("../models/ahorros").itemAhorro;
|
|
const { checkAuth } = require("../middlewares/authentication");
|
|
|
|
router.get("/ahorro", checkAuth, async (req, res) => {
|
|
var ahorros;
|
|
let limite = req.get('limite');
|
|
ahorros = await ahorro.find({ user: req.userData._id }).sort({
|
|
date: "desc",
|
|
}).limit(parseInt(limite));
|
|
|
|
|
|
return res.send({
|
|
status: "ok",
|
|
data: ahorros,
|
|
});
|
|
});
|
|
|
|
router.post("/ahorro", checkAuth, async (req, res) => {
|
|
const { nombreAhorro,detalleAhorro } = req.body;
|
|
|
|
var ahorros = await ahorro.find({
|
|
user: req.userData._id,
|
|
nombreAhorro: nombreAhorro,
|
|
});
|
|
|
|
if (ahorros.length == 0) {
|
|
const Ahorro = new ahorro({
|
|
nombreAhorro: nombreAhorro,
|
|
detalleAhorro:detalleAhorro,
|
|
});
|
|
|
|
console.log(Ahorro);
|
|
Ahorro.user = req.userData._id;
|
|
await Ahorro.save();
|
|
|
|
return res.json({
|
|
status: "OK",
|
|
});
|
|
}
|
|
|
|
return res.status(500).json({
|
|
status: "FAIL",
|
|
});
|
|
});
|
|
|
|
router.delete("/ahorro", checkAuth, async (req, res) => {
|
|
try {
|
|
const userId = req.userData._id;
|
|
const id = req.query.id;
|
|
|
|
const resultado = await ahorro.deleteOne({ user: userId, _id: id });
|
|
|
|
return res.json({ status: "ok", data: resultado });
|
|
} catch (error) {
|
|
console.log(error);
|
|
return res.status(500).json({ status: "fail", error: error });
|
|
}
|
|
});
|
|
|
|
router.put("/ahorro", checkAuth, async (req, res) => {
|
|
const { _id, detalle, valor, tipo } = req.body;
|
|
const ahorro_edit = await ahorro.findOne({
|
|
_id: _id,
|
|
user: req.userData._id,
|
|
});
|
|
const itemP = new itemAhorro({ detalle, valor, tipo });
|
|
ahorro_edit.datos.push(itemP);
|
|
await ahorro_edit.save();
|
|
|
|
res.json({
|
|
status: "OK",
|
|
});
|
|
});
|
|
|
|
router.get("/ahorro_items", checkAuth, async (req, res) => {
|
|
const _id = req.query.ahorro_id;
|
|
const ahorro_edit = await ahorro.findOne({
|
|
_id: _id,
|
|
user: req.userData._id,
|
|
});
|
|
|
|
return res.json({
|
|
status: "OK",
|
|
data: ahorro_edit.datos,
|
|
});
|
|
});
|
|
|
|
router.delete("/ahorroitem", checkAuth, async (req, res) => {
|
|
try {
|
|
const userId = req.userData._id;
|
|
|
|
const iditem = req.query.iditem;
|
|
const idAhorro = req.query.idAhorro;
|
|
|
|
var ahorro_edit = await ahorro.findOne({
|
|
user: userId,
|
|
_id: idAhorro,
|
|
});
|
|
ahorro_edit.datos.id(iditem).remove();
|
|
await ahorro_edit.save();
|
|
|
|
return res.json({ status: "ok" });
|
|
} catch (error) {
|
|
console.log(error);
|
|
return res.status(500).json({ status: "fail", error: error });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|