22 KiB
Dyolink — Agent guide
This file orients Cursor agents at the start of a new chat. Project conventions live in .cursor/rules/ (auto-loaded). Workflow playbooks live in .cursor/skills/.
What Dyolink is
Dental clinic ↔ lab platform (monorepo):
| Path | Stack |
|---|---|
backend/ |
NestJS, Prisma, PostgreSQL |
frontend/ |
Next.js 16, React 19, next-intl, Tailwind |
infrastructure/ |
Docker — staging https://wixur.ir (Windows, STAGING-DEPLOY.md); prod https://nudentic.ir (Linux, DEPLOY.md) |
Organization types: CLINIC (patients, appointments, treatment) and LAB (cases, tasks). Many features are org-type-specific. Permissions use TAB_*_READ / TAB_*_EDIT codes — see backend/src/common/permissions.ts.
Before you code
- Read applicable rules in
.cursor/rules/(especiallydyolink-overviewand the file-scoped rule for the area you touch). - Match existing patterns in the nearest feature folder — do not invent parallel structures.
- Keep diffs small — one concern per change unless the user asks for a refactor.
- Verify:
npm run build(backend) andnpx tsc --noEmit(frontend) when you change types or cross-cutting code.
Frontend layout (critical)
frontend/src/
app/ → thin page.tsx only; compose from ui/
components/
ui/shared/ → cross-feature UI (Button, Sidebar, …)
ui/{feature}/ → feature UI (+ {Feature}Page.tsx for route logic)
shared/ → cross-feature non-UI (formatApiError, permissions, …)
{feature}/ → feature non-UI (helpers, config, pure functions)
lib/ → api clients, hooks
types/ → shared TS types
assets/brand|fdi/ → brand + FDI SVG sources (not public/) — see `.cursor/rules/frontend-assets.mdc`
messages/{en,fa,nl}.json → all user-facing strings
Example thin page: app/.../treatment/page.tsx → imports TreatmentWorkspace from components/ui/treatment/.
i18n formatting: Display dates/times/numbers via lib/i18n/format.ts + useLocale(). Form dates: AppDateInput (all locales — same component, masked typing + calendar popup). Appointments / Treatment headers: ScheduleDayPicker (compact centers the date). Filter <select>s: FORM_SELECT_CLASS; data tables: Table with logical text-start/text-end (not text-left/text-right). Skill: .cursor/skills/i18n-formatting/SKILL.md.
Treatment tab: Preview and editable form are separate until the user clicks Load into workspace on a history item. See .cursor/skills/treatment-workspace/SKILL.md before changing that flow.
Treatment edit / details (quick ref):
- Day/mode gate: editable only for live draft on today/future (
canEditTreatmentForDay). Past day / historical load → read-only form. Patient search sits in the page header (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. Day arrows that land on a day with no visit reset the workspace to one blank detail and no patient, the same as opening Treatment with nothing selected. A day that has a visit still opens it. If neither exists, the editor shows an inline empty state (no dialog) pointing to New treatment in the rail — do not auto-create. New treatment is at the top of the left rail (selected-patient card below it) and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as[]until Add. - Unscheduled strip cards use the same treatment-type banner as appointments from the first detail’s type only (
unscheduledStripColorCode; live draft for the open card). Empty first line → chip theming even if later lines are typed. Strip trash only when every line is blank (no type/teeth/notes/attachments, including[]); typed cards need chip-delete first. BackendDELETE /treatments/:idis empty-only (TREATMENT_HAS_DETAILS). - A sent line stays editable until any lab task is completed, including a step finished by a further lab. Then the line locks (
TREATMENT_DETAIL_SENT). Add detail still OK same day; Remove detail = trash on chip (unsent, including last line; day/edit gates apply). A sent line cannot be removed. Empty details persist as[]. - Entry: Type dropdown + compact attachments strip (
TreatmentDetailAttachmentsStrip) on one row (plus Lab dispatch / Chart toggle when the type is lab-dependent; dispatch is primary, Chart is outline; Add detail uses the same width), then bordered FDI chart (Cases chrome/scale) or the lab dispatch panel in that same slot, then full-width auto-growing Notes. Prosthesis types are assigned on the chart (teeth, or Upper/Lower arch labels for jaw products — dashed outline + plus). Arch Upper/Lower/Both remaps existingUA/LAjobs (Both→Upper clears lower). Picker:4frwrapping category grid /1fradd-ons with a vertical divider; tiles useProsthesisCatalogIcon(md+ two-line labels on category/addon;sm+ centered icon/label on child cards); expanded children use a parent-colored L rail sized to the first child card; parent-bar back arrow is black; empty crown slot is plus + dashed “Crown can be added”; filled crown slot stays visible so it can be changed. Screen type names useprosthesisTypeLabelStyleFromCatalog. Implant/post & core show a crown suggestion slot; a veneer/inlay/onlay/overlay hides it. The empty Pontic suggestion appears only beside an immediate crown/indirect neighbor; a filled Pontic stays visible and the category remains available for pontic-first entry. Post & core is disabled after crown or implant; Implant is disabled after post & core; screw-retained does not suggest another crown. Removable on a tooth shows the full-arch notice (partial is tooth-selected; complete/overdenture use arch controls). Prosthesis teeth always have jobs (hydrate/save prune). Lab-rail / Go to dispatch opens the dispatch view (pendingScrollToLabRef). Detail chips show type + teeth; lab-dependent chips use colored sent/unsent text. Sent follows the linked lab casesentAt(or the detail’s ownsentAt); editing stays open until a lab step is completed. The sent date stays on dispatch. Lab dispatch keeps comments. - Tooth selection: Hit target is the unrotated cell (
pointerdownonly — do not also bindclick). Glyph ispointer-events-none; nest hover/selected scale inside the rotate wrapper. Neighbor circles connect/disconnect adjacent selected teeth; midline 11–21 / 41–31 is allowed; never keep a 1-tooth connected group. Prosthesis plain click opens the picker; Done stores the jobs copy brush; Clear this tooth stores a clear brush. Ctrl/Cmd+click or drag replays either action on one tooth; Shift+click replays it across an inclusive same-arch range as singles. Brushes reset when the active detail/line changes. Pontic is a no-child tile for pontic-first entry. A tooth immediately beside Pontic initially enables Crown, Indirect, and Pontic, allowing Pontic chains; assigning a Crown immediately enables Implant without reopening the picker (Indirect does not). Choosing a new restoration leaf on one connected abutment updates every restoration abutment in that span while preserving each tooth’s implant/post-core jobs. Orphan/mixed Pontics remain drafts with amber warning but block Send/Start (PONTIC_BRIDGE_INVALID). Helpers live inprosthesisTree.ts. Same-type teeth in one detail are one display job; stacked types remain distinct. A connected crown/indirect + Pontic span uses the abutment leaf’s steps and renders13 · Pontic - 14 · PFZ Crown; Pontic adds none.UA/LAare arch jobs; partial denture is one tooth-selected job across all selected FDI teeth. - Lab dispatch layout: due date beside title (
justify-between, logical start/end for RTL); job rows fromLabCaseToothJobsList→ProsthesisJobLineLabel(same-type teeth in one detail share a row; Connected badge only for a real bridge). Sent cases: dest/jobs share a row with the Cases QR thumb; tracker + comments are full width below. - Schedule date: Treatment strip and Appointments page headers use
ScheduleDayPickercompact(date centered in a 3-col header; no “Schedule date” label; Today on the navigator).
Treatment lab rules (quick ref):
- Lab-dependent details (e.g. prosthesis) without teeth or an arch product can save but cannot ship — same inline amber banner (
labShipmentBlockedBody). Arch jobs store asUA/LAonLabCaseToothProsthesis.tooth(not ondetail.teeth). Un-bridged / mixed pontics use the same banner chrome (ponticBridgeBlockedBody) and disable Send / lab-origin Start before the API; send/Start still reject withPONTIC_BRIDGE_INVALID/PROSTHESIS_STACK_INVALID. Draft autosave does not. - New prosthesis dispatch lines start empty (no default lab). Types are assigned only on the chart (
ProsthesisAssignChart/ProsthesisJobPopover). Recent-lab chips are the last 3 sent destinations — pick is explicit, never auto-selected. - Detail treatment type need not match appointment purpose — purpose only seeds the first line of an empty appointment draft (first open, and Add detail when the plan is
[]). Further Add detail starts with an empty type. Unscheduled / New treatment still seeds a blank first line. - History filters are client-side only (
treatmentHistoryFilters.ts): “Not shipped to lab” + single date on already-fetched patient history; includes live current draft when filtering. - Lab shipments rail: unified list with scope toggle This patient vs All updates (unread across org for this clinician's cases only, includes patient name). Opening a case from the rail opens the lab dispatch view (same slot as the chart).
- Unread semantics: Treatment tab badge = count of unread cases for the user's own treatment plans (per-case read cursor) and clears when a case is opened/marked read (not on tab visit). Completions count only when every task in the case is done (
CASE_COMPLETED) — not each workflow step. - Live lab rail:
notification.created→notifyTabBadgesChanged()silently refreshes patient lab cases + unread rail (does not clear draft/form state). - Lab shipment progress + comments: shown in Lab dispatch panel for the active shipment; expanding activity / opening comments marks that case read. Shared UI:
LabCaseCommentsPanel— newest first; sent = start / received = end (text-start/justify-start, RTL-safe); passviewerSide.
Appointments (quick ref): Do not delete (or change patient) when hasTreatment; codes APPOINTMENT_HAS_TREATMENT / APPOINTMENT_PATIENT_LOCKED. Past days: no new bookings; edit/delete OK without treatment; with treatment → toast. Appointment delete does not cascade-delete treatments. Working hours: client IANA timeZone on create/update — never Date#getHours()/getDay() on the UTC server. Logical API errors: AppException + errors.* (never Nest English throws). Patient must belong to this org (ensurePatientInOrg). See .cursor/rules/appointments.mdc, .cursor/skills/api-errors/SKILL.md.
Patients (quick ref): List/get/update/create are this-org named patients (createdByOrganizationId, isWalkIn: false). identification stays globally unique; mobile is not. Same-org identification create returns existing: true; other org / walk-in / null creator → PATIENT_IDENTIFICATION_UNAVAILABLE (409, no leak). See .cursor/rules/patients.mdc.
Staff (quick ref): Owner / TAB_STAFF_EDIT can remove a password (POST /staff/members/:id/clear-password) and copy a setup link — never set one for someone else. Login page unchanged (passwordHash: null cannot sign in). /accept-invite password_setup is password-only. See .cursor/rules/staff.mdc.
Billing (quick ref): Same three-tab hub for CLINIC + LAB (/billing?view=). Clinic: CLINIC_PRICE / CLINIC_COMMISSION + patient receipts + partner payments. Lab: LAB_PRICE / LAB_COMMISSION + partner ledger only. Commissions are fixed amounts (not percents). Partner list is a shared ledger (both orgs see both sides’ rows; always CONFIRMED). Money inputs: AppMoneyInput. This publish: Billing is hidden for CLINIC via hidden-tabs.ts (billingOrgTypes: ['CLINIC']). See .cursor/rules/billing.mdc, .cursor/skills/billing/SKILL.md.
Lab Tasks tab: Newest case first (listedAt); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has requiresModelSteps) → packing/shipping. lineCount stays 1. __line__ tasks are independently completable and non-outsourceable; historical __case__ scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become typeA+typeB sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use ProsthesisJobLineLabel; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. CASE_COMPLETED drives inbox/tab badges only after all case tasks finish. See .cursor/skills/lab-tasks/SKILL.md.
Lab Cases tab: Filter by prosthesis type (not treatment type); auto-select newest case on open; list 10 per page; left rail list fills column height (flex-1 overflow-y-auto). Unstarted lab-origin drafts sit in a collapsed expandable rail section (opens on click or Add case); received + started cases list below, newest first by send or start time (listedAt, same key as Tasks). List cards use LabCaseProsthesisGroupsList (colored type + teeth, shared with Treatment rail) plus From clinic / Generated / From lab origin badges. Job titles use ProsthesisJobLineLabel the same as Treatment/Tasks (13 · Pontic - 14 · PFZ Crown; no category; indirect keeps Inlay · Layered ceramic). Deep link: ?caseId=, ?clinicOrganizationId=. Share link: QR + URL on sent cases and started lab-origin cases (attachment left, QR right); opens /lab-case/[token] focus page. Case Sheet PDF: same portrait/landscape layout, one A4 page (jspdf/html2canvas, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional externalCode replaces order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use 0px letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (PARTNER_CASE_CREATED, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases or Tasks permission. Unstarted generated drafts can be deleted (DELETE /cases/:id). Edit (POST /cases/:id/stop) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. Outsource gives selected in-progress prosthesis steps to one linked lab as a child case. Child sourceKey stays the child case id unless two selected steps share tooth, type, and workflow (childId:parentSourceKey). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. Live: inbox Socket.IO → notifyTabBadgesChanged() soft-refreshes list + selected detail (no remount). A file upload emits case-section.changed on that socket (no inbox card) so Files and Messages unread counts refresh the same way. Add case is a full-width split button with the lab mic. One file can be removed from its card menu. Attachments have no size cap; production must recreate nginx from the SSL template or /api stays at 50MB. See .cursor/skills/lab-cases/SKILL.md and .cursor/skills/lab-case-share-link/SKILL.md.
Lab case share link (quick ref):
- Token on first ship or lab-origin Start →
/{locale}/lab-case/{token}after login. Editing a generated case keeps that token. The page reads the current round and the live patient/clinic snapshots. Cases, Treatment lab dispatch, and the Case Sheet QR all use this URL. - Lab: view with Cases or Tasks access; edit task status only with Tasks edit + assignee rules; comments if Cases or Tasks edit.
- Clinic: treatment provider with
TAB_TREATMENT_EDIT— read-only tasks, can comment. Same QR as lab Cases appears on Treatment Lab dispatch after send (dest/jobs beside the thumb; tracker + comments full width below). - Logged out → login with
?from=→storeAuthRedirectFromPaththenuseEnterAppWhenAuthenticated(consumeAuthRedirectonce after org ready — not insideuseAuth.login()/registerTrial). Trial register uses the same hook; staff/org invite (includingpassword_setup) thenlogin()+navigateIntoAppIfOrgSelected. See.cursor/rules/post-auth-navigation.mdc.
Today dashboard: KPIs + charts per org type/permissions; deep links via today-deep-links.ts (Tasks KPIs/charts, case partners). See .cursor/skills/today-dashboard/SKILL.md.
Backend layout
backend/src/
modules/{feature}/ → controller, service, dto, module
common/ → guards, permissions, errors, utils
admin/ → AdminJS `/admin` panel (curated Prisma resources)
prisma/ → schema, migrations, seed
Errors: AppException + ErrorCode → frontend getUserFacingError(). Unexpected 500s: GlitchTip (SENTRY_DSN). Never throw raw strings for user-facing failures.
AdminJS: Manual resource allowlist in backend/src/admin/resources.ts. Whenever schema.prisma changes, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite @@id must not be registered (list 500) — including LabCaseAttachment. Single-id models such as StaffWorkingHoursSchedule / StaffWorkingHoursBlock are registered. LabCase.listedAt is trigger-maintained (list/filter/show only; never write). Rule: .cursor/rules/adminjs.mdc.
Database backups: Production dumps three times a day on the Linux server and keeps them for 3 days. The Mac copies them once at 17:00. The Windows staging PC copies each dump 30 minutes later and keeps them for 30 days (task Nudentic copy prod backup). Runbook: infrastructure/BACKUP.md.
Git & commits
- Do not commit or push unless the user explicitly asks.
- Do not amend commits, force-push, or skip hooks unless explicitly requested.
Skills (workflows)
| Skill | When to use |
|---|---|
.cursor/skills/add-feature/ |
New tab, API module, or end-to-end feature |
.cursor/skills/treatment-workspace/ |
Treatment tab: preview vs form, history, load flow, drafts, type-first entry, connected teeth |
.cursor/skills/lab-tasks/ |
Lab Tasks tab: listedAt sort (same as Cases), case grouping, step-completed filter, prosthesis colors |
.cursor/skills/lab-cases/ |
Lab Cases tab: listedAt newest-first, prosthesis filter, auto-select, Case Sheet PDF, external code |
.cursor/skills/lab-case-share-link/ |
Case QR share link: access token, focus page, auth redirect, access rules |
.cursor/skills/tab-badges/ |
Sidebar tab badges: Cases/Tasks/Treatment, LabCaseActivity, tab-counts API, read cursors |
.cursor/skills/notifications-inbox/ |
Header bell inbox: UserNotification fan-out, Socket.IO realtime |
.cursor/skills/today-dashboard/ |
Today tab: KPIs, charts, deep links, gadget registry |
.cursor/skills/billing/ |
Billing hub: fee/commission sheets, patient & partner ledger |
.cursor/skills/frontend-structure/ |
Moving components, auditing folder layout |
.cursor/skills/api-errors/ |
New backend errors + frontend translations |
.cursor/skills/i18n-formatting/ |
Dates, times, numbers, Jalali picker, RTL formatting |
Subagents (Task tool)
Use subagents to save context, not to avoid work:
| Type | Use for |
|---|---|
explore |
Broad codebase search, unfamiliar areas |
shell |
Git, npm, long command sequences |
generalPurpose |
Multi-step research when parent context is large |
Do not delegate the user's main task to a subagent and return its summary — implement in the parent unless the user asked for exploration only.
Improving this setup
When you and the user agree on a new convention, add or update a rule in .cursor/rules/ (keep each rule under ~50 lines, one topic). For multi-step workflows, extend .cursor/skills/.
To save a convention mid-task, say: "Remember this" or "Add to project rules" — the agent uses the capture-convention skill and updates the repo (commit with your code).
| You say | Agent does |
|---|---|
| "Remember this: …" | Updates the right .mdc rule or skill |
| "Add a skill for …" | Creates .cursor/skills/{name}/SKILL.md |
| "This rule is wrong" | Edits the rule file; you commit |
Rules/skills load automatically in new chats; they do not update themselves unless you ask.