Compare commits
2 Commits
feature/ex
...
bug/ci-cd
| Author | SHA1 | Date | |
|---|---|---|---|
| ea0b2ad547 | |||
| 599371846c |
@@ -14,7 +14,7 @@ alwaysApply: false
|
||||
- **Comments:** a generated case hides the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on.
|
||||
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps plus `model_design` / `model_create`, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge, or that line’s teeth for a model step (the whole plan for a historical `__case__` model step). Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Scan, packing, and shipping stay on the owning lab. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` uses `childId:parentSourceKey` so the current-round unique index accepts both. `dedupeToothJobs` includes `sourceKey`.
|
||||
- **Share link:** QR + URL when the case is sent **or** a lab-origin case is started; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
- **Send to Exocad:** writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder (`showDirectoryPicker`, Chrome/Edge only). Does not open or mutate DentalDB SQLite. Builder: `components/lab/exocad/exocadDentalProject.ts` (PDF Tables 2–4 are the value source of truth). Folder session: `ExocadExportFolderProvider` (changeable Auto-Import folder). Monolithic = `AnatomicCrown`/`ZI`; prefab/Ti-base/multi-unit = `CustomAbutment`/`TI`; empty plans refuse export; Coping pontics use `ReducedPontic`, full-contour use `AnatomicPontic`; shade is `VCL` or bleach `V3DM`. No antagonists or scan files in this phase. `externalCode` stays manual. See `.cursor/skills/lab-cases/SKILL.md`.
|
||||
- **Send to Exocad:** writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder (`showDirectoryPicker`, Chrome/Edge only). Does not open or mutate DentalDB SQLite. Builder: `components/lab/exocad/exocadDentalProject.ts`. Folder session: `ExocadExportFolderProvider` (changeable Auto-Import folder). Active indirect leaves and implant stacks are mapped; empty plans refuse export; Coping pontics use `ReducedPontic`, full-contour use `AnatomicPontic`; shade is `VCL` or bleach `V3DM`. No antagonists or scan files in this phase. `externalCode` stays manual. See `.cursor/skills/lab-cases/SKILL.md`.
|
||||
- **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Files and Messages show unread counts (`LabCaseSectionReadState`); opening Details does not clear them. `ATTACHMENT_ADDED` is not a sidebar badge. Origin is one combobox of linked clinics and labs, or a typed name. Dentist/Technician stays optional. Arch jobs (`UA`/`LA`) highlight the read-only FDI chart.
|
||||
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, 56px line box so html2canvas does not clip the 28px glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print root top padding is 16px portrait / 24px landscape so the QR is not clipped; `html2canvas` `scrollY` is 0. The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). Section rules keep a 12px gap and 8px padding so the line clears the values; `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename.
|
||||
- **Detail chrome:** The header follows the detail panel width (`@container`, not the viewport): two columns (info start, actions end) from `@2xl`, otherwise one stack with the buttons under the info: name and the same QR thumb (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, then progress bar, external code, **Mark as important**, and billed, stacked and left aligned. The destination lab with `TAB_BILLING_EDIT` edits that fee (`PUT /billing/cases/:id/amount`) and the open case updates immediately; anyone else sees the stored fee, or the calculated quote when no fee is stored. Edit / Outsource / Send to Exocad / Get PDF are one equal-width grid (`responsiveFill`, truncating caption): 2 columns when narrow, one column per button from `@xl`, 2 columns in the `@2xl` end column with the QR below. Get PDF is a primary `CaseLifecycleButton` with no icon. Add files uses that button at the treatment action width. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”.
|
||||
|
||||
@@ -64,7 +64,7 @@ Writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import fo
|
||||
- `ExocadExportFolderProvider` remembers the Auto-Import directory handle (IndexedDB). The next export reopens that folder when permission remains and skips Browse. A missing or denied folder shows the folder picker again.
|
||||
- The connect dialog asks for the DentalDB Project Auto-Import folder and notes that this release exports case data only (scan companion files are still placed by the user when needed).
|
||||
- Builder: `frontend/src/components/lab/exocad/exocadDentalProject.ts`. Root is `<Treatment UseRecipientMaterialConfiguration="True">`. `ProjectGUID` is the Dyolink case id. `PracticeName` is the clinic name (no `PracticeId`). Patient family/given names are mandatory (`PatientName` / `PatientFirstName`); a one-word name is refused. `Notes` are the case comment bodies, or the detail comment when the thread is empty. File name is `{date}-{shortCaseId}.dentalProject`.
|
||||
- Tooth mapping follows the official `.dentalProject` Tables 2–4 in `docs/exocad_Specification_Document_dentalProject_Format_to_Be_Written.pdf` (XML `ReconstructionType` / `Material` / `ImplantType`). Full-contour Monolithic Zirconia = `AnatomicCrown`/`ZI`; cutback PFZ = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic = `AnatomicCrown`/`GCER`; Pressed Ceramic = `AnatomicCrown`/`LS2`; PEEK = `AnatomicCrown`/`PEEK`; Temporary Resin = `ProvisionalCrown`/`TEMP`. Active indirect: `veneer_*` → `Veneer`/`LS2`; `*_full_contour` inlay/onlay/overlay → `AnatomicInlay`/`LS2`; `*_layered` inlay/onlay/overlay → `OffsetInlay`/`LS2`. Legacy veneer/overlay leaves keep their old pairs; overlays never use OverlayCrown. Pontic follows the abutment family: `Coping` → `ReducedPontic`, full-contour → `AnatomicPontic`, with the abutment material. Implant stacks (Table 4 only has `None` / `CustomAbutment` / `WithoutAbutment`; DentalDB “On stock abutment” is not writable): `customized_abutment` → `CustomAbutment`/`TI`; `zirconia_abutment` → `CustomAbutment`/`ZI`; prefab / Ti-base / multi-unit → `CustomAbutment`/`TI`; `screw_retained` → `WithoutAbutment`. Post & core stacks are skipped and never force `ImplantType None`. A plain implant-capable restoration with no stack sets `ImplantType` `None`. Bridge groups set `MesialConnector` toward the mesial neighbor in the same `selectionGroupId`. Empty exports are refused (`NOTHING_TO_EXPORT`). Antagonists and scan files are not exported in this phase. Case shade → `ToothShade` as `VCL:<code>` or bleach `V3DM:0M*`.
|
||||
- Tooth mapping (XML `ReconstructionType` / `Material`): Monolithic Zirconia and PFZ = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic = `AnatomicCrown`/`GCER`; Pressed Ceramic = `AnatomicCrown`/`LS2`; PEEK = `AnatomicCrown`/`PEEK`; Temporary Resin = `ProvisionalCrown`/`TEMP`. Active indirect: `veneer_*` → `Veneer`/`LS2`; `*_full_contour` inlay/onlay/overlay → `AnatomicInlay`/`LS2`; `*_layered` inlay/onlay/overlay → `OffsetInlay`/`LS2`. Legacy veneer/overlay leaves keep their old pairs; overlays never use OverlayCrown. Pontic follows the abutment family: `Coping` → `ReducedPontic`, full-contour → `AnatomicPontic`, with the abutment material. `customized_abutment` → `CustomAbutment`/`TI`; `zirconia_abutment` → `CustomAbutment`/`ZI`; `screw_retained` → `WithoutAbutment`. Unmapped stacks (`ti_base_abutment`, prefab/multi-unit, post & core) are skipped and never force `ImplantType None`. A plain Coping with no implant stack sets `ImplantType` `None`. Bridge groups set `MesialConnector` toward the mesial neighbor in the same `selectionGroupId`. Empty exports are refused (`NOTHING_TO_EXPORT`). Antagonists and scan files are not exported in this phase. Case shade → `ToothShade` as `VCL:<code>` or bleach `V3DM:0M*`.
|
||||
- Auto-Import folder can be changed from the case header; success toast names the folder when known.
|
||||
- `externalCode` stays manual-only — export does not auto-fill it.
|
||||
- There is no Local database tab.
|
||||
|
||||
@@ -74,7 +74,7 @@ frontend/src/
|
||||
|
||||
**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. A type with both dry milling and sintering generates `milling_dry_sinter`; both wet milling and sintering generate `milling_wet_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Model design and model create can be outsourced with that line’s teeth, or the whole plan for a historical `__case__` model step; scan, packing, and shipping cannot. 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 the printed order number and the `case-sheet-{orderNumber}.pdf` filename. 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, plus model design and model create, 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. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper or download) writes an official `.dentalProject` XML into DentalDB's Project Auto-Import folder (`showDirectoryPicker`). It does not open or mutate DentalDB SQLite. Mapping follows the official PDF tables: monolithic = `AnatomicCrown`/`ZI`, PFZ/PFM = `Coping`, prefab/Ti-base/multi-unit/custom abutments = `CustomAbutment` (+ material), screw-retained = `WithoutAbutment`; IPS Overlay uses `AnatomicInlay`/`LS2`; active indirect leaves are mapped; Coping bridges use `ReducedPontic`, full-contour use `AnatomicPontic`. Case shade maps to `VCL:<code>` or bleach `V3DM:0M*`. Empty plans refuse export. The Auto-Import folder can be changed. `externalCode` stays manual. No antagonists or scan files in this phase. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/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 the printed order number and the `case-sheet-{orderNumber}.pdf` filename. 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, plus model design and model create, 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. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper or download) writes an official `.dentalProject` XML into DentalDB's Project Auto-Import folder (`showDirectoryPicker`). It does not open or mutate DentalDB SQLite. Prosthesis pairs stay the same (`Coping`/`ZI` for monolithic/PFZ, custom abutment on Coping, etc.); IPS Overlay uses `AnatomicInlay`/`LS2`; active indirect leaves and implant stacks are mapped; Coping bridges use `ReducedPontic`, full-contour use `AnatomicPontic`. Case shade maps to `VCL:<code>` or bleach `V3DM:0M*`. Empty plans refuse export. The Auto-Import folder can be changed. `externalCode` stays manual. No antagonists or scan files in this phase. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
|
||||
**Tooth shade (quick ref):** One optional VITA shade per lab case (`LabCase.toothShadeCode`, nullable; historical shades stay in notes). Full guide in Treatment (lab-dependent) and Cases create/detail; text only on Tasks, share page, and Case Sheet. Locks once any step in the outsource tree is completed; an unchanged resend is a no-op. See `.cursor/rules/tooth-shade.mdc`.
|
||||
|
||||
|
||||
@@ -560,7 +560,7 @@
|
||||
"sendToExocad": "Send to Exocad",
|
||||
"sendToExocadSaved": "Exported {fileName}. DentalDB will import it from the Auto-Import folder.",
|
||||
"sendToExocadSavedWithFolder": "Exported {fileName} to {folder}. DentalDB will import it from that Auto-Import folder.",
|
||||
"sendToExocadSkipped": "File exported. Exocad has no match for: {lines}. Set those in DentalDB if needed.",
|
||||
"sendToExocadSkipped": "Not exported: {lines}.",
|
||||
"sendToExocadConnectTitle": "Choose Exocad Auto-Import folder",
|
||||
"sendToExocadChangeFolderTitle": "Change Exocad Auto-Import folder",
|
||||
"sendToExocadFolderHint": "Select the Project Auto-Import folder configured in DentalDB. The next export reuses that folder when it is still available.",
|
||||
|
||||
@@ -560,7 +560,7 @@
|
||||
"sendToExocad": "ارسال به Exocad",
|
||||
"sendToExocadSaved": "پرونده {fileName} صادر شد. DentalDB آن را از پوشه Auto-Import وارد میکند.",
|
||||
"sendToExocadSavedWithFolder": "پرونده {fileName} در {folder} صادر شد. DentalDB آن را از همان پوشه Auto-Import وارد میکند.",
|
||||
"sendToExocadSkipped": "پرونده صادر شد. اکزوکد معادلی برای این موارد ندارد: {lines}. در صورت نیاز در DentalDB تنظیم کنید.",
|
||||
"sendToExocadSkipped": "صادر نشد: {lines}.",
|
||||
"sendToExocadConnectTitle": "انتخاب پوشه Auto-Import اکزوکد",
|
||||
"sendToExocadChangeFolderTitle": "تغییر پوشه Auto-Import اکزوکد",
|
||||
"sendToExocadFolderHint": "پوشه Project Auto-Import تنظیمشده در DentalDB را انتخاب کنید. ارسال بعدی در صورت در دسترس بودن همان پوشه را دوباره استفاده میکند.",
|
||||
|
||||
@@ -560,7 +560,7 @@
|
||||
"sendToExocad": "Naar Exocad sturen",
|
||||
"sendToExocadSaved": "{fileName} geëxporteerd. DentalDB importeert dit vanuit de Auto-Import-map.",
|
||||
"sendToExocadSavedWithFolder": "{fileName} geëxporteerd naar {folder}. DentalDB importeert dit vanuit die Auto-Import-map.",
|
||||
"sendToExocadSkipped": "Bestand geëxporteerd. Exocad heeft geen match voor: {lines}. Stel dit indien nodig in DentalDB in.",
|
||||
"sendToExocadSkipped": "Niet geëxporteerd: {lines}.",
|
||||
"sendToExocadConnectTitle": "Exocad Auto-Import-map kiezen",
|
||||
"sendToExocadChangeFolderTitle": "Exocad Auto-Import-map wijzigen",
|
||||
"sendToExocadFolderHint": "Selecteer de Project Auto-Import-map die in DentalDB is geconfigureerd. De volgende export hergebruikt die map wanneer die nog beschikbaar is.",
|
||||
|
||||
BIN
frontend/public/sql-wasm-browser.wasm
Executable file
BIN
frontend/public/sql-wasm-browser.wasm
Executable file
Binary file not shown.
@@ -96,21 +96,14 @@ describe('buildExocadDentalProject', () => {
|
||||
expect(project.xml).toContain('<PatientFirstName>John</PatientFirstName>');
|
||||
expect(project.xml).toContain('<Notes>Please check occlusion</Notes>');
|
||||
expect(project.xml).toContain('<Number>16</Number>');
|
||||
expect(project.xml).toContain('<ReconstructionType>Coping</ReconstructionType>');
|
||||
expect(project.xml).toContain('<Material>ZI</Material>');
|
||||
expect(project.xml).toContain('<Material>NP</Material>');
|
||||
expect(project.xml).toContain('<ReconstructionType>AnatomicCrown</ReconstructionType>');
|
||||
expect(project.xml).toContain('<ReconstructionType>Coping</ReconstructionType>');
|
||||
expect(project.xml).toContain('<Material>LS2</Material>');
|
||||
expect(project.xml).toContain('<ToothShade>VCL:A2</ToothShade>');
|
||||
expect(project.xml).toContain('<ImplantType>None</ImplantType>');
|
||||
expect(project.xml).not.toContain('Antagonist');
|
||||
// Monolithic is full-contour (AnatomicCrown); PFM is cutback (Coping).
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>16<\/Number>\s*<ReconstructionType>AnatomicCrown<\/ReconstructionType>[\s\S]*?<Material>ZI<\/Material>/,
|
||||
);
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>26<\/Number>\s*<ReconstructionType>Coping<\/ReconstructionType>[\s\S]*?<Material>NP<\/Material>/,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the export date for the file name, not the due date', () => {
|
||||
@@ -218,38 +211,18 @@ describe('buildExocadDentalProject', () => {
|
||||
expect(screw.xml).not.toContain('MaterialAbutment');
|
||||
});
|
||||
|
||||
it('maps prefabricated, Ti-base, and multi-unit abutments as CustomAbutment/TI', () => {
|
||||
for (const code of [
|
||||
'prefabricated_abutment',
|
||||
'ti_base_abutment',
|
||||
'multi_unit_abutment',
|
||||
] as const) {
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [
|
||||
{ tooth: '14', prosthesisTypeCode: 'pfz_crown' },
|
||||
{ tooth: '14', prosthesisTypeCode: code },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(project.skipped).toEqual([]);
|
||||
expect(project.xml).toContain('<ImplantType>CustomAbutment</ImplantType>');
|
||||
expect(project.xml).toContain('<MaterialAbutment>TI</MaterialAbutment>');
|
||||
}
|
||||
});
|
||||
|
||||
it('omits ImplantType None when an unmapped post-and-core stack is present and lists it as skipped', () => {
|
||||
it('omits ImplantType None when an unmapped implant stack is present and lists it as skipped', () => {
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [
|
||||
{ tooth: '16', prosthesisTypeCode: 'pfz_crown' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'cast_post_core' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'ti_base_abutment' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(project.xml).not.toContain('<ImplantType>');
|
||||
expect(project.skipped).toEqual([
|
||||
{ tooth: '16', prosthesisTypeCode: 'cast_post_core', reason: 'unmapped' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'ti_base_abutment', reason: 'unmapped' },
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
/**
|
||||
* Build an official Exocad `.dentalProject` XML file (3rd-party auto-import).
|
||||
*
|
||||
* Source of truth for allowed XML values: exocad’s
|
||||
* `.dentalProject` 3rd-party specification (Tables 2–4). Dyolink catalog codes are
|
||||
* mapped onto those values by the PDF definitions (e.g. full-contour → AnatomicCrown,
|
||||
* cutback framework → Coping). Older DentalDB reverse-engineering is kept only when
|
||||
* it does not contradict those tables.
|
||||
* Prosthesis → ReconstructionType / Material pairs follow the prior DentalDB mapping
|
||||
* where those values appear in the official specification tables.
|
||||
*/
|
||||
|
||||
export type ExocadExportFailure = 'PATIENT_NAME_INCOMPLETE' | 'NOTHING_TO_EXPORT';
|
||||
@@ -23,13 +19,12 @@ type MaterialMatch = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Catalog → ReconstructionType / Material (PDF Tables 2–3).
|
||||
* - Full-contour crowns → AnatomicCrown; cutback frameworks (PFZ/PFM) → Coping.
|
||||
* - OverlayCrown is outside Table 2, so overlays use AnatomicInlay / OffsetInlay.
|
||||
* - Active indirect leaves use Veneer / AnatomicInlay / OffsetInlay.
|
||||
* Catalog codes with one obvious Exocad work type and material.
|
||||
* OverlayCrown is not in the official 3rd-party ReconstructionType table, so overlays
|
||||
* use AnatomicInlay. Active indirect leaves use Veneer / AnatomicInlay / OffsetInlay.
|
||||
*/
|
||||
const MATERIAL_MATCH: Record<string, MaterialMatch> = {
|
||||
monolithic_zirconia: { reconstructionType: 'AnatomicCrown', material: 'ZI' },
|
||||
monolithic_zirconia: { reconstructionType: 'Coping', material: 'ZI' },
|
||||
pfz_crown: { reconstructionType: 'Coping', material: 'ZI' },
|
||||
pfm_crown: { reconstructionType: 'Coping', material: 'NP' },
|
||||
full_metal_crown: { reconstructionType: 'AnatomicCrown', material: 'NP' },
|
||||
@@ -60,30 +55,27 @@ type ImplantMatch = {
|
||||
materialAbutment?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Implant stacks → PDF Table 4 ImplantType (and MaterialAbutment when CustomAbutment).
|
||||
* Table 4 only lists None / CustomAbutment / WithoutAbutment. DentalDB’s separate
|
||||
* “On stock abutment” UI option is not writable here, so stock / Ti-base / multi-unit
|
||||
* abutments use CustomAbutment + TI — the only Table 4 value that means implant with
|
||||
* abutment (sample tooth 33 in the PDF uses the same pair).
|
||||
*/
|
||||
/** Implant stacks we can express with official ImplantType / MaterialAbutment values. */
|
||||
const IMPLANT_MATCH: Record<string, ImplantMatch> = {
|
||||
customized_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
zirconia_abutment: { implantType: 'CustomAbutment', materialAbutment: 'ZI' },
|
||||
prefabricated_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
ti_base_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
multi_unit_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
screw_retained: { implantType: 'WithoutAbutment' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Stacks with no ReconstructionType / ImplantType in the official tables.
|
||||
* When present with a restoration they are listed as skipped and ImplantType is
|
||||
* omitted (never written as None — that would claim a natural prep).
|
||||
* Implant / post stacks that are not representable in the official ImplantType table.
|
||||
* When present with a restoration, they are listed as skipped and ImplantType is omitted
|
||||
* (never written as None — that would claim a natural prep).
|
||||
*/
|
||||
const UNMAPPED_STACK_CODES = new Set(['cast_post_core', 'fiber_post_core']);
|
||||
const UNMAPPED_STACK_CODES = new Set([
|
||||
'ti_base_abutment',
|
||||
'prefabricated_abutment',
|
||||
'multi_unit_abutment',
|
||||
'cast_post_core',
|
||||
'fiber_post_core',
|
||||
]);
|
||||
|
||||
/** Reconstruction types that may carry ImplantType (PDF Table 2 “yes” column). */
|
||||
/** Reconstruction types that may carry ImplantType in the official table. */
|
||||
const IMPLANT_ALLOWED = new Set([
|
||||
'AnatomicCrown',
|
||||
'AnatomicWaxup',
|
||||
@@ -91,6 +83,7 @@ const IMPLANT_ALLOWED = new Set([
|
||||
'Coping',
|
||||
'OverpressCrown',
|
||||
'PrimaryTelescope',
|
||||
'ProvisionalCrown',
|
||||
'ReducedWaxup',
|
||||
]);
|
||||
|
||||
@@ -317,8 +310,8 @@ function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: Exo
|
||||
let materialAbutment: string | undefined;
|
||||
if (allowImplant) {
|
||||
if (implant.implantType === 'None') {
|
||||
// Natural prep on an implant-capable type (PDF Example II sets None explicitly).
|
||||
implantType = 'None';
|
||||
// Natural prep: only Coping historically always carried an explicit None.
|
||||
implantType = mapped.reconstructionType === 'Coping' ? 'None' : null;
|
||||
} else if (implant.implantType) {
|
||||
implantType = implant.implantType;
|
||||
materialAbutment = implant.materialAbutment;
|
||||
|
||||
@@ -16,7 +16,6 @@ import { labTaskStatusVariant } from '@/components/lab/labTaskStatusDisplay';
|
||||
import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
|
||||
import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
|
||||
import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel';
|
||||
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
|
||||
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
|
||||
import {
|
||||
buildCaseLinkedEdges,
|
||||
@@ -312,7 +311,6 @@ export function CaseDetailPanel({
|
||||
const tComments = useTranslations('caseComments');
|
||||
const tErrors = useTranslations('errors');
|
||||
const tCommon = useTranslations('common');
|
||||
const tProsthesis = useTranslations('prosthesis');
|
||||
const intlLocale = useLocale();
|
||||
const { settings: currencySettings } = useBillingCurrency(true);
|
||||
const { currentOrganization } = useAuth();
|
||||
@@ -496,10 +494,7 @@ export function CaseDetailPanel({
|
||||
toast.showInfo(
|
||||
t('sendToExocadSkipped', {
|
||||
lines: project.skipped
|
||||
.map(
|
||||
(line) =>
|
||||
`${line.tooth} ${prosthesisJobPathLabel(line.prosthesisTypeCode, prosthesisCatalog, (key) => tProsthesis(key as never))}`,
|
||||
)
|
||||
.map((line) => `${line.tooth} ${line.prosthesisTypeCode}`)
|
||||
.join(', '),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -267,6 +267,21 @@ curl http://wixur.ir/health
|
||||
|
||||
**Mobinnet:** public **80** is the modem. Use **443** instead: router forward **TCP 443 → 192.168.1.100**, then `https://wixur.ir`. Let's Encrypt after mobile-data `/health` works (self-signed is enough for that test).
|
||||
|
||||
### HTTPS certificates
|
||||
|
||||
Public port 80 is the modem, so Let's Encrypt cannot renew `wixur.ir` over HTTP. Renewal writes a TXT record in the Arvan zone `wixur.ir` and never uses port 80. That is the same check production uses for `nudentic.ir`. Do not run `install-arvan-renew.sh` on this PC. That script is only for the Linux certbot container.
|
||||
|
||||
One certificate covers `wixur.ir`, `www.wixur.ir`, `gitea.wixur.ir`, and `errors.wixur.ir`. Windows nginx keeps the PEM filenames already in `C:\tools\nginx-1.29.5\conf\nginx.conf`. [`scripts/renew-wixur-cert.ps1`](scripts/renew-wixur-cert.ps1) copies the new chain and key onto each of those paths and reloads nginx.
|
||||
|
||||
Put the Arvan API key on one line in `C:\dyolink\secrets\arvan-api-key`. Do not commit it. Docker Desktop must be running. On this PC:
|
||||
|
||||
```powershell
|
||||
cd C:\path\to\dyolink\infrastructure\scripts
|
||||
.\renew-wixur-cert.ps1 -Register
|
||||
```
|
||||
|
||||
`-Register` schedules that script daily at 03:15 under the signed-in account, then issues or renews immediately. A later run with no switch only renews and reloads.
|
||||
|
||||
---
|
||||
|
||||
## Test the pipeline
|
||||
@@ -375,6 +390,7 @@ On the Windows host, from repo `infrastructure/`:
|
||||
| Git clone fails in workflow | Set `CLONE_HOST=127.0.0.1:3000` |
|
||||
| Port 80 bind forbidden / access permissions | Portproxy already owns 80. Bind Docker to `18088` and point portproxy **80 → 127.0.0.1:18088**. Free IIS if it holds 80. |
|
||||
| `http://wixur.ir` unreachable / empty reply | Docker Desktop: run **portproxy** (§7). `127.0.0.1:18088/health` must work on Windows first. Router must forward **80**. |
|
||||
| Browser says the certificate date is invalid for `wixur.ir`, `gitea.wixur.ir`, or `errors.wixur.ir` | The Let's Encrypt files on the Windows nginx expired. HTTP renewal cannot succeed while public port 80 is the modem. On the PC run `infrastructure\scripts\renew-wixur-cert.ps1`. |
|
||||
| Port 8088 bind forbidden / access permissions | Portproxy already owns 8088. Bind Docker to `18088` and point portproxy **8088 → 127.0.0.1:18088**. |
|
||||
| Port 8088 unreachable from Mac / empty reply | Legacy URL. Prefer `http://wixur.ir`. Same 18088 backend; add portproxy 8088 only as fallback. |
|
||||
| Backend restart loop | JWT secrets still placeholder; fix `backend.staging.env` |
|
||||
@@ -410,6 +426,8 @@ docker logs dyolink_frontend_staging --tail 50
|
||||
| `infrastructure/nginx/http-only.conf` | HTTP reverse proxy **inside Docker** staging |
|
||||
| `infrastructure/nginx/windows-edge-http.conf` | Windows **host** nginx on port 80/443 → 18088 |
|
||||
| `infrastructure/nginx/windows-gitea.wixur.snippet.conf` | Windows nginx vhost for `https://gitea.wixur.ir` (unlimited body — Docker push) |
|
||||
| `infrastructure/scripts/renew-wixur-cert.ps1` | Renew `wixur.ir` / `gitea` / `errors` by Arvan DNS and reload Windows nginx |
|
||||
| `infrastructure/scripts/arvan-dns-auth.py` | Certbot hook: create the Arvan TXT record (`arvan_dns.py`, cleanup hook beside it) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,72 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create the _acme-challenge TXT record for a Certbot DNS-01 renewal.
|
||||
|
||||
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The Arvan key is one line
|
||||
in /etc/letsencrypt/arvan-api-key (never printed).
|
||||
"""
|
||||
import json
|
||||
"""Create the _acme-challenge TXT record for a Certbot DNS-01 renewal."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
|
||||
def auth_header():
|
||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||
if raw.lower().startswith("apikey "):
|
||||
return "Apikey " + raw.split(None, 1)[1]
|
||||
return "Apikey " + raw
|
||||
|
||||
|
||||
def request(method, url, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
method=method,
|
||||
headers={
|
||||
"Authorization": auth_header(),
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read().decode()
|
||||
|
||||
|
||||
def txt_visible(name, value):
|
||||
url = "https://dns.google/resolve?name={}&type=TXT".format(name)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=15) as resp:
|
||||
payload = json.loads(resp.read().decode())
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
||||
return False
|
||||
for answer in payload.get("Answer") or []:
|
||||
data = answer.get("data", "").strip('"')
|
||||
if value in data:
|
||||
return True
|
||||
return False
|
||||
from arvan_dns import txt_visible, upsert_txt, zone_and_record
|
||||
|
||||
|
||||
def main():
|
||||
domain = os.environ["CERTBOT_DOMAIN"]
|
||||
value = os.environ["CERTBOT_VALIDATION"]
|
||||
status, body = request(
|
||||
"POST",
|
||||
"{}/{}/dns-records".format(API, domain),
|
||||
{"type": "txt", "name": "_acme-challenge", "value": {"text": value}, "ttl": 120},
|
||||
)
|
||||
if status == 422 and "duplicate" in body.lower():
|
||||
status = 200
|
||||
if status < 200 or status >= 300:
|
||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||
fqdn = "_acme-challenge.{}".format(domain)
|
||||
zone, name, fqdn = zone_and_record(domain)
|
||||
upsert_txt(zone, name, value)
|
||||
for _ in range(18):
|
||||
if txt_visible(fqdn, value):
|
||||
print("TXT record is visible")
|
||||
|
||||
@@ -1,69 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Remove the _acme-challenge TXT record created for one Certbot attempt."""
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
|
||||
def auth_header():
|
||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||
if raw.lower().startswith("apikey "):
|
||||
return "Apikey " + raw.split(None, 1)[1]
|
||||
return "Apikey " + raw
|
||||
|
||||
|
||||
def request(method, url):
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
method=method,
|
||||
headers={"Authorization": auth_header(), "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read().decode()
|
||||
|
||||
|
||||
def walk(node):
|
||||
if isinstance(node, list):
|
||||
for item in node:
|
||||
yield from walk(item)
|
||||
elif isinstance(node, dict):
|
||||
if "id" in node and "type" in node:
|
||||
yield node
|
||||
for value in node.values():
|
||||
yield from walk(value)
|
||||
from arvan_dns import delete_record, list_txt, record_names_match, txt_text, zone_and_record
|
||||
|
||||
|
||||
def main():
|
||||
domain = os.environ["CERTBOT_DOMAIN"]
|
||||
value = os.environ.get("CERTBOT_VALIDATION", "")
|
||||
status, body = request("GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, domain))
|
||||
if status < 200 or status >= 300:
|
||||
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
||||
payload = json.loads(body)
|
||||
for record in walk(payload):
|
||||
zone, name, fqdn = zone_and_record(domain)
|
||||
for record in list_txt(zone):
|
||||
if str(record.get("type", "")).lower() != "txt":
|
||||
continue
|
||||
if record.get("name") not in ("_acme-challenge", "_acme-challenge." + domain):
|
||||
if not record_names_match(record.get("name"), name, fqdn):
|
||||
continue
|
||||
text = ""
|
||||
raw_value = record.get("value")
|
||||
if isinstance(raw_value, dict):
|
||||
text = str(raw_value.get("text", ""))
|
||||
if value and value not in text:
|
||||
if value and value not in txt_text(record):
|
||||
continue
|
||||
del_status, _ = request(
|
||||
"DELETE",
|
||||
"{}/{}/dns-records/{}".format(API, domain, record["id"]),
|
||||
)
|
||||
if del_status not in (200, 204, 404):
|
||||
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(del_status))
|
||||
delete_record(zone, record["id"])
|
||||
print("TXT record removed")
|
||||
|
||||
|
||||
|
||||
148
infrastructure/scripts/arvan_dns.py
Normal file
148
infrastructure/scripts/arvan_dns.py
Normal file
@@ -0,0 +1,148 @@
|
||||
"""Arvan DNS helpers for a Certbot DNS-01 check.
|
||||
|
||||
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The API key is one line
|
||||
in /etc/letsencrypt/arvan-api-key and is never printed.
|
||||
|
||||
nudentic.ir is its own zone, so the TXT name is _acme-challenge.
|
||||
A name under wixur.ir uses that zone: gitea.wixur.ir becomes
|
||||
_acme-challenge.gitea in zone wixur.ir.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||
|
||||
|
||||
def auth_header():
|
||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||
if raw.lower().startswith("apikey "):
|
||||
return "Apikey " + raw.split(None, 1)[1]
|
||||
return "Apikey " + raw
|
||||
|
||||
|
||||
def request(method, url, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
headers = {"Authorization": auth_header(), "Accept": "application/json"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read().decode()
|
||||
|
||||
|
||||
def zone_and_record(domain):
|
||||
domain = domain.strip().rstrip(".")
|
||||
override = os.environ.get("ARVAN_ZONE", "").strip().rstrip(".")
|
||||
labels = domain.split(".")
|
||||
if override:
|
||||
zone = override
|
||||
elif len(labels) > 2:
|
||||
zone = ".".join(labels[-2:])
|
||||
else:
|
||||
zone = domain
|
||||
if domain == zone:
|
||||
name = "_acme-challenge"
|
||||
elif domain.endswith("." + zone):
|
||||
prefix = domain[: -(len(zone) + 1)]
|
||||
name = "_acme-challenge." + prefix
|
||||
else:
|
||||
raise SystemExit("CERTBOT_DOMAIN is not in the Arvan zone")
|
||||
fqdn = name + "." + zone
|
||||
return zone, name, fqdn
|
||||
|
||||
|
||||
def record_names_match(got, name, fqdn):
|
||||
if not isinstance(got, str):
|
||||
return False
|
||||
got = got.strip().rstrip(".").lower()
|
||||
return got in (name.lower(), fqdn.lower())
|
||||
|
||||
|
||||
def walk(node):
|
||||
if isinstance(node, list):
|
||||
for item in node:
|
||||
yield from walk(item)
|
||||
elif isinstance(node, dict):
|
||||
if "id" in node and "type" in node:
|
||||
yield node
|
||||
for value in node.values():
|
||||
yield from walk(value)
|
||||
|
||||
|
||||
def txt_text(record):
|
||||
raw_value = record.get("value")
|
||||
if isinstance(raw_value, dict):
|
||||
return str(raw_value.get("text", ""))
|
||||
if isinstance(raw_value, str):
|
||||
return raw_value
|
||||
return ""
|
||||
|
||||
|
||||
def list_txt(zone):
|
||||
status, body = request(
|
||||
"GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, zone)
|
||||
)
|
||||
if status < 200 or status >= 300:
|
||||
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
||||
return list(walk(json.loads(body)))
|
||||
|
||||
|
||||
def delete_record(zone, record_id):
|
||||
status, _body = request(
|
||||
"DELETE", "{}/{}/dns-records/{}".format(API, zone, record_id)
|
||||
)
|
||||
if status not in (200, 204, 404):
|
||||
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(status))
|
||||
|
||||
|
||||
def upsert_txt(zone, name, value):
|
||||
status, body = request(
|
||||
"POST",
|
||||
"{}/{}/dns-records".format(API, zone),
|
||||
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
||||
)
|
||||
if 200 <= status < 300:
|
||||
return
|
||||
if status == 422 and "duplicate" in body.lower():
|
||||
for record in list_txt(zone):
|
||||
if str(record.get("type", "")).lower() != "txt":
|
||||
continue
|
||||
if not record_names_match(record.get("name"), name, name + "." + zone):
|
||||
continue
|
||||
if value and value in txt_text(record):
|
||||
return
|
||||
delete_record(zone, record["id"])
|
||||
status, _body = request(
|
||||
"POST",
|
||||
"{}/{}/dns-records".format(API, zone),
|
||||
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
||||
)
|
||||
if 200 <= status < 300 or (status == 422 and "duplicate" in _body.lower()):
|
||||
return
|
||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||
|
||||
|
||||
def txt_visible(fqdn, value):
|
||||
urls = (
|
||||
"https://dns.google/resolve?name={}&type=TXT".format(fqdn),
|
||||
"https://cloudflare-dns.com/dns-query?name={}&type=TXT".format(fqdn),
|
||||
)
|
||||
for url in urls:
|
||||
req = urllib.request.Request(url, headers={"Accept": "application/dns-json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
payload = json.loads(resp.read().decode())
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
||||
continue
|
||||
for answer in payload.get("Answer") or []:
|
||||
data = answer.get("data", "").strip('"')
|
||||
if value in data:
|
||||
return True
|
||||
return False
|
||||
@@ -14,10 +14,11 @@ if [ ! -s "$KEY" ]; then
|
||||
fi
|
||||
|
||||
docker cp "$KEY" dyolink_certbot_prod:/etc/letsencrypt/arvan-api-key
|
||||
docker cp "$SCRIPT_DIR/arvan_dns.py" dyolink_certbot_prod:/etc/letsencrypt/arvan_dns.py
|
||||
docker cp "$SCRIPT_DIR/arvan-dns-auth.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-auth.py
|
||||
docker cp "$SCRIPT_DIR/arvan-dns-cleanup.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-cleanup.py
|
||||
docker exec dyolink_certbot_prod chmod 600 /etc/letsencrypt/arvan-api-key
|
||||
docker exec dyolink_certbot_prod chmod 755 /etc/letsencrypt/arvan-dns-auth.py /etc/letsencrypt/arvan-dns-cleanup.py
|
||||
docker exec dyolink_certbot_prod chmod 755 /etc/letsencrypt/arvan_dns.py /etc/letsencrypt/arvan-dns-auth.py /etc/letsencrypt/arvan-dns-cleanup.py
|
||||
|
||||
docker exec -i dyolink_certbot_prod python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
|
||||
204
infrastructure/scripts/renew-wixur-cert.ps1
Normal file
204
infrastructure/scripts/renew-wixur-cert.ps1
Normal file
@@ -0,0 +1,204 @@
|
||||
# Issue or renew the wixur.ir certificate with an Arvan DNS check, copy it onto
|
||||
# the PEM files Windows nginx already uses, and reload nginx.
|
||||
# Requires Docker Desktop. The Arvan API key is one line in
|
||||
# C:\dyolink\secrets\arvan-api-key and is not printed.
|
||||
# -Register also schedules this script daily at 03:15.
|
||||
|
||||
param(
|
||||
[switch]$Register
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$KeyFile = 'C:\dyolink\secrets\arvan-api-key'
|
||||
$LeDir = 'C:\dyolink\letsencrypt'
|
||||
$NginxHome = 'C:\tools\nginx-1.29.5'
|
||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$TaskName = 'Dyolink renew wixur certificate'
|
||||
$Names = @('wixur.ir', 'www.wixur.ir', 'gitea.wixur.ir', 'errors.wixur.ir')
|
||||
|
||||
function Convert-DockerPath {
|
||||
param([string]$Path)
|
||||
$full = [IO.Path]::GetFullPath($Path)
|
||||
if ($full -match '^([A-Za-z]):\\(.*)$') {
|
||||
return '/' + $Matches[1].ToLower() + '/' + ($Matches[2] -replace '\\', '/')
|
||||
}
|
||||
return ($full -replace '\\', '/')
|
||||
}
|
||||
|
||||
function Register-RenewTask {
|
||||
param([string]$ScriptPath)
|
||||
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`""
|
||||
$trigger = New-ScheduledTaskTrigger -Daily -At '03:15'
|
||||
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd
|
||||
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
|
||||
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
|
||||
Write-Host "Scheduled $TaskName daily at 03:15."
|
||||
}
|
||||
|
||||
function Get-NginxText {
|
||||
param([string]$Path, [int]$Depth = 0)
|
||||
if ($Depth -gt 5 -or -not (Test-Path -LiteralPath $Path)) { return '' }
|
||||
$dir = Split-Path -Parent $Path
|
||||
$raw = Get-Content -LiteralPath $Path -Raw
|
||||
$included = [regex]::Replace($raw, '(?m)^\s*include\s+([^;]+);', {
|
||||
param($match)
|
||||
$spec = $match.Groups[1].Value.Trim().Trim('"').Trim("'")
|
||||
$full = $spec
|
||||
if ($spec -notmatch '^[A-Za-z]:\\' -and -not $spec.StartsWith('\\')) {
|
||||
$full = Join-Path $dir ($spec -replace '/', '\')
|
||||
}
|
||||
$chunks = @()
|
||||
foreach ($file in @(Get-Item -Path $full -ErrorAction SilentlyContinue)) {
|
||||
$chunks += Get-NginxText -Path $file.FullName -Depth ($Depth + 1)
|
||||
}
|
||||
$chunks -join "`n"
|
||||
})
|
||||
return $included
|
||||
}
|
||||
|
||||
function Split-ServerBlocks {
|
||||
param([string]$Text)
|
||||
$blocks = @()
|
||||
$idx = 0
|
||||
while ($true) {
|
||||
$start = $Text.IndexOf('server', $idx)
|
||||
if ($start -lt 0) { break }
|
||||
$brace = $Text.IndexOf('{', $start)
|
||||
if ($brace -lt 0) { break }
|
||||
$depth = 0
|
||||
$end = -1
|
||||
for ($i = $brace; $i -lt $Text.Length; $i++) {
|
||||
$ch = $Text[$i]
|
||||
if ($ch -eq '{') { $depth++ }
|
||||
elseif ($ch -eq '}') {
|
||||
$depth--
|
||||
if ($depth -eq 0) { $end = $i; break }
|
||||
}
|
||||
}
|
||||
if ($end -lt 0) { break }
|
||||
$blocks += $Text.Substring($start, $end - $start + 1)
|
||||
$idx = $end + 1
|
||||
}
|
||||
return $blocks
|
||||
}
|
||||
|
||||
function Resolve-NginxPath {
|
||||
param([string]$Relative)
|
||||
$clean = $Relative.Trim().Trim('"').Trim("'")
|
||||
if ($clean -match '^[A-Za-z]:\\' -or $clean.StartsWith('\\')) { return $clean }
|
||||
$rel = $clean -replace '/', '\'
|
||||
$candidates = @(
|
||||
(Join-Path $NginxHome $rel),
|
||||
(Join-Path $NginxHome (Join-Path 'conf' $rel))
|
||||
)
|
||||
foreach ($candidate in $candidates) {
|
||||
if (Test-Path -LiteralPath $candidate) { return $candidate }
|
||||
}
|
||||
return $candidates[1]
|
||||
}
|
||||
|
||||
function Get-CertTargets {
|
||||
$conf = Join-Path $NginxHome 'conf\nginx.conf'
|
||||
$text = Get-NginxText -Path $conf
|
||||
$targets = @()
|
||||
foreach ($block in (Split-ServerBlocks -Text $text)) {
|
||||
$serverNames = @()
|
||||
foreach ($match in [regex]::Matches($block, '(?m)^\s*server_name\s+([^;]+);')) {
|
||||
$serverNames += ($match.Groups[1].Value -split '\s+')
|
||||
}
|
||||
$hit = $false
|
||||
foreach ($name in $serverNames) {
|
||||
if ($Names -contains $name.Trim()) { $hit = $true }
|
||||
}
|
||||
if (-not $hit) { continue }
|
||||
$chain = [regex]::Match($block, '(?m)^\s*ssl_certificate\s+(\S+)\s*;')
|
||||
$key = [regex]::Match($block, '(?m)^\s*ssl_certificate_key\s+(\S+)\s*;')
|
||||
if (-not $chain.Success -or -not $key.Success) { continue }
|
||||
$targets += [pscustomobject]@{
|
||||
Chain = Resolve-NginxPath $chain.Groups[1].Value
|
||||
Key = Resolve-NginxPath $key.Groups[1].Value
|
||||
}
|
||||
}
|
||||
if ($targets.Count -eq 0) {
|
||||
$ssl = Join-Path $NginxHome 'conf\ssl'
|
||||
$targets = @(
|
||||
[pscustomobject]@{ Chain = Join-Path $ssl 'wixur-chain.pem'; Key = Join-Path $ssl 'wixur-key.pem' },
|
||||
[pscustomobject]@{ Chain = Join-Path $ssl 'gitea-chain.pem'; Key = Join-Path $ssl 'gitea-key.pem' },
|
||||
[pscustomobject]@{ Chain = Join-Path $ssl 'errors-chain.pem'; Key = Join-Path $ssl 'errors-key.pem' }
|
||||
)
|
||||
}
|
||||
return $targets
|
||||
}
|
||||
|
||||
if ($Register) {
|
||||
Register-RenewTask -ScriptPath $PSCommandPath
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $KeyFile)) {
|
||||
throw "Missing $KeyFile"
|
||||
}
|
||||
foreach ($hook in @('arvan_dns.py', 'arvan-dns-auth.py', 'arvan-dns-cleanup.py')) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $ScriptDir $hook))) {
|
||||
throw "Missing $hook next to this script"
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $LeDir | Out-Null
|
||||
$hookDir = Join-Path $LeDir 'hooks'
|
||||
New-Item -ItemType Directory -Force -Path $hookDir | Out-Null
|
||||
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan_dns.py') -Destination (Join-Path $hookDir 'arvan_dns.py')
|
||||
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan-dns-auth.py') -Destination (Join-Path $hookDir 'arvan-dns-auth.py')
|
||||
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan-dns-cleanup.py') -Destination (Join-Path $hookDir 'arvan-dns-cleanup.py')
|
||||
Copy-Item -Force -Path $KeyFile -Destination (Join-Path $LeDir 'arvan-api-key')
|
||||
|
||||
$renewal = Join-Path $LeDir 'renewal\wixur.ir.conf'
|
||||
$emailArgs = '--register-unsafely-without-email'
|
||||
if ($env:LETSENCRYPT_EMAIL) {
|
||||
$emailArgs = "--email $env:LETSENCRYPT_EMAIL --no-eff-email"
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $renewal) {
|
||||
$certbotCmd = "chmod 755 /etc/letsencrypt/hooks/*.py; chmod 600 /etc/letsencrypt/arvan-api-key; certbot renew --cert-name wixur.ir --non-interactive"
|
||||
} else {
|
||||
$certbotCmd = "chmod 755 /etc/letsencrypt/hooks/*.py; chmod 600 /etc/letsencrypt/arvan-api-key; certbot certonly --manual --preferred-challenges dns --manual-auth-hook /etc/letsencrypt/hooks/arvan-dns-auth.py --manual-cleanup-hook /etc/letsencrypt/hooks/arvan-dns-cleanup.py --cert-name wixur.ir -d wixur.ir -d www.wixur.ir -d gitea.wixur.ir -d errors.wixur.ir --agree-tos --non-interactive $emailArgs"
|
||||
}
|
||||
|
||||
$leMount = Convert-DockerPath $LeDir
|
||||
Write-Host 'Requesting the certificate.'
|
||||
docker run --rm --entrypoint sh -v "${leMount}:/etc/letsencrypt" certbot/certbot -c $certbotCmd
|
||||
if ($LASTEXITCODE -ne 0) { throw "certbot failed ($LASTEXITCODE)" }
|
||||
|
||||
$exportCmd = 'cp -L /etc/letsencrypt/live/wixur.ir/fullchain.pem /etc/letsencrypt/export-fullchain.pem && cp -L /etc/letsencrypt/live/wixur.ir/privkey.pem /etc/letsencrypt/export-privkey.pem'
|
||||
docker run --rm --entrypoint sh -v "${leMount}:/etc/letsencrypt" certbot/certbot -c $exportCmd
|
||||
if ($LASTEXITCODE -ne 0) { throw "could not read the new certificate ($LASTEXITCODE)" }
|
||||
|
||||
$chainSrc = Join-Path $LeDir 'export-fullchain.pem'
|
||||
$keySrc = Join-Path $LeDir 'export-privkey.pem'
|
||||
$seen = @{}
|
||||
foreach ($target in (Get-CertTargets)) {
|
||||
$dir = Split-Path -Parent $target.Chain
|
||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||
if (-not $seen.ContainsKey($target.Chain)) {
|
||||
Copy-Item -Force -Path $chainSrc -Destination $target.Chain
|
||||
Write-Host "Updated $($target.Chain)"
|
||||
$seen[$target.Chain] = $true
|
||||
}
|
||||
if (-not $seen.ContainsKey($target.Key)) {
|
||||
Copy-Item -Force -Path $keySrc -Destination $target.Key
|
||||
Write-Host "Updated $($target.Key)"
|
||||
$seen[$target.Key] = $true
|
||||
}
|
||||
}
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue $chainSrc, $keySrc
|
||||
|
||||
Push-Location $NginxHome
|
||||
try {
|
||||
& .\nginx.exe -t
|
||||
if ($LASTEXITCODE -ne 0) { throw 'nginx -t failed' }
|
||||
& .\nginx.exe -s reload
|
||||
if ($LASTEXITCODE -ne 0) { throw 'nginx reload failed' }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
Write-Host 'Nginx reloaded.'
|
||||
Reference in New Issue
Block a user