Compare commits

...
10 Commits
16 changed files with 1596 additions and 10 deletions

No files matched your search

-8
View File
@@ -1,8 +0,0 @@
# Environment variables declared in this file are NOT automatically loaded by Prisma.
# Please add `import "dotenv/config";` to your `prisma7.config.ts` file, or use the Prisma CLI with Bun
# to load environment variables from .env files: https://pris.ly/prisma-config-env-vars.
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
+3
View File
@@ -41,3 +41,6 @@ yarn-error.log*
package-lock.json
**/*.bun
/generated/prisma
/.idea/dataSources.xml
.idea
+41
View File
@@ -0,0 +1,41 @@
# Explanation
## Database Design
### ER Diagram
![ER Diagram](assets/er-diagram.svg)
### Design Decisions
The database is structured around customers, their cars and the work orders created when those cars need repair.
I separated car brands and model into their own tables to avoid storing the same information and prevent inaccurate data.<br />
Each car references a model, which references a brand.<br />
So this disallows the Car table to have a row with a "Toyota M3" (aka, a BMW model on the Toyota brand), without having to add the model on the CarBrand table.
Invoice.workOrderId is both an id/PK and FK to only allow one invoice per work order.<br />
So the backend don't have to update WorkOrder.invoice.total on every update of WorkOrder while it's status == IN_PROGRESS, it is currently optional with the plan the backend only adds and keeps track of it after WorkOrder.status == DONE. Though this is not enforced by the DB.<br />
When a WorkOrder is done it should in a transaction both set WorkOrder.status = DONE and create the invoice.
All prices/rates is using an integer of "Øre" to avoid floating point precision problems, especially on larger amounts.
I used explicit junction tables to handle many-to-many relationships betwithout editing migration files.ween mechanics and skills, mechanics and work orders and spare parts and work orders.
Some of those tables store extra information about the relationship itself, such as how many minutes a mechanic worked on a work order or the quantity and price of spare parts used.<br />
I store the price charged for each spare part in WorkOrderToSparePart rather than SparePart so previous work orders keep their original prices even if the price of the part changes.
I used composite PKs in the junction tables to prevent duplicates.<br />
I also added composite unique constraints where it depends on multiple columns, such as the car model's name within a brand.
### PostgreSQL constraints.
I wanted to add the CHECK constraint in PostgreSQL.<br />
It is currently only possible in Prisma 8 without editing migration files.<br />
So for now I only have the one migration file with checks, the Prisma schema does not include these checks.
## AI
AI have been used to explain concepts and having the correct lingo.
prisma/seed.ts is fully AI generated, just so I could see the db in action.
File diff suppressed because it is too large. Load diff

After

Width:  |  Height:  |  Size: 179 KiB

+2 -1
View File
@@ -3,7 +3,8 @@
"version": "1.0.50",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "bun run --watch src/index.ts"
"dev": "bun run --watch src/index.ts",
"db:seed": "bun prisma/seed.ts"
},
"dependencies": {
"@prisma/adapter-pg": "^7.10.1",
@@ -0,0 +1,180 @@
-- CreateEnum
CREATE TYPE "WorkOrderStatus" AS ENUM ('OPEN', 'IN_PROGRESS', 'DONE');
-- CreateTable
CREATE TABLE "CarBrand" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
CONSTRAINT "CarBrand_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CarModel" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"carBrandId" INTEGER NOT NULL,
CONSTRAINT "CarModel_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Car" (
"id" SERIAL NOT NULL,
"licensePlate" TEXT NOT NULL,
"productionYear" INTEGER NOT NULL,
"carModelId" INTEGER NOT NULL,
"customerId" INTEGER NOT NULL,
CONSTRAINT "Car_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Customer" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"phone" TEXT NOT NULL,
CONSTRAINT "Customer_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Invoice" (
"workOrderId" INTEGER NOT NULL,
"total" INTEGER NOT NULL CHECK("total" >= 0),
"paidDate" TIMESTAMP(3),
CONSTRAINT "Invoice_pkey" PRIMARY KEY ("workOrderId")
);
-- CreateTable
CREATE TABLE "Mechanic" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"hourlyRate" INTEGER NOT NULL CHECK("hourlyRate" >= 0),
CONSTRAINT "Mechanic_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MechanicToSkill" (
"mechanicId" INTEGER NOT NULL,
"skillId" INTEGER NOT NULL,
CONSTRAINT "MechanicToSkill_pkey" PRIMARY KEY ("mechanicId","skillId")
);
-- CreateTable
CREATE TABLE "MechanicSkill" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
CONSTRAINT "MechanicSkill_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SparePart" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"partNumber" TEXT NOT NULL,
"supplierId" INTEGER NOT NULL,
CONSTRAINT "SparePart_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Supplier" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
CONSTRAINT "Supplier_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "WorkOrderToSparePart" (
"sparePartId" INTEGER NOT NULL,
"workOrderId" INTEGER NOT NULL,
"quantity" INTEGER NOT NULL CHECK("quantity" > 0),
"pricePerUnit" INTEGER NOT NULL CHECK("pricePerUnit" >= 0),
CONSTRAINT "WorkOrderToSparePart_pkey" PRIMARY KEY ("sparePartId","workOrderId")
);
-- CreateTable
CREATE TABLE "WorkOrder" (
"id" SERIAL NOT NULL,
"currentMileage" INTEGER NOT NULL CHECK("currentMileage" >= 0),
"problem" TEXT NOT NULL,
"carId" INTEGER NOT NULL,
"status" "WorkOrderStatus" NOT NULL DEFAULT 'OPEN',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WorkOrder_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "WorkOrderToMechanic" (
"mechanicId" INTEGER NOT NULL,
"workOrderId" INTEGER NOT NULL,
"minutesWorked" INTEGER NOT NULL CHECK("minutesWorked" >= 0),
CONSTRAINT "WorkOrderToMechanic_pkey" PRIMARY KEY ("mechanicId","workOrderId")
);
-- CreateIndex
CREATE UNIQUE INDEX "CarBrand_name_key" ON "CarBrand"("name");
-- CreateIndex
CREATE UNIQUE INDEX "CarModel_carBrandId_name_key" ON "CarModel"("carBrandId", "name");
-- CreateIndex
CREATE UNIQUE INDEX "Car_licensePlate_key" ON "Car"("licensePlate");
-- CreateIndex
CREATE UNIQUE INDEX "Customer_email_key" ON "Customer"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Invoice_workOrderId_key" ON "Invoice"("workOrderId");
-- CreateIndex
CREATE UNIQUE INDEX "MechanicSkill_name_key" ON "MechanicSkill"("name");
-- CreateIndex
CREATE UNIQUE INDEX "SparePart_supplierId_partNumber_key" ON "SparePart"("supplierId", "partNumber");
-- AddForeignKey
ALTER TABLE "CarModel" ADD CONSTRAINT "CarModel_carBrandId_fkey" FOREIGN KEY ("carBrandId") REFERENCES "CarBrand"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Car" ADD CONSTRAINT "Car_carModelId_fkey" FOREIGN KEY ("carModelId") REFERENCES "CarModel"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Car" ADD CONSTRAINT "Car_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Invoice" ADD CONSTRAINT "Invoice_workOrderId_fkey" FOREIGN KEY ("workOrderId") REFERENCES "WorkOrder"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MechanicToSkill" ADD CONSTRAINT "MechanicToSkill_mechanicId_fkey" FOREIGN KEY ("mechanicId") REFERENCES "Mechanic"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MechanicToSkill" ADD CONSTRAINT "MechanicToSkill_skillId_fkey" FOREIGN KEY ("skillId") REFERENCES "MechanicSkill"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SparePart" ADD CONSTRAINT "SparePart_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "Supplier"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WorkOrderToSparePart" ADD CONSTRAINT "WorkOrderToSparePart_sparePartId_fkey" FOREIGN KEY ("sparePartId") REFERENCES "SparePart"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WorkOrderToSparePart" ADD CONSTRAINT "WorkOrderToSparePart_workOrderId_fkey" FOREIGN KEY ("workOrderId") REFERENCES "WorkOrder"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WorkOrder" ADD CONSTRAINT "WorkOrder_carId_fkey" FOREIGN KEY ("carId") REFERENCES "Car"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WorkOrderToMechanic" ADD CONSTRAINT "WorkOrderToMechanic_mechanicId_fkey" FOREIGN KEY ("mechanicId") REFERENCES "Mechanic"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WorkOrderToMechanic" ADD CONSTRAINT "WorkOrderToMechanic_workOrderId_fkey" FOREIGN KEY ("workOrderId") REFERENCES "WorkOrder"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+33
View File
@@ -0,0 +1,33 @@
model CarBrand {
id Int @id @default(autoincrement())
name String @unique
carModels CarModel[]
}
model CarModel {
id Int @id @default(autoincrement())
name String
carBrandId Int
brand CarBrand @relation(fields: [carBrandId], references: [id])
cars Car[]
@@unique([carBrandId, name])
}
model Car {
id Int @id @default(autoincrement())
licensePlate String @unique
productionYear Int
carModelId Int
model CarModel @relation(fields: [carModelId], references: [id])
customerId Int
customer Customer @relation(fields: [customerId], references: [id])
workOrders WorkOrder[]
}
+9
View File
@@ -0,0 +1,9 @@
model Customer {
id Int @id @default(autoincrement())
name String
email String @unique
phone String
cars Car[]
}
+9
View File
@@ -0,0 +1,9 @@
model Invoice {
workOrderId Int @id @unique
workOrder WorkOrder @relation(fields: [workOrderId], references: [id])
// total >= 0
total Int
paidDate DateTime?
}
+28
View File
@@ -0,0 +1,28 @@
model Mechanic {
id Int @id @default(autoincrement())
name String
// hourlyRate >= 0
hourlyRate Int
skills MechanicToSkill[]
workOrders WorkOrderToMechanic[]
}
model MechanicToSkill {
mechanicId Int
mechanic Mechanic @relation(fields: [mechanicId], references: [id])
skillId Int
skill MechanicSkill @relation(fields: [skillId], references: [id])
@@id([mechanicId, skillId])
}
model MechanicSkill {
id Int @id @default(autoincrement())
name String @unique
mechanics MechanicToSkill[]
}
+33
View File
@@ -0,0 +1,33 @@
model SparePart {
id Int @id @default(autoincrement())
name String
partNumber String
supplierId Int
supplier Supplier @relation(fields: [supplierId], references: [id])
workOrderToSpareParts WorkOrderToSparePart[]
@@unique([supplierId, partNumber])
}
model Supplier {
id Int @id @default(autoincrement())
name String
spareParts SparePart[]
}
model WorkOrderToSparePart {
sparePartId Int
sparePart SparePart @relation(fields: [sparePartId], references: [id])
workOrderId Int
workOrder WorkOrder @relation(fields: [workOrderId], references: [id])
// quantity > 0
quantity Int
// pricePerUnit >= 0
pricePerUnit Int
@@id([sparePartId, workOrderId])
}
+37
View File
@@ -0,0 +1,37 @@
enum WorkOrderStatus {
OPEN
IN_PROGRESS
DONE
}
model WorkOrder {
id Int @id @default(autoincrement())
// currentMileage >= 0
currentMileage Int
problem String
carId Int
car Car @relation(fields: [carId], references: [id])
mechanics WorkOrderToMechanic[]
sparePart WorkOrderToSparePart[]
// Add when status == DONE
invoice Invoice?
status WorkOrderStatus @default(OPEN)
createdAt DateTime @default(now())
}
model WorkOrderToMechanic {
mechanicId Int
mechanic Mechanic @relation(fields: [mechanicId], references: [id])
workOrderId Int
workOrder WorkOrder @relation(fields: [workOrderId], references: [id])
// minutesWorked >= 0
minutesWorked Int
@@id([mechanicId, workOrderId])
}
+154
View File
@@ -0,0 +1,154 @@
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import { PrismaClient } from "../generated/prisma/client";
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error("DATABASE_URL must be set to run the Prisma seed.");
}
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
async function main() {
const customers = await Promise.all([
prisma.customer.upsert({
where: { email: "anna@example.com" },
update: {},
create: { name: "Anna Jensen", email: "anna@example.com", phone: "+45 20 11 22 33" },
}),
prisma.customer.upsert({
where: { email: "mikkel@example.com" },
update: {},
create: { name: "Mikkel Sørensen", email: "mikkel@example.com", phone: "+45 30 44 55 66" },
}),
]);
const [volvo, toyota] = await Promise.all([
prisma.carBrand.upsert({ where: { name: "Volvo" }, update: {}, create: { name: "Volvo" } }),
prisma.carBrand.upsert({ where: { name: "Toyota" }, update: {}, create: { name: "Toyota" } }),
]);
const [xc60, corolla] = await Promise.all([
prisma.carModel.upsert({
where: { carBrandId_name: { carBrandId: volvo.id, name: "XC60" } },
update: {},
create: { name: "XC60", carBrandId: volvo.id },
}),
prisma.carModel.upsert({
where: { carBrandId_name: { carBrandId: toyota.id, name: "Corolla" } },
update: {},
create: { name: "Corolla", carBrandId: toyota.id },
}),
]);
const cars = await Promise.all([
prisma.car.upsert({
where: { licensePlate: "AB12345" },
update: {},
create: { licensePlate: "AB12345", productionYear: 2021, carModelId: xc60.id, customerId: customers[0].id },
}),
prisma.car.upsert({
where: { licensePlate: "CD67890" },
update: {},
create: { licensePlate: "CD67890", productionYear: 2018, carModelId: corolla.id, customerId: customers[1].id },
}),
]);
const skillNames = ["Diagnostics", "Brakes", "Engine"];
const skills = await Promise.all(skillNames.map((name) =>
prisma.mechanicSkill.upsert({ where: { name }, update: {}, create: { name } }),
));
const mechanicData = [
{ name: "Sofie Nielsen", hourlyRate: 42_500, skills: ["Diagnostics", "Engine"] },
{ name: "Lars Holm", hourlyRate: 39_000, skills: ["Brakes", "Diagnostics"] },
];
const mechanics = await Promise.all(mechanicData.map(async (data) => {
let mechanic = await prisma.mechanic.findFirst({ where: { name: data.name } });
mechanic ??= await prisma.mechanic.create({ data: { name: data.name, hourlyRate: data.hourlyRate } });
const mechanicSkills = skills.filter((skill) => data.skills.includes(skill.name));
await Promise.all(mechanicSkills.map((skill) => prisma.mechanicToSkill.upsert({
where: { mechanicId_skillId: { mechanicId: mechanic.id, skillId: skill.id } },
update: {},
create: { mechanicId: mechanic.id, skillId: skill.id },
})));
return mechanic;
}));
const supplier = await prisma.supplier.findFirst({ where: { name: "Nordic Auto Parts" } })
?? await prisma.supplier.create({ data: { name: "Nordic Auto Parts" } });
const [oilFilter, airFilter, brakePads] = await Promise.all([
prisma.sparePart.upsert({
where: { supplierId_partNumber: { supplierId: supplier.id, partNumber: "OF-204" } },
update: {},
create: { name: "Oil filter", partNumber: "OF-204", supplierId: supplier.id },
}),
prisma.sparePart.upsert({
where: { supplierId_partNumber: { supplierId: supplier.id, partNumber: "AF-310" } },
update: {},
create: { name: "Air filter", partNumber: "AF-310", supplierId: supplier.id },
}),
prisma.sparePart.upsert({
where: { supplierId_partNumber: { supplierId: supplier.id, partNumber: "BP-118" } },
update: {},
create: { name: "Brake pads", partNumber: "BP-118", supplierId: supplier.id },
}),
]);
const workOrderData = [
{ carId: cars[0].id, currentMileage: 48_200, problem: "Annual service and oil change", status: "IN_PROGRESS" as const },
{ carId: cars[1].id, currentMileage: 92_450, problem: "Inspect and replace worn front brakes", status: "OPEN" as const },
];
for (const [index, data] of workOrderData.entries()) {
let workOrder = await prisma.workOrder.findFirst({ where: { carId: data.carId, problem: data.problem } });
if (!workOrder) {
workOrder = await prisma.workOrder.create({ data });
}
const assignedMechanics = index === 0 ? mechanics : [mechanics[index]];
for (const mechanic of assignedMechanics) {
if (!mechanic) continue;
await prisma.workOrderToMechanic.upsert({
where: { mechanicId_workOrderId: { mechanicId: mechanic.id, workOrderId: workOrder.id } },
update: {},
create: { mechanicId: mechanic.id, workOrderId: workOrder.id, minutesWorked: index === 0 ? 75 : 0 },
});
}
const partAssignments = index === 0
? [{ part: oilFilter, quantity: 2, pricePerUnit: 12_000 }, { part: airFilter, quantity: 1, pricePerUnit: 18_000 }]
: [{ part: brakePads, quantity: 1, pricePerUnit: 68_000 }];
await Promise.all(partAssignments.map(({ part, quantity, pricePerUnit }) =>
prisma.workOrderToSparePart.upsert({
where: { sparePartId_workOrderId: { sparePartId: part.id, workOrderId: workOrder.id } },
update: { quantity, pricePerUnit },
create: { sparePartId: part.id, workOrderId: workOrder.id, quantity, pricePerUnit },
}),
));
if (index === 0) {
await prisma.invoice.upsert({
where: { workOrderId: workOrder.id },
update: {},
create: { workOrderId: workOrder.id, total: 125_000 },
});
}
}
console.log("Seed data is ready.");
}
main()
.catch((error: unknown) => {
console.error("Failed to seed the database:", error);
process.exitCode = 1;
})
.finally(async () => {
await prisma.$disconnect();
await pool.end();
});
+2 -1
View File
@@ -2,9 +2,10 @@
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
schema: "prisma",
migrations: {
path: "prisma/migrations",
seed: "bun ./prisma/seed.ts"
},
datasource: {
url: env("DATABASE_URL"),
+25
View File
@@ -0,0 +1,25 @@
SELECT COALESCE(SUM("minutesWorked") / 60.0, 0.0) as "totalHours"
FROM "WorkOrderToMechanic"
WHERE "workOrderId" = 1;
SELECT SUM("quantity" * "pricePerUnit") / 100.0 as "totalPrice"
FROM "WorkOrderToSparePart"
WHERE "workOrderId" = 1;
SELECT COALESCE(SUM(wo."minutesWorked") / 60.0, 0.0) as "totalHours", SUM(ws."quantity" * ws."pricePerUnit") / 100.0 as "totalPrice"
FROM "WorkOrderToMechanic" AS wo
JOIN "WorkOrderToSparePart" AS ws
ON wo."workOrderId" = ws."workOrderId";
SELECT
COALESCE(SUM("minutesWorked") / 60.0, 0) AS "totalHours",
(
SELECT SUM(ws.quantity * ws."pricePerUnit") / 100.0
FROM "WorkOrderToSparePart" as ws
WHERE ws."workOrderId" = wo.id
) AS "totalPrice"
FROM "WorkOrder" as wo
LEFT JOIN "WorkOrderToMechanic" as wm
ON wo.id = wm."workOrderId"
WHERE wo.id = 1
GROUP BY wo.id