Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x | import { Prisma } from "@prisma/client";
import { AppError } from "@ontrack/backend-common";
import type { FastifyPluginAsync, FastifyRequest } from "fastify";
import type { AppConfig } from "../config.js";
import { assertAdmin } from "../lib/admin-role.js";
import { assertServiceToken } from "../lib/service-token.js";
import { readUserUid } from "../lib/user-uid.js";
import { prisma } from "../lib/prisma.js";
const CODE_RE = /^[A-Z][A-Z0-9_]{1,30}$/;
const createBody = {
type: "object",
required: ["code", "label"],
additionalProperties: false,
properties: {
code: { type: "string" },
label: { type: "string", minLength: 1, maxLength: 60 },
},
} as const;
const labelBody = {
type: "object",
required: ["label"],
additionalProperties: false,
properties: { label: { type: "string", minLength: 1, maxLength: 60 } },
} as const;
const idParam = {
type: "object",
required: ["id"],
additionalProperties: false,
properties: { id: { type: "string", pattern: "^[1-9][0-9]*$" } },
} as const;
type EntryRow = { id: number; code: string; label: string; _count: { tracks: number } };
function normalizeCode(code: string): string {
const c = code.trim().toUpperCase();
if (!CODE_RE.test(c)) {
throw new AppError(400, "INVALID_CODE", "Код: латиница/цифры/_, начинается с буквы (2–31)");
}
return c;
}
export const dictionariesRoutes: FastifyPluginAsync<{ config: AppConfig }> = async (app, opts) => {
const { config } = opts;
function requireServiceToken(request: FastifyRequest): void {
const token = request.headers["x-service-token"];
assertServiceToken(Array.isArray(token) ? token[0] : token, config.serviceToken);
}
async function requireAdmin(request: FastifyRequest): Promise<void> {
requireServiceToken(request);
await assertAdmin(readUserUid(request));
}
/** Публично: коды/лейблы типов и раскладок (для форм каталога). */
app.get("/dictionaries", async (request, reply) => {
requireServiceToken(request);
const [trackTypes, routeLayouts] = await Promise.all([
prisma.trackType.findMany({ orderBy: { id: "asc" }, select: { code: true, label: true } }),
prisma.routeLayout.findMany({ orderBy: { id: "asc" }, select: { code: true, label: true } }),
]);
return reply.send({ trackTypes, routeLayouts });
});
/** Админ: справочники со счётчиком использования. */
app.get("/admin/dictionaries", async (request, reply) => {
await requireAdmin(request);
const select = { id: true, code: true, label: true, _count: { select: { tracks: true } } };
const [types, layouts] = await Promise.all([
prisma.trackType.findMany({ orderBy: { id: "asc" }, select }),
prisma.routeLayout.findMany({ orderBy: { id: "asc" }, select }),
]);
const map = (r: EntryRow) => ({ id: r.id, code: r.code, label: r.label, trackCount: r._count.tracks });
return reply.send({ trackTypes: types.map(map), routeLayouts: layouts.map(map) });
});
// ── Типы трека ──
app.post("/admin/track-types", { schema: { body: createBody } }, async (request, reply) => {
await requireAdmin(request);
const { code, label } = request.body as { code: string; label: string };
try {
const t = await prisma.trackType.create({ data: { code: normalizeCode(code), label: label.trim() } });
return reply.send({ id: t.id, code: t.code, label: t.label, trackCount: 0 });
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2002") {
throw new AppError(409, "CODE_TAKEN", "Такой код уже есть");
}
throw err;
}
});
app.put("/admin/track-types/:id", { schema: { params: idParam, body: labelBody } }, async (request, reply) => {
await requireAdmin(request);
const id = Number.parseInt((request.params as { id: string }).id, 10);
const { label } = request.body as { label: string };
try {
const t = await prisma.trackType.update({ where: { id }, data: { label: label.trim() } });
const trackCount = await prisma.gpxTrack.count({ where: { trackTypeId: id } });
return reply.send({ id: t.id, code: t.code, label: t.label, trackCount });
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2025") {
throw new AppError(404, "NOT_FOUND", "Тип не найден");
}
throw err;
}
});
app.delete("/admin/track-types/:id", { schema: { params: idParam } }, async (request, reply) => {
await requireAdmin(request);
const id = Number.parseInt((request.params as { id: string }).id, 10);
const used = await prisma.gpxTrack.count({ where: { trackTypeId: id } });
if (used > 0) throw new AppError(409, "IN_USE", `Тип используется (${used}). Удалять нельзя.`);
try {
await prisma.trackType.delete({ where: { id } });
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError) {
if (err.code === "P2025") throw new AppError(404, "NOT_FOUND", "Тип не найден");
if (err.code === "P2003") throw new AppError(409, "IN_USE", "Тип используется. Удалять нельзя.");
}
throw err;
}
return reply.send({ deleted: true });
});
// ── Типы маршрута ──
app.post("/admin/route-layouts", { schema: { body: createBody } }, async (request, reply) => {
await requireAdmin(request);
const { code, label } = request.body as { code: string; label: string };
try {
const l = await prisma.routeLayout.create({ data: { code: normalizeCode(code), label: label.trim() } });
return reply.send({ id: l.id, code: l.code, label: l.label, trackCount: 0 });
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2002") {
throw new AppError(409, "CODE_TAKEN", "Такой код уже есть");
}
throw err;
}
});
app.put("/admin/route-layouts/:id", { schema: { params: idParam, body: labelBody } }, async (request, reply) => {
await requireAdmin(request);
const id = Number.parseInt((request.params as { id: string }).id, 10);
const { label } = request.body as { label: string };
try {
const l = await prisma.routeLayout.update({ where: { id }, data: { label: label.trim() } });
const trackCount = await prisma.gpxTrack.count({ where: { routeLayoutId: id } });
return reply.send({ id: l.id, code: l.code, label: l.label, trackCount });
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === "P2025") {
throw new AppError(404, "NOT_FOUND", "Раскладка не найдена");
}
throw err;
}
});
app.delete("/admin/route-layouts/:id", { schema: { params: idParam } }, async (request, reply) => {
await requireAdmin(request);
const id = Number.parseInt((request.params as { id: string }).id, 10);
const used = await prisma.gpxTrack.count({ where: { routeLayoutId: id } });
if (used > 0) throw new AppError(409, "IN_USE", `Раскладка используется (${used}). Удалять нельзя.`);
try {
await prisma.routeLayout.delete({ where: { id } });
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError) {
if (err.code === "P2025") throw new AppError(404, "NOT_FOUND", "Раскладка не найдена");
if (err.code === "P2003") throw new AppError(409, "IN_USE", "Раскладка используется. Удалять нельзя.");
}
throw err;
}
return reply.send({ deleted: true });
});
};
|