resman/backend/controllers/resourceController.js
2026-03-10 14:46:47 +01:00

168 lines
2.5 KiB
JavaScript

const pool = require("../db");
/* ACTIVE */
exports.getActive = async (req,res)=>{
const [rows] = await pool.query(`
SELECT
r.*,
JSON_ARRAYAGG(
JSON_OBJECT(
'id', ip.id,
'ip', ip.ip,
'type', ip.type,
'comment', ip.comment
)
) AS ips
FROM resources r
LEFT JOIN resource_ips ip ON r.id = ip.resource_id
WHERE r.status != 'gekündigt'
GROUP BY r.id
`);
rows.forEach(r=>{
/* JSON string → array */
if(typeof r.ips === "string"){
try{
r.ips = JSON.parse(r.ips);
}catch{
r.ips=[];
}
}
/* remove null entries */
if(r.ips && r.ips[0] && r.ips[0].id === null){
r.ips=[];
}
});
res.json(rows);
};
/* CANCELLED */
exports.getCancelled = async (req,res)=>{
const [rows] = await pool.query(`
SELECT
r.*,
JSON_ARRAYAGG(
JSON_OBJECT(
'id', ip.id,
'ip', ip.ip,
'type', ip.type,
'comment', ip.comment
)
) AS ips
FROM resources r
LEFT JOIN resource_ips ip ON r.id = ip.resource_id
WHERE r.status = 'gekündigt'
GROUP BY r.id
`);
rows.forEach(r=>{
if(typeof r.ips === "string"){
try{
r.ips = JSON.parse(r.ips);
}catch{
r.ips=[];
}
}
if(r.ips && r.ips[0] && r.ips[0].id === null){
r.ips=[];
}
});
res.json(rows);
};
/* CREATE */
exports.create = async (req,res)=>{
const clean = v => v === "" ? null : v;
function decimal(val){
if(!val) return null
return String(val).replace(",", ".")
}
const data = {
name: req.body.name,
produkt: clean(req.body.produkt),
provider: clean(req.body.provider),
art: clean(req.body.art),
cpu: clean(req.body.cpu),
ram: clean(req.body.ram),
disk: clean(req.body.disk),
os: clean(req.body.os),
ipv6_net: clean(req.body.ipv6_net),
providername: clean(req.body.providername),
kosten_monat: decimal(req.body.kosten_monat),
kosten_jahr: decimal(req.body.kosten_jahr),
laufzeit_monate: clean(req.body.laufzeit_monate),
bestelldatum: clean(req.body.bestelldatum),
kuendbar_ab: clean(req.body.kuendbar_ab),
status: clean(req.body.status),
kuendigungsdatum: clean(req.body.kuendigungsdatum),
bemerkung: clean(req.body.bemerkung)
};
await pool.query("INSERT INTO resources SET ?",data);
res.json({message:"created"});
};
/* UPDATE */
exports.update = async (req,res)=>{
const clean = v => v === "" ? null : v;
Object.keys(req.body).forEach(k=>{
req.body[k]=clean(req.body[k]);
});
await pool.query(
"UPDATE resources SET ? WHERE id=?",
[req.body,req.params.id]
);
res.json({message:"updated"});
};
/* DELETE */
exports.remove = async (req,res)=>{
await pool.query(
"DELETE FROM resources WHERE id=?",
[req.params.id]
);
res.json({message:"deleted"});
};