339 lines
14 KiB
TypeScript
339 lines
14 KiB
TypeScript
import { TRPCError } from "@trpc/server";
|
|
import { z } from "zod";
|
|
import {
|
|
createBlocFonctionnel,
|
|
createDemandeContact,
|
|
createEditeur,
|
|
createSolution,
|
|
deleteLogicielEtablissement,
|
|
getAllDemandes,
|
|
getAllEtablissements,
|
|
getAllUsers,
|
|
getBlocsFonctionnels,
|
|
getConsultationCount,
|
|
getConsultationsList,
|
|
getDemandeById,
|
|
getDemandesByDemandeur,
|
|
getDemandesRecuesParEtablissement,
|
|
getEditeurs,
|
|
getEtablissementById,
|
|
getEtablissementsByReferent,
|
|
getLogicielsByEtablissement,
|
|
getSolutions,
|
|
recordConsultation,
|
|
repondreDemandeContact,
|
|
updateUserCgu,
|
|
updateUserSonumRole,
|
|
upsertLogicielEtablissement,
|
|
upsertUser,
|
|
} from "./db";
|
|
import { COOKIE_NAME } from "@shared/const";
|
|
import { getSessionCookieOptions } from "./_core/cookies";
|
|
import { systemRouter } from "./_core/systemRouter";
|
|
import { protectedProcedure, publicProcedure, router } from "./_core/trpc";
|
|
import { notifyOwner } from "./_core/notification";
|
|
import { getDb } from "./db";
|
|
import { etablissements } from "../drizzle/schema";
|
|
import { eq } from "drizzle-orm";
|
|
|
|
// ─── Middleware gestionnaire SONUM ────────────────────────────────────────────
|
|
|
|
const gestionnaireProcedure = protectedProcedure.use(({ ctx, next }) => {
|
|
if (ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
|
throw new TRPCError({ code: "FORBIDDEN", message: "Accès réservé aux gestionnaires SONUM" });
|
|
}
|
|
return next({ ctx });
|
|
});
|
|
|
|
// ─── Router principal ─────────────────────────────────────────────────────────
|
|
|
|
export const appRouter = router({
|
|
system: systemRouter,
|
|
|
|
// ─── Auth ──────────────────────────────────────────────────────────────────
|
|
auth: router({
|
|
me: publicProcedure.query((opts) => opts.ctx.user),
|
|
logout: publicProcedure.mutation(({ ctx }) => {
|
|
const cookieOptions = getSessionCookieOptions(ctx.req);
|
|
ctx.res.clearCookie(COOKIE_NAME, { ...cookieOptions, maxAge: -1 });
|
|
return { success: true } as const;
|
|
}),
|
|
}),
|
|
|
|
// ─── CGU ───────────────────────────────────────────────────────────────────
|
|
cgu: router({
|
|
accept: protectedProcedure.mutation(async ({ ctx }) => {
|
|
await updateUserCgu(ctx.user.id);
|
|
return { success: true };
|
|
}),
|
|
status: protectedProcedure.query(({ ctx }) => ({
|
|
accepted: ctx.user.cguAccepted,
|
|
acceptedAt: ctx.user.cguAcceptedAt,
|
|
})),
|
|
}),
|
|
|
|
// ─── Référentiel ───────────────────────────────────────────────────────────
|
|
referentiel: router({
|
|
editeurs: publicProcedure.query(() => getEditeurs()),
|
|
blocsFonctionnels: publicProcedure.query(() => getBlocsFonctionnels()),
|
|
solutions: publicProcedure
|
|
.input(z.object({ search: z.string().optional() }))
|
|
.query(({ input }) => getSolutions(input.search)),
|
|
|
|
createEditeur: protectedProcedure
|
|
.input(z.object({ nom: z.string().min(1) }))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
|
return createEditeur(input.nom, isGestionnaire);
|
|
}),
|
|
|
|
createBlocFonctionnel: protectedProcedure
|
|
.input(z.object({ nom: z.string().min(1) }))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
|
return createBlocFonctionnel(input.nom, isGestionnaire);
|
|
}),
|
|
|
|
createSolution: protectedProcedure
|
|
.input(z.object({
|
|
nom: z.string().min(1),
|
|
editeurId: z.number().int(),
|
|
blocFonctionnelId: z.number().int().optional().nullable(),
|
|
}))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const isGestionnaire = ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
|
return createSolution(input.nom, input.editeurId, input.blocFonctionnelId, isGestionnaire);
|
|
}),
|
|
}),
|
|
|
|
// ─── Établissements ────────────────────────────────────────────────────────
|
|
etablissements: router({
|
|
mesEtablissements: protectedProcedure.query(({ ctx }) =>
|
|
getEtablissementsByReferent(ctx.user.id)
|
|
),
|
|
|
|
all: gestionnaireProcedure.query(() => getAllEtablissements()),
|
|
|
|
byId: protectedProcedure
|
|
.input(z.object({ id: z.number().int() }))
|
|
.query(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.id);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
// Vérifier visibilité
|
|
if (etab.visibilite === "gestionnaires" && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
|
if (etab.referentId !== ctx.user.id) {
|
|
throw new TRPCError({ code: "FORBIDDEN" });
|
|
}
|
|
}
|
|
return etab;
|
|
}),
|
|
|
|
search: protectedProcedure
|
|
.input(z.object({
|
|
solutionId: z.number().int().optional(),
|
|
editeurId: z.number().int().optional(),
|
|
blocFonctionnelId: z.number().int().optional(),
|
|
region: z.string().optional(),
|
|
typeActivite: z.string().optional(),
|
|
tailleEffectifs: z.string().optional(),
|
|
etatDeploiement: z.string().optional(),
|
|
}))
|
|
.query(({ input, ctx }) => {
|
|
return import("./db").then(({ searchEtablissements }) =>
|
|
searchEtablissements({
|
|
...input,
|
|
userId: ctx.user.id,
|
|
sonumRole: ctx.user.sonumRole,
|
|
})
|
|
);
|
|
}),
|
|
|
|
create: gestionnaireProcedure
|
|
.input(z.object({
|
|
finess: z.string().optional(),
|
|
nom: z.string().min(1),
|
|
region: z.string().optional(),
|
|
departement: z.string().optional(),
|
|
typeActivite: z.string().optional(),
|
|
tailleEffectifs: z.string().optional(),
|
|
referentId: z.number().int().optional(),
|
|
}))
|
|
.mutation(async ({ input }) => {
|
|
const db = await getDb();
|
|
if (!db) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
|
const result = await db.insert(etablissements).values(input);
|
|
return result[0];
|
|
}),
|
|
|
|
update: protectedProcedure
|
|
.input(z.object({
|
|
id: z.number().int(),
|
|
visibilite: z.enum(["tous", "gestionnaires"]).optional(),
|
|
accepteMiseEnRelation: z.boolean().optional(),
|
|
}))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.id);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
if (etab.referentId !== ctx.user.id && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
|
throw new TRPCError({ code: "FORBIDDEN" });
|
|
}
|
|
const db = await getDb();
|
|
if (!db) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
|
const { id, ...updateData } = input;
|
|
await db.update(etablissements).set(updateData).where(eq(etablissements.id, id));
|
|
return { success: true };
|
|
}),
|
|
}),
|
|
|
|
// ─── Logiciels ─────────────────────────────────────────────────────────────
|
|
logiciels: router({
|
|
byEtablissement: protectedProcedure
|
|
.input(z.object({ etablissementId: z.number().int() }))
|
|
.query(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.etablissementId);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
if (etab.visibilite === "gestionnaires" && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
|
if (etab.referentId !== ctx.user.id) throw new TRPCError({ code: "FORBIDDEN" });
|
|
}
|
|
return getLogicielsByEtablissement(input.etablissementId);
|
|
}),
|
|
|
|
upsert: protectedProcedure
|
|
.input(z.object({
|
|
id: z.number().int().optional(),
|
|
etablissementId: z.number().int(),
|
|
solutionId: z.number().int(),
|
|
etatDeploiement: z.enum(["demarrage", "en_cours", "operationnel", "en_remplacement"]),
|
|
modeHebergement: z.enum(["hds", "on_premise", "hybride"]).optional().nullable(),
|
|
modeFacturation: z.enum(["saas", "achat_maintenance", "location"]).optional().nullable(),
|
|
interoperabilite: z.enum(["non", "oui_interface", "oui_eai"]).optional().nullable(),
|
|
versionMajeure: z.string().optional().nullable(),
|
|
commentaire: z.string().optional().nullable(),
|
|
contactNom: z.string().optional().nullable(),
|
|
contactFonction: z.string().optional().nullable(),
|
|
contactEmail: z.string().optional().nullable(),
|
|
}))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.etablissementId);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
if (etab.referentId !== ctx.user.id && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
|
throw new TRPCError({ code: "FORBIDDEN" });
|
|
}
|
|
return upsertLogicielEtablissement({ ...input, saisiePar: ctx.user.id });
|
|
}),
|
|
|
|
delete: protectedProcedure
|
|
.input(z.object({ id: z.number().int(), etablissementId: z.number().int() }))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.etablissementId);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
if (etab.referentId !== ctx.user.id && ctx.user.sonumRole !== "gestionnaire" && ctx.user.role !== "admin") {
|
|
throw new TRPCError({ code: "FORBIDDEN" });
|
|
}
|
|
await deleteLogicielEtablissement(input.id);
|
|
return { success: true };
|
|
}),
|
|
}),
|
|
|
|
// ─── Traçabilité ───────────────────────────────────────────────────────────
|
|
tracabilite: router({
|
|
enregistrerConsultation: protectedProcedure
|
|
.input(z.object({ etablissementId: z.number().int() }))
|
|
.mutation(async ({ input, ctx }) => {
|
|
await recordConsultation(input.etablissementId, ctx.user.id, ctx.user.name ?? "Inconnu");
|
|
return { success: true };
|
|
}),
|
|
|
|
compteur: protectedProcedure
|
|
.input(z.object({ etablissementId: z.number().int() }))
|
|
.query(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.etablissementId);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
const canSee = etab.referentId === ctx.user.id || ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
|
if (!canSee) throw new TRPCError({ code: "FORBIDDEN" });
|
|
return { count: await getConsultationCount(input.etablissementId) };
|
|
}),
|
|
|
|
liste: protectedProcedure
|
|
.input(z.object({ etablissementId: z.number().int() }))
|
|
.query(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.etablissementId);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
const canSee = etab.referentId === ctx.user.id || ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
|
if (!canSee) throw new TRPCError({ code: "FORBIDDEN" });
|
|
return getConsultationsList(input.etablissementId);
|
|
}),
|
|
}),
|
|
|
|
// ─── Demandes de Contact ───────────────────────────────────────────────────
|
|
contact: router({
|
|
envoyer: protectedProcedure
|
|
.input(z.object({
|
|
etablissementCibleId: z.number().int(),
|
|
message: z.string().min(1),
|
|
}))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const etab = await getEtablissementById(input.etablissementCibleId);
|
|
if (!etab) throw new TRPCError({ code: "NOT_FOUND" });
|
|
|
|
await createDemandeContact({
|
|
etablissementCibleId: input.etablissementCibleId,
|
|
demandeurId: ctx.user.id,
|
|
demandeurNom: ctx.user.name ?? "Inconnu",
|
|
demandeurEmail: ctx.user.email ?? "",
|
|
message: input.message,
|
|
});
|
|
|
|
// Notification au propriétaire (gestionnaire SONUM)
|
|
await notifyOwner({
|
|
title: `Nouvelle demande de contact — ${etab.nom}`,
|
|
content: `${ctx.user.name} souhaite contacter le référent de ${etab.nom}.\n\nMessage : ${input.message}`,
|
|
});
|
|
|
|
return { success: true };
|
|
}),
|
|
|
|
mesDemandes: protectedProcedure.query(({ ctx }) =>
|
|
getDemandesByDemandeur(ctx.user.id)
|
|
),
|
|
|
|
demandesRecues: protectedProcedure.query(({ ctx }) =>
|
|
getDemandesRecuesParEtablissement(ctx.user.id)
|
|
),
|
|
|
|
toutesLesDemandes: gestionnaireProcedure.query(() => getAllDemandes()),
|
|
|
|
repondre: protectedProcedure
|
|
.input(z.object({
|
|
id: z.number().int(),
|
|
reponse: z.string().min(1),
|
|
}))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const demande = await getDemandeById(input.id);
|
|
if (!demande) throw new TRPCError({ code: "NOT_FOUND" });
|
|
const etab = await getEtablissementById(demande.etablissementCibleId);
|
|
const canReply = (etab?.referentId === ctx.user.id) || ctx.user.sonumRole === "gestionnaire" || ctx.user.role === "admin";
|
|
if (!canReply) throw new TRPCError({ code: "FORBIDDEN" });
|
|
await repondreDemandeContact(input.id, input.reponse, ctx.user.id);
|
|
return { success: true };
|
|
}),
|
|
}),
|
|
|
|
// ─── Administration ────────────────────────────────────────────────────────
|
|
admin: router({
|
|
users: gestionnaireProcedure.query(() => getAllUsers()),
|
|
|
|
updateRole: gestionnaireProcedure
|
|
.input(z.object({
|
|
userId: z.number().int(),
|
|
sonumRole: z.enum(["referent", "gestionnaire"]),
|
|
}))
|
|
.mutation(async ({ input }) => {
|
|
await updateUserSonumRole(input.userId, input.sonumRole);
|
|
return { success: true };
|
|
}),
|
|
}),
|
|
});
|
|
|
|
export type AppRouter = typeof appRouter;
|