Initial commit
This commit is contained in:
commit
48ed7fe65e
209 files changed
+49979
No files matched your search
@@ -0,0 +1,65 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import db from '../db/index.js';
|
||||
import { HttpError } from '../middleware/errorHandler.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
const DEFAULT_CATEGORIES = [
|
||||
'Crowdfunding immobilier',
|
||||
'Dette privée',
|
||||
'Immobilier fractionné',
|
||||
'P2P Crowdlending',
|
||||
];
|
||||
|
||||
/** Insère les catégories par défaut si l'utilisateur n'en a aucune. */
|
||||
function seedDefaults(userId) {
|
||||
const { n } = db
|
||||
.prepare('SELECT COUNT(*) AS n FROM categories_plateforme WHERE user_id=?')
|
||||
.get(userId);
|
||||
if (n === 0) {
|
||||
const ins = db.prepare(
|
||||
'INSERT OR IGNORE INTO categories_plateforme (user_id, nom) VALUES (?,?)'
|
||||
);
|
||||
db.transaction((uid) => {
|
||||
for (const nom of DEFAULT_CATEGORIES) ins.run(uid, nom);
|
||||
})(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/* GET /api/categories — liste (avec auto-seed au premier appel) */
|
||||
router.get('/', (req, res) => {
|
||||
seedDefaults(req.user.id);
|
||||
const rows = db
|
||||
.prepare('SELECT id, nom FROM categories_plateforme WHERE user_id=? ORDER BY nom')
|
||||
.all(req.user.id);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
/* POST /api/categories — créer une catégorie */
|
||||
router.post('/', (req, res, next) => {
|
||||
try {
|
||||
const { nom } = z.object({ nom: z.string().min(1).max(100) }).parse(req.body);
|
||||
const r = db
|
||||
.prepare('INSERT INTO categories_plateforme (user_id, nom) VALUES (?,?)')
|
||||
.run(req.user.id, nom.trim());
|
||||
res.status(201).json({ id: r.lastInsertRowid, nom: nom.trim() });
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
/* DELETE /api/categories/:id — supprimer (bloqué si utilisée) */
|
||||
router.delete('/:id', (req, res, next) => {
|
||||
try {
|
||||
const { n } = db
|
||||
.prepare('SELECT COUNT(*) AS n FROM plateforme_categories WHERE categorie_id=?')
|
||||
.get(req.params.id);
|
||||
if (n > 0) throw new HttpError(409, `Catégorie utilisée par ${n} plateforme(s) — retirez-la d'abord.`);
|
||||
const r = db
|
||||
.prepare('DELETE FROM categories_plateforme WHERE id=? AND user_id=?')
|
||||
.run(req.params.id, req.user.id);
|
||||
if (r.changes === 0) throw new HttpError(404, 'Not found');
|
||||
res.status(204).end();
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
export default router;
|
||||
Reference in new issue
Block a user