Datalumina

Signing

Send for signing

Build the agreement as data with Python-filled prices, dates, and clauses, freeze it with a SHA-256 hash, and email the client a signing link.

By the end of this page Send freezes a drafted contract and emails the client a private signing link.

The agreement is frozen at Send. A SHA-256 hash covers the whole document, the sections and the template text alike. If anything changes after Send, even one section in the database, the hash no longer matches and signing is refused.

Turn a contract into a document

Replace backend/app/templates.py. The highlighted lines are new.

backend/app/templates.py
from app.config import settings
from app.db import Contract

CLIENT_INPUT = ("What we need from the client", "Access, data, people and decisions, as bullets.")

# The three contract types. "sections" are written by the AI, one call each, with their own
# prompt. "pages" decide what the client sees on each page; the other keys there are filled
# in by Python below. The model never writes a price, a date or a legal clause.
TEMPLATES = {
    "fixed_price": {
        "title": "Statement of Work",
        "sections": {
            "summary": ("Project summary", "Two or three sentences: the problem and the change."),
            "scope": ("Scope and deliverables", "What we build and hand over, as bullets."),
            "milestones": ("Milestones", "The phases in order and what each delivers, as bullets."),
            "client_input": CLIENT_INPUT,
            "out_of_scope": ("Out of scope", "Exclusions as bullets. Never restate the scope."),
        },
        "pages": [
            ("Project & Scope", ["summary", "scope"]),
            ("Milestones & Payment", ["milestones", "timeline", "payments"]),
            ("Working Together", ["client_input", "out_of_scope"]),
            ("Legal Terms", ["ip", "confidentiality", "liability", "termination"]),
        ],
    },
    "retainer": {
        "title": "Monthly Retainer",
        "sections": {
            "purpose": ("Purpose", "In two or three sentences: what the retainer is for."),
            "services": ("Monthly services", "The work we do every month, as bullets."),
            "requests": ("How the client asks for work", "How requests reach us and get priority."),
            "reporting": ("Reporting", "What we report to the client each month."),
            "client_input": CLIENT_INPUT,
            "not_included": ("Not included", "What the retainer does not cover, as bullets."),
        },
        "pages": [
            ("Purpose & Terms", ["purpose", "terms"]),
            ("Monthly Services", ["services", "requests", "reporting"]),
            ("Working Together", ["client_input", "not_included"]),
            ("Legal Terms", ["ip", "confidentiality", "liability", "termination"]),
        ],
    },
    "discovery": {
        "title": "Discovery & AI Audit",
        "sections": {
            "context": ("Context", "In two or three sentences: the business and why audit now."),
            "questions": ("Questions we answer", "The main questions of the audit, as bullets."),
            "approach": ("Approach", "Interviews, data and process review, as bullets."),
            "roadmap": ("Deliverable: the AI roadmap", "What the report contains, as bullets."),
        },
        "pages": [  # One page.
            ("Discovery & AI Audit", ["context", "questions", "approach", "roadmap", "fee"]),
        ],
    },
}

CLAUSES = {
    "ip": (
        "Intellectual property",
        "When the client has paid in full, the client owns the deliverables made for this "
        f"agreement. {settings.company_name} keeps its general know-how, tools and code.",
    ),
    "confidentiality": (
        "Confidentiality",
        "Both parties keep the other party's non-public information confidential, during this "
        "agreement and for two years after it ends.",
    ),
    "liability": (
        "Liability",
        f"The total liability of {settings.company_name} is limited to the fees paid under this "
        "agreement. Neither party is liable for indirect or consequential loss.",
    ),
    "termination": (
        "Termination",
        "Either party may end this agreement in writing if the other party breaches it and does "
        "not fix the breach within 14 days. The client pays for the work done until then.",
    ),
}


def text(title: str, body: str) -> dict:
    lines = [line.strip() for line in body.splitlines() if line.strip()]
    return {
        "title": title,
        "paragraphs": [line for line in lines if not line.startswith("- ")],
        "items": [line[2:] for line in lines if line.startswith("- ")],
    }


def money(amount: float, currency: str | None) -> str:
    return f"{currency or 'USD'} {amount:,.2f}".removesuffix(".00")


def filled_in(f: dict) -> dict:
    """The parts Python writes from the checked fields."""
    price, currency, half = f["price"], f["currency"], f["price"] / 2
    start = f["start_date"] or "a date both parties agree in writing"
    duration = f["duration"] or "to be agreed"
    return {
        "timeline": text("Timeline", f"The work starts on {start}. Planned duration: {duration}."),
        "payments": {"title": "Payments", "table": [
            ["Payment", "Due", "Amount"],
            ["Deposit (50%)", "On signing", money(half, currency)],
            ["Final payment (50%)", "On delivery", money(half, currency)],
            ["Total, fixed price", "", money(price, currency)],
        ]},
        "terms": {"title": "Retainer terms", "box": [
            ["Monthly fee", money(price, currency)],
            ["Hours per month", str(f["hours_per_month"] or "Not capped")],
            ["Start date", start],
            ["Notice period", "30 days, in writing, from the end of a month"],
            ["Invoicing", "Monthly in advance, due within 14 days"],
        ]},
        "fee": {"title": "Fee and timing", "box": [
            ["Fixed fee", money(price, currency)],
            ["Payment", "100% on signing"],
            ["Start date", start],
            ["Duration", duration],
        ]},
    }


def build_document(contract: Contract) -> dict:
    """The agreement as data. The signing page, the PDF and the hash all use this."""
    template, f = TEMPLATES[contract.contract_type], contract.fields
    parts = {key: text(*clause) for key, clause in CLAUSES.items()} | filled_in(f)
    parts |= {s["key"]: text(s["title"], s["text"]) for s in contract.sections}
    return {
        "ref": f"AGR-{contract.id:05d}",
        "title": template["title"],
        "company": settings.company_name,
        "sender": settings.email_from,
        "client": {"company": f["client_company"], "name": f["contact_name"],
                   "email": f["contact_email"]},
        "pages": [{"title": t, "blocks": [parts[k] for k in ks]} for t, ks in template["pages"]],
        "acceptance": "By signing below, the client agrees to the terms of this agreement.",
    }

pages decides what the client sees on each page. Most keys on a page are sections the model wrote. The others are filled in by Python.

  • CLAUSES holds the legal text. It is fixed template text, and the model never touches it.
  • filled_in() writes every part with a number or a date from the checked fields. That covers the timeline, the payment table, the retainer terms box, and the discovery fee box.
  • build_document() puts it all together as one dict. The signing page, the PDF, and the hash all use this one function, so what the client signs is exactly what was hashed.

Add the send route

Replace backend/app/main.py. The highlighted lines are new.

backend/app/main.py
import hashlib
import json
import secrets
from contextlib import asynccontextmanager
from datetime import UTC, datetime

from fastapi import BackgroundTasks, FastAPI, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import select, update
from sqlalchemy.orm.attributes import flag_modified

from app import ai
from app.config import settings
from app.db import Base, Contract, SessionDep, engine, new_session
from app.email import send_email
from app.templates import TEMPLATES, build_document


@asynccontextmanager
async def lifespan(app: FastAPI):
    Base.metadata.create_all(engine)  # Creates the table if it is missing. Never alters it.
    # Work that was running when the app stopped will never finish. Retry picks it up.
    with new_session() as session:
        session.execute(update(Contract).where(Contract.status.in_(["pending", "processing"]))
                        .values(status="failed", reason="Interrupted by a restart"))
        session.commit()
    yield


app = FastAPI(title="Contract drafting", lifespan=lifespan)


@app.get("/health")
def health() -> dict:
    return {"status": "ok", "company": settings.company_name}


def found[T](row: T | None) -> T:
    if row is None:
        raise HTTPException(404, "Not found")
    return row


# Admin API. Not published: the browser reaches it only through Next.js, which asks for
# the admin password.
class Upload(BaseModel):
    notes: str = Field(min_length=20, max_length=50_000)


@app.post("/api/contracts")
def upload(upload: Upload, background: BackgroundTasks, session: SessionDep) -> dict:
    title = upload.notes.strip().splitlines()[0].strip("# ")[:120]
    contract = Contract(title=title, notes=upload.notes)
    session.add(contract)
    session.commit()
    background.add_task(process, contract.id)
    return {"id": contract.id}


@app.get("/api/contracts")
def list_contracts(session: SessionDep) -> list[dict]:
    columns = Contract.id, Contract.title, Contract.status, Contract.contract_type
    return session.execute(select(*columns).order_by(Contract.id.desc())).mappings().all()


@app.get("/api/contracts/{contract_id}")
def get_contract(contract_id: int, session: SessionDep) -> dict:
    return found(session.get(Contract, contract_id)).as_dict()


@app.post("/api/contracts/{contract_id}/retry")
def retry(contract_id: int, background: BackgroundTasks, session: SessionDep) -> dict:
    # with_for_update locks the row until commit, so two clicks cannot both pass the check.
    contract = found(session.get(Contract, contract_id, with_for_update=True))
    if contract.status != "failed":
        raise HTTPException(409, "Not failed")
    contract.status = "pending"
    session.commit()
    background.add_task(process, contract_id)
    return {"status": "pending"}


def process(contract_id: int) -> None:
    """Runs after the response, in its own session. Every commit shows in the admin page."""
    with new_session() as session:
        contract = session.get(Contract, contract_id)
        contract.status, contract.reason = "processing", None
        session.commit()
        try:
            if not contract.fields:  # LLM step 1, then Python decides.
                extraction = ai.extract(contract.notes)
                reasons = ai.review_reasons(extraction, contract.notes)
                contract.contract_type = extraction.contract_type
                contract.fields = extraction.model_dump(mode="json")
                if reasons:
                    contract.status, contract.reason = "needs_review", "\n".join(reasons)
                    session.commit()
                    return
                template = TEMPLATES[contract.contract_type]
                contract.title = f"{template['title']}: {contract.fields['client_company']}"
                contract.sections = [{"key": key, "title": title, "status": "pending", "text": ""}
                                     for key, (title, _) in template["sections"].items()]
                session.commit()

            prompts = TEMPLATES[contract.contract_type]["sections"]
            for section in [s for s in contract.sections if s["status"] != "done"]:  # LLM step 2
                section["status"] = "writing"
                flag_modified(contract, "sections")  # SQLAlchemy can't see changes inside a list.
                session.commit()
                title, prompt = prompts[section["key"]]
                section["text"] = ai.write_section(contract.notes, contract.fields, title, prompt)
                section["status"] = "done"
                flag_modified(contract, "sections")
                session.commit()
            contract.status = "drafted"
            session.commit()
        except Exception as error:
            session.rollback()
            contract.status, contract.reason = "failed", str(error)
            session.commit()


def fingerprint(document: dict) -> str:
    return hashlib.sha256(json.dumps(document, sort_keys=True).encode()).hexdigest()


@app.post("/api/contracts/{contract_id}/send")
def send(contract_id: int, background: BackgroundTasks, session: SessionDep) -> dict:
    """Freeze the agreement: from now on, it can only be signed while its hash matches."""
    contract = found(session.get(Contract, contract_id, with_for_update=True))
    if contract.status != "drafted":
        raise HTTPException(409, "Only a drafted contract can be sent.")
    document = build_document(contract)
    contract.status, contract.token = "sent", secrets.token_urlsafe()
    contract.content_hash, contract.sent_at = fingerprint(document), datetime.now(UTC)
    session.commit()
    link = f"{settings.base_url}/sign/{contract.token}"
    client = document["client"]
    body = f"Hi {client['name']},\n\nPlease review and sign {document['title']}:\n{link}\n"
    background.add_task(send_email, [client["email"]], f"Please sign: {document['title']}", body)
    return {"link": link}

send builds the document, hashes it, and saves the hash with a random token. It locks the row with with_for_update=True, like retry, so only a drafted contract becomes sent, even when you click twice. The email goes out as a background task, so a slow mail server never holds up the response.

secrets.token_urlsafe() makes the token. It is the only key to the signing page, so treat a signing link like a password.

Check

The sample intakes use made-up addresses such as dana.whitfield@harborviewdental.example.com, and email to them bounces. With Gmail set up, change that address to your personal one before you process a sample.

  1. In the admin page, pick samples/intakes/01-dental-phone-receptionist.md.
  2. In the text box, replace the client's email address with yours. It appears once, near the end of the notes.
  3. Click Process and wait until the contract is Drafted.
  4. Click Send.

The admin page now shows the signing link, and the email "Please sign: Statement of Work" arrives in your inbox. Without Gmail, the email is in the API log. The link opens a 404 page for now. The signing page comes next.

TestExpected
Send the same contract again with curl -i -X POST http://localhost:8000/api/contracts/<id>/send409 with "Only a drafted contract can be sent."
Send a contract in review409

On Windows, use curl.exe.

On this page