49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
import crypto from "node:crypto";
|
|
import { and, asc, eq } from "drizzle-orm";
|
|
import { db } from "../client.js";
|
|
import { circuitSections } from "../schema/circuit-sections.js";
|
|
|
|
export function createDefaultCircuitSectionValues(circuitListId: string) {
|
|
return [
|
|
{ key: "lighting", displayName: "Lighting", prefix: "-1F", sortOrder: 10 },
|
|
{ key: "single_phase", displayName: "Single-phase circuits", prefix: "-2F", sortOrder: 20 },
|
|
{ key: "three_phase", displayName: "Three-phase circuits", prefix: "-3F", sortOrder: 30 },
|
|
{ key: "unassigned", displayName: "Unassigned", prefix: "-UF", sortOrder: 90 },
|
|
].map((entry) => ({
|
|
id: crypto.randomUUID(),
|
|
circuitListId,
|
|
...entry,
|
|
}));
|
|
}
|
|
|
|
export class CircuitSectionRepository {
|
|
async findById(sectionId: string) {
|
|
const [row] = await db.select().from(circuitSections).where(eq(circuitSections.id, sectionId)).limit(1);
|
|
return row ?? null;
|
|
}
|
|
|
|
async listByCircuitList(circuitListId: string) {
|
|
return db
|
|
.select()
|
|
.from(circuitSections)
|
|
.where(eq(circuitSections.circuitListId, circuitListId))
|
|
.orderBy(asc(circuitSections.sortOrder));
|
|
}
|
|
|
|
async createDefaults(circuitListId: string) {
|
|
for (const entry of createDefaultCircuitSectionValues(circuitListId)) {
|
|
const existing = await db
|
|
.select({ id: circuitSections.id })
|
|
.from(circuitSections)
|
|
.where(
|
|
and(eq(circuitSections.circuitListId, circuitListId), eq(circuitSections.key, entry.key))
|
|
)
|
|
.limit(1);
|
|
if (existing.length) {
|
|
continue;
|
|
}
|
|
await db.insert(circuitSections).values(entry);
|
|
}
|
|
}
|
|
}
|