98 lines
3.1 KiB
JavaScript
98 lines
3.1 KiB
JavaScript
const db = require('../config/db');
|
|
|
|
class Herramienta {
|
|
static async findAll(companyId, filtros = {}) {
|
|
let sql = 'SELECT * FROM herramientas WHERE company_id = ?';
|
|
const params = [companyId];
|
|
|
|
if (filtros.estado) {
|
|
sql += ' AND estado = ?';
|
|
params.push(filtros.estado);
|
|
}
|
|
if (filtros.categoria) {
|
|
sql += ' AND categoria = ?';
|
|
params.push(filtros.categoria);
|
|
}
|
|
if (filtros.buscar) {
|
|
sql += ' AND (nombre LIKE ? OR codigo LIKE ? OR numero_serie LIKE ? OR marca LIKE ?)';
|
|
const term = `%${filtros.buscar}%`;
|
|
params.push(term, term, term, term);
|
|
}
|
|
|
|
sql += ' ORDER BY id DESC';
|
|
const [rows] = await db.query(sql, params);
|
|
return rows;
|
|
}
|
|
|
|
static async findById(id, companyId) {
|
|
const [rows] = await db.query(
|
|
'SELECT * FROM herramientas WHERE id = ? AND company_id = ?',
|
|
[id, companyId]
|
|
);
|
|
return rows[0] || null;
|
|
}
|
|
|
|
static async create(data) {
|
|
const {
|
|
company_id,
|
|
nombre,
|
|
codigo = null,
|
|
numero_serie = null,
|
|
categoria = 'general',
|
|
marca = null,
|
|
modelo = null,
|
|
estado = 'operativo',
|
|
ubicacion_bodega = null,
|
|
notas = null,
|
|
foto_url = null
|
|
} = data;
|
|
|
|
const [result] = await db.query(
|
|
`INSERT INTO herramientas
|
|
(company_id, nombre, codigo, numero_serie, categoria, marca, modelo, estado, ubicacion_bodega, notas, foto_url)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
[company_id, nombre, codigo, numero_serie, categoria, marca, modelo, estado, ubicacion_bodega, notas, foto_url]
|
|
);
|
|
return result.insertId;
|
|
}
|
|
|
|
static async update(id, companyId, data) {
|
|
const fields = [];
|
|
const values = [];
|
|
|
|
const allowed = ['nombre', 'codigo', 'numero_serie', 'categoria', 'marca', 'modelo', 'estado', 'ubicacion_bodega', 'notas', 'foto_url'];
|
|
for (const [key, val] of Object.entries(data)) {
|
|
if (allowed.includes(key)) {
|
|
fields.push(`${key} = ?`);
|
|
values.push(val);
|
|
}
|
|
}
|
|
|
|
if (fields.length === 0) return;
|
|
values.push(id, companyId);
|
|
|
|
await db.query(`UPDATE herramientas SET ${fields.join(', ')} WHERE id = ? AND company_id = ?`, values);
|
|
}
|
|
|
|
static async delete(id, companyId) {
|
|
await db.query('DELETE FROM herramientas WHERE id = ? AND company_id = ?', [id, companyId]);
|
|
}
|
|
|
|
static async countByEstado(companyId) {
|
|
const [rows] = await db.query(
|
|
'SELECT estado, COUNT(*) as count FROM herramientas WHERE company_id = ? GROUP BY estado',
|
|
[companyId]
|
|
);
|
|
const stats = { operativo: 0, en_mantenimiento: 0, danado: 0, baja: 0, total: 0 };
|
|
rows.forEach(r => {
|
|
if (stats[r.estado] !== undefined) {
|
|
stats[r.estado] = r.count;
|
|
}
|
|
stats.total += r.count;
|
|
});
|
|
return stats;
|
|
}
|
|
}
|
|
|
|
module.exports = Herramienta;
|