Skip to content

dleerdefi/claude-code-construction / skills/subcontract-writer

subcontract-writer

Verified

Generate a complete subcontract from a firm's template, awarded bid, and project specs. Outputs a Word document. Triggers: 'subcontract', 'sub agreement', 'write contract', 'draft subcontract'. Requires awarded bid.

scripts/generate_subcontract_docx.py

View on GitHub
#!/usr/bin/env python3
"""Generate a subcontract Word document from fully-populated JSON data.

This is a THIN FORMATTER. It renders pre-populated content from
template_data.json into a .docx file. It makes no content decisions —
all article text, tables, and lists are generated upstream by Claude Code.
"""

import argparse
import json
import sys
from pathlib import Path

from shared import safe_output_path

from subcontract_formatters import render_block, write_signature_block, write_header, write_footer


def _num(v):
    """float for a number or numeric string; None for blank or non-numeric text."""
    if isinstance(v, bool) or v is None:
        return None
    if isinstance(v, (int, float)):
        return float(v)
    try:
        return float(str(v).replace("$", "").replace(",", "").strip())
    except ValueError:
        return None


def check_money(scope):
    """Every line's quantity x rate must equal its amount, and the lines must sum to
    the contract value. A subcontract with money that does not add up is not written."""
    problems = []
    items = scope.get("line_items") or []
    total = 0.0
    for n, li in enumerate(items, 1):
        qty, rate, amount = _num(li.get("quantity")), _num(li.get("rate")), _num(li.get("amount"))
        if amount is None:
            # "Included", "No charge", an allowance stated in words: not an error by itself,
            # but it carries nothing into the sum, so the remaining lines must still reach
            # the contract value.
            print(f"NOTE: line {n} ({li.get('spec', '')}): amount {li.get('amount')!r} is not a number; "
                  "excluded from the sum")
            continue
        total += amount
        if qty is not None and rate is not None and abs(qty * rate - amount) > 0.01:
            problems.append(f"line {n} ({li.get('spec', '')}): {qty:g} x {rate:,.2f} = {qty * rate:,.2f}, "
                            f"amount states {amount:,.2f}")
    value = _num(scope.get("contract_value"))
    if items and value is not None and abs(total - value) > 0.01:
        problems.append(f"line items sum to {total:,.2f}; contract_value is {value:,.2f} "
                        f"(difference {value - total:+,.2f})")
    return problems


def generate_subcontract(template_data_path, scope_data_path, output="Subcontract.docx"):
    try:
        from docx import Document
        from docx.shared import Pt, Inches
    except ImportError:
        print("ERROR: python-docx not installed. Run: pip install python-docx")
        sys.exit(1)

    with open(template_data_path) as f:
        template = json.load(f)
    with open(scope_data_path) as f:
        scope = json.load(f)

    problems = check_money(scope)
    if problems:
        print("ERROR: the scope data's money does not reconcile; no document written.")
        for msg in problems:
            print(f"  - {msg}")
        print("Fix scope_data.json (or carry the discrepancy as a [GC TO CONFIRM] note) and run again.")
        sys.exit(2)

    # Use existing .docx template if provided
    docx_template = template.get("docx_template_path")
    if docx_template and Path(docx_template).exists():
        doc = Document(docx_template)
    else:
        doc = Document()

    _format_document(doc, template, scope)

    out = safe_output_path(output)
    doc.save(str(out))
    print(f"OK: {out}")


def _format_document(doc, template, scope):
    """Render all pre-populated content into the document."""
    from docx.shared import Pt, Inches
    from docx.enum.text import WD_ALIGN_PARAGRAPH

    # Document setup
    style = doc.styles["Normal"]
    style.font.name = "Arial"
    style.font.size = Pt(10)

    for section in doc.sections:
        section.top_margin = Inches(1)
        section.bottom_margin = Inches(1)
        section.left_margin = Inches(1)
        section.right_margin = Inches(1)

    # Header and footer
    contractor_name = scope.get("contractor_name", "")
    sc_number = scope.get("subcontract_number", "")
    project_name = scope.get("project_name", "")
    if contractor_name or sc_number:
        write_header(doc, contractor_name, sc_number)
    if project_name:
        write_footer(doc, project_name)

    # Cover page
    cover = template.get("cover_page", {})
    _render_section(doc, cover, is_cover=True)

    # Articles
    for article in template.get("articles", []):
        art_num = article.get("number", "")
        art_title = article.get("title", "")

        heading = doc.add_heading(f"Article {art_num} — {art_title}", level=1)
        heading.runs[0].font.size = Pt(12)

        text = article.get("text", "")
        if not text:
            print(f"WARNING: Article {art_num} ({art_title}) has empty text")
            text = f"[Article {art_num} content not provided]"

        # Render text as paragraphs (split on double newline)
        for para_text in text.split("\n\n"):
            stripped = para_text.strip()
            if stripped:
                doc.add_paragraph(stripped)

        # Render blocks (tables, bullet lists, etc.)
        for block in article.get("blocks", []):
            render_block(doc, block)

    # Exhibits
    exhibits = template.get("exhibits", [])
    if exhibits:
        doc.add_page_break()
        heading = doc.add_heading("Exhibits", level=1)
        heading.runs[0].font.size = Pt(12)

        doc.add_paragraph("The following Exhibits are incorporated into this Agreement:")
        doc.add_paragraph()
        for ex in exhibits:
            letter = ex.get("letter", "")
            title = ex.get("title", "")
            doc.add_paragraph(f"Exhibit {letter}: {title}", style="List Bullet")

    # Signature block
    write_signature_block(doc, scope)


def _render_section(doc, section, is_cover=False):
    """Render a section's text and blocks."""
    from docx.shared import Pt
    from docx.enum.text import WD_ALIGN_PARAGRAPH

    text = section.get("text", "")
    if text:
        for para_text in text.split("\n\n"):
            stripped = para_text.strip()
            if not stripped:
                continue
            p = doc.add_paragraph(stripped)
            # Center the title line on cover pages
            if is_cover and "SUBCONTRACT AGREEMENT" in stripped:
                p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                if p.runs:
                    p.runs[0].bold = True
                    p.runs[0].font.size = Pt(16)

    for block in section.get("blocks", []):
        render_block(doc, block)

    if text or section.get("blocks"):
        doc.add_paragraph()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Format subcontract Word document")
    parser.add_argument("--template", required=True,
                        help="JSON file with fully-populated template structure")
    parser.add_argument("--scope", required=True,
                        help="JSON file with scope/project data")
    parser.add_argument("--output", "-o", default="Subcontract.docx")
    args = parser.parse_args()
    generate_subcontract(args.template, args.scope, args.output)
canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.Stars: 197kUpdated Claude CodeCodexVerifiedInstall