Files
lab/src/lib/appwrite/patient-actions.ts
T
kovakmedya ee9c0015a5 feat(patients): clinic-side patient registry
Clinics get a real patient ledger. Labs see only patientCode — no name,
phone, date of birth, or notes ever cross the team boundary.

Data model
  - New table 'patients' (clinicTenantId, patientCode, firstName, lastName,
    phone?, dateOfBirth?, notes?, archived). Unique index on
    (clinicTenantId, patientCode) so each clinic gets its own code space.
    Fulltext index on (firstName, lastName) for future patient search.
    Row permissions Role.team(clinicTenantId) only — labs literally cannot
    read the rows.
  - jobs.patientId attribute (optional) + key index, references the
    patient row when one exists. patientCode stays denormalised on jobs so
    labs keep a stable identifier without joining patients.

Server
  - createPatientAction: clinic-only, requireTenantKind guard. Protocol no
    is optional; if absent we generate a 6-char unique code (re-roll on
    collision, 8 attempts). Duplicate protocol no within a clinic is
    rejected with a friendly error.
  - updatePatientAction: edits name/phone/dob/notes. patientCode is
    explicitly NOT mutable — re-keying historical jobs would be confusing.
  - archivePatientAction: toggle, preserves history.
  - listPatients / getPatient queries return plain objects via toPlain.

UI
  - /patients page (clinic-only, sidebar nav 'Hastalar', middleware
    protected): table + add form + edit dialog + archive.
  - /jobs/new: patient Select replaces the bare patientCode input. Picking
    a patient locks the patientCode field to that patient's code; falling
    back to 'Hasta listesinde yok — kodu manuel gir' keeps the old free-
    text flow.
  - createJobAction validates patientId ownership and overwrites
    patientCode with the patient's code on the server, so a manipulated
    form can't desync the two.
  - /jobs/[jobId] (clinic side only): adds a 'Hasta Bilgileri' card with
    name/phone/dob/notes and uses the patient's full name as the page
    title. Lab side is unchanged — code only.

The protocol-no / generated-code split matches what the user asked for:
existing patient management software's protocol number flows in directly,
otherwise the system mints one.
2026-05-21 21:54:35 +03:00

260 lines
7.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use server";
import { revalidatePath } from "next/cache";
import { AppwriteException, ID, Permission, Query, Role } from "node-appwrite";
import { z } from "zod";
import { logAudit } from "./audit";
import { DATABASE_ID, TABLES, type Patient } from "./schema";
import { createAdminClient } from "./server";
import { requireRole, requireTenant, requireTenantKind } from "./tenant-guard";
import type {
PatientActionState,
PatientFormState,
} from "./patient-types";
import { patientSchema } from "@/lib/validation/patient";
const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
function appwriteError(e: unknown, fallback = "Beklenmeyen bir hata oluştu."): string {
if (e instanceof AppwriteException) return e.message || fallback;
return process.env.NODE_ENV !== "production" && e instanceof Error
? `${fallback} (${e.message})`
: fallback;
}
function flattenErrors(err: z.ZodError): Record<string, string> {
const out: Record<string, string> = {};
for (const issue of err.issues) {
const key = issue.path.join(".");
if (key && !out[key]) out[key] = issue.message;
}
return out;
}
function pickFields(formData: FormData) {
return {
patientCode: String(formData.get("patientCode") ?? "").trim(),
firstName: String(formData.get("firstName") ?? "").trim(),
lastName: String(formData.get("lastName") ?? "").trim(),
phone: String(formData.get("phone") ?? "").trim(),
dateOfBirth: String(formData.get("dateOfBirth") ?? "").trim(),
notes: String(formData.get("notes") ?? "").trim(),
};
}
function patientPermissions(clinicTenantId: string): string[] {
return [
Permission.read(Role.team(clinicTenantId)),
Permission.update(Role.team(clinicTenantId, "owner")),
Permission.update(Role.team(clinicTenantId, "admin")),
Permission.update(Role.team(clinicTenantId, "member")),
Permission.delete(Role.team(clinicTenantId, "owner")),
Permission.delete(Role.team(clinicTenantId, "admin")),
];
}
function generateCode(): string {
let out = "";
for (let i = 0; i < 6; i++) {
out += CODE_ALPHABET[Math.floor(Math.random() * CODE_ALPHABET.length)];
}
return out;
}
async function reserveUniqueCode(clinicTenantId: string): Promise<string> {
const { tablesDB } = createAdminClient();
for (let attempt = 0; attempt < 8; attempt++) {
const candidate = generateCode();
const existing = await tablesDB.listRows({
databaseId: DATABASE_ID,
tableId: TABLES.patients,
queries: [
Query.equal("clinicTenantId", clinicTenantId),
Query.equal("patientCode", candidate),
Query.limit(1),
],
});
if (existing.total === 0) return candidate;
}
throw new Error("PATIENT_CODE_GENERATION_FAILED");
}
export async function createPatientAction(
_prev: PatientFormState,
formData: FormData,
): Promise<PatientFormState> {
let ctx;
try {
ctx = await requireTenant();
requireRole(ctx, ["owner", "admin", "member"]);
requireTenantKind(ctx, ["clinic"]);
} catch {
return { ok: false, error: "Hasta kaydı yalnızca klinik hesapları için." };
}
const parsed = patientSchema.safeParse(pickFields(formData));
if (!parsed.success) {
return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
}
const { tablesDB } = createAdminClient();
// If user supplied a code, make sure it isn't already in use within this clinic.
let code = parsed.data.patientCode;
if (code) {
const dup = await tablesDB.listRows({
databaseId: DATABASE_ID,
tableId: TABLES.patients,
queries: [
Query.equal("clinicTenantId", ctx.tenantId),
Query.equal("patientCode", code),
Query.limit(1),
],
});
if (dup.total > 0) {
return {
ok: false,
error: "Bu protokol no kayıtlı.",
fieldErrors: { patientCode: "Bu kod başka bir hasta için kullanılmış." },
};
}
} else {
code = await reserveUniqueCode(ctx.tenantId);
}
try {
const created = await tablesDB.createRow(
DATABASE_ID,
TABLES.patients,
ID.unique(),
{
clinicTenantId: ctx.tenantId,
createdBy: ctx.user.id,
patientCode: code,
firstName: parsed.data.firstName,
lastName: parsed.data.lastName,
phone: parsed.data.phone,
dateOfBirth: parsed.data.dateOfBirth,
notes: parsed.data.notes,
archived: false,
},
patientPermissions(ctx.tenantId),
);
await logAudit({
tenantId: ctx.tenantId,
userId: ctx.user.id,
action: "create",
entityType: "patient",
entityId: created.$id,
changes: { patientCode: code, firstName: parsed.data.firstName },
});
revalidatePath("/patients");
return { ok: true, patientId: created.$id };
} catch (e) {
return { ok: false, error: appwriteError(e, "Hasta eklenemedi.") };
}
}
export async function updatePatientAction(
_prev: PatientFormState,
formData: FormData,
): Promise<PatientFormState> {
const id = String(formData.get("id") ?? "").trim();
if (!id) return { ok: false, error: "Hasta bulunamadı." };
let ctx;
try {
ctx = await requireTenant();
requireRole(ctx, ["owner", "admin", "member"]);
requireTenantKind(ctx, ["clinic"]);
} catch {
return { ok: false, error: "Yetkiniz yok." };
}
const parsed = patientSchema.safeParse(pickFields(formData));
if (!parsed.success) {
return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
}
try {
const { tablesDB } = createAdminClient();
const row = (await tablesDB.getRow(
DATABASE_ID,
TABLES.patients,
id,
)) as unknown as Patient;
if (row.clinicTenantId !== ctx.tenantId) {
return { ok: false, error: "Bu hastayı düzenleme yetkiniz yok." };
}
// patientCode is intentionally NOT updatable here — re-keying historical
// jobs would be confusing. Only firstName/lastName/phone/dateOfBirth/notes.
await tablesDB.updateRow(DATABASE_ID, TABLES.patients, id, {
firstName: parsed.data.firstName,
lastName: parsed.data.lastName,
phone: parsed.data.phone,
dateOfBirth: parsed.data.dateOfBirth,
notes: parsed.data.notes,
});
await logAudit({
tenantId: ctx.tenantId,
userId: ctx.user.id,
action: "update",
entityType: "patient",
entityId: id,
changes: parsed.data,
});
} catch (e) {
return { ok: false, error: appwriteError(e, "Güncellenemedi.") };
}
revalidatePath("/patients");
return { ok: true, patientId: id };
}
export async function archivePatientAction(
_prev: PatientActionState,
formData: FormData,
): Promise<PatientActionState> {
const id = String(formData.get("id") ?? "").trim();
if (!id) return { ok: false, error: "Hasta bulunamadı." };
let ctx;
try {
ctx = await requireTenant();
requireRole(ctx, ["owner", "admin"]);
requireTenantKind(ctx, ["clinic"]);
} catch {
return { ok: false, error: "Yetkiniz yok." };
}
try {
const { tablesDB } = createAdminClient();
const row = (await tablesDB.getRow(
DATABASE_ID,
TABLES.patients,
id,
)) as unknown as Patient;
if (row.clinicTenantId !== ctx.tenantId) {
return { ok: false, error: "Yetkiniz yok." };
}
await tablesDB.updateRow(DATABASE_ID, TABLES.patients, id, {
archived: !row.archived,
});
await logAudit({
tenantId: ctx.tenantId,
userId: ctx.user.id,
action: "update",
entityType: "patient",
entityId: id,
changes: { archived: !row.archived },
});
} catch (e) {
return { ok: false, error: appwriteError(e, "İşlem başarısız.") };
}
revalidatePath("/patients");
return { ok: true };
}