const categoriaModel = require("../database/models/categoria.model.js");
const itemModel = require("../database/models/item.model.js");
const listarItems = async (args) => {
let items = [];
if (args.categoria) {
// Primero buscar la categoría por nombre
const categoria = await categoriaModel.findOne({ nombre: args.categoria });
if (!categoria) {
return {
content: [
{
type: "text",
text: JSON.stringify(
{
mensaje: `Categoría '${args.categoria}' no encontrada`,
items: [],
},
null,
2
),
},
],
};
}
// Buscar items por el ObjectId de la categoría y hacer populate
items = await itemModel
.find({ categoria: categoria._id })
.populate("categoria");
} else {
// Si no hay filtro de categoría, traer todos los items
items = await itemModel.find().populate("categoria");
}
return {
content: [
{
type: "text",
text: JSON.stringify(items, null, 2),
},
],
};
};
/**
* Busca items por nombre (case-insensitive)
*/
const buscarItem = async (args) => {
// Búsqueda case-insensitive usando regex
const itemsEncontrados = await itemModel
.find({
nombre: { $regex: args.nombre, $options: "i" },
})
.populate("categoria");
if (itemsEncontrados.length === 0) {
return {
content: [
{
type: "text",
text: JSON.stringify({ mensaje: "No se encontraron items" }, null, 2),
},
],
};
}
return {
content: [
{
type: "text",
text: JSON.stringify(itemsEncontrados, null, 2),
},
],
};
};
/**
* Cuenta items y calcula totales
*/
const contarItems = async () => {
const items = await itemModel.find();
const totalItems = items.length;
const cantidadTotal = items.reduce((sum, item) => sum + item.cantidad, 0);
const valorTotal = items.reduce(
(sum, item) => sum + item.cantidad * item.precio,
0
);
return {
content: [
{
type: "text",
text: JSON.stringify(
{
total_productos: totalItems,
cantidad_total: cantidadTotal,
valor_total: valorTotal,
moneda: "USD",
},
null,
2
),
},
],
};
};
/**
* Crea uno o más items
*/
const crearItems = async (args) => {
const nuevosItems = args.items;
if (!Array.isArray(nuevosItems) || nuevosItems.length === 0) {
throw new Error("Debe proporcionar al menos un item");
}
const itemsCreados = [];
for (const [index, item] of nuevosItems.entries()) {
if (
!item.nombre ||
!item.categoria ||
typeof item.cantidad !== "number" ||
typeof item.precio !== "number"
) {
throw new Error(
`Item en posición ${index} tiene datos inválidos. Asegúrese de incluir nombre, categoría, cantidad y precio.`
);
}
// Buscar o crear la categoría
let categoria = await categoriaModel.findOne({ nombre: item.categoria });
if (!categoria) {
categoria = new categoriaModel({ nombre: item.categoria });
await categoria.save();
}
// Crear el item
const nuevoItem = new itemModel({
nombre: item.nombre,
categoria: categoria._id,
cantidad: item.cantidad,
precio: item.precio,
});
await nuevoItem.save();
itemsCreados.push(nuevoItem);
}
const totalItems = await itemModel.countDocuments();
return {
content: [
{
type: "text",
text: JSON.stringify(
{
mensaje: `${nuevosItems.length} items creados exitosamente.`,
items_creados: itemsCreados,
items_total: totalItems,
},
null,
2
),
},
],
};
};
/**
* Elimina un item por ID
*/
const eliminarItem = async (args) => {
const item = await itemModel.findByIdAndDelete(args.id);
if (!item) {
throw new Error(`Item con ID ${args.id} no encontrado.`);
}
return {
content: [
{
type: "text",
text: JSON.stringify(
{
mensaje: `Item con ID ${args.id} eliminado exitosamente.`,
item_eliminado: item,
},
null,
2
),
},
],
};
};
/**
* Actualiza un item por ID
*/
const actualizarItem = async (args) => {
const item = await itemModel.findById(args.id);
if (!item) {
throw new Error(`Item con ID ${args.id} no encontrado.`);
}
if (args.nombre) item.nombre = args.nombre;
if (typeof args.cantidad === "number") item.cantidad = args.cantidad;
if (typeof args.precio === "number") item.precio = args.precio;
// Si se actualiza la categoría, buscar o crear
if (args.categoria) {
let categoria = await categoriaModel.findOne({ nombre: args.categoria });
if (!categoria) {
categoria = new categoriaModel({ nombre: args.categoria });
await categoria.save();
}
item.categoria = categoria._id;
}
await item.save();
const itemActualizado = await itemModel.findById(args.id).populate("categoria");
return {
content: [
{
type: "text",
text: JSON.stringify(
{
mensaje: `Item con ID ${args.id} actualizado exitosamente.`,
item_actualizado: itemActualizado,
},
null,
2
),
},
],
};
};
module.exports = {
listarItems,
buscarItem,
contarItems,
crearItems,
eliminarItem,
actualizarItem,
};