dueDate was sitting on every job but the UI never warned anyone about
it. Added a small badge primitive and surfaced it everywhere a job is
listed plus a dedicated dashboard card.
- lib/appwrite/due-date.ts: dueState() buckets a job into overdue /
today / soon (1-3 days) / future / none, with delivered + cancelled
jobs always resolving to none. dueLabel() returns the Turkish text.
- components/due-badge.tsx: renders nothing for future/none, a
secondary badge for today/soon, a destructive badge for overdue.
Drop-in (job, className).
- JobsTable (inbound + outbound): new 'Termin' column shows the date
and the DueBadge stacked. Sorting still on createdAt for now —
explicit ordering by dueDate will come with the filter task.
- Job detail header: badge stack now has the DueBadge before the
status pill so a glance at the page shows whether the case is
behind schedule.
- Dashboard: getDashboardData fetches up to 10 overdue jobs in
parallel (lessThan('dueDate', now), excluding delivered/cancelled).
Added a destructive-tinted 'Geciken İşler' card above the rest of
the widgets when the list is non-empty, with quick links into each
job's detail page.
Active scan + image traffic was going to bloat Storage fast — every
delivered case has tens of MB of STL hanging around forever. Now closing
a case via 'Teslim Aldım' fires a background archive sweep that deletes
the binary from the bucket but keeps the job_files row, so audit
('kim, ne, ne zaman yükledi') is preserved.
- DB: job_files.archivedAt datetime (nullable).
- archiveJobFiles(jobId) (lib/appwrite/job-file-archive.ts):
lists rows, storage.deleteFile each, stamps archivedAt on the row.
All in try/catch so partial Storage failures don't roll back the
'delivered' transition.
- markDeliveredAction fires it as 'void archiveJobFiles(jobId)' — same
fire-and-forget pattern as audit/notifications/finance sync.
UI / API
- Job detail file row dims to 60% opacity, shows 'Arşivlendi
{tarih}' inline, and disables both the download dialog trigger and
the STL viewer button.
- /api/jobs/[jobId]/files/[fileId]/download returns 410 Gone with a
Turkish message when archivedAt is set — direct-URL hot links can't
fish the file back either.
A payment recorded by the lab itself is self-evident (the lab knows it
got paid). One recorded by the clinic is just a claim until the lab
agrees. Added a status field to enforce that distinction so labs can
approve payments per-clinic instead of trusting whatever the clinic
typed in.
DB
- payments.status enum (pending | confirmed | rejected, default
confirmed). Existing rows keep the default and continue to be
counted in balances.
Server
- recordPaymentAction now stamps status='pending' when the caller is a
clinic and 'confirmed' when the caller is a lab. A clinic submission
pings the lab via createNotification so it surfaces on the
notifications bell as well as on /finance.
- confirmPaymentAction (lab only): flips a pending row to confirmed
after verifying the lab is the counterpart. Notifies the clinic on
success.
- rejectPaymentAction (lab only): flips to rejected, notifies the
clinic. Rejected rows stay visible for audit but never count toward
the balance.
Queries
- listIncomingPayments(tenantId) — payments where this tenant is the
counterpart (the other side recorded them). Paired with listPayments
we now see the same physical payment from either ledger.
- computeBalancesByCounterpart upgraded to handle both shapes via an
inflowFor() helper that normalises 'who got the money'. Only
confirmed rows reduce the open balance.
- filterPendingForConfirmation() returns the lab-side approval queue,
sorted newest-first.
UI
- /finance loads own + incoming payments, dedupes by $id, then feeds
the merged list to balance/pending helpers.
- New PendingPaymentsCard sits above the balances table on the lab
side. Per-row: clinic name, amount, date, method, note, plus inline
Onayla / Reddet buttons. Empty state hides the whole card.
- Confirm + reject use the same router.refresh pattern as the rest of
the action panels so the queue and the balances both update without
a manual reload.
Klinik-laboratuvar finance in TR is dönemsel, not job-by-job. Forcing
the lab to mark each finance_entry as paid was unrealistic — labs get a
single 50.000 TL transfer covering twelve jobs and don't want to walk a
list. Reworked the page around connection balances and free-amount
payments.
Data model
- New 'payments' table:
tenantId whose ledger it lives in
counterpartTenantId the other side of the transaction
direction inflow (lab received) | outflow (clinic paid)
amount, currency, paymentDate
method cash | bank | card | check | other
notes, recordedBy
Indexes: (tenantId, counterpartTenantId), paymentDate DESC. Permission:
both teams can read, only owners/admins of the recording side can
update or delete.
Server
- recordPaymentAction: requires owner/admin, verifies an approved
connection exists between (lab, clinic), then writes a single row.
Direction is inferred from the caller's tenant kind so a lab can
never accidentally book an outflow.
- deletePaymentAction: same auth, tenant-scoped delete.
- listPayments(tenantId) + computeBalancesByCounterpart({ kind,
entries, payments }): one pass over both ledgers, returns
[{ counterpartTenantId, invoiced, paid, open, lastPaymentAt }]
sorted by open desc. invoiced pulls from finance_entries (receivable
for lab, debt for clinic); paid pulls from the new payments table.
UI
- /finance now leads with a Bakiye kartı: a row per connected
counterpart showing invoiced, paid, last payment date and the open
amount tinted green (lab alacak) or red (clinic borç), each with an
inline 'Ödeme Al' / 'Ödeme Yap' button.
- RecordPaymentDialog: amount (defaults to the open balance, lump
sums obviously not pre-filled with a specific entry), date,
currency, method (Nakit/Banka/Kart/Çek/Diğer), free-text note.
Posts to recordPaymentAction, refresh on success.
- Stat cards reworked: Toplam Açık Alacak/Borç and Tahsil Edilen /
Ödenen replaced the old pending-totals so the headline numbers
actually reflect the new flow.
Existing finance_entries (job-driven receivables/debts) remain the
single source of truth for 'how much was invoiced'; the new table tracks
'how much was actually collected'. Open balance = invoiced - paid, always
computed live — no individual entry needs to be marked 'paid' anymore.
Real prosthetic production isn't a one-way pipeline — the work moves
between lab and clinic multiple times. After substructure is produced
the lab hands it to the clinic for a fitting, the clinic approves it
back to the lab, the lab builds the superstructure, hands it back for
a second fitting, the clinic approves again, the lab does cila/bitim,
and finally delivers it to the clinic for handover to the patient.
Previously we only had a single 'advance step' action callable by the
lab, which collapsed all of that into a linear forward push and didn't
capture who physically had the work at any given moment.
DB
- New jobs.location enum (at_clinic | at_lab, default at_clinic).
- Existing jobs keep working via a 'location ?? at_lab' fallback in
code; no manual backfill required for the four test rows.
State machine
- acceptJobAction (lab): pending → in_progress, currentStep=alt_yapi_prova,
location=at_lab. Skips the implicit 'olcu' production step now that
accepting the job means the lab has the impression in hand.
- handToClinicAction (lab, NEW): at_lab → at_clinic, step stays the
same. If step is cila_bitim, status becomes 'sent' (final delivery)
and finance sync fires.
- approveAtClinicAction (clinic, NEW): at_clinic → at_lab, step
advances to the next stage so the lab knows what to produce next.
- markDeliveredAction unchanged — clinic confirms the final handoff.
- advanceStepAction removed; its single forward push doesn't fit the
new bidirectional flow.
UI
- JobActionsPanel now picks the right button from the role + status +
location matrix:
* Lab + pending → 'İşleme Al'
* Lab + in_progress + at_lab + cila_bitim → 'Cila Bitim — Nihai Teslime Gönder'
* Lab + in_progress + at_lab + other → '{stage} Provaya Gönder'
* Clinic + in_progress + at_clinic → '{stage} Provası Tamam'
* Clinic + sent → 'Teslim Aldım'
* Both + pending → 'İptal Et'
- Job detail surfaces a new 'Şu An' info row that resolves to a
human-readable location ('Klinikte', 'Laboratuvarda', 'Hasta'ya
teslim edildi', ...) so anyone glancing at the page can tell where
the work physically is.
Two problems reported by the user:
1. File downloads broken on the lab side.
The link in JobFilesPanel pointed straight at Appwrite's
/storage/.../view URL. Storage permissions are scoped to the job's two
teams, but the browser only has a session cookie for our app domain,
not for db.kovaksoft.com — so the cross-origin request hit Appwrite
as a guest and 401'd.
New /api/jobs/[jobId]/files/[fileId]/download route. requireTenant()
first, then verify the caller's tenant is one of (clinicTenantId,
labTenantId) on the parent job, then storage.getFileDownload via the
admin SDK and stream the buffer back with Content-Disposition:
attachment so the browser saves it under the original filename.
listJobFiles now hands out that relative URL instead of the Appwrite
one — same anchor in the panel, just routed through us.
2. Saves and edits feel slow whenever a notification is involved.
Every mutation was awaiting logAudit, createNotification and
syncFinanceForJob in sequence. None of these need to block the user
response — audit is best-effort logging, notifications are async UX,
and the finance sync is idempotent and re-runs on the next mutation
anyway. Switched all 46 call sites across the action modules to
void-fire-and-forget (matching the pattern we already used in
clinic-pricing-actions). Net effect: each mutation drops ~3 sequential
Appwrite roundtrips before the server action returns.
What the clinic sees has changed from a fixed 6-item Protez Türü dropdown
to the actual products that lab has published in its catalog. Picking 'Premium
Zirkonyum (1500 TRY / diş)' is now an option; picking the generic
'Zirkonyum' bucket is not.
Wiring
- DB: jobs.prostheticId string column (optional — legacy jobs stay valid).
The denormalised prostheticType is still written, sourced server-side
from the chosen catalog row, so reports/aggregates keep working.
- validation/job.ts: prostheticId required, prostheticType removed from
the form payload (computed instead).
- job-actions.ts: looks up the catalog row, verifies tenantId match +
not archived, then pulls .type and .unitPrice from it to drive
calculateJobPriceForProsthetic.
Pricing helper
- New calculateJobPriceForProsthetic(prosthetic, clinicTenantId,
teethCount). Reuses the same clinic_pricing cascade
(custom price wins, otherwise discountPercent off catalog) but skips
the type-based catalog lookup entirely — it already has the row.
- /api/pricing/quote rewritten to accept { prostheticId, teethCount },
still gated on an approved connection between clinic and the lab that
owns the product.
UI
- jobs/new page server-loads each connected lab's active prosthetics
once and hands them to NewJobForm as prostheticsByLab.
- NewJobForm: 'Ürün *' Select replaces 'Protez Türü *'. The list filters
by the currently selected lab; switching labs clears the chosen
product. Each option shows name + 'unitPrice / diş' on the right.
Once selected, a small caption surfaces the underlying category
label ('Kategori: Zirkonyum') so the clinic still understands what
bucket the product falls into.
- PriceQuoteCard's hasInputs gating moved off prostheticType to
prostheticId.
Reduced the patient record to the minimum a dental clinic actually needs:
just a code, optional first/last name and free-text notes. Phone and
date-of-birth fields are gone from the UI everywhere — Add form, edit
dialog inside the table, the Bağlantı Bilgileri block on job detail, and
the table column list. The patient list now surfaces 'Notlar' instead.
Backend
- DB: firstName and lastName columns set to required=false via Appwrite
MCP (tables_db_update_string_column). Existing rows untouched.
- schema.ts Patient interface: firstName/lastName now optional, phone
and dateOfBirth removed from the type entirely. The underlying columns
are still in the DB so legacy rows aren't broken — we just stop
referencing them in code.
- validation/patient.ts: firstName/lastName drop min(1), phone and dob
fields removed.
- patient-actions.ts: pickFields no longer reads phone/dob, create and
update payloads no longer write them.
UI fallbacks
- PatientsTable: header has 'Notlar' instead of Telefon/Doğum. Ad Soyad
cell shows the joined name or em-dash. Edit dialog mirrors the same
simplified form.
- jobs/[jobId] detail page: when patient row has neither name, the page
title falls back to 'Hasta {patientCode}' (same as before for jobs
without a linked patient). The Hasta Bilgileri card now shows Ad Soyad
and Patient Code side by side, with notes spanning both columns.
Clinics couldn't see what an order would cost them before publishing.
Added a server-priced quote box that updates as the lab, prosthetic type
and tooth selection change. Three rendered states:
1. Discounted (custom unit price or discountPercent):
Katalog (4 × 1.500 ₺) 6.000 ₺
Klinik indirimi (%15) -900 ₺
──────────────────────
Toplam 5.100 ₺
2. Plain catalog match (no clinic override):
4 × 1.500 ₺ 6.000 ₺
'Katalog fiyatı uygulanıyor'
3. No catalog row for the chosen type:
'Fiyat işe başlanırken laboratuvar tarafından belirlenecek'
Bits to make this work
- calculateJobPrice now returns catalogUnitPrice, catalogTotal, savings
and teethCount alongside the final amount, so the client can render
a breakdown without reaching for any other table.
- POST /api/pricing/quote endpoint guards on clinic kind + an approved
connection before exposing pricing — no leaking catalog data to
unconnected clinics, and no per-lab discount snooping.
- NewJobForm's lab and prosthetic Selects became controlled (hidden
inputs mirror state to the form action), and a debounced effect
(250ms) re-fetches the quote when any of {lab, type, teeth.length}
changes. AbortController cancels in-flight requests when inputs change
again.
The /connections page was firing one listClinicPricing call per approved
counterpart inside Promise.all. That meant a lab with 10 clinics paid 10
sequential Appwrite roundtrips on every load, and worse, every time the
ClinicPricingDialog saved a row revalidatePath('/connections') ran the
whole fan-out again — saving a single discount felt like the request had
hung.
Replaced the per-peer query with listAllPricingForLab /
listAllPricingForClinic (single Query.equal on the side-specific column,
limit 500) and group the result into a Map client-side. One roundtrip
regardless of how many connections you have.
Also flipped the audit-log calls in setClinicPricingAction /
clearClinicPricingAction from 'await logAudit(...)' to 'void logAudit(...)'
— audit is best-effort by design and never blocks the user-facing
mutation; awaiting it doubled the perceived latency for nothing.
What changed
- jobs.teeth (FDI string[]). memberCount becomes a derived field (teeth.length).
A new TeethChart component renders the full permanent dentition as a
16-column grid for each arch with click-toggle selection.
- /jobs/new: removed the price + currency inputs and the manual memberCount
field. Clinics now pick teeth via the chart; the form blocks submission
until at least one tooth is selected.
- createJobAction calls a new calculateJobPrice() helper that walks the
pricing cascade and writes price + currency on the job server-side. A
clinic-supplied price hidden field would now be ignored — the field
isn't even in the schema.
Pricing cascade (calculateJobPrice, lib/appwrite/pricing.ts)
1. clinic_pricing row matching (lab, clinic, type) with customUnitPrice
→ use that flat unit price.
2. clinic_pricing row with discountPercent → catalog unitPrice × (1-d).
3. lab's prosthetics catalog row matching type (not archived).
4. nothing → price stays null; lab can still set it manually later.
Clinic-specific overrides (clinic_pricing table)
- Unique on (labTenantId, clinicTenantId, prostheticType) so each
combination has at most one rule.
- Row permissions: read by both teams (transparency for clinic), write
only by lab — clinic can see the discount they're getting but cannot
edit it.
- setClinicPricingAction validates an approved connection exists before
creating/updating, and rejects requests where neither customUnitPrice
nor discountPercent is set.
- clearClinicPricingAction wipes a rule (catalog price re-applies).
UI
- /connections 'Bağlantılarım' table gets a new column showing the active
pricing rules per counterpart. Lab side has a 'Fiyatlandırma' button
that opens a dialog (PROSTHETIC_TYPE × customPrice|discountPercent form
+ list of active rules with delete). Clinic side is read-only.
- Job detail: 'Fiyat' field now shows 'Lab tarafından belirlenecek' when
null, instead of a literal —. Adds a 'Dişler' info block listing the
selected FDI numbers.
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.
Memory [[feedback_use_server_only_async]]: 'use server' files can only
export async functions. notification-actions.ts also exported the
NotificationActionState type and an initialNotificationActionState const,
which Next 16 now flags hard at runtime ('A "use server" file can only
export async functions, found object.').
Moved both to a sibling notification-types.ts (same pattern we already
follow for connection-types / job-file-types / prosthetic-types). The
client component imports the const from -types and the actions from
-actions; no behaviour change.
Cluster: Appwrite container _APP_STORAGE_LIMIT 30000000 → 209715200
(200MB) in /root/services/appwrite/.env on kovaksoft-coolify, then
docker compose up -d to roll the worker pool with the new value.
Backup of the .env left at .env.bak.<date>.
Bucket: job-files maximumFileSize updated to 209715200 via Appwrite MCP
(storage_update_bucket).
App: MAX_FILE_BYTES in both the upload API route and the original server
action raised to 200MB. Client-side panel guard relaxed accordingly —
one large file is now allowed to fill the entire batch (the 200MB
proxy/serverActions cap is the bottleneck, not the per-file rule).
Error copy updated.
isletmem and any other tenants on the cluster also get the new limit,
which is the desired behaviour — old 30MB ceiling was a relic of an
Appwrite default that no DLS workflow can actually live with.
node-appwrite's storage.createFile happily takes the Web File API today,
but Next.js's multipart parser had already consumed the request body by
the time the SDK tries to stream it again — the SDK's second pass dies
with 'Unexpected end of form'. isletmem-kovakcrm's logo-actions uses the
documented pattern: arrayBuffer → Buffer → InputFile.fromBuffer(buf,
name). Adopting the same approach in uploadJobFilesAction.
The middlewareClientMaxBodySize bump from the previous commit still
matters (lifts the 10MB cap so the body even reaches us), but on its own
it wasn't enough: the Web File handoff itself was broken.
InputFile is exported from 'node-appwrite/file' (separate entry point —
the helper isn't on the main package export).
Next 16 caps any request body that flows through middleware at 10MB by
default. Our auth middleware matches every path, so /jobs/:id POSTs from
the file upload form hit 'Request body exceeded 10MB / Unexpected end of
form' the moment a user picked anything bigger than ~10MB total — the
server action never even ran.
serverActions.bodySizeLimit alone isn't enough; the new
middlewareClientMaxBodySize knob (Next 16) is the one that gates
middleware-handled bodies. Set both to 100mb so the 30MB-per-file bucket
limit is what actually matters.
The key isn't in NextConfig's TS types yet (Next 16.1), so it's assigned
via a narrow cast on the side rather than dropped into the object literal.
Also added console.log/error breadcrumbs to uploadJobFilesAction so the
next mystery upload failure shows up in the dev server log immediately
instead of silently bouncing back as 'Bağlantı hatası'.
Next 16's server-to-client serializer rejects values whose prototype is
not plain Object. node-appwrite returns row objects carrying internal
helpers (toString etc.), so every <ClientComponent prop={row}> crashed with
'Only plain objects, and a few built-ins, can be passed to Client
Components from Server Components.'
Added a tiny toPlain helper that JSON-roundtrips any value and applied it
at the boundary of every query that returns rows consumed by 'use client'
files:
- connection-queries (enrich)
- job-queries (inbound, outbound, approved labs)
- job-file-queries (listJobFiles)
- job-history-queries (listJobHistory)
- prosthetic-queries (listProsthetics, listActiveProsthetics)
- finance-queries (listFinanceEntries)
- notification-helpers (listNotifications)
- dashboard-queries (getDashboardData)
- jobs/[jobId] page (direct getRow for the job prop on JobActionsPanel)
Internal Maps inside queries stay live — only the data crossing the
server/client boundary is normalised.
- getDashboardData aggregates open jobs, pending-action jobs, unread
notifications, pending finance totals, approved connection count, recent
jobs (up to 8) and recent notifications (up to 5) — single Promise.all so
the dashboard renders in one round-trip.
- Four stat cards, each a Link to the relevant module; tone (positive /
negative) flips between clinic (payable) and lab (receivable).
- Clinic users with zero approved connections see a 'Bağlantı Kur' prompt
card so they don't get stuck on /jobs/new.
- Recent jobs table is role-aware: lab sees Klinik column + 'Son Gelen
İşler' header, clinic sees Laboratuvar column + 'Son Giden İşler' header.
- Recent notifications panel with read/unread dot, clickable header arrow
to /notifications.
- ActiveContext now carries 'kind' (mirror of TenantSettings.kind) so we no
longer reach into ctx.settings?.kind in callers.
Previously, signing in with a kind toggle when the account had no
tenant_settings row in the lab database returned 'Bu hesap için kayıt
bulunamadı'. For a freshly-imported isletmem user that has never opened
DLS, the right behaviour is onboarding — not a dead end.
resolveTenantOnLogin now distinguishes three states:
- no_tenants → redirect /onboarding?kind=<pill> (session stays)
- mismatch → real error naming the existing kind, session rolled back
- matched → existing tenant set as active, /dashboard
Onboarding page accepts ?kind= and the workspace form pre-selects it, so
the user keeps their login pill choice without re-picking. Also fixed the
'teams.total > 0' redirect — it now requires a tenant_settings row before
sending users off to /dashboard, otherwise users with cross-app teams but
no DLS workspace would bounce.
node-appwrite 23.1.0 ships a bundled undici Agent via node-fetch-native-with-agent.
That bundle uses an older undici dispatcher API that crashes on Node 26 with
'invalid onError method' (UND_ERR_INVALID_ARG), making every Appwrite call
fail with 'fetch failed' / our user-facing 'Bağlantı hatası' fallback.
The patch replaces createAgent/createFetch with thin pass-throughs to
globalThis.fetch — Node native fetch handles HTTPS to db.kovaksoft.com
directly, no proxy/agent customization needed. Verified end-to-end via
users.listMemberships against the live project.
Also added dev-mode error surfacing in appwriteError so future SDK
exceptions show the real message instead of 'Bağlantı hatası'.
Sign-in form now has a Klinik / Laboratuvar pill toggle (defaults to clinic).
The selected kind is posted alongside email+password; the server action
resolves the user's memberships, picks a tenant_settings row matching the
chosen kind, and sets it as active. If no matching tenant exists the session
is rolled back with a clear error.
Invite-flow logins skip the kind check — invite code drives team assignment.