Initial roborto accounting implementation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Reporting, export, and document-generation adapters."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Printable/PDF document rendering."""
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Branded PDF presentation for values produced by accounting report services."""
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.platypus import Paragraph, Spacer, Table, TableStyle
|
||||
|
||||
from roborto_accounting.persistence.models import BusinessSettings
|
||||
from roborto_accounting.reporting.documents.theme import DARK, GREEN, DocumentTheme
|
||||
from roborto_accounting.reporting.financial import CashFlowSummary, ProfitLossSummary
|
||||
from roborto_accounting.reporting.ledgers import LedgerRow, TrialBalanceSummary
|
||||
|
||||
|
||||
def _money(value: Decimal) -> str:
|
||||
return f"EUR {value:,.2f}"
|
||||
|
||||
|
||||
def _contact(settings: BusinessSettings) -> list[str]:
|
||||
return [
|
||||
value
|
||||
for value in (
|
||||
settings.postal_address,
|
||||
settings.general_email,
|
||||
settings.website,
|
||||
settings.telephone,
|
||||
)
|
||||
if value
|
||||
]
|
||||
|
||||
|
||||
def _period(start: date, end: date, theme: DocumentTheme) -> list[object]:
|
||||
return [
|
||||
Paragraph(f"PERIOD: {start.isoformat()} TO {end.isoformat()}", theme.section),
|
||||
Spacer(1, 3 * mm),
|
||||
]
|
||||
|
||||
|
||||
def _summary_table(rows: list[list[str]]) -> Table:
|
||||
table = Table(rows, colWidths=[80 * mm, 40 * mm], hAlign="RIGHT")
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("ALIGN", (1, 0), (1, -1), "RIGHT"),
|
||||
("FONTNAME", (0, -1), (-1, -1), "Helvetica-Bold"),
|
||||
("TEXTCOLOR", (1, -1), (1, -1), GREEN),
|
||||
("LINEABOVE", (0, -1), (-1, -1), 0.5, GREEN),
|
||||
("LINEBELOW", (0, -1), (-1, -1), 0.5, GREEN),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 9),
|
||||
("TEXTCOLOR", (0, 0), (0, -1), DARK),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 5),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
|
||||
]
|
||||
)
|
||||
)
|
||||
return table
|
||||
|
||||
|
||||
def render_profit_and_loss_pdf(
|
||||
path: Path,
|
||||
*,
|
||||
report: ProfitLossSummary,
|
||||
start: date,
|
||||
end: date,
|
||||
settings: BusinessSettings,
|
||||
theme: DocumentTheme,
|
||||
) -> Path:
|
||||
"""Render supplied P&L values without recalculating ledger amounts."""
|
||||
story = theme.header(_contact(settings)) + theme.heading("PROFIT & LOSS") + _period(start, end, theme)
|
||||
data: list[list[object]] = [["CODE", "ACCOUNT", "CLASS", "AMOUNT (EUR)"]]
|
||||
data.extend(
|
||||
[row.account_code, Paragraph(row.account_name, theme.body), row.account_class, f"{row.amount:,.2f}"]
|
||||
for row in report.rows
|
||||
)
|
||||
story.extend([theme.data_table(data, [22 * mm, 73 * mm, 30 * mm, 35 * mm], {3}), Spacer(1, 6 * mm)])
|
||||
story.append(_summary_table([["Total income", _money(report.income)], ["Total expenses", _money(report.expenses)], ["NET PROFIT / (LOSS)", _money(report.net)]]))
|
||||
return theme.build(path, story)
|
||||
|
||||
|
||||
def render_cash_flow_pdf(
|
||||
path: Path,
|
||||
*,
|
||||
summary: CashFlowSummary,
|
||||
start: date,
|
||||
end: date,
|
||||
settings: BusinessSettings,
|
||||
theme: DocumentTheme,
|
||||
) -> Path:
|
||||
"""Render the cash-flow summary supplied by the report service."""
|
||||
story = theme.header(_contact(settings)) + theme.heading("CASH FLOW") + _period(start, end, theme)
|
||||
story.append(
|
||||
_summary_table(
|
||||
[
|
||||
["Cash received", _money(summary.incoming)],
|
||||
["Cash paid", _money(summary.outgoing)],
|
||||
["NET CASH FLOW", _money(summary.net)],
|
||||
]
|
||||
)
|
||||
)
|
||||
return theme.build(path, story)
|
||||
|
||||
|
||||
def render_transaction_ledger_pdf(
|
||||
path: Path, *, rows: list[LedgerRow], start: date, end: date,
|
||||
settings: BusinessSettings, theme: DocumentTheme, title: str = "TRANSACTION LEDGER",
|
||||
) -> Path:
|
||||
story = theme.header(_contact(settings)) + theme.heading(title) + _period(start, end, theme)
|
||||
data: list[list[object]] = [["DATE", "CODE", "DESCRIPTION", "DEBIT", "CREDIT"]]
|
||||
data.extend([
|
||||
row.journal_date.isoformat(), row.account_code, Paragraph(row.description, theme.body),
|
||||
f"{row.debit:,.2f}", f"{row.credit:,.2f}",
|
||||
] for row in rows)
|
||||
story.append(theme.data_table(data, [25 * mm, 19 * mm, 66 * mm, 25 * mm, 25 * mm], {3, 4}))
|
||||
return theme.build(path, story)
|
||||
|
||||
|
||||
def render_trial_balance_pdf(
|
||||
path: Path, *, report: TrialBalanceSummary, start: date, end: date,
|
||||
settings: BusinessSettings, theme: DocumentTheme,
|
||||
) -> Path:
|
||||
story = theme.header(_contact(settings)) + theme.heading("TRIAL BALANCE") + _period(start, end, theme)
|
||||
data: list[list[object]] = [["CODE", "ACCOUNT", "DEBIT (EUR)", "CREDIT (EUR)"]]
|
||||
data.extend([row.account_code, Paragraph(row.account_name, theme.body), f"{row.debit:,.2f}", f"{row.credit:,.2f}"] for row in report.rows)
|
||||
data.append(["", "TOTAL", f"{report.total_debit:,.2f}", f"{report.total_credit:,.2f}"])
|
||||
table=theme.data_table(data,[22*mm,78*mm,30*mm,30*mm],{2,3})
|
||||
table.setStyle(TableStyle([("FONTNAME",(0,-1),(-1,-1),"Helvetica-Bold"),("LINEABOVE",(0,-1),(-1,-1),.5,GREEN)]))
|
||||
story.extend([table,Paragraph("BALANCED" if report.is_balanced else "NOT BALANCED",theme.section)])
|
||||
return theme.build(path,story)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Branded business-letter PDF renderer."""
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.platypus import Paragraph,Spacer,Table,TableStyle
|
||||
|
||||
from roborto_accounting.persistence.models import BusinessLetter,BusinessSettings
|
||||
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||
|
||||
def render_letter_pdf(path:Path,*,letter:BusinessLetter,settings:BusinessSettings,theme:DocumentTheme)->Path:
|
||||
contact=[value for value in (settings.postal_address,settings.general_email,settings.website,settings.telephone) if value]
|
||||
recipient="<br/>".join(escape(value) for value in (letter.recipient_name,*letter.recipient_address.splitlines(),letter.recipient_email) if value)
|
||||
story=theme.header(contact)
|
||||
story.extend([Paragraph(letter.letter_date.strftime("%d %B %Y"),theme.body),Spacer(1,10*mm),Paragraph("TO",theme.section),Paragraph(recipient,theme.body),Spacer(1,10*mm)])
|
||||
if letter.reference:story.extend([Paragraph("REFERENCE",theme.section),Paragraph(escape(letter.reference),theme.body),Spacer(1,4*mm)])
|
||||
story.extend([Paragraph("SUBJECT",theme.section),Paragraph(f"<b>{escape(letter.subject)}</b>",theme.body),Spacer(1,9*mm)])
|
||||
for block in letter.body_text.split("\n\n"):
|
||||
story.extend([Paragraph(escape(block).replace("\n","<br/>"),theme.body),Spacer(1,5*mm)])
|
||||
sender=settings.trading_name or "roborto"
|
||||
story.extend([Spacer(1,4*mm),Paragraph("Kind regards,",theme.body),Spacer(1,5*mm),Paragraph(f"<b>{escape(sender)}</b>",theme.body)])
|
||||
if settings.business_descriptor:story.append(Paragraph(escape(settings.business_descriptor),theme.body))
|
||||
return theme.build(path,story)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Branded invoice and quotation PDF renderers."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.platypus import KeepTogether,Paragraph,Spacer,Table,TableStyle
|
||||
from roborto_accounting.persistence.models import BusinessSettings,Invoice,Quotation
|
||||
from roborto_accounting.reporting.documents.theme import DARK,GREEN,DocumentTheme
|
||||
|
||||
def _money(value)->str:return f"EUR {value:,.2f}"
|
||||
def _contact(settings:BusinessSettings,email:str|None)->list[str]:
|
||||
return [value for value in (settings.postal_address,email,settings.website,settings.telephone) if value]
|
||||
def _client_block(snapshot_json:str|None,theme:DocumentTheme):
|
||||
data=json.loads(snapshot_json or "{}")
|
||||
values=[data.get("name"),data.get("billing_address"),data.get("contact_person"),data.get("email")]
|
||||
return [Paragraph("BILL TO",theme.section),Paragraph("<br/>".join(str(v) for v in values if v),theme.body)]
|
||||
def _totals(theme:DocumentTheme,net,vat,gross,label:str):
|
||||
table=Table([["Subtotal",_money(net)],["VAT",_money(vat)],[label,_money(gross)]],colWidths=[45*mm,35*mm],hAlign="RIGHT")
|
||||
table.setStyle(TableStyle([("ALIGN",(1,0),(-1,-1),"RIGHT"),("FONTNAME",(0,2),(-1,2),"Helvetica-Bold"),
|
||||
("TEXTCOLOR",(1,2),(1,2),GREEN),("LINEABOVE",(0,2),(-1,2),.5,GREEN),("LINEBELOW",(0,2),(-1,2),.5,GREEN),
|
||||
("FONTSIZE",(0,0),(-1,-1),9),("TEXTCOLOR",(0,0),(0,-1),DARK),("TOPPADDING",(0,0),(-1,-1),4),("BOTTOMPADDING",(0,0),(-1,-1),4)]))
|
||||
return table
|
||||
|
||||
def render_invoice_pdf(path:Path,*,invoice:Invoice,settings:BusinessSettings,theme:DocumentTheme)->Path:
|
||||
if invoice.status=="DRAFT" or not invoice.number or not invoice.client_snapshot_json:raise ValueError("invoice must be issued before rendering")
|
||||
story=theme.header(_contact(settings,settings.accounts_email))+theme.heading("INVOICE")
|
||||
metadata=Table([["Invoice Number",invoice.number],["Issue Date",invoice.invoice_date.isoformat()],
|
||||
["Due Date",invoice.due_date.isoformat() if invoice.due_date else ""]],colWidths=[35*mm,45*mm],hAlign="RIGHT")
|
||||
metadata.setStyle(TableStyle([("FONTNAME",(0,0),(0,-1),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,-1),9)]))
|
||||
story.extend(_client_block(invoice.client_snapshot_json,theme));story.extend([Spacer(1,5*mm),metadata,Spacer(1,7*mm)])
|
||||
data=[["DESCRIPTION","QUANTITY","RATE (EUR)","AMOUNT (EUR)"]]
|
||||
data += [[Paragraph(line.description,theme.body),str(line.quantity.normalize()),f"{line.unit_price:,.2f}",f"{line.gross_total:,.2f}"] for line in invoice.lines]
|
||||
story.extend([theme.data_table(data,[78*mm,23*mm,28*mm,31*mm],{1,2,3}),Spacer(1,5*mm),
|
||||
KeepTogether([_totals(theme,invoice.net_total,invoice.vat_total,invoice.gross_total,"TOTAL DUE (EUR)")])])
|
||||
if settings.bank_payment_instructions:story.extend([Paragraph("PAYMENT DETAILS",theme.section),Paragraph(settings.bank_payment_instructions.replace("\n","<br/>"),theme.body)])
|
||||
return theme.build(path,story)
|
||||
|
||||
def render_quotation_pdf(path:Path,*,quotation:Quotation,settings:BusinessSettings,theme:DocumentTheme)->Path:
|
||||
if quotation.status=="DRAFT" or not quotation.number or not quotation.client_snapshot_json:raise ValueError("quotation must be issued before rendering")
|
||||
story=theme.header(_contact(settings,settings.general_email))+theme.heading("QUOTATION")
|
||||
metadata=Table([["Quotation Number",quotation.number],["Issue Date",quotation.quotation_date.isoformat()]],colWidths=[35*mm,45*mm],hAlign="RIGHT")
|
||||
metadata.setStyle(TableStyle([("FONTNAME",(0,0),(0,-1),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,-1),9)]))
|
||||
story.extend(_client_block(quotation.client_snapshot_json,theme));story.extend([Spacer(1,5*mm),metadata,Spacer(1,7*mm)])
|
||||
data=[["DESCRIPTION","QUANTITY","RATE (EUR)","AMOUNT (EUR)"]]
|
||||
data += [[Paragraph(line.description,theme.body),str(line.quantity.normalize()),f"{line.unit_price:,.2f}",f"{line.gross_total:,.2f}"] for line in quotation.lines]
|
||||
story.extend([theme.data_table(data,[78*mm,23*mm,28*mm,31*mm],{1,2,3}),Spacer(1,5*mm),
|
||||
KeepTogether([_totals(theme,quotation.net_total,quotation.vat_total,quotation.gross_total,"TOTAL (EUR)")])])
|
||||
return theme.build(path,story)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Deterministic, non-production document samples for visual review."""
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from roborto_accounting.persistence.base import Base
|
||||
from roborto_accounting.persistence.db import make_engine, make_session_factory
|
||||
from roborto_accounting.persistence.models import BusinessSettings, Client
|
||||
from roborto_accounting.reporting.documents.financial import render_cash_flow_pdf, render_profit_and_loss_pdf
|
||||
from roborto_accounting.reporting.documents.sales import render_invoice_pdf, render_quotation_pdf
|
||||
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||
from roborto_accounting.reporting.financial import CashFlowSummary, ProfitLossRow, ProfitLossSummary
|
||||
from roborto_accounting.services.invoices import create_invoice, issue_invoice
|
||||
from roborto_accounting.services.quotations import create_quotation, issue_quotation
|
||||
from roborto_accounting.services.chart import seed_default_accounts
|
||||
from roborto_accounting.services.letters import create_letter
|
||||
from roborto_accounting.reporting.documents.letters import render_letter_pdf
|
||||
from sqlalchemy import select
|
||||
from roborto_accounting.persistence.models import Account
|
||||
|
||||
|
||||
def generate_document_samples(output_dir: Path, *, logo_path: Path) -> list[Path]:
|
||||
"""Generate the four approved representative PDFs in ``output_dir``."""
|
||||
engine = make_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
session = make_session_factory(engine)()
|
||||
try:
|
||||
settings = BusinessSettings(
|
||||
trading_name="roborto",
|
||||
business_descriptor="Software Development",
|
||||
website="roborto.net",
|
||||
general_email="hello@roborto.net",
|
||||
accounts_email="accounts@roborto.net",
|
||||
telephone="+353 00 000 0000",
|
||||
postal_address="Sample configuration\nDublin, Ireland",
|
||||
bank_payment_instructions="Sample payment instructions configured for visual review only.",
|
||||
)
|
||||
client = Client(
|
||||
name="Sample Client Limited",
|
||||
billing_address="1 Example Street\nDublin, Ireland",
|
||||
contact_person="Example Contact",
|
||||
email="client@example.invalid",
|
||||
)
|
||||
session.add_all([settings, client])
|
||||
seed_default_accounts(session);session.flush()
|
||||
income=session.scalar(select(Account).where(Account.code=="4000"));receivables=session.scalar(select(Account).where(Account.code=="1100"))
|
||||
settings.default_income_account_id=income.id
|
||||
lines = [
|
||||
{
|
||||
"description": f"Software development service {number}: representative line text used to test wrapping and pagination",
|
||||
"quantity": Decimal("2.5"),
|
||||
"unit": "hours",
|
||||
"unit_price": Decimal("80.00"),
|
||||
"vat_amount": Decimal("0"),
|
||||
"income_account_id": income.id,
|
||||
}
|
||||
for number in range(1, 32)
|
||||
]
|
||||
invoice = create_invoice(session, settings=settings, client=client, invoice_date=date(2026, 8, 29), lines=lines)
|
||||
issue_invoice(session, invoice, client,receivables_account_id=receivables.id)
|
||||
quotation = create_quotation(session, client=client, quotation_date=date(2026, 8, 29), lines=lines[:8])
|
||||
issue_quotation(session, quotation, client)
|
||||
theme = DocumentTheme(logo_path)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
paths = [
|
||||
render_invoice_pdf(output_dir / "invoice-sample.pdf", invoice=invoice, settings=settings, theme=theme),
|
||||
render_quotation_pdf(output_dir / "quotation-sample.pdf", quotation=quotation, settings=settings, theme=theme),
|
||||
]
|
||||
report_rows = [
|
||||
ProfitLossRow("4000", "Software development", "INCOME", Decimal("12400.00")),
|
||||
ProfitLossRow("4010", "Hosting and maintenance", "INCOME", Decimal("1500.00")),
|
||||
ProfitLossRow("7000", "Hosting", "EXPENSE", Decimal("420.00")),
|
||||
ProfitLossRow("7010", "Software subscriptions", "EXPENSE", Decimal("860.00")),
|
||||
ProfitLossRow("7020", "Professional fees", "EXPENSE", Decimal("300.00")),
|
||||
]
|
||||
report = ProfitLossSummary(report_rows, Decimal("13900.00"), Decimal("1580.00"), Decimal("12320.00"))
|
||||
paths.extend(
|
||||
[
|
||||
render_cash_flow_pdf(
|
||||
output_dir / "cash-flow-sample.pdf",
|
||||
summary=CashFlowSummary(Decimal("11200.00"), Decimal("1850.00"), Decimal("9350.00")),
|
||||
start=date(2026, 1, 1), end=date(2026, 12, 31), settings=settings, theme=theme,
|
||||
),
|
||||
render_profit_and_loss_pdf(
|
||||
output_dir / "profit-loss-sample.pdf", report=report,
|
||||
start=date(2026, 1, 1), end=date(2026, 12, 31), settings=settings, theme=theme,
|
||||
),
|
||||
]
|
||||
)
|
||||
letter=create_letter(session,letter_date=date(2026,8,29),recipient_name="Sample Client Limited",recipient_address="1 Example Street\nDublin, Ireland",recipient_email="client@example.invalid",reference="SAMPLE-REFERENCE",subject="Software development services",body_text="Hello,\n\nThank you for discussing your software project. This representative letter exercises the approved Roborto layout using configured sender details and non-production recipient data.\n\nPlease contact me if you would like to discuss the next steps.")
|
||||
paths.append(render_letter_pdf(output_dir/"letter-sample.pdf",letter=letter,settings=settings,theme=theme))
|
||||
return paths
|
||||
finally:
|
||||
session.close()
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Approved shared light-mode Roborto A4 document theme."""
|
||||
from pathlib import Path
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.enums import TA_RIGHT
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.styles import ParagraphStyle,getSampleStyleSheet
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import Paragraph,SimpleDocTemplate,Spacer,Table,TableStyle
|
||||
from svglib.svglib import svg2rlg
|
||||
|
||||
GREEN=colors.HexColor("#7ee787");DARK=colors.HexColor("#0b0f14");RULE=colors.HexColor("#dce7de")
|
||||
|
||||
class DeterministicCanvas(canvas.Canvas):
|
||||
def __init__(self,*args,**kwargs):kwargs["invariant"]=1;super().__init__(*args,**kwargs)
|
||||
|
||||
class DocumentTheme:
|
||||
page_size=A4;left_margin=22*mm;right_margin=22*mm;top_margin=18*mm;bottom_margin=20*mm
|
||||
def __init__(self,logo_path:Path):
|
||||
self.logo_path=logo_path;styles=getSampleStyleSheet()
|
||||
self.body=ParagraphStyle("RobortoBody",parent=styles["BodyText"],fontName="Helvetica",fontSize=9,leading=12,textColor=DARK)
|
||||
self.title=ParagraphStyle("RobortoTitle",parent=styles["Title"],fontName="Helvetica-Bold",fontSize=23,leading=27,textColor=DARK,spaceAfter=4)
|
||||
self.section=ParagraphStyle("RobortoSection",parent=self.body,fontName="Helvetica-Bold",fontSize=8,textColor=colors.HexColor("#2e8b3c"),spaceBefore=8,spaceAfter=5)
|
||||
self.right=ParagraphStyle("RobortoRight",parent=self.body,alignment=TA_RIGHT)
|
||||
def logo(self,width:float=55*mm):
|
||||
drawing=svg2rlg(str(self.logo_path));scale=width/drawing.width;drawing.width*=scale;drawing.height*=scale;drawing.scale(scale,scale);return drawing
|
||||
def header(self,contact_lines:list[str]):
|
||||
right=Paragraph("<br/>".join(contact_lines),self.right)
|
||||
table=Table([[self.logo(),right]],colWidths=[95*mm,60*mm]);table.setStyle(TableStyle([
|
||||
("VALIGN",(0,0),(-1,-1),"TOP"),("ALIGN",(1,0),(1,0),"RIGHT"),("LEFTPADDING",(0,0),(-1,-1),0),("RIGHTPADDING",(0,0),(-1,-1),0)]))
|
||||
return [table,Spacer(1,12*mm)]
|
||||
def heading(self,text:str):return [Paragraph(text,self.title),Table([[""]],colWidths=[10*mm],rowHeights=[1.2]),Spacer(1,7*mm)]
|
||||
def data_table(self,data:list[list[object]],widths:list[float],numeric_columns:set[int]|None=None):
|
||||
table=Table(data,colWidths=widths,repeatRows=1)
|
||||
commands=[("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("TEXTCOLOR",(0,0),(-1,0),colors.HexColor("#2e8b3c")),
|
||||
("BACKGROUND",(0,0),(-1,0),colors.HexColor("#f4faf5")),("LINEABOVE",(0,0),(-1,0),0.5,GREEN),
|
||||
("LINEBELOW",(0,0),(-1,-1),0.25,RULE),("FONTNAME",(0,1),(-1,-1),"Helvetica"),
|
||||
("FONTSIZE",(0,0),(-1,-1),8),("LEADING",(0,0),(-1,-1),10),("VALIGN",(0,0),(-1,-1),"TOP"),
|
||||
("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5)]
|
||||
for col in numeric_columns or set():commands.append(("ALIGN",(col,1),(col,-1),"RIGHT"))
|
||||
table.setStyle(TableStyle(commands));return table
|
||||
def build(self,path:Path,story:list[object])->Path:
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
doc=SimpleDocTemplate(str(path),pagesize=self.page_size,leftMargin=self.left_margin,rightMargin=self.right_margin,
|
||||
topMargin=self.top_margin,bottomMargin=self.bottom_margin,title="Roborto document")
|
||||
def footer(canv,document):
|
||||
canv.saveState();canv.setStrokeColor(GREEN);canv.setLineWidth(.5);canv.line(self.left_margin,13*mm,A4[0]-self.right_margin,13*mm)
|
||||
canv.setFillColor(DARK);canv.setFont("Helvetica",7);canv.drawCentredString(A4[0]/2,8*mm,"roborto — Software Development")
|
||||
if document.page>1:canv.drawRightString(A4[0]-self.right_margin,8*mm,str(document.page))
|
||||
canv.restoreState()
|
||||
doc.build(story,onFirstPage=footer,onLaterPages=footer,canvasmaker=DeterministicCanvas);return path
|
||||
@@ -0,0 +1,32 @@
|
||||
"""CSV and minimal standards-compliant ODS report exports."""
|
||||
import csv,html,zipfile
|
||||
from collections.abc import Mapping,Sequence
|
||||
from pathlib import Path
|
||||
|
||||
def export_csv(path:Path,rows:Sequence[Mapping[str,object]])->Path:
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
fields=list(rows[0].keys()) if rows else []
|
||||
with path.open("w",newline="",encoding="utf-8") as handle:
|
||||
writer=csv.DictWriter(handle,fieldnames=fields);writer.writeheader();writer.writerows(rows)
|
||||
return path
|
||||
|
||||
def export_ods(path:Path,rows:Sequence[Mapping[str,object]],*,sheet_name:str="Report")->Path:
|
||||
path.parent.mkdir(parents=True,exist_ok=True);fields=list(rows[0].keys()) if rows else []
|
||||
def cell(value:object)->str:
|
||||
return f'<table:table-cell office:value-type="string"><text:p>{html.escape(str(value))}</text:p></table:table-cell>'
|
||||
table_rows=['<table:table-row>'+''.join(cell(field) for field in fields)+'</table:table-row>']
|
||||
table_rows += ['<table:table-row>'+''.join(cell(row.get(field,"")) for field in fields)+'</table:table-row>' for row in rows]
|
||||
content=('<?xml version="1.0" encoding="UTF-8"?>'
|
||||
'<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '
|
||||
'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" '
|
||||
'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.2">'
|
||||
'<office:body><office:spreadsheet><table:table table:name="'+html.escape(sheet_name)+'">'
|
||||
+''.join(table_rows)+'</table:table></office:spreadsheet></office:body></office:document-content>')
|
||||
manifest=('<?xml version="1.0" encoding="UTF-8"?>'
|
||||
'<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">'
|
||||
'<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>'
|
||||
'<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>')
|
||||
with zipfile.ZipFile(path,"w") as archive:
|
||||
archive.writestr("mimetype","application/vnd.oasis.opendocument.spreadsheet",compress_type=zipfile.ZIP_STORED)
|
||||
archive.writestr("content.xml",content);archive.writestr("META-INF/manifest.xml",manifest)
|
||||
return path
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Profit/loss, cash-flow, receivable, and payable report views."""
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from roborto_accounting.persistence.models import Account,AccountClass,Invoice,Journal,JournalLine,SupplierBill
|
||||
from roborto_accounting.services.invoices import outstanding_balance
|
||||
from roborto_accounting.services.payables import bill_outstanding
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProfitLossRow: account_code:str;account_name:str;account_class:str;amount:Decimal
|
||||
@dataclass(frozen=True)
|
||||
class ProfitLossSummary: rows:list[ProfitLossRow];income:Decimal;expenses:Decimal;net:Decimal
|
||||
@dataclass(frozen=True)
|
||||
class CashFlowSummary: incoming:Decimal;outgoing:Decimal;net:Decimal
|
||||
|
||||
def profit_and_loss(session:Session,*,start:date,end:date)->list[ProfitLossRow]:
|
||||
query=(select(JournalLine,Journal,Account).join(Journal,JournalLine.journal_id==Journal.id)
|
||||
.join(Account,JournalLine.account_id==Account.id)
|
||||
.where(Journal.is_posted.is_(True),Journal.journal_date>=start,Journal.journal_date<=end,
|
||||
Account.account_class.in_([AccountClass.INCOME,AccountClass.EXPENSE])))
|
||||
totals={}
|
||||
for line,journal,account in session.execute(query):
|
||||
key=(account.code,account.name,account.account_class.value if hasattr(account.account_class,"value") else str(account.account_class))
|
||||
amount=(line.credit-line.debit) if account.account_class==AccountClass.INCOME else (line.debit-line.credit)
|
||||
totals[key]=totals.get(key,Decimal("0"))+amount
|
||||
return [ProfitLossRow(*key,amount) for key,amount in sorted(totals.items())]
|
||||
|
||||
def profit_and_loss_summary(session:Session,*,start:date,end:date)->ProfitLossSummary:
|
||||
rows=profit_and_loss(session,start=start,end=end)
|
||||
income=sum((row.amount for row in rows if row.account_class=="INCOME"),Decimal("0"))
|
||||
expenses=sum((row.amount for row in rows if row.account_class=="EXPENSE"),Decimal("0"))
|
||||
return ProfitLossSummary(rows,income,expenses,income-expenses)
|
||||
|
||||
def cash_flow(session:Session,*,start:date,end:date)->CashFlowSummary:
|
||||
query=(select(JournalLine).join(Journal,JournalLine.journal_id==Journal.id)
|
||||
.join(Account,JournalLine.account_id==Account.id)
|
||||
.where(Journal.is_posted.is_(True),Journal.journal_date>=start,Journal.journal_date<=end,
|
||||
Account.is_financial_account.is_(True)))
|
||||
incoming=sum((line.debit for line in session.scalars(query)),Decimal("0"))
|
||||
outgoing=sum((line.credit for line in session.scalars(query)),Decimal("0"))
|
||||
return CashFlowSummary(incoming,outgoing,incoming-outgoing)
|
||||
|
||||
def outstanding_invoices(session:Session,*,as_of:date)->list[Invoice]:
|
||||
return [invoice for invoice in session.scalars(select(Invoice).where(Invoice.invoice_date<=as_of,
|
||||
Invoice.status.in_(["ISSUED","PARTIALLY_PAID"]))) if outstanding_balance(invoice)>0]
|
||||
|
||||
def outstanding_supplier_bills(session:Session,*,as_of:date)->list[SupplierBill]:
|
||||
return [bill for bill in session.scalars(select(SupplierBill).where(SupplierBill.bill_date<=as_of,
|
||||
SupplierBill.status.in_(["OUTSTANDING","PARTIALLY_PAID"]))) if bill_outstanding(bill)>0]
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Authoritative journal ledger and trial-balance queries."""
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from roborto_accounting.persistence.models import Account,Journal,JournalLine
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LedgerRow:
|
||||
journal_id:int;journal_date:date;account_code:str;account_name:str;description:str;debit:Decimal;credit:Decimal
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TrialBalanceRow:
|
||||
account_code:str;account_name:str;debit:Decimal;credit:Decimal
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TrialBalanceSummary:
|
||||
rows:list[TrialBalanceRow];total_debit:Decimal;total_credit:Decimal;is_balanced:bool
|
||||
|
||||
def transaction_ledger(session:Session,*,start:date,end:date,account_id:int|None=None)->list[LedgerRow]:
|
||||
query=(select(JournalLine,Journal,Account).join(Journal,JournalLine.journal_id==Journal.id)
|
||||
.join(Account,JournalLine.account_id==Account.id)
|
||||
.where(Journal.is_posted.is_(True),Journal.journal_date>=start,Journal.journal_date<=end))
|
||||
if account_id is not None:query=query.where(Account.id==account_id)
|
||||
rows=session.execute(query.order_by(Journal.journal_date,Journal.id,JournalLine.id))
|
||||
return [LedgerRow(j.id,j.journal_date,a.code,a.name,line.description or j.description,line.debit,line.credit)
|
||||
for line,j,a in rows]
|
||||
|
||||
def trial_balance(session:Session,*,start:date,end:date)->list[TrialBalanceRow]:
|
||||
totals:dict[tuple[str,str],list[Decimal]]={}
|
||||
for row in transaction_ledger(session,start=start,end=end):
|
||||
bucket=totals.setdefault((row.account_code,row.account_name),[Decimal("0"),Decimal("0")])
|
||||
bucket[0]+=row.debit;bucket[1]+=row.credit
|
||||
return [TrialBalanceRow(code,name,values[0],values[1]) for (code,name),values in sorted(totals.items())]
|
||||
|
||||
def trial_balance_is_balanced(rows:list[TrialBalanceRow])->bool:
|
||||
return sum((r.debit for r in rows),Decimal("0"))==sum((r.credit for r in rows),Decimal("0"))
|
||||
|
||||
def trial_balance_summary(session:Session,*,start:date,end:date)->TrialBalanceSummary:
|
||||
rows=trial_balance(session,start=start,end=end)
|
||||
debit=sum((row.debit for row in rows),Decimal("0"));credit=sum((row.credit for row in rows),Decimal("0"))
|
||||
return TrialBalanceSummary(rows,debit,credit,debit==credit)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Asset, profitability, and tax-preparation report views."""
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from roborto_accounting.persistence.models import AssetRecord,Expense,Invoice,TaxDetail
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProfitabilitySummary:
|
||||
client_id:int;project_id:int|None;invoiced:Decimal;direct_expenses:Decimal;net:Decimal
|
||||
|
||||
def asset_register(session:Session,*,as_of:date)->list[AssetRecord]:
|
||||
return list(session.scalars(select(AssetRecord).where(AssetRecord.purchase_date<=as_of).order_by(AssetRecord.purchase_date,AssetRecord.id)))
|
||||
|
||||
def client_project_profitability(session:Session,*,client_id:int,project_id:int|None=None)->ProfitabilitySummary:
|
||||
invoices=select(Invoice).where(Invoice.client_id==client_id,Invoice.status!="VOID")
|
||||
expenses=select(Expense).where(Expense.client_id==client_id)
|
||||
if project_id is not None:
|
||||
invoices=invoices.where(Invoice.project_id==project_id);expenses=expenses.where(Expense.project_id==project_id)
|
||||
invoiced=sum((item.net_total for item in session.scalars(invoices)),Decimal("0"))
|
||||
direct=sum((item.business_amount for item in session.scalars(expenses)),Decimal("0"))
|
||||
return ProfitabilitySummary(client_id,project_id,invoiced,direct,invoiced-direct)
|
||||
|
||||
def tax_preparation_details(session:Session)->list[TaxDetail]:
|
||||
return list(session.scalars(select(TaxDetail).order_by(TaxDetail.record_type,TaxDetail.record_id)))
|
||||
|
||||
def items_requiring_tax_review(session:Session)->list[TaxDetail]:
|
||||
return list(session.scalars(select(TaxDetail).where(TaxDetail.tax_classification=="REVIEW")
|
||||
.order_by(TaxDetail.record_type,TaxDetail.record_id)))
|
||||
Reference in New Issue
Block a user