from django.utils import timezone from django.contrib.contenttypes.models import ContentType from .models import Document, DocumentVersion, DocumentLink def create_document_and_link(*, tenant, patient, encounter=None, doc_type:str, title:str, body_markdown:str="", body_json=None, links=None, author=None, sign=False): doc = Document.objects.create( tenant=tenant, patient=patient, encounter=encounter, doc_type=doc_type, title=title, body_markdown=body_markdown, body_json=body_json or {}, authored_by=author, status="final" if sign else "draft", signed_at=timezone.now() if sign else None, signed_by=author if sign else None ) DocumentVersion.objects.create( document=doc, version=1, snapshot_markdown=body_markdown, snapshot_json=body_json or {}, changed_by=author ) for ln in links or []: ct = ContentType.objects.get(app_label=ln["app_label"], model=ln["model"].lower()) DocumentLink.objects.create(document=doc, content_type=ct, object_id=str(ln["pk"]), role=ln.get("role","context")) return doc def sign_document(doc: Document, user): doc.status = "final"; doc.signed_at = timezone.now(); doc.signed_by = user doc.save(update_fields=["status","signed_at","signed_by"]) return doc def amend_document(doc: Document, user, *, new_markdown:str="", new_json=None): next_version = (doc.versions.first().version + 1) if doc.versions.exists() else 2 DocumentVersion.objects.create( document=doc, version=next_version, snapshot_markdown=new_markdown, snapshot_json=new_json or {}, changed_by=user ) doc.body_markdown, doc.body_json, doc.is_amendment = new_markdown, (new_json or {}), True doc.save(update_fields=["body_markdown","body_json","updated_at","is_amendment"]) return doc