102 lines
2.7 KiB
Python
102 lines
2.7 KiB
Python
from fastapi import APIRouter
|
|
from fastapi.responses import HTMLResponse, FileResponse
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
from beanie.operators import ElemMatch
|
|
|
|
from weasyprint import HTML, CSS
|
|
from weasyprint.text.fonts import FontConfiguration
|
|
|
|
from pathlib import Path
|
|
|
|
from app.entity.models import Entity
|
|
from app.template.models import ProvisionTemplate
|
|
from ..schemas import ContractDraft, Contract
|
|
|
|
|
|
async def build_model(model):
|
|
parties = []
|
|
for p in model.parties:
|
|
party = {
|
|
"entity": await Entity.get(p.entity_id),
|
|
"part": p.part
|
|
}
|
|
if p.representative_id:
|
|
party['representative'] = await Entity.get(p.representative_id)
|
|
|
|
parties.append(party)
|
|
|
|
model.parties = parties
|
|
|
|
provisions = []
|
|
for p in model.provisions:
|
|
if p.provision.type == "template":
|
|
provisions.append(await ProvisionTemplate.get(p.provision.provision_template_id))
|
|
else:
|
|
provisions.append(p.provision)
|
|
model.provisions = provisions
|
|
|
|
model.location = "Toulouse"
|
|
model.date = "01/01/1970"
|
|
return model
|
|
|
|
|
|
BASE_PATH = Path(__file__).resolve().parent
|
|
|
|
print_router = APIRouter()
|
|
|
|
|
|
templates = Jinja2Templates(directory=str(BASE_PATH / "templates"))
|
|
|
|
|
|
async def render_print(host, contract, lawyer):
|
|
template = templates.get_template("print.html")
|
|
return template.render({
|
|
"contract": contract,
|
|
"lawyer": lawyer,
|
|
"static_host": host
|
|
})
|
|
|
|
|
|
async def render_css(host, draft):
|
|
template = templates.get_template("styles.css")
|
|
return template.render({
|
|
"draft": draft,
|
|
"static_host": host
|
|
})
|
|
|
|
|
|
@print_router.get("/preview/{signatureId}", response_class=HTMLResponse)
|
|
async def create(signatureId: str) -> str:
|
|
# await build_model(await ContractDraft.get("63e92534aafed8b509f229c4"))
|
|
|
|
crit = ElemMatch(Contract.parties, {"signature_uuid": "85476dc8-8b98-4f25-8e7d-1542c152074f"})
|
|
contract = await Contract.find_one(crit)
|
|
|
|
lawyer = {
|
|
"firstname": "Nathaniel",
|
|
"lastname": "Toshi",
|
|
}
|
|
|
|
return await render_print('localhost', contract, lawyer)
|
|
|
|
|
|
@print_router.get("/pdf", response_class=FileResponse)
|
|
async def create_pdf() -> str:
|
|
draft = await build_model(await ContractDraft.get("63e92534aafed8b509f229c4"))
|
|
lawyer = {
|
|
"firstname": "Nathaniel",
|
|
"lastname": "Toshi",
|
|
}
|
|
|
|
font_config = FontConfiguration()
|
|
html = HTML(string=await render_print('nginx', draft, lawyer))
|
|
css = CSS(string=await render_css('nginx', draft), font_config=font_config)
|
|
|
|
html.write_pdf('out.pdf', stylesheets=[css], font_config=font_config)
|
|
|
|
return FileResponse(
|
|
"out.pdf",
|
|
media_type="application/pdf",
|
|
filename=draft.name)
|