A draft from scratch, and the provisions it cites checked in Insider

Atrium#53, stage 2 (the Umowy module).

From scratch: POST /drafts with no template_id makes a draft that is its
text - no fields, no slots, no {{...}} - written through PATCH body. It is
marked by template_name "" (never inferred from template_id, which also goes
NULL when a template is deleted); a template's draft refuses a body (409).
The same checks gate export, an empty text included. The console offers "Bez
szablonu (od zera)" and a text editor for such a draft.

Provisions: every provision the rendered document cites ("art. 471 k.c.",
"art. 6 ust. 1 lit. b RODO", "Dz.U. 1964 poz. 93", the patterns Atrium's chat
recognises) is looked up in Insider's GET /resolve with the person's token
(INSIDER_URL, optional like Lexicon and Galena). Not found, not in force, or
not checked is a warning, never an error: the lawyer decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 11:27:17 +01:00
co-authored by Claude Opus 5.5
parent 380f926a03
commit dc3baa9a40
10 changed files with 355 additions and 23 deletions
+2
View File
@@ -163,4 +163,6 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
# (DATA_DIR/files). Calls carry the signed-in person's own token — there is no service account.
LEXICON_URL=
GALENA_URL=
# Insider: the provisions a draft cites ("art. 471 k.c.") are looked up there before export.
INSIDER_URL=
MODULE_CALL_TIMEOUT=15
+10 -1
View File
@@ -308,7 +308,16 @@ MVP built 2026-11-14 on dredd-core v0.23.0 (scaffold + domain). Not deployed, no
- **D9: every sibling is optional.** `LEXICON_URL` / `GALENA_URL` empty = not deployed. Without
Lexicon, clauses come from the template (`origin: "template"`); without Galena, exports go to
`dredd_core.plain_files` (`DATA_DIR/files`). Never make either a hard dependency.
`dredd_core.plain_files` (`DATA_DIR/files`). Never make either a hard dependency. `INSIDER_URL`
the same: without Insider the provisions check reports that it did not run.
- **A draft from scratch** (Atrium#53, stage 2): `template_id` None at creation, `template_name` ""
(`drafts.FROM_SCRATCH`; never a template's name, which is at least one character, and never
inferred from `template_id`, which also goes NULL when a template is deleted). Its text is
written directly (`PATCH body`), with no fields, slots or `{{…}}`; a template's draft refuses a
body (409 `body_from_template`). The same checks, the empty text included, gate export.
- **Provisions are advice.** `checks.provisions` looks up every cited provision ("art. 471 k.c.",
"Dz.U. 1964 poz. 93") in Insider's `GET /resolve` as the person; not found, not in force or not
checked is always a WARNING, never an error: the lawyer decides.
- **Sibling calls carry the acting person's token** (`deps.extract_token`) through
`dredd_core.module_client` — never a service account, never a configured token. `services/siblings.py`
is the only place that talks to them.
+4 -1
View File
@@ -290,9 +290,12 @@ class Settings(BaseSettings):
# sibling's own authorization decides what that person may read or write there.
lexicon_url: str = ""
galena_url: str = ""
# Insider (laws and rulings): the provisions a draft cites are looked up there ("sprawdzanie
# przepisów", Atrium#53 stage 2). Empty = not deployed; the check then says it could not run.
insider_url: str = ""
module_call_timeout: float = 15.0
@field_validator("lexicon_url", "galena_url")
@field_validator("lexicon_url", "galena_url", "insider_url")
@classmethod
def _a_module_base_url(cls, v: str) -> str:
from dredd_core.errors import AppError
+1 -1
View File
@@ -49,7 +49,7 @@ def get_draft(draft_id: uuid.UUID, db: Session = Depends(get_db),
def update_draft(draft_id: uuid.UUID, body: DraftUpdateIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
out = service.update(db, user, draft_id, title=body.title, values=body.values,
ip=client_ip(request))
body=body.body, ip=client_ip(request))
db.commit()
return out
+4 -1
View File
@@ -138,13 +138,16 @@ class TemplateUpdateIn(BaseModel):
class DraftCreateIn(BaseModel):
template_id: uuid.UUID
"""`template_id` None: a draft from scratch (Atrium#53, stage 2), written as text, no template."""
template_id: uuid.UUID | None = None
title: str = Field(default="", max_length=300)
class DraftUpdateIn(BaseModel):
title: str | None = Field(default=None, max_length=300)
values: dict[str, str | None] | None = Field(default=None, max_length=100)
#: Only a draft from scratch: a template's draft keeps the template's text (409).
body: str | None = Field(default=None, max_length=200_000)
class ClauseIn(BaseModel):
+77 -3
View File
@@ -1,7 +1,7 @@
"""Kontrola w kodzie — the deterministic checks a draft passes before it may leave Scribe.
Pure functions, no database, no network, no model: the same input always gives the same report,
and every rule here can be read and tested on its own. Four families of check, each with a stable
and every rule here can be read and tested on its own. Five families of check, each with a stable
machine code so the console (and a future core `quotes`/`amounts`/`dates` contract, see the split
plan, P4) can act on them:
@@ -11,7 +11,9 @@ plan, P4) can act on them:
words (`amount_words`) says the same number as its digits;
* **dates** — every date is a real calendar date, and every ``[earlier, later]`` pair holds;
* **quotes** — a clause quoted into the draft is byte-identical to its source: the template's own
clause, or Lexicon's current text (fetched with the acting person's token by the caller).
clause, or Lexicon's current text (fetched with the acting person's token by the caller);
* **provisions** — every provision the document cites ("art. 471 k.c.", "Dz.U. 1964 poz. 93") is
one Insider can place and says is in force. Advice only: always a warning (Atrium#53, stage 2).
An ``error`` blocks export; a ``warning`` does not (e.g. Lexicon unreachable, so the quote is
checked only against the hash pinned when it was picked).
@@ -237,19 +239,89 @@ def _issue(level: str, check: str, code: str, message: str, key: str | None = No
#: `(slot, clause) -> current source text`, or None when the source is unreachable. Raises nothing.
SourceLookup = Callable[[str, dict], "str | None"]
#: One citation -> `"ok"` | `"not_found"` | `"repealed"`, or None when Insider cannot say.
ProvisionLookup = Callable[[str], "str | None"]
# ── provisions ("sprawdzanie przepisów", Atrium#53 stage 2) ──────────────────
# The citations Atrium's chat recognises (`CHAT_CITES`), ported: an article of a code by its
# abbreviation or its name, of RODO and the EU acts Insider knows by name, and a Journal of Laws
# reference. Each is looked up in Insider; what it says is advice (a WARNING), never a block: a
# citation Insider cannot place may still be right, and the lawyer decides.
_ART = r"\bart(?:ykuł|\.)?\s*\d+[a-z]?(?:\s*(?:§|ust\.|pkt|lit\.)\s*\w+\)?)*\s+"
_CODE = (r"Kodeks[a-ząćęłńóśźż]*\s+(?:postępowania\s+(?:cywiln|karn|administracyjn)|"
r"karn[a-ząćęłńóśźż]*\s+(?:skarbow|wykonawcz)|cywiln|karn|pracy|spółek\s+handlowych|"
r"wykroczeń|rodzinn[a-ząćęłńóśźż]*\s+i\s+opiekuńcz|morsk|wyborcz)[a-ząćęłńóśźż]*")
CITES = (
re.compile(_ART + r"(?:" + _CODE + r"|k(?!odeks)\.?\s?[a-z]{1,3}\.?(?:\s?[a-z]\.?){0,3}"
r"(?![a-ząćęłńóśźż])|p\.p\.s\.a\.|o\.p\.|RODO|GDPR|DSA|DMA|NIS2|eIDAS|MiCA)",
re.IGNORECASE),
re.compile(r"\bDz\.\s?U\.\s*(?:z\s*)?\d{4}(?:\s*r\.)?\s*(?:nr\s*\d+\s*)?poz\.\s*\d+",
re.IGNORECASE),
)
MAX_CITES = 30
def cites(text: str) -> list[str]:
"""The citations in `text`, in order, each once, whitespace folded. "art. 471 k.c. i art. 6
RODO": an abbreviation's optional letters may run on into the "i", which is cut off."""
found: list[tuple[int, str]] = []
for pattern in CITES:
for m in pattern.finditer(text):
c = re.sub(r"\s+", " ", m.group(0)).strip()
c = re.sub(r"\.\s[a-ząćęłńóśźż]$", ".", c, flags=re.IGNORECASE)
found.append((m.start(), c))
out: list[str] = []
for _, c in sorted(found):
if c not in out:
out.append(c)
return out[:MAX_CITES]
def provisions(text: str, lookup: ProvisionLookup | None) -> list[dict]:
"""A WARNING per cited provision Insider cannot place or says is not in force, and one when
the check could not run at all. Nothing when the text cites nothing."""
found = cites(text)
if not found:
return []
if lookup is None:
return [_issue(WARNING, "provisions", "provisions_unchecked",
f"Dokument powołuje {len(found)} przepis(y), ale Insider nie jest "
"podłączony, więc ich nie sprawdzono.")]
issues: list[dict] = []
unknown = 0
for c in found:
state = lookup(c)
if state == "not_found":
issues.append(_issue(WARNING, "provisions", "provision_not_found",
f"Nie znalazłem w Insiderze przepisu „{c}”. Sprawdź numer "
"artykułu i nazwę aktu.", c))
elif state == "repealed":
issues.append(_issue(WARNING, "provisions", "provision_repealed",
f"„{c}”: według Insidera akt nie obowiązuje.", c))
elif state is None:
unknown += 1
if unknown:
issues.append(_issue(WARNING, "provisions", "provisions_unchecked",
f"Insider nie odpowiedział o {unknown} przepis(y); sprawdź je ręcznie."))
return issues
def run(*, body: str, fields: list[dict], slots: list[dict], date_order: list, values: dict,
clauses: dict, template_slots: dict[str, str] | None,
lexicon_text: SourceLookup | None) -> dict:
lexicon_text: SourceLookup | None, provision_lookup: Any = None,
check_provisions: bool = False) -> dict:
"""Every check over one draft. ``{"ok": no errors, "issues": [...], "markdown": rendered}``.
`template_slots` is the CURRENT template's clause text per slot (None when the template is
gone; then the draft's own copy is the source). `lexicon_text` fetches a Lexicon clause's
current text (None when Lexicon is not configured).
`check_provisions` adds the provisions check over the rendered document, through
`provision_lookup` (None when Insider is not configured: the check then says it did not run).
"""
issues: list[dict] = []
by_key = {f["key"]: f for f in fields}
if not body.strip():
issues.append(_issue(ERROR, "placeholders", "body_empty", "Dokument jest pusty."))
slot_keys = {s["key"] for s in slots}
used_fields, used_slots = placeholders(body)
@@ -351,5 +423,7 @@ def run(*, body: str, fields: list[dict], slots: list[dict], date_order: list, v
if LEFTOVER.search(markdown):
issues.append(_issue(ERROR, "placeholders", "placeholder_left",
"W dokumencie zostały niewypełnione znaczniki {{…}}."))
if check_provisions:
issues.extend(provisions(markdown, provision_lookup))
return {"ok": not any(i["level"] == ERROR for i in issues), "issues": issues,
"markdown": markdown}
+44 -4
View File
@@ -24,11 +24,15 @@ from . import templates as template_service
FORMATS = {"md": "text/markdown", "docx": docx_render.MEDIA_TYPE}
MAX_VALUE = 20_000
#: A draft from scratch has no fields and no slots, so a `{{` or `}}` in its text could only be
#: left over (and would fail export as `placeholder_left`): refused when written instead.
PLACEHOLDER_IN_SCRATCH = checks.LEFTOVER
def _summary(d: Draft) -> dict:
return {"id": str(d.id), "title": d.title, "template_id": str(d.template_id) if d.template_id
else None, "template_name": d.template_name, "status": d.status.value,
else None, "template_name": d.template_name, "from_scratch": from_scratch(d),
"status": d.status.value,
"owner_id": str(d.owner_id) if d.owner_id else None,
"created_at": d.created_at.isoformat() if d.created_at else None,
"updated_at": d.updated_at.isoformat() if d.updated_at else None}
@@ -79,8 +83,31 @@ def _template_clause(slot: dict) -> dict | None:
"sha256": checks.sha256_text(text)}
def create(db: DbSession, user: AppUser, *, template_id: uuid.UUID, title: str,
#: `draft.template_name` of a draft written from scratch. A template's name is never empty
#: (`TemplateIn.name` min_length=1), so "" says "no template" for good - unlike `template_id`, which
#: also goes NULL when a template is deleted (SET NULL) and the draft keeps the template's text.
FROM_SCRATCH = ""
def from_scratch(row: Draft) -> bool:
return row.template_name == FROM_SCRATCH
def create(db: DbSession, user: AppUser, *, template_id: uuid.UUID | None, title: str,
ip: str | None = None) -> dict:
"""A draft from a template (its copy: body, fields, slots, own clauses), or with no template
(`template_id` None, Atrium#53 stage 2): an empty text the person writes, no fields, no slots.
Both pass the same checks before export."""
if template_id is None:
title = (title or "").strip() or "Nowy projekt"
row = Draft(title=title[:300], template_id=None, template_name=FROM_SCRATCH, body="",
fields=[], slots=[], date_order=[], values={}, clauses={},
status=DraftStatus.draft, owner_id=user.id, created_by=user.id)
db.add(row)
db.flush()
audit.record(db, action="draft.create", entity_type="draft", entity_id=row.id,
actor_id=user.id, detail=f"{title} (bez szablonu)", ip=ip)
return as_dict(row)
tpl = template_service.get(db, template_id)
title = (title or "").strip() or tpl.name
clauses = {s["key"]: c for s in tpl.slots or [] if (c := _template_clause(s))}
@@ -96,9 +123,19 @@ def create(db: DbSession, user: AppUser, *, template_id: uuid.UUID, title: str,
def update(db: DbSession, user: AppUser, draft_id: uuid.UUID, *, title: str | None = None,
values: dict | None = None, ip: str | None = None) -> dict:
values: dict | None = None, body: str | None = None, ip: str | None = None) -> dict:
row = _get(db, user, draft_id, write=True)
before = {"title": row.title, "values": dict(row.values or {})}
body_changed = False
if body is not None:
if not from_scratch(row):
raise ConflictError("Tekst projektu z szablonu pochodzi z szablonu; zmień szablon albo "
"zacznij projekt bez szablonu.", {"code": "body_from_template"})
if PLACEHOLDER_IN_SCRATCH.search(body):
raise ValidationError("Projekt bez szablonu nie ma pól ani miejsc na klauzule; usuń "
"znaczniki {{…}}.", {"code": "placeholder_in_scratch"})
body_changed = body != row.body
row.body = body
if title is not None:
row.title = title.strip()[:300] or row.title
if values is not None:
@@ -116,6 +153,8 @@ def update(db: DbSession, user: AppUser, draft_id: uuid.UUID, *, title: str | No
db.flush()
audit.record(db, action="draft.update", entity_type="draft", entity_id=row.id,
actor_id=user.id, ip=ip,
# The text itself never goes into the log: it is the contract.
detail="tekst zmieniony" if body_changed else None,
diff=changes.diff_of(before, {"title": row.title, "values": dict(row.values)}))
return as_dict(row)
@@ -161,7 +200,8 @@ def _check(db: DbSession, row: Draft, token: str | None) -> dict:
return checks.run(body=row.body, fields=row.fields or [], slots=row.slots or [],
date_order=row.date_order or [], values=row.values or {},
clauses=row.clauses or {}, template_slots=template_slots,
lexicon_text=siblings.lexicon_lookup(token))
lexicon_text=siblings.lexicon_lookup(token),
provision_lookup=siblings.insider_lookup(token), check_provisions=True)
_UNSAFE = re.compile(r'[\\/:*?"<>|\x00-\x1f]+')
+53 -4
View File
@@ -1,7 +1,9 @@
"""Lexicon and Galena, reached through `dredd_core.module_client` with the acting person's token.
"""Lexicon, Galena and Insider, reached through `dredd_core.module_client` with the acting
person's token.
Both are optional (D9). `lexicon()` / `galena()` return None when the module is not configured, and
every caller has a path for that: clauses from the template itself, exports into `plain_files`.
All are optional (D9). `lexicon()` / `galena()` / `insider()` return None when the module is not
configured, and every caller has a path for that: clauses from the template itself, exports into
`plain_files`, a provisions check that says it could not run.
The token is ALWAYS the one the person's own request carried — `deps.extract_token` — so Lexicon
decides which sources they may quote and Galena which projects they may write. Scribe holds no
@@ -34,8 +36,14 @@ def galena() -> ModuleClient | None:
return _client(get_settings().galena_url, "Galena")
def insider() -> ModuleClient | None:
return _client(get_settings().insider_url, "Insider")
def availability() -> dict:
return {"lexicon": bool(get_settings().lexicon_url), "galena": bool(get_settings().galena_url)}
s = get_settings()
return {"lexicon": bool(s.lexicon_url), "galena": bool(s.galena_url),
"insider": bool(s.insider_url)}
def _need_lexicon() -> ModuleClient:
@@ -106,6 +114,47 @@ def lexicon_lookup(token: str | None):
return look
# ── Insider ──────────────────────────────────────────────────────────────────
#: How Insider's status says an act is no longer in force (Atrium's chat judges by the same words).
_REPEALED = ("uchylon", "nieobowiązuj", "wygaśnięcie")
def insider_lookup(token: str | None):
"""A `checks.ProvisionLookup`: what Insider says of one citation, as this person -
`"ok"`, `"not_found"` (no such act, or no such article in it), `"repealed"` (the act is not in
force), or None when Insider cannot say (unreachable, 5xx, a citation it does not parse). The
whole lookup is None when Insider is not configured."""
client = insider()
if client is None:
return None
def look(citation: str) -> str | None:
try:
answer = client.request("GET", "/resolve", token=token, params={"citation": citation})
except AppError:
return None
if answer.status == 404:
return "not_found"
if not answer.ok:
return None
try:
body = answer.json()
except (ValueError, UnicodeDecodeError):
return None
docs = body.get("documents") or []
article = body.get("article")
if not docs or (article is not None and not article.get("located")):
return "not_found"
doc = docs[0]
status = str(doc.get("status") or "").lower()
if ((doc.get("extra") or {}).get("in_force") == "NOT_IN_FORCE"
or any(word in status for word in _REPEALED)):
return "repealed"
return "ok"
return look
# ── Galena ───────────────────────────────────────────────────────────────────
def save_to_galena(token: str | None, project_id: Any, path: str, data: bytes,
@@ -0,0 +1,143 @@
"""A draft from scratch and the provisions check (Atrium#53, stage 2). DB-free."""
from __future__ import annotations
import json
import types
import uuid
import pytest
from dredd_core.module_client import ModuleCallError, ModuleResponse
from app.errors import ConflictError, ValidationError
from app.services import checks, drafts, siblings
TEXT = ("§ 1. Strony stosują art. 471 k.c. oraz art. 6 ust. 1 lit. b RODO i art. 22 Kodeksu pracy.\n"
"§ 2. Zob. Dz.U. 1964 poz. 93. Ponownie art. 471 k.c.")
# ── citations ────────────────────────────────────────────────────────────────
def test_citations_are_found_in_order_once_each():
assert checks.cites(TEXT) == ["art. 471 k.c.", "art. 6 ust. 1 lit. b RODO",
"art. 22 Kodeksu pracy", "Dz.U. 1964 poz. 93"]
assert checks.cites("art. 471 k.c. i art. 6 RODO") == ["art. 471 k.c.", "art. 6 RODO"]
assert checks.cites("Strony zawierają umowę.") == []
def _states(**by_cite):
return lambda c: by_cite.get(c, "ok")
def test_provisions_warn_and_never_block():
issues = checks.provisions(TEXT, _states(**{"art. 22 Kodeksu pracy": "not_found",
"Dz.U. 1964 poz. 93": "repealed",
"art. 6 ust. 1 lit. b RODO": None}))
assert {i["level"] for i in issues} == {checks.WARNING}
assert [i["code"] for i in issues] == ["provision_not_found", "provision_repealed",
"provisions_unchecked"]
assert issues[0]["key"] == "art. 22 Kodeksu pracy"
def test_without_insider_the_check_says_it_did_not_run():
[issue] = checks.provisions(TEXT, None)
assert issue["code"] == "provisions_unchecked" and "nie jest podłączony" in issue["message"]
assert checks.provisions("Bez przepisów.", None) == []
def test_run_checks_provisions_only_when_asked():
base = dict(body=TEXT, fields=[], slots=[], date_order=[], values={}, clauses={},
template_slots=None, lexicon_text=None)
assert checks.run(**base)["issues"] == []
report = checks.run(**base, provision_lookup=_states(**{"art. 471 k.c.": "not_found"}),
check_provisions=True)
assert report["ok"] is True # a warning, not an error: export stays open
assert [i["code"] for i in report["issues"]] == ["provision_not_found"]
def test_an_empty_draft_does_not_export():
report = checks.run(body=" \n", fields=[], slots=[], date_order=[], values={}, clauses={},
template_slots=None, lexicon_text=None)
assert report["ok"] is False and report["issues"][0]["code"] == "body_empty"
# ── Insider, as the person ───────────────────────────────────────────────────
class _Insider:
service = "Insider"
def __init__(self, answers):
self.answers, self.calls = answers, []
def request(self, method, path, *, token, params=None, **_):
self.calls.append((method, path, token, params["citation"]))
got = self.answers[params["citation"]]
if isinstance(got, Exception):
raise got
status, body = got
return ModuleResponse(status, {}, json.dumps(body).encode())
def test_insider_lookup_reads_resolve_with_the_persons_token(monkeypatch):
fake = _Insider({
"art. 471 k.c.": (200, {"documents": [{"status": "obowiązujący"}],
"article": {"located": True}}),
"art. 9999 k.c.": (200, {"documents": [{"status": "obowiązujący"}],
"article": {"located": False}}),
"Dz.U. 1950 poz. 1": (200, {"documents": [{"status": "uchylony"}]}),
"art. 1 k.x.": (404, {"detail": "no"}),
"art. 2 k.c.": (503, {"detail": "busy"}),
"art. 3 k.c.": ModuleCallError("down", {"code": "unreachable"}),
})
monkeypatch.setattr(siblings, "insider", lambda: fake)
look = siblings.insider_lookup("tok-1")
assert [look(c) for c in fake.answers] == ["ok", "not_found", "repealed", "not_found", None,
None]
assert {c[:3] for c in fake.calls} == {("GET", "/resolve", "tok-1")}
monkeypatch.setattr(siblings, "insider", lambda: None)
assert siblings.insider_lookup("tok-1") is None
# ── a draft from scratch ─────────────────────────────────────────────────────
class _DB:
def __init__(self, row=None):
self.row, self.added = row, []
def add(self, obj):
self.added.append(obj)
def flush(self):
for obj in self.added:
if getattr(obj, "id", None) is None:
obj.id = uuid.uuid4()
@pytest.fixture
def quiet(monkeypatch):
monkeypatch.setattr(drafts.audit, "record", lambda *a, **k: None)
def test_a_draft_without_a_template_is_an_empty_text(quiet):
user = types.SimpleNamespace(id=uuid.uuid4())
out = drafts.create(_DB(), user, template_id=None, title="")
assert out["from_scratch"] is True and out["template_id"] is None
assert (out["title"], out["body"], out["fields"], out["slots"]) == ("Nowy projekt", "", [], [])
def _row(template_name):
from app.enums import DraftStatus
from app.models import Draft
return Draft(id=uuid.uuid4(), title="P", template_id=None, template_name=template_name,
body="stary", fields=[], slots=[], date_order=[], values={}, clauses={},
status=DraftStatus.draft)
def test_only_a_draft_from_scratch_takes_a_text(quiet, monkeypatch):
user = types.SimpleNamespace(id=uuid.uuid4())
scratch, templated = _row(drafts.FROM_SCRATCH), _row("Umowa o dzieło")
rows = {scratch.id: scratch, templated.id: templated}
monkeypatch.setattr(drafts, "_get", lambda db, u, i, write=False: rows[i])
out = drafts.update(_DB(), user, scratch.id, body=TEXT)
assert out["body"] == TEXT
# A template's draft whose template was deleted (template_id NULL) is still a template's.
with pytest.raises(ConflictError):
drafts.update(_DB(), user, templated.id, body="nowy")
with pytest.raises(ValidationError):
drafts.update(_DB(), user, scratch.id, body="Kwota {{kwota}}")
+17 -8
View File
@@ -213,6 +213,10 @@ const I18N = {
'Szablon': 'Template',
'Zmieniono': 'Changed',
'Pola': 'Fields',
'Tekst': 'Text',
'bez szablonu': 'no template',
'Bez szablonu (od zera)': 'No template (from scratch)',
'Przepisy powołane w tekście („art. 471 k.c.”) kontrola sprawdzi w Insiderze.': 'The check looks up the provisions the text cites (“art. 471 k.c.”) in Insider.',
'Klauzule': 'Clauses',
'Klauzule szablonu': 'Template clauses',
'Klucz': 'Key',
@@ -552,7 +556,7 @@ function draftTable(rows) {
<th>Nazwa</th><th>Szablon</th><th>Status</th><th>Zmieniono</th>
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/drafts/${encodeURIComponent(r.id)}'">
<td>${esc(r.title)}</td>
<td class="faint"${lbl('Szablon')}>${esc(r.template_name)}</td>
<td class="faint"${lbl('Szablon')}>${r.from_scratch ? _tr('bez szablonu') : esc(r.template_name)}</td>
<td${lbl('Status')}>${statusChip(r.status)}</td>
<td class="faint tiny"${lbl('Zmieniono')}>${fmtDateTime(r.updated_at)}</td>
</tr>`).join('')}</tbody></table></div>`;
@@ -702,9 +706,8 @@ async function viewDrafts(C, q) {
function openDraftNew(templateId) {
guard(async () => {
const tpls = await api('GET', '/templates');
if (!tpls.length) { toast('Najpierw potrzebny jest szablon.'); return; }
modal('Nowy projekt', '',
`<label class="field">Szablon<select id="dnTpl">${tpls.map((t) =>
`<label class="field">Szablon<select id="dnTpl"><option value="" ${templateId ? '' : 'selected'}>Bez szablonu (od zera)</option>${tpls.map((t) =>
`<option value="${esc(t.id)}" ${t.id === templateId ? 'selected' : ''}>${esc(t.name)}</option>`).join('')}</select></label>
<label class="field" style="margin-top:12px">Nazwa<input id="dnTitle" /></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
@@ -714,7 +717,7 @@ function openDraftNew(templateId) {
function saveDraftNew() {
guard(async () => {
const d = await api('POST', '/drafts', { template_id: $('dnTpl').value, title: $('dnTitle').value });
const d = await api('POST', '/drafts', { template_id: $('dnTpl').value || null, title: $('dnTitle').value });
closeModal();
location.hash = '#/drafts/' + encodeURIComponent(d.id);
await router();
@@ -757,10 +760,15 @@ async function viewDraft(C, id) {
</div></div>`;
}).join('');
C.innerHTML = pageHead(d.title, d.template_name,
// A draft from scratch (Atrium#53, stage 2) is its text: no fields, no slots, the same checks.
const top = d.from_scratch
? `<div class="card"><h3>Tekst</h3><div class="faint tiny">Przepisy powołane w tekście („art. 471 k.c.”) kontrola sprawdzi w Insiderze.</div>
<textarea id="dBody" rows="24" class="mono" style="width:100%;margin-top:8px" data-no-i18n>${esc(d.body)}</textarea>`
: `<div class="card"><h3>Pola</h3><div class="grid2" id="dFields">${d.fields.map((f) => fieldInput(f, d.values[f.key])).join('')}</div>`;
C.innerHTML = pageHead(d.title, d.from_scratch ? _tr('bez szablonu') : d.template_name,
`<button class="btn" onclick="renameDraft('${esc(d.id)}')">${svg(ICN.check)}Zmień nazwę</button>`
+ (exports.length ? '' : `<button class="btn danger" onclick="deleteDraft('${esc(d.id)}')">${svg(ICN.trash)}Usuń</button>`))
+ `<div class="card"><h3>Pola</h3><div class="grid2" id="dFields">${d.fields.map((f) => fieldInput(f, d.values[f.key])).join('')}</div>
+ top + `
<div class="row" style="margin-top:12px;gap:8px">
<button class="btn primary" onclick="saveDraftValues('${esc(d.id)}')">Zapisz</button>
<button class="btn" onclick="runCheck('${esc(d.id)}')">${svg(ICN.check)}Sprawdź</button>
@@ -794,7 +802,8 @@ function collectValues() {
}
async function saveDraftValuesQuiet(id) {
await api('PATCH', '/drafts/' + encodeURIComponent(id), { values: collectValues() });
const body = $('dBody') ? { body: $('dBody').value } : { values: collectValues() };
await api('PATCH', '/drafts/' + encodeURIComponent(id), body);
}
function saveDraftValues(id) {
@@ -1117,7 +1126,7 @@ function openSearch() {
<span class="sb"><span class="st">${esc(title)}</span>
<span class="ss">${esc(sub || '')}</span></span></button>`;
const html = (drafts.length ? '<div class="sgroup">Projekty</div>' + drafts.slice(0, 8).map((r) =>
item('#/drafts/' + encodeURIComponent(r.id), ICN.file, r.title, r.template_name)).join('') : '')
item('#/drafts/' + encodeURIComponent(r.id), ICN.file, r.title, r.from_scratch ? _tr('bez szablonu') : r.template_name)).join('') : '')
+ (tpls.length ? '<div class="sgroup">Szablony</div>' + tpls.slice(0, 8).map((t) =>
item('#/templates/' + encodeURIComponent(t.id), ICN.folder, t.name, t.description)).join('') : '');
$('sres').innerHTML = html || '<div class="search-empty">Brak wyników</div>';