Initial roborto accounting implementation
@@ -0,0 +1,8 @@
|
|||||||
|
.venv/
|
||||||
|
.pytest_cache/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
accounts.db
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
*.egg-info/
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Repository Working Instructions
|
||||||
|
|
||||||
|
Before significant work, read `docs/PROJECT_OVERVIEW.md`, `docs/CURRENT_STATE.md`,
|
||||||
|
`docs/DECISIONS.md`, `docs/TASKS.md`, and `docs/HANDOFF.md`. Inspect the source and
|
||||||
|
configuration relevant to the task, and check Git status before editing.
|
||||||
|
|
||||||
|
Repository code and configuration are authoritative. Preserve existing behaviour
|
||||||
|
unless the approved task explicitly changes it. Follow existing conventions, avoid
|
||||||
|
unrelated refactoring, and never invent requirements, features, commands, data
|
||||||
|
fields, workflows, or architectural decisions.
|
||||||
|
|
||||||
|
Never expose or commit secrets or `.env` values. Validate changes appropriately
|
||||||
|
before considering a task complete. After meaningful work, update the relevant
|
||||||
|
context documents with verified facts; keep `CURRENT_STATE.md` concise and refresh
|
||||||
|
`HANDOFF.md` for the next conversation.
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
# roborto accounting
|
||||||
|
|
||||||
|
Local, single-user double-entry accounting for the roborto sole-trader software
|
||||||
|
business. SQLite is authoritative; CSV, ODS and PDF files are outputs.
|
||||||
|
|
||||||
|
The business has not started trading. Set the official commencement date only when
|
||||||
|
known. Existing ODS files are reference/archive material and are not imported.
|
||||||
|
|
||||||
|
## Install and initialize
|
||||||
|
|
||||||
|
Python 3.11 or newer is required.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/pip install -e .
|
||||||
|
.venv/bin/accounts init
|
||||||
|
```
|
||||||
|
|
||||||
|
The command can then be run from any working directory. By default it uses:
|
||||||
|
|
||||||
|
- configuration: `~/.config/roborto-accounting/`
|
||||||
|
- optional env file location: `~/.config/roborto-accounting/env`
|
||||||
|
- database: `~/.local/share/roborto-accounting/accounts.sqlite`
|
||||||
|
- documents: `~/.local/share/roborto-accounting/documents/`
|
||||||
|
- backups: `~/.local/share/roborto-accounting/backups/`
|
||||||
|
|
||||||
|
`XDG_CONFIG_HOME`, `XDG_DATA_HOME`, and `XDG_STATE_HOME` override their respective
|
||||||
|
base directories. Operational `.env` files and secrets do not belong in this
|
||||||
|
repository. The application currently needs no secret environment variables.
|
||||||
|
|
||||||
|
Use `--database PATH` before the command name to operate on a different database:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts --database /path/to/test.sqlite init
|
||||||
|
```
|
||||||
|
|
||||||
|
Never point tests or experiments at the real accounting database.
|
||||||
|
|
||||||
|
## Initial configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts settings-set trading_name roborto
|
||||||
|
accounts settings-set business_descriptor "Software Development"
|
||||||
|
accounts settings-set general_email hello@roborto.net
|
||||||
|
accounts settings-set accounts_email accounts@roborto.net
|
||||||
|
accounts settings-set default_payment_terms_days 14
|
||||||
|
accounts settings-set default_hourly_rate 85.00
|
||||||
|
accounts settings-set default_income_account 4000
|
||||||
|
accounts settings-set commencement_date unset
|
||||||
|
accounts settings-show
|
||||||
|
accounts chart-list
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `commencement_date` to `YYYY-MM-DD` when it becomes official. `vat_enabled`
|
||||||
|
accepts `true` or `false`. The v1 base currency remains EUR.
|
||||||
|
|
||||||
|
## Core records and bookkeeping
|
||||||
|
|
||||||
|
Commands accept ISO dates and exact decimal amounts.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts client-add --name "Example Client" --email client@example.com --non-interactive
|
||||||
|
accounts supplier-add --name "Example Supplier" --non-interactive
|
||||||
|
|
||||||
|
accounts expense-add \
|
||||||
|
--date 2026-09-15 \
|
||||||
|
--description "Monthly hosting" \
|
||||||
|
--amount 25.00 \
|
||||||
|
--expense-account 5000 \
|
||||||
|
--payment-account 1000 \
|
||||||
|
--non-interactive
|
||||||
|
|
||||||
|
accounts transfer \
|
||||||
|
--date 2026-09-15 --description "Cash float" --amount 50.00 \
|
||||||
|
--from-account 1000 --to-account 1010 --non-interactive
|
||||||
|
```
|
||||||
|
|
||||||
|
Owner movements use `capital-add` and `drawings-add`. Advanced corrections use the
|
||||||
|
explicit `journal-manual` command and require a reason. Manual journal lines use:
|
||||||
|
|
||||||
|
```text
|
||||||
|
ACCOUNT_CODE|DEBIT|CREDIT
|
||||||
|
```
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts journal-manual --date 2026-09-30 \
|
||||||
|
--description "Reclassify cost" --reason "Correct category" \
|
||||||
|
--line '5090|10.00|' --line '5020||10.00'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quotations, invoices and payments
|
||||||
|
|
||||||
|
Quotation and invoice line arguments use:
|
||||||
|
|
||||||
|
```text
|
||||||
|
DESCRIPTION|QUANTITY|UNIT|UNIT_PRICE|VAT_AMOUNT|VAT_TREATMENT|INCOME_ACCOUNT
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts quotation-create --client-id 1 --date 2026-09-01 \
|
||||||
|
--line 'Development|10|hours|85.00|0|NONE|4000'
|
||||||
|
accounts quotation-issue 1
|
||||||
|
accounts quotation-accept 1
|
||||||
|
accounts invoice-from-quotation 1 --date 2026-09-02
|
||||||
|
accounts invoice-issue 1
|
||||||
|
accounts invoice-payment 1 --date 2026-09-16 --amount 850.00 \
|
||||||
|
--financial-account 1000
|
||||||
|
accounts invoice-list
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `credit-note`, `bad-debt`, and `invoice-void` for explicit non-destructive
|
||||||
|
adjustments. Do not rewrite or delete issued history. Generate an issued sales PDF:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts sales-document-generate invoice 1 \
|
||||||
|
--archive ~/.local/share/roborto-accounting/documents
|
||||||
|
```
|
||||||
|
|
||||||
|
Supplier purchasing commands include `supplier-bill-add`, `supplier-bill-pay`,
|
||||||
|
`supplier-refund`, and `supplier-bill-list`. Time/recharge and recurring-definition
|
||||||
|
commands are visible in `accounts --help`. Recurring definitions never issue invoices
|
||||||
|
or create accounting transactions automatically.
|
||||||
|
|
||||||
|
## Bank controls, periods and reports
|
||||||
|
|
||||||
|
Bank imports require an explicit CSV column mapping. Imported rows remain pending
|
||||||
|
until a match is explicitly approved or manually reconciled.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts bank-import statement.csv --financial-account 1000 \
|
||||||
|
--date-column Date --description-column Description --amount-column Amount
|
||||||
|
accounts bank-list
|
||||||
|
|
||||||
|
accounts period-close 2026-09 \
|
||||||
|
--backups ~/.local/share/roborto-accounting/backups
|
||||||
|
accounts period-reopen 2026-09 --reason "Approved correction"
|
||||||
|
```
|
||||||
|
|
||||||
|
Representative reports and exports:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts report trial-balance --start 2026-01-01 --end 2026-12-31
|
||||||
|
accounts report profit-loss --start 2026-01-01 --end 2026-12-31 \
|
||||||
|
--format ods --output profit-loss.ods
|
||||||
|
accounts report cash-flow --start 2026-01-01 --end 2026-12-31 \
|
||||||
|
--format pdf --output cash-flow.pdf
|
||||||
|
accounts report tax-review
|
||||||
|
```
|
||||||
|
|
||||||
|
Run a safe backup and read-only integrity check regularly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts backup
|
||||||
|
accounts check
|
||||||
|
```
|
||||||
|
|
||||||
|
Integrity checks report problems; they never silently repair accounting history.
|
||||||
|
|
||||||
|
## Business letters and document samples
|
||||||
|
|
||||||
|
```bash
|
||||||
|
accounts letter-create --date 2026-09-01 --recipient "Example Client" \
|
||||||
|
--address '1 Example Street\nDublin' --subject "Project follow-up" \
|
||||||
|
--body-file letter.txt
|
||||||
|
accounts letter-finalize 1
|
||||||
|
|
||||||
|
accounts document-samples --output /tmp/roborto-document-samples
|
||||||
|
```
|
||||||
|
|
||||||
|
Letter finalization is explicit and one-way. The application records and archives the
|
||||||
|
PDF but does not send email. The sample command generates deterministic invoice,
|
||||||
|
quotation, Cash Flow, P&L and letter PDFs for visual review.
|
||||||
|
|
||||||
|
## Development validation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/pytest -q
|
||||||
|
.venv/bin/alembic upgrade head
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests use isolated temporary databases and files. Read `AGENTS.md` and the maintained
|
||||||
|
documents in `docs/` before significant development work.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = %(here)s/alembic
|
||||||
|
prepend_sys_path = .
|
||||||
|
path_separator = os
|
||||||
|
sqlalchemy.url = sqlite:///accounts.db
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
from roborto_accounting.persistence.base import Base
|
||||||
|
from roborto_accounting.persistence import models # noqa: F401
|
||||||
|
config = context.config
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(url=url, target_metadata=target_metadata, literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"})
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
connectable = engine_from_config(config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.", poolclass=pool.NullPool)
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""Initial empty migration; application tables arrive in later revisions."""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
revision: str = "0001_initial"
|
||||||
|
down_revision: Union[str, Sequence[str], None] = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
pass
|
||||||
|
def downgrade() -> None:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""Add business settings and chart of accounts foundation."""
|
||||||
|
from datetime import datetime
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0002_settings_accounts"
|
||||||
|
down_revision = "0001_initial"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"business_settings",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("trading_name", sa.String(length=200)),
|
||||||
|
sa.Column("commencement_date", sa.Date()),
|
||||||
|
sa.Column("base_currency", sa.String(length=3), nullable=False, server_default="EUR"),
|
||||||
|
sa.Column("default_hourly_rate_micro", sa.Integer()),
|
||||||
|
sa.Column("default_payment_terms_days", sa.Integer(), nullable=False, server_default="14"),
|
||||||
|
sa.Column("vat_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||||
|
sa.Column("invoice_prefix", sa.String(length=20), nullable=False, server_default="INV"),
|
||||||
|
sa.Column("quotation_prefix", sa.String(length=20), nullable=False, server_default="Q"),
|
||||||
|
sa.Column("document_path", sa.Text()),
|
||||||
|
sa.Column("report_path", sa.Text()),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"accounts",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("code", sa.String(length=32), nullable=False, unique=True),
|
||||||
|
sa.Column("name", sa.String(length=200), nullable=False),
|
||||||
|
sa.Column("account_class", sa.String(length=20), nullable=False),
|
||||||
|
sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||||
|
sa.Column("is_financial_account", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||||
|
sa.Column("financial_account_type", sa.String(length=40)),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
)
|
||||||
|
accounts = (
|
||||||
|
("1000", "Business bank", "ASSET"), ("1010", "Cash", "ASSET"),
|
||||||
|
("1020", "PayPal", "ASSET"), ("1030", "Credit card", "LIABILITY"),
|
||||||
|
("1100", "Accounts receivable", "ASSET"), ("1200", "Equipment and assets", "ASSET"),
|
||||||
|
("2000", "Accounts payable", "LIABILITY"), ("2100", "VAT/tax liability", "LIABILITY"),
|
||||||
|
("3000", "Capital introduced", "EQUITY"), ("3100", "Drawings", "EQUITY"),
|
||||||
|
("4000", "Software development income", "INCOME"),
|
||||||
|
("4010", "Hosting and maintenance income", "INCOME"), ("4090", "Other income", "INCOME"),
|
||||||
|
("5000", "Hosting", "EXPENSE"), ("5010", "Domains", "EXPENSE"),
|
||||||
|
("5020", "Software subscriptions", "EXPENSE"), ("5030", "Equipment and small tools", "EXPENSE"),
|
||||||
|
("5040", "Advertising", "EXPENSE"), ("5050", "Professional fees", "EXPENSE"),
|
||||||
|
("5060", "Bank charges", "EXPENSE"), ("5070", "Phone and internet", "EXPENSE"),
|
||||||
|
("5080", "Travel", "EXPENSE"), ("5090", "Other expenses", "EXPENSE"),
|
||||||
|
)
|
||||||
|
accounts_table = sa.table(
|
||||||
|
"accounts", sa.column("code", sa.String), sa.column("name", sa.String),
|
||||||
|
sa.column("account_class", sa.String), sa.column("is_active", sa.Boolean),
|
||||||
|
sa.column("created_at", sa.DateTime), sa.column("updated_at", sa.DateTime),
|
||||||
|
)
|
||||||
|
now = datetime.utcnow()
|
||||||
|
op.bulk_insert(accounts_table, [
|
||||||
|
{"code": code, "name": name, "account_class": account_class, "is_active": True,
|
||||||
|
"created_at": now, "updated_at": now}
|
||||||
|
for code, name, account_class in accounts
|
||||||
|
])
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("accounts")
|
||||||
|
op.drop_table("business_settings")
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Add balanced journal and journal line tables."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0003_journals"
|
||||||
|
down_revision = "0002_settings_accounts"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("journals",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("journal_date", sa.Date(), nullable=False),
|
||||||
|
sa.Column("description", sa.String(length=500), nullable=False),
|
||||||
|
sa.Column("source", sa.String(length=40), nullable=False),
|
||||||
|
sa.Column("is_posted", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False))
|
||||||
|
op.create_table("journal_lines",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("journal_id", sa.Integer(), sa.ForeignKey("journals.id"), nullable=False),
|
||||||
|
sa.Column("account_id", sa.Integer(), sa.ForeignKey("accounts.id"), nullable=False),
|
||||||
|
sa.Column("description", sa.String(length=500)),
|
||||||
|
sa.Column("debit", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("credit", sa.Integer(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("journal_lines")
|
||||||
|
op.drop_table("journals")
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""Add durable audit events."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0004_audit_events"
|
||||||
|
down_revision = "0003_journals"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("audit_events",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("record_type", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("record_id", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("action", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("occurred_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("old_values", sa.Text()),
|
||||||
|
sa.Column("new_values", sa.Text()),
|
||||||
|
sa.Column("reason", sa.Text()),
|
||||||
|
sa.Column("source", sa.String(length=40), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("audit_events")
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"""Add reusable client records."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0005_clients"
|
||||||
|
down_revision = "0004_audit_events"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("clients",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("name", sa.String(length=200), nullable=False),
|
||||||
|
sa.Column("billing_address", sa.Text()), sa.Column("email", sa.String(length=320)),
|
||||||
|
sa.Column("phone", sa.String(length=80)), sa.Column("contact_person", sa.String(length=200)),
|
||||||
|
sa.Column("tax_identifier", sa.String(length=100)),
|
||||||
|
sa.Column("default_payment_terms_days", sa.Integer()), sa.Column("notes", sa.Text()),
|
||||||
|
sa.Column("is_active", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("updated_at", sa.DateTime(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("clients")
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Add reusable supplier records."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0006_suppliers"
|
||||||
|
down_revision = "0005_clients"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("suppliers",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("name", sa.String(length=200), nullable=False),
|
||||||
|
sa.Column("billing_address", sa.Text()), sa.Column("email", sa.String(length=320)),
|
||||||
|
sa.Column("phone", sa.String(length=80)), sa.Column("tax_identifier", sa.String(length=100)),
|
||||||
|
sa.Column("notes", sa.Text()), sa.Column("is_active", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("updated_at", sa.DateTime(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("suppliers")
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""Add projects and client/project billing-rate overrides."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0007_projects_rates"
|
||||||
|
down_revision = "0006_suppliers"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("clients", sa.Column("default_hourly_rate_micro", sa.Integer()))
|
||||||
|
op.create_table("projects",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("client_id", sa.Integer(), sa.ForeignKey("clients.id"), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=200), nullable=False),
|
||||||
|
sa.Column("code", sa.String(length=80), unique=True),
|
||||||
|
sa.Column("hourly_rate_micro", sa.Integer()), sa.Column("notes", sa.Text()),
|
||||||
|
sa.Column("is_active", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("projects")
|
||||||
|
op.drop_column("clients", "default_hourly_rate_micro")
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Add expense records with mixed-use preservation."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0008_expenses"
|
||||||
|
down_revision = "0007_projects_rates"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("expenses",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("expense_date", sa.Date(), nullable=False),
|
||||||
|
sa.Column("description", sa.String(length=500), nullable=False),
|
||||||
|
sa.Column("supplier_id", sa.Integer(), sa.ForeignKey("suppliers.id")),
|
||||||
|
sa.Column("expense_account_id", sa.Integer(), sa.ForeignKey("accounts.id"), nullable=False),
|
||||||
|
sa.Column("payment_account_id", sa.Integer(), sa.ForeignKey("accounts.id"), nullable=False),
|
||||||
|
sa.Column("journal_id", sa.Integer(), sa.ForeignKey("journals.id"), nullable=False),
|
||||||
|
sa.Column("actual_amount_micro", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("business_amount_micro", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("business_use_ppm", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("business_use_basis", sa.Text()),
|
||||||
|
sa.Column("paid_personally", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("expenses")
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Add managed supporting-document metadata."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0009_attachments"
|
||||||
|
down_revision = "0008_expenses"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("attachments",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("category", sa.String(length=40), nullable=False),
|
||||||
|
sa.Column("original_filename", sa.String(length=500), nullable=False),
|
||||||
|
sa.Column("stored_relative_path", sa.String(length=1000), nullable=False, unique=True),
|
||||||
|
sa.Column("record_type", sa.String(length=100)), sa.Column("record_id", sa.String(length=100)),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("attachments")
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Add lightweight generic tags."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0010_tags"
|
||||||
|
down_revision = "0009_attachments"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("tags", sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("name", sa.String(length=100), nullable=False, unique=True))
|
||||||
|
op.create_table("record_tags", sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("tag_id", sa.Integer(), sa.ForeignKey("tags.id"), nullable=False),
|
||||||
|
sa.Column("record_type", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("record_id", sa.String(length=100), nullable=False),
|
||||||
|
sa.UniqueConstraint("tag_id", "record_type", "record_id"))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("record_tags"); op.drop_table("tags")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Add quotation numbering, headers, and lines."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision = "0011_quotations"
|
||||||
|
down_revision = "0010_tags"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("document_counters", sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("document_type", sa.String(length=40), nullable=False),
|
||||||
|
sa.Column("calendar_year", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("next_number", sa.Integer(), nullable=False),
|
||||||
|
sa.UniqueConstraint("document_type", "calendar_year"))
|
||||||
|
op.create_table("quotations", sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("client_id", sa.Integer(), sa.ForeignKey("clients.id"), nullable=False),
|
||||||
|
sa.Column("project_id", sa.Integer(), sa.ForeignKey("projects.id")),
|
||||||
|
sa.Column("quotation_date", sa.Date(), nullable=False), sa.Column("status", sa.String(length=30), nullable=False),
|
||||||
|
sa.Column("number", sa.String(length=40), unique=True), sa.Column("client_snapshot_json", sa.Text()),
|
||||||
|
sa.Column("net_total_micro", sa.Integer(), nullable=False), sa.Column("vat_total_micro", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("gross_total_micro", sa.Integer(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False))
|
||||||
|
op.create_table("quotation_lines", sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("quotation_id", sa.Integer(), sa.ForeignKey("quotations.id"), nullable=False),
|
||||||
|
sa.Column("description", sa.String(length=500), nullable=False), sa.Column("quantity_micro", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("unit", sa.String(length=40), nullable=False), sa.Column("unit_price_micro", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("vat_treatment", sa.String(length=60), nullable=False), sa.Column("net_total_micro", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("vat_amount_micro", sa.Integer(), nullable=False), sa.Column("gross_total_micro", sa.Integer(), nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("quotation_lines"); op.drop_table("quotations"); op.drop_table("document_counters")
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""Add invoice headers, lines, terms, and snapshots."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0012_invoices"; down_revision="0011_quotations"; branch_labels=None; depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("invoices", sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("client_id",sa.Integer(),sa.ForeignKey("clients.id"),nullable=False),
|
||||||
|
sa.Column("project_id",sa.Integer(),sa.ForeignKey("projects.id")),
|
||||||
|
sa.Column("source_quotation_id",sa.Integer(),sa.ForeignKey("quotations.id")),
|
||||||
|
sa.Column("invoice_date",sa.Date(),nullable=False),sa.Column("due_date",sa.Date()),
|
||||||
|
sa.Column("status",sa.String(30),nullable=False),sa.Column("number",sa.String(40),unique=True),
|
||||||
|
sa.Column("client_snapshot_json",sa.Text()),sa.Column("net_total_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("vat_total_micro",sa.Integer(),nullable=False),sa.Column("gross_total_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("paid_total_micro",sa.Integer(),nullable=False),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
op.create_table("invoice_lines",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("invoice_id",sa.Integer(),sa.ForeignKey("invoices.id"),nullable=False),
|
||||||
|
sa.Column("description",sa.String(500),nullable=False),sa.Column("quantity_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("unit",sa.String(40),nullable=False),sa.Column("unit_price_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("vat_treatment",sa.String(60),nullable=False),sa.Column("net_total_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("vat_amount_micro",sa.Integer(),nullable=False),sa.Column("gross_total_micro",sa.Integer(),nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("invoice_lines"); op.drop_table("invoices")
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Add client payments, allocations, and unapplied credit."""
|
||||||
|
from datetime import datetime
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0013_client_payments"; down_revision="0012_invoices"; branch_labels=None; depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
now=datetime.utcnow()
|
||||||
|
accounts=sa.table("accounts",sa.column("code",sa.String),sa.column("name",sa.String),
|
||||||
|
sa.column("account_class",sa.String),sa.column("is_active",sa.Boolean),
|
||||||
|
sa.column("is_financial_account",sa.Boolean),sa.column("created_at",sa.DateTime),sa.column("updated_at",sa.DateTime))
|
||||||
|
op.bulk_insert(accounts,[{"code":"2110","name":"Unapplied client credits","account_class":"LIABILITY",
|
||||||
|
"is_active":True,"is_financial_account":False,"created_at":now,"updated_at":now}])
|
||||||
|
op.create_table("client_payments",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("client_id",sa.Integer(),sa.ForeignKey("clients.id"),nullable=False),
|
||||||
|
sa.Column("payment_date",sa.Date(),nullable=False),sa.Column("amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("unapplied_amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("financial_account_id",sa.Integer(),sa.ForeignKey("accounts.id"),nullable=False),
|
||||||
|
sa.Column("receipt_journal_id",sa.Integer(),sa.ForeignKey("journals.id"),nullable=False),
|
||||||
|
sa.Column("reference",sa.String(200)),sa.Column("notes",sa.Text()),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
op.create_table("payment_allocations",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("payment_id",sa.Integer(),sa.ForeignKey("client_payments.id"),nullable=False),
|
||||||
|
sa.Column("invoice_id",sa.Integer(),sa.ForeignKey("invoices.id"),nullable=False),
|
||||||
|
sa.Column("amount_micro",sa.Integer(),nullable=False),sa.Column("allocation_date",sa.Date(),nullable=False),
|
||||||
|
sa.Column("journal_id",sa.Integer(),sa.ForeignKey("journals.id")),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("payment_allocations"); op.drop_table("client_payments")
|
||||||
|
op.execute("DELETE FROM accounts WHERE code = '2110'")
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""Add credit notes and bad-debt write-offs."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0014_credits_writeoffs";down_revision="0013_client_payments";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("invoices",sa.Column("credited_total_micro",sa.Integer(),nullable=False,server_default="0"))
|
||||||
|
op.add_column("invoices",sa.Column("written_off_total_micro",sa.Integer(),nullable=False,server_default="0"))
|
||||||
|
op.create_table("credit_notes",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("invoice_id",sa.Integer(),sa.ForeignKey("invoices.id"),nullable=False),
|
||||||
|
sa.Column("number",sa.String(40),nullable=False,unique=True),sa.Column("credit_date",sa.Date(),nullable=False),
|
||||||
|
sa.Column("amount_micro",sa.Integer(),nullable=False),sa.Column("reason",sa.Text(),nullable=False),
|
||||||
|
sa.Column("journal_id",sa.Integer(),sa.ForeignKey("journals.id"),nullable=False),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
op.create_table("bad_debt_write_offs",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("invoice_id",sa.Integer(),sa.ForeignKey("invoices.id"),nullable=False),
|
||||||
|
sa.Column("write_off_date",sa.Date(),nullable=False),sa.Column("amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("reason",sa.Text(),nullable=False),sa.Column("journal_id",sa.Integer(),sa.ForeignKey("journals.id"),nullable=False),
|
||||||
|
sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("bad_debt_write_offs");op.drop_table("credit_notes")
|
||||||
|
op.drop_column("invoices","written_off_total_micro");op.drop_column("invoices","credited_total_micro")
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Add supplier bills, payments, and refunds."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0015_payables";down_revision="0014_credits_writeoffs";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("supplier_bills",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("supplier_id",sa.Integer(),sa.ForeignKey("suppliers.id"),nullable=False),
|
||||||
|
sa.Column("bill_date",sa.Date(),nullable=False),sa.Column("due_date",sa.Date()),
|
||||||
|
sa.Column("description",sa.String(500),nullable=False),sa.Column("amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("paid_total_micro",sa.Integer(),nullable=False),sa.Column("status",sa.String(30),nullable=False),
|
||||||
|
sa.Column("expense_account_id",sa.Integer(),sa.ForeignKey("accounts.id"),nullable=False),
|
||||||
|
sa.Column("journal_id",sa.Integer(),sa.ForeignKey("journals.id"),nullable=False),
|
||||||
|
sa.Column("supplier_reference",sa.String(200)),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
op.create_table("supplier_payments",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("bill_id",sa.Integer(),sa.ForeignKey("supplier_bills.id"),nullable=False),
|
||||||
|
sa.Column("payment_date",sa.Date(),nullable=False),sa.Column("amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("financial_account_id",sa.Integer(),sa.ForeignKey("accounts.id"),nullable=False),
|
||||||
|
sa.Column("journal_id",sa.Integer(),sa.ForeignKey("journals.id"),nullable=False),
|
||||||
|
sa.Column("reference",sa.String(200)),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
op.create_table("supplier_refunds",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("bill_id",sa.Integer(),sa.ForeignKey("supplier_bills.id"),nullable=False),
|
||||||
|
sa.Column("refund_date",sa.Date(),nullable=False),sa.Column("amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("financial_account_id",sa.Integer(),sa.ForeignKey("accounts.id"),nullable=False),
|
||||||
|
sa.Column("reason",sa.Text(),nullable=False),sa.Column("journal_id",sa.Integer(),sa.ForeignKey("journals.id"),nullable=False),
|
||||||
|
sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("supplier_refunds");op.drop_table("supplier_payments");op.drop_table("supplier_bills")
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
"""Add billable time entries and invoice assignment."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0016_time_entries";down_revision="0015_payables";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("time_entries",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("client_id",sa.Integer(),sa.ForeignKey("clients.id"),nullable=False),
|
||||||
|
sa.Column("project_id",sa.Integer(),sa.ForeignKey("projects.id")),sa.Column("entry_date",sa.Date(),nullable=False),
|
||||||
|
sa.Column("hours_micro",sa.Integer(),nullable=False),sa.Column("description",sa.String(500),nullable=False),
|
||||||
|
sa.Column("billing_rate_micro",sa.Integer(),nullable=False),sa.Column("is_billable",sa.Boolean(),nullable=False),
|
||||||
|
sa.Column("invoice_id",sa.Integer(),sa.ForeignKey("invoices.id")),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("time_entries")
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""Add rechargeable expense links and invoice state."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0017_rechargeable_expenses";down_revision="0016_time_entries";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table("expenses") as batch:
|
||||||
|
batch.add_column(sa.Column("client_id",sa.Integer()))
|
||||||
|
batch.add_column(sa.Column("project_id",sa.Integer()))
|
||||||
|
batch.add_column(sa.Column("is_rechargeable",sa.Boolean(),nullable=False,server_default=sa.false()))
|
||||||
|
batch.add_column(sa.Column("recharge_invoice_id",sa.Integer()))
|
||||||
|
batch.create_foreign_key("fk_expenses_client_id","clients",["client_id"],["id"])
|
||||||
|
batch.create_foreign_key("fk_expenses_project_id","projects",["project_id"],["id"])
|
||||||
|
batch.create_foreign_key("fk_expenses_recharge_invoice_id","invoices",["recharge_invoice_id"],["id"])
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table("expenses") as batch:
|
||||||
|
batch.drop_constraint("fk_expenses_recharge_invoice_id",type_="foreignkey")
|
||||||
|
batch.drop_constraint("fk_expenses_project_id",type_="foreignkey")
|
||||||
|
batch.drop_constraint("fk_expenses_client_id",type_="foreignkey")
|
||||||
|
batch.drop_column("recharge_invoice_id");batch.drop_column("is_rechargeable")
|
||||||
|
batch.drop_column("project_id");batch.drop_column("client_id")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Add advisory recurring invoice and expense definitions."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0018_recurring_definitions";down_revision="0017_rechargeable_expenses";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("recurring_invoice_definitions",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("client_id",sa.Integer(),sa.ForeignKey("clients.id"),nullable=False),
|
||||||
|
sa.Column("project_id",sa.Integer(),sa.ForeignKey("projects.id")),sa.Column("frequency",sa.String(40),nullable=False),
|
||||||
|
sa.Column("next_due_date",sa.Date(),nullable=False),sa.Column("template_lines_json",sa.Text(),nullable=False),
|
||||||
|
sa.Column("is_active",sa.Boolean(),nullable=False),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
op.create_table("recurring_expense_definitions",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("supplier_id",sa.Integer(),sa.ForeignKey("suppliers.id"),nullable=False),
|
||||||
|
sa.Column("frequency",sa.String(40),nullable=False),sa.Column("next_expected_date",sa.Date(),nullable=False),
|
||||||
|
sa.Column("category_account_id",sa.Integer(),sa.ForeignKey("accounts.id"),nullable=False),
|
||||||
|
sa.Column("expected_amount_micro",sa.Integer()),sa.Column("reconciliation_hints",sa.Text()),
|
||||||
|
sa.Column("is_active",sa.Boolean(),nullable=False),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("recurring_expense_definitions");op.drop_table("recurring_invoice_definitions")
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
"""Add pending imported bank transactions."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0019_bank_imports";down_revision="0018_recurring_definitions";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("imported_bank_transactions",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("financial_account_id",sa.Integer(),sa.ForeignKey("accounts.id"),nullable=False),
|
||||||
|
sa.Column("transaction_date",sa.Date(),nullable=False),sa.Column("description",sa.String(1000),nullable=False),
|
||||||
|
sa.Column("amount_micro",sa.Integer(),nullable=False),sa.Column("currency",sa.String(3),nullable=False),
|
||||||
|
sa.Column("source_format",sa.String(100),nullable=False),sa.Column("source_hash",sa.String(64),nullable=False,unique=True),
|
||||||
|
sa.Column("raw_json",sa.Text(),nullable=False),sa.Column("status",sa.String(30),nullable=False),
|
||||||
|
sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:op.drop_table("imported_bank_transactions")
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
"""Add explicit bank reconciliation matches."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0020_reconciliation";down_revision="0019_bank_imports";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("reconciliation_matches",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("imported_transaction_id",sa.Integer(),sa.ForeignKey("imported_bank_transactions.id"),nullable=False),
|
||||||
|
sa.Column("record_type",sa.String(100),nullable=False),sa.Column("record_id",sa.String(100),nullable=False),
|
||||||
|
sa.Column("score_ppm",sa.Integer()),sa.Column("status",sa.String(30),nullable=False),sa.Column("reason",sa.Text()),
|
||||||
|
sa.Column("created_at",sa.DateTime(),nullable=False),sa.Column("decided_at",sa.DateTime()))
|
||||||
|
def downgrade() -> None:op.drop_table("reconciliation_matches")
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""Add immutable foreign-currency value snapshots."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0021_currency_snapshots";down_revision="0020_reconciliation";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("currency_snapshots",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("record_type",sa.String(100),nullable=False),sa.Column("record_id",sa.String(100),nullable=False),
|
||||||
|
sa.Column("field_name",sa.String(100),nullable=False),sa.Column("original_amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("original_currency",sa.String(3),nullable=False),sa.Column("exchange_rate_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("eur_amount_micro",sa.Integer(),nullable=False),sa.Column("created_at",sa.DateTime(),nullable=False),
|
||||||
|
sa.UniqueConstraint("record_type","record_id","field_name"))
|
||||||
|
def downgrade() -> None:op.drop_table("currency_snapshots")
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""Add VAT-ready amounts and separate tax classification."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0022_tax_details";down_revision="0021_currency_snapshots";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("tax_details",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("record_type",sa.String(100),nullable=False),sa.Column("record_id",sa.String(100),nullable=False),
|
||||||
|
sa.Column("net_amount_micro",sa.Integer(),nullable=False),sa.Column("vat_rate_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("vat_amount_micro",sa.Integer(),nullable=False),sa.Column("gross_amount_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("vat_treatment",sa.String(60),nullable=False),sa.Column("tax_classification",sa.String(40),nullable=False),
|
||||||
|
sa.Column("created_at",sa.DateTime(),nullable=False),sa.UniqueConstraint("record_type","record_id"))
|
||||||
|
def downgrade() -> None:op.drop_table("tax_details")
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
"""Add asset register."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0023_assets";down_revision="0022_tax_details";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("asset_records",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("purchase_date",sa.Date(),nullable=False),sa.Column("description",sa.String(500),nullable=False),
|
||||||
|
sa.Column("supplier_id",sa.Integer(),sa.ForeignKey("suppliers.id")),sa.Column("original_cost_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("original_currency",sa.String(3),nullable=False),sa.Column("eur_value_micro",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("business_use_ppm",sa.Integer(),nullable=False),sa.Column("attachment_id",sa.Integer(),sa.ForeignKey("attachments.id")),
|
||||||
|
sa.Column("disposal_date",sa.Date()),sa.Column("disposal_proceeds_micro",sa.Integer()),sa.Column("notes",sa.Text()),
|
||||||
|
sa.Column("tax_treatment",sa.String(40),nullable=False),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade() -> None:op.drop_table("asset_records")
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""Add accounting period locks and backup references."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0024_periods";down_revision="0023_assets";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table("accounting_periods",sa.Column("id",sa.Integer(),primary_key=True),
|
||||||
|
sa.Column("year",sa.Integer(),nullable=False),sa.Column("month",sa.Integer(),nullable=False),
|
||||||
|
sa.Column("status",sa.String(20),nullable=False),sa.Column("closed_at",sa.DateTime()),
|
||||||
|
sa.Column("reopened_at",sa.DateTime()),sa.Column("backup_path",sa.Text()),sa.UniqueConstraint("year","month"))
|
||||||
|
def downgrade() -> None:op.drop_table("accounting_periods")
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""Add configuration-driven business document identity and payment details."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0025_document_settings";down_revision="0024_periods";branch_labels=None;depends_on=None
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("business_settings",sa.Column("business_descriptor",sa.String(200)))
|
||||||
|
op.add_column("business_settings",sa.Column("website",sa.String(300)))
|
||||||
|
op.add_column("business_settings",sa.Column("general_email",sa.String(320)))
|
||||||
|
op.add_column("business_settings",sa.Column("accounts_email",sa.String(320),nullable=False,server_default="accounts@roborto.net"))
|
||||||
|
op.add_column("business_settings",sa.Column("telephone",sa.String(80)))
|
||||||
|
op.add_column("business_settings",sa.Column("postal_address",sa.Text()))
|
||||||
|
op.add_column("business_settings",sa.Column("tax_identifier",sa.String(100)))
|
||||||
|
op.add_column("business_settings",sa.Column("bank_payment_instructions",sa.Text()))
|
||||||
|
def downgrade() -> None:
|
||||||
|
for name in ("bank_payment_instructions","tax_identifier","postal_address","telephone","accounts_email","general_email","website","business_descriptor"):
|
||||||
|
op.drop_column("business_settings",name)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Add per-line income mapping and invoice issue journal linkage."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision="0026_invoice_accounting";down_revision="0025_document_settings";branch_labels=None;depends_on=None
|
||||||
|
|
||||||
|
def upgrade()->None:
|
||||||
|
with op.batch_alter_table("business_settings") as batch:
|
||||||
|
batch.add_column(sa.Column("default_income_account_id",sa.Integer()))
|
||||||
|
batch.create_foreign_key("fk_settings_default_income","accounts",["default_income_account_id"],["id"])
|
||||||
|
with op.batch_alter_table("quotation_lines") as batch:
|
||||||
|
batch.add_column(sa.Column("income_account_id",sa.Integer()))
|
||||||
|
batch.create_foreign_key("fk_quotation_lines_income","accounts",["income_account_id"],["id"])
|
||||||
|
with op.batch_alter_table("invoice_lines") as batch:
|
||||||
|
batch.add_column(sa.Column("income_account_id",sa.Integer()))
|
||||||
|
batch.create_foreign_key("fk_invoice_lines_income","accounts",["income_account_id"],["id"])
|
||||||
|
with op.batch_alter_table("invoices") as batch:
|
||||||
|
batch.add_column(sa.Column("issue_journal_id",sa.Integer()))
|
||||||
|
batch.create_foreign_key("fk_invoices_issue_journal","journals",["issue_journal_id"],["id"])
|
||||||
|
|
||||||
|
def downgrade()->None:
|
||||||
|
for table,constraint,column in (("invoices","fk_invoices_issue_journal","issue_journal_id"),("invoice_lines","fk_invoice_lines_income","income_account_id"),("quotation_lines","fk_quotation_lines_income","income_account_id"),("business_settings","fk_settings_default_income","default_income_account_id")):
|
||||||
|
with op.batch_alter_table(table) as batch:
|
||||||
|
batch.drop_constraint(constraint,type_="foreignkey");batch.drop_column(column)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""Add invoice reversal linkage and void date."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0027_invoice_voids";down_revision="0026_invoice_accounting";branch_labels=None;depends_on=None
|
||||||
|
def upgrade()->None:
|
||||||
|
with op.batch_alter_table("invoices") as batch:
|
||||||
|
batch.add_column(sa.Column("void_journal_id",sa.Integer()))
|
||||||
|
batch.add_column(sa.Column("voided_on",sa.Date()))
|
||||||
|
batch.create_foreign_key("fk_invoices_void_journal","journals",["void_journal_id"],["id"])
|
||||||
|
def downgrade()->None:
|
||||||
|
with op.batch_alter_table("invoices") as batch:
|
||||||
|
batch.drop_constraint("fk_invoices_void_journal",type_="foreignkey");batch.drop_column("voided_on");batch.drop_column("void_journal_id")
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"""Add persisted business letter drafts and finalized archive linkage."""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
revision="0028_business_letters";down_revision="0027_invoice_voids";branch_labels=None;depends_on=None
|
||||||
|
def upgrade()->None:
|
||||||
|
op.create_table("business_letters",sa.Column("id",sa.Integer(),primary_key=True),sa.Column("letter_date",sa.Date(),nullable=False),sa.Column("recipient_name",sa.String(200),nullable=False),sa.Column("recipient_address",sa.Text(),nullable=False),sa.Column("recipient_email",sa.String(320)),sa.Column("reference",sa.String(200)),sa.Column("subject",sa.String(300),nullable=False),sa.Column("body_text",sa.Text(),nullable=False),sa.Column("status",sa.String(30),nullable=False),sa.Column("attachment_id",sa.Integer(),sa.ForeignKey("attachments.id")),sa.Column("finalized_at",sa.DateTime()),sa.Column("created_at",sa.DateTime(),nullable=False))
|
||||||
|
def downgrade()->None:op.drop_table("business_letters")
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<svg width="420" height="120" viewBox="0 0 420 120" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<rect width="100%" height="100%" fill="#0b0f14"/>
|
||||||
|
<!-- small robot -->
|
||||||
|
<rect x="20" y="50" width="28" height="28" rx="6" fill="#7ee787"/>
|
||||||
|
<circle cx="30" cy="64" r="2.5" fill="#0b0f14"/>
|
||||||
|
<circle cx="38" cy="64" r="2.5" fill="#0b0f14"/>
|
||||||
|
<!-- text -->
|
||||||
|
<text x="60" y="72" font-family="JetBrains Mono, monospace" font-size="24" fill="#e6edf3">
|
||||||
|
roborto.net
|
||||||
|
</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 476 B |
@@ -0,0 +1,6 @@
|
|||||||
|
<svg width="420" height="120" viewBox="0 0 420 120" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<rect x="20" y="50" width="28" height="28" rx="6" fill="#7ee787"/>
|
||||||
|
<circle cx="30" cy="64" r="2.5" fill="#0b0f14"/>
|
||||||
|
<circle cx="38" cy="64" r="2.5" fill="#0b0f14"/>
|
||||||
|
<text x="60" y="72" font-family="JetBrains Mono, monospace" font-size="24" fill="#0b0f14">roborto.net</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 377 B |
@@ -0,0 +1,29 @@
|
|||||||
|
# Current State
|
||||||
|
|
||||||
|
- Development stage: approved v1 and business-letter workflow implemented; no active task.
|
||||||
|
- Implemented: persistence/migrations, exact money, chart/settings, balanced journals,
|
||||||
|
audit, all core records and sales/payables workflows, recurring definitions, bank
|
||||||
|
import/reconciliation, currency/VAT/tax records, assets, period locks/backups,
|
||||||
|
integrity checking, CLI foundation, reports, CSV/ODS exports, managed attachments,
|
||||||
|
and branded invoice/quotation/accounting-report/business-letter PDFs.
|
||||||
|
- CLI commands: initialization/upgrade; settings/chart administration; clients,
|
||||||
|
suppliers and projects; expenses, transfers, capital and drawings; attachments and
|
||||||
|
tags; quotations/invoices/payments/credits; supplier bills/payments/refunds; time,
|
||||||
|
recharges and recurring definitions; generated sales documents; safe backup,
|
||||||
|
integrity check, business-letter draft/finalize/list, and document-sample generation.
|
||||||
|
- Runtime storage: XDG user directories; database/documents/backups under
|
||||||
|
`~/.local/share/roborto-accounting`, configuration and optional env file under
|
||||||
|
`~/.config/roborto-accounting`. Paths can follow the corresponding XDG overrides.
|
||||||
|
- Migration state: revisions through `0028_business_letters`; a full empty-database
|
||||||
|
upgrade creates 35 tables and passes SQLite foreign-key checking.
|
||||||
|
- Testing: `.venv/bin/pytest -q` passes (60 tests). Tests use isolated databases/files.
|
||||||
|
- Document validation: deterministic A4 samples for invoice, quotation, Cash Flow,
|
||||||
|
and P&L were generated and visually inspected against `docs/design/references/`;
|
||||||
|
multi-page invoice and ledger/report pagination was checked.
|
||||||
|
- Missing approved functionality: none identified by the completed requirements audit.
|
||||||
|
- Known problems: no known failing test or migration.
|
||||||
|
- Repository baseline: the completed implementation is captured in the initial Git
|
||||||
|
commit; generated runtime/test artifacts remain ignored.
|
||||||
|
- Current active task: none.
|
||||||
|
- Operator documentation: root `README.md` covers installation, XDG data locations,
|
||||||
|
configuration, representative workflows, controls, reports, documents and validation.
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
# Decisions
|
||||||
|
|
||||||
|
## ADR-001: Local Python CLI and single-user v1
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Begin as a local Python CLI for one user; no identity, login, roles, or
|
||||||
|
multi-tenancy.
|
||||||
|
- Context: Explicit v1 scope.
|
||||||
|
- Consequences: CLI is an interface over reusable services; no web functionality in v1.
|
||||||
|
- Evidence / related task: Specification; `FND-001`, `CLI-001`.
|
||||||
|
|
||||||
|
## ADR-002: SQLite authority and migrations
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: SQLite is authoritative, accessed via SQLAlchemy and evolved with Alembic.
|
||||||
|
- Context: Local application must preserve data through schema changes.
|
||||||
|
- Consequences: CSV/ODS/PDF are outputs, not databases; no recreate-on-change workflow.
|
||||||
|
- Evidence / related task: Specification; `FND-002`, `FND-003`.
|
||||||
|
|
||||||
|
## ADR-003: Reusable accounting architecture
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Separate domain, persistence, application services, CLI, reporting/exports,
|
||||||
|
and document storage; future Flask/React reuses the core.
|
||||||
|
- Context: Interfaces must not own accounting rules.
|
||||||
|
- Consequences: No Flask/React/routes/auth in v1.
|
||||||
|
- Evidence / related task: Specification; `FND-004`.
|
||||||
|
|
||||||
|
## ADR-004: Double-entry and exact historical values
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Posted journals balance; use `Decimal` only; preserve applied currency rates,
|
||||||
|
issue-time document snapshots, and never-reused annual numbers.
|
||||||
|
- Context: Accounting correctness and stable history.
|
||||||
|
- Consequences: Monetary conversions use the centralized micro-unit persistence type.
|
||||||
|
- Evidence / related task: Specification; `ACC-001`, `FND-003`, `SALE-002`.
|
||||||
|
|
||||||
|
## ADR-009: Store money as integer micro-units in SQLite
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Persist monetary values as signed integer micro-units (10^-6 of the
|
||||||
|
currency unit), expose `Decimal` values in Python, quantize with half-up rounding,
|
||||||
|
and reject binary floats.
|
||||||
|
- Context: SQLite must represent accounting amounts exactly and historical values
|
||||||
|
must be stable.
|
||||||
|
- Consequences: Values are limited to six fractional decimal places; the conversion
|
||||||
|
policy is centralized in the persistence money type.
|
||||||
|
- Evidence / related task: `src/roborto_accounting/persistence/money.py`; `FND-003`.
|
||||||
|
|
||||||
|
## ADR-005: EUR/VAT, commencement, and tax separation
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: EUR is base currency; VAT-ready fields/configuration exist; commencement
|
||||||
|
date is nullable; pre-trading remains identifiable; accounting classification and
|
||||||
|
tax treatment are separate, with uncertain treatment `REVIEW`.
|
||||||
|
- Context: Business has not traded and tax conclusions must not be invented.
|
||||||
|
- Consequences: v1 supports preparation, not filing or tax advice.
|
||||||
|
- Evidence / related task: Specification; `FND-005`, `CORE-005`, `CTRL-004`.
|
||||||
|
|
||||||
|
## ADR-006: Non-destructive history, audit, periods, and attachments
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Correct/void/credit/write off rather than casually delete; audit meaningful
|
||||||
|
changes; closed periods reject ordinary edits; managed filesystem attachments use
|
||||||
|
SQLite references and collision-safe names.
|
||||||
|
- Context: Accounting history must remain recoverable and inspectable.
|
||||||
|
- Consequences: Backups and integrity checks are first-class controls.
|
||||||
|
- Evidence / related task: Specification; `AUD-001`, `CTRL-006`, `CORE-006`.
|
||||||
|
|
||||||
|
## ADR-007: Human approval for automation and reconciliation
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Recurring invoices prepare drafts only; recurring expenses detect expected
|
||||||
|
items only; ambiguous bank matches require approval; no online banking.
|
||||||
|
- Context: Automation must not silently create financial history.
|
||||||
|
- Consequences: User approval is explicit in services/CLI.
|
||||||
|
- Evidence / related task: Specification; `SALE-009`, `SALE-010`, `CTRL-002`.
|
||||||
|
|
||||||
|
## ADR-008: Explicit v1 exclusions
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Exclude ODS migration, purchase orders, estimates, email, cloud backup,
|
||||||
|
Revenue filing, online bank connections, payroll, inventory, project management,
|
||||||
|
automatic tax advice, Flask, React, and authentication.
|
||||||
|
- Context: Explicit scope boundaries.
|
||||||
|
- Consequences: These are non-goals, not backlog tasks.
|
||||||
|
- Evidence / related task: Specification.
|
||||||
|
|
||||||
|
## ADR-010: Approved light-mode A4 document family
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Generated professional documents use the shared minimalist light-mode
|
||||||
|
Roborto A4 identity in `docs/design/DOCUMENT_DESIGN.md`; the invoice reference is
|
||||||
|
canonical, using `logo-light.svg`, green `#7ee787`, dark `#0b0f14`, restrained
|
||||||
|
accents, thin rules, structured tables, and the standard footer.
|
||||||
|
- Context: The supplied document-design handoff establishes the approved visual direction.
|
||||||
|
- Consequences: Styling is a reusable UI-independent theme; identity/payment data is
|
||||||
|
configured; accounting values remain outside templates; visual parity requires
|
||||||
|
actual generated-output inspection.
|
||||||
|
- Evidence / related task: `docs/design/`; `DOC-001` through `DOC-005`.
|
||||||
|
|
||||||
|
## ADR-011: Preserve overpayments as unapplied client credit
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Record the full client payment, allocate no more than the invoice balance,
|
||||||
|
and retain excess as a client-credit liability available for later allocation or refund.
|
||||||
|
- Context: Actual cash receipts must be preserved without overstating invoice settlement.
|
||||||
|
- Consequences: Applying credit later is a separate allocation and balanced journal;
|
||||||
|
the original payment is never rewritten.
|
||||||
|
- Evidence / related task: User approval of recommended next step; `SALE-004`.
|
||||||
|
|
||||||
|
## ADR-012: Annual credit-note prefix
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Credit notes use annual sequential numbers in the form `CN-YYYY-NNN`;
|
||||||
|
assigned numbers are never reused.
|
||||||
|
- Context: Credit notes require an analogous documented annual numbering scheme.
|
||||||
|
- Consequences: Corrections reduce invoice balances through linked events rather than
|
||||||
|
rewriting issued invoices.
|
||||||
|
- Evidence / related task: Continued implementation approval; `SALE-005`.
|
||||||
|
|
||||||
|
## ADR-013: XDG user runtime locations
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Runtime configuration, data, and state follow XDG user directories. The
|
||||||
|
optional env file is `~/.config/roborto-accounting/env`; SQLite, documents, and
|
||||||
|
backups default below `~/.local/share/roborto-accounting`.
|
||||||
|
- Context: The installed application must run independently of the projects checkout,
|
||||||
|
without requiring system-wide `/opt` permissions or storing secrets in source.
|
||||||
|
- Consequences: Standard XDG environment variables can relocate data; the repository
|
||||||
|
contains no operational `.env` values.
|
||||||
|
- Evidence / related task: User deployment-path request; `CLI-001`.
|
||||||
|
|
||||||
|
## ADR-014: ReportLab document rendering
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Use ReportLab with svglib for deterministic A4 PDFs and the repository SVG
|
||||||
|
logo through one UI-independent shared theme.
|
||||||
|
- Context: Approved reference designs require print-safe PDF output, pagination,
|
||||||
|
wrapping, and reusable styling.
|
||||||
|
- Consequences: Templates only present values supplied by services; ReportLab and
|
||||||
|
svglib are runtime dependencies; visual samples are generated for review.
|
||||||
|
- Evidence / related task: `DOC-002` through `DOC-005`.
|
||||||
|
|
||||||
|
## ADR-015: Invoice revenue-account mapping
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Store a revenue account on each quotation/invoice line, optionally
|
||||||
|
defaulted by the application from a configured business default during draft entry.
|
||||||
|
- Context: Current invoice issue snapshots the document but does not post accounts
|
||||||
|
receivable, income, or VAT. The chart distinguishes software-development, hosting/
|
||||||
|
maintenance, and other income, so a single hard-coded income account loses approved
|
||||||
|
reporting classification.
|
||||||
|
- Consequences: The selected mapping must be persisted and immutable after issue;
|
||||||
|
quotation conversion carries it to invoice lines; issue debits receivables for gross
|
||||||
|
and credits the selected income account(s) for net plus VAT liability for VAT.
|
||||||
|
- Evidence / related task: User approval; completion audit during `CLI-004`; `ACC-003`.
|
||||||
|
|
||||||
|
## ADR-016: Narrow business-letter workflow
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-08-29
|
||||||
|
- Decision: Persist business-letter drafts containing recipient and content snapshots,
|
||||||
|
then explicitly finalize them to the shared branded PDF theme and managed archive.
|
||||||
|
- Context: The user approved proceeding after the letter design had previously been
|
||||||
|
deferred for lack of workflow scope.
|
||||||
|
- Consequences: Finalized letters are stable and auditable; no email, mail merge,
|
||||||
|
campaigns, delivery tracking, or correspondence automation is introduced.
|
||||||
|
- Evidence / related task: User approval; `DOC-FUTURE-001`.
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# Handoff
|
||||||
|
|
||||||
|
## 1. Project overview
|
||||||
|
|
||||||
|
roborto accounting is a local, single-user Python/SQLite double-entry application for
|
||||||
|
a pre-trading sole-trader software business. SQLite is authoritative.
|
||||||
|
|
||||||
|
## 2. Repository state
|
||||||
|
|
||||||
|
The accounting/service layers and full backlog are implemented and captured in the
|
||||||
|
initial Git baseline. `.venv`, caches, generated databases, bytecode, and package
|
||||||
|
metadata are ignored.
|
||||||
|
|
||||||
|
## 3. Current application state
|
||||||
|
|
||||||
|
Foundation, accounting/core workflows, sales/payables, controls, operational CLI,
|
||||||
|
reports/exports, managed documents, and branded PDFs are implemented. Approved daily
|
||||||
|
workflows have command coverage, including the approved narrow business-letter flow.
|
||||||
|
|
||||||
|
## 4. Architecture/data flow
|
||||||
|
|
||||||
|
SQLite → persistence → domain/services → CLI and reports/documents. Filesystem
|
||||||
|
documents use SQLite attachment metadata. PDF templates present service/core values
|
||||||
|
and do not own accounting calculations.
|
||||||
|
|
||||||
|
## 5. Important accepted decisions
|
||||||
|
|
||||||
|
See `docs/DECISIONS.md`. Highlights: Decimal integer micro-units, balanced posted
|
||||||
|
journals, non-destructive history, `CN-YYYY-NNN`, explicit reconciliation/recurring
|
||||||
|
approval, XDG runtime locations, and ReportLab/svglib shared A4 rendering.
|
||||||
|
|
||||||
|
## 6. Recent work
|
||||||
|
|
||||||
|
Completed the full backlog, including migrations 0014–0028, all controls
|
||||||
|
and reports, CLI/runtime paths, PDF renderers, managed generated-document metadata,
|
||||||
|
and deterministic visual samples. Corrected migration 0017 to use SQLite batch mode.
|
||||||
|
|
||||||
|
## 7. Current task
|
||||||
|
|
||||||
|
No active approved task. The final audit tasks and `DOC-FUTURE-001` business-letter
|
||||||
|
draft/finalize/archive workflow are complete. `DOC-006` added the root operator guide.
|
||||||
|
|
||||||
|
## 8. Important code locations
|
||||||
|
|
||||||
|
- Models/migrations: `src/roborto_accounting/persistence/`, `alembic/versions/`
|
||||||
|
- Services: `src/roborto_accounting/services/`
|
||||||
|
- Reports/documents: `src/roborto_accounting/reporting/`
|
||||||
|
- CLI/runtime paths: `src/roborto_accounting/cli/`, `src/roborto_accounting/config.py`
|
||||||
|
- Tests/backlog/design: `tests/`, `docs/TASKS.md`, `docs/design/`
|
||||||
|
- Operator guide: `README.md`
|
||||||
|
|
||||||
|
## 9. Verified commands
|
||||||
|
|
||||||
|
- `.venv/bin/pytest -q` — 60 passed
|
||||||
|
- `.venv/bin/alembic -c <temporary-config> upgrade head` — fresh SQLite through 0028
|
||||||
|
- `.venv/bin/accounts --help`
|
||||||
|
- `.venv/bin/accounts document-samples --output <directory>`
|
||||||
|
- `git diff --check`
|
||||||
|
|
||||||
|
## 10. Environment variables by NAME ONLY
|
||||||
|
|
||||||
|
`HOME`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_STATE_HOME`.
|
||||||
|
|
||||||
|
## 11. Testing/quality status
|
||||||
|
|
||||||
|
60 isolated tests pass. Fresh migration through 0028 has no SQLite foreign-key
|
||||||
|
violations. Representative A4 invoice, quotation, Cash Flow, and P&L PDFs were
|
||||||
|
visually inspected; multi-page headers, wrapping, totals, footers, and page numbering
|
||||||
|
were checked.
|
||||||
|
|
||||||
|
## 12. Known risks/issues
|
||||||
|
|
||||||
|
Reference-image content is fictional and sample PDFs use visibly labelled
|
||||||
|
non-production data. The command interface is broad and tested,
|
||||||
|
but usability feedback from real bookkeeping use may justify separately approved
|
||||||
|
command refinements.
|
||||||
|
|
||||||
|
## 13. Open questions
|
||||||
|
|
||||||
|
None currently.
|
||||||
|
|
||||||
|
## 14. Recommended next task
|
||||||
|
|
||||||
|
No next approved task.
|
||||||
|
|
||||||
|
## 15. Instructions for the next conversation
|
||||||
|
|
||||||
|
Read `AGENTS.md` and all maintained context, inspect Git status/current source, and
|
||||||
|
confirm a newly approved task before changing behaviour. Preserve the XDG storage
|
||||||
|
policy and accounting safety invariants; run isolated tests and fresh migrations for
|
||||||
|
persistence changes.
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# roborto Accounting — Project Overview
|
||||||
|
|
||||||
|
## Purpose and users
|
||||||
|
|
||||||
|
roborto accounting is a local bookkeeping and accounting application for the
|
||||||
|
roborto sole-trader software-development business. Trading has not begun; the
|
||||||
|
official commencement date is configurable and initially unset. v1 starts clean.
|
||||||
|
Existing ODS files are archive/reference material and are not migrated.
|
||||||
|
|
||||||
|
## Workflows and scope
|
||||||
|
|
||||||
|
The approved v1 covers business settings, a customisable chart of accounts,
|
||||||
|
double-entry journals, clients, suppliers, lightweight projects/jobs, expenses,
|
||||||
|
capital/drawings, transfers, quotations, invoices/payments, credit notes/write-offs,
|
||||||
|
supplier bills/payments/refunds, billable time, rechargeable expenses, recurring
|
||||||
|
definitions, assets, VAT-ready and foreign-currency transactions, reconciliation,
|
||||||
|
period controls, attachments, audit history, backups, integrity checks, reports,
|
||||||
|
CSV/ODS exports, and generated invoice/quotation/report/business-letter PDF documents.
|
||||||
|
|
||||||
|
It is bookkeeping and tax-preparation support, not tax filing, Revenue submission,
|
||||||
|
authoritative tax advice, payroll, inventory, project management, email delivery, or
|
||||||
|
online banking. Purchase orders and separate estimates are excluded.
|
||||||
|
|
||||||
|
## Architecture and data flow
|
||||||
|
|
||||||
|
SQLite is authoritative. A reusable accounting/domain core is persisted through a
|
||||||
|
database layer, exposed through application services, and consumed by the CLI and
|
||||||
|
report/export components. Supporting documents use managed filesystem storage with
|
||||||
|
SQLite metadata/references. Future Flask API and React frontend work may consume the
|
||||||
|
same services, rules, and persistence layer; neither is v1 functionality.
|
||||||
|
|
||||||
|
Boundaries are: domain logic; persistence; application services; CLI; reporting/
|
||||||
|
exports/documents; and supporting-document storage. Accounting logic must not live
|
||||||
|
primarily in CLI commands, and formatted documents must not calculate authoritative
|
||||||
|
values.
|
||||||
|
|
||||||
|
## Technology and accounting model
|
||||||
|
|
||||||
|
Use Python, SQLite, SQLAlchemy, Alembic, and `Decimal`; never binary floating point
|
||||||
|
for money. SQLite stores signed integer micro-units (10^-6) behind a centralized
|
||||||
|
SQLAlchemy type. EUR is the base currency. Foreign transactions preserve original amount,
|
||||||
|
currency, applied rate, and EUR value. VAT fields exist from the beginning but VAT is
|
||||||
|
configurable. Classification and tax treatment are separate; uncertain treatment is
|
||||||
|
`REVIEW`.
|
||||||
|
|
||||||
|
Every posted journal balances. Issued documents preserve client/rate/line snapshots;
|
||||||
|
annual numbers (`INV-YYYY-NNN`, `Q-YYYY-NNN`, and `CN-YYYY-NNN`) are
|
||||||
|
never reused. Pre-trading dates remain actual and distinguishable. Cash flow uses
|
||||||
|
payment dates while incurred dates remain available for accrual views. Closed periods
|
||||||
|
reject ordinary edits; normal operations do not permanently delete history.
|
||||||
|
|
||||||
|
## CLI, persistence, and reporting
|
||||||
|
|
||||||
|
The CLI supports interactive and reliable non-interactive use through shared services;
|
||||||
|
missing required non-interactive values fail clearly. Alembic owns schema evolution;
|
||||||
|
development must not recreate databases to change schema. Reports include ledgers,
|
||||||
|
trial balance, P&L, Cash Flow, receivables/payables, assets, profitability, and tax
|
||||||
|
preparation/review views over arbitrary date ranges. CSV/ODS/PDF are outputs; SQLite
|
||||||
|
remains authoritative. Printable output uses the approved shared light-mode Roborto
|
||||||
|
A4 family in `docs/design/DOCUMENT_DESIGN.md`, with the invoice reference canonical.
|
||||||
|
Users send generated documents manually.
|
||||||
|
Business letters use a narrow persisted draft/finalize workflow with recipient and
|
||||||
|
content snapshots, explicit PDF finalization, and managed archive metadata; the
|
||||||
|
application does not send or automate correspondence.
|
||||||
|
|
||||||
|
Default runtime data is location-independent from the source checkout and follows XDG
|
||||||
|
user directories: configuration in `~/.config/roborto-accounting`, authoritative data,
|
||||||
|
documents, and backups in `~/.local/share/roborto-accounting`, and state in
|
||||||
|
`~/.local/state/roborto-accounting`. An optional env file belongs at
|
||||||
|
`~/.config/roborto-accounting/env`, never in the repository.
|
||||||
|
|
||||||
|
## Repository structure
|
||||||
|
|
||||||
|
- `src/roborto_accounting/`: package and separated layers
|
||||||
|
- `tests/`: isolated automated tests
|
||||||
|
- `alembic/`: migrations
|
||||||
|
- `docs/`: maintained context
|
||||||
|
- `AGENTS.md`: working instructions
|
||||||
|
|
||||||
|
## Permanent constraints
|
||||||
|
|
||||||
|
No silent destruction/history rewriting, number reuse, casual closed-period edits,
|
||||||
|
guessed tax treatment, ambiguous automatic bank matching, automatic recurring
|
||||||
|
transaction creation/issuance, secrets in settings/docs, or v1 web/authentication/
|
||||||
|
cloud/Revenue/email integrations.
|
||||||
@@ -0,0 +1,529 @@
|
|||||||
|
# Approved v1 Implementation Backlog
|
||||||
|
|
||||||
|
Statuses: `NOT STARTED`, `IN PROGRESS`, `BLOCKED`, `COMPLETE`. Normally only one
|
||||||
|
major task is `IN PROGRESS`.
|
||||||
|
|
||||||
|
## P0 Foundation
|
||||||
|
|
||||||
|
### FND-001 — Python package and test tooling skeleton
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Create an installable `src` package and isolated test entry point.
|
||||||
|
- Scope: package metadata, `src/roborto_accounting/`, `tests/`, smoke test only.
|
||||||
|
- Acceptance criteria: package imports; test command passes; layout leaves clear
|
||||||
|
domain/persistence/services/CLI/report boundaries.
|
||||||
|
- Relevant code: `pyproject.toml`, `src/roborto_accounting/`, `tests/`.
|
||||||
|
- Validation: `.venv/bin/python -m pytest -q` passes.
|
||||||
|
- Dependencies/blockers: none.
|
||||||
|
- Non-goals: schema, migrations, CLI commands, accounting logic, web code.
|
||||||
|
- Open questions: packaging details may be refined without changing boundaries.
|
||||||
|
|
||||||
|
### FND-002 — SQLAlchemy/SQLite persistence foundation
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Configure engine/session and persistence boundary.
|
||||||
|
- Scope: SQLite URL/config, session lifecycle, repository conventions, temp DB support.
|
||||||
|
- Acceptance criteria: service-facing persistence API opens SQLite without CLI imports.
|
||||||
|
- Relevant code: `persistence/`, tests.
|
||||||
|
- Validation: temporary SQLite integration/error tests.
|
||||||
|
- Dependencies: FND-001. Non-goals: schema, reports, web server. Open questions: none.
|
||||||
|
|
||||||
|
### FND-003 — Alembic and exact monetary representation
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Establish migrations and exact `Decimal` storage policy.
|
||||||
|
- Scope: Alembic environment, initial migration workflow, SQLite encoding/scale/rounding.
|
||||||
|
- Acceptance criteria: upgrade/downgrade works; monetary round-trip proves no floats.
|
||||||
|
- Relevant code: `alembic/`, persistence money type, tests.
|
||||||
|
- Validation: migration and arithmetic tests.
|
||||||
|
- Dependencies: FND-002. Non-goals: business tables. Open questions: exact encoding is proposed.
|
||||||
|
|
||||||
|
### FND-004 — Domain/application-service boundaries
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Define dependency direction and reusable service contracts.
|
||||||
|
- Scope: modules, errors/results, transaction boundary, no CLI dependency.
|
||||||
|
- Acceptance criteria: service can be called without CLI imports and boundary tests pass.
|
||||||
|
- Relevant code: `domain/`, `services/`, `persistence/`.
|
||||||
|
- Validation: import/service contract tests.
|
||||||
|
- Dependencies: FND-001, FND-002. Non-goals: workflows. Open questions: none.
|
||||||
|
|
||||||
|
### FND-005 — Business settings and chart of accounts
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Persist required settings and a safe customisable sole-trader chart.
|
||||||
|
- Scope: nullable commencement, EUR, defaults, VAT toggle/prefixes/paths, account classes,
|
||||||
|
add/rename/disable and protected posted accounts.
|
||||||
|
- Acceptance criteria: required asset/liability/equity/income/expense coverage is
|
||||||
|
seeded; settings defaults and account lifecycle constraints pass.
|
||||||
|
- Relevant code: settings/accounts domain and persistence.
|
||||||
|
- Validation: defaults and account lifecycle tests.
|
||||||
|
- Dependencies: FND-003, FND-004. Non-goals: tax conclusions, settings UI. Open questions: none.
|
||||||
|
|
||||||
|
### ACC-001 — Balanced journal/posting engine
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Provide balanced journal primitives and explicit audited manual journals.
|
||||||
|
- Scope: headers/lines, posting, account validation, Decimal totals, reason requirement.
|
||||||
|
- Acceptance criteria: every posted journal balances; invalid manual journals reject.
|
||||||
|
- Relevant code: accounting domain/persistence/services.
|
||||||
|
- Validation: balancing, invalid-post, exact arithmetic tests.
|
||||||
|
- Dependencies: FND-003, FND-005. Non-goals: higher workflows. Open questions: none.
|
||||||
|
|
||||||
|
### ACC-002 — Audit and accounting invariants
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Record meaningful changes and enforce non-destructive correction hooks.
|
||||||
|
- Scope: audit type/id/action/time/old/new/reason/source and invariant helpers.
|
||||||
|
- Acceptance criteria: audit metadata is persisted; posted history is not silently deleted.
|
||||||
|
- Relevant code: audit/journal services.
|
||||||
|
- Validation: audit/correction tests.
|
||||||
|
- Dependencies: ACC-001. Non-goals: identity system/period lock. Open questions: none.
|
||||||
|
|
||||||
|
## P1 Core records and workflows
|
||||||
|
|
||||||
|
### CORE-001 — Clients and issue-time snapshots
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Manage client contacts, VAT ID, terms, notes, and immutable snapshots.
|
||||||
|
- Scope: reusable client record and snapshot value/storage.
|
||||||
|
- Acceptance criteria: edits never alter issued document snapshots.
|
||||||
|
- Relevant code: client domain/persistence/services.
|
||||||
|
- Validation: validation and snapshot tests.
|
||||||
|
- Dependencies: FND-005, ACC-001. Non-goals: rendering. Open questions: none.
|
||||||
|
|
||||||
|
### CORE-002 — Suppliers and financial accounts
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Add supplier records and extensible owned payment accounts.
|
||||||
|
- Scope: supplier info, bank/cash/PayPal/card/personal funds, notes/tags.
|
||||||
|
- Acceptance criteria: later bills/expenses can link; transfers avoid income/expense.
|
||||||
|
- Relevant code: supplier/account domain.
|
||||||
|
- Validation: constraints/type tests.
|
||||||
|
- Dependencies: FND-005, ACC-001. Non-goals: online banking. Open questions: none.
|
||||||
|
|
||||||
|
### CORE-003 — Projects and billing-rate hierarchy
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Link lightweight client jobs and resolve business→client→project→entry rates.
|
||||||
|
- Scope: project links and captured rate overrides.
|
||||||
|
- Acceptance criteria: precedence works; historical captured rates are stable.
|
||||||
|
- Relevant code: project/rate services.
|
||||||
|
- Validation: precedence/history tests.
|
||||||
|
- Dependencies: CORE-001, FND-005. Non-goals: project management. Open questions: none.
|
||||||
|
|
||||||
|
### CORE-004 — Expenses, funding, transfers, and mixed use
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Record expenses, capital, drawings, transfers, personal funding, and proportions.
|
||||||
|
- Scope: immediate-paid expenses, non-wage drawings, business-use percentage/basis/notes.
|
||||||
|
- Acceptance criteria: transfers are not income/expense; full actual and business portion preserved;
|
||||||
|
supplied percentages only.
|
||||||
|
- Relevant code: expense/funding services and journal mappings.
|
||||||
|
- Validation: balanced workflow and mixed-use tests.
|
||||||
|
- Dependencies: ACC-001, CORE-002, FND-005. Non-goals: supplier bills/tax advice. Open questions: none.
|
||||||
|
|
||||||
|
### CORE-005 — Pre-trading expenditure
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Distinguish pre-commencement transactions without changing actual dates.
|
||||||
|
- Scope: comparison, flags/queries, review classification.
|
||||||
|
- Acceptance criteria: unset/date boundaries work; no deductibility claim.
|
||||||
|
- Relevant code: transaction/report queries.
|
||||||
|
- Validation: boundary/report tests.
|
||||||
|
- Dependencies: FND-005, CORE-004. Non-goals: tax engine. Open questions: none.
|
||||||
|
|
||||||
|
### CORE-006 — Managed document archive and attachments
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Copy files to managed collision-safe storage with SQLite references.
|
||||||
|
- Scope: categories, original filename, links, configured paths.
|
||||||
|
- Acceptance criteria: copies survive source path changes; collisions safe; missing files detectable.
|
||||||
|
- Relevant code: `documents/`, persistence/services.
|
||||||
|
- Validation: temp filesystem/collision/metadata tests.
|
||||||
|
- Dependencies: FND-002, FND-005. Non-goals: large SQLite blobs/OCR. Open questions: none.
|
||||||
|
|
||||||
|
### CORE-007 — Notes, tags, and audit integration
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Add organisation metadata that cannot affect calculations.
|
||||||
|
- Scope: notes/tags and shared audit hooks.
|
||||||
|
- Acceptance criteria: tags are calculation-neutral and relevant changes auditable.
|
||||||
|
- Relevant code: shared domain/persistence.
|
||||||
|
- Validation: isolation/audit tests.
|
||||||
|
- Dependencies: ACC-002, CORE-001, CORE-002. Non-goals: search platform. Open questions: none.
|
||||||
|
|
||||||
|
## P1 Sales and purchasing
|
||||||
|
|
||||||
|
### SALE-001 — Quotations, lines, numbering, lifecycle
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Structured `Q-YYYY-NNN` quotations with no number reuse.
|
||||||
|
- Scope: draft/issued/accepted, lines, VAT, totals, client snapshot.
|
||||||
|
- Acceptance criteria: annual counters restart; numbers never reuse; exact totals.
|
||||||
|
- Relevant code: sales domain/services.
|
||||||
|
- Validation: numbering/totals/snapshot/state tests.
|
||||||
|
- Dependencies: CORE-001, FND-003, ACC-001. Non-goals: estimates. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-002 — Invoices, lines, terms, numbering, snapshots
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Structured `INV-YYYY-NNN` invoices with stable issue history.
|
||||||
|
- Scope: lifecycle, terms hierarchy, due/overdue derivation, VAT/totals, snapshots.
|
||||||
|
- Acceptance criteria: annual non-reused numbering; issued content cannot silently rewrite.
|
||||||
|
- Relevant code: sales domain/services.
|
||||||
|
- Validation: totals/terms/lifecycle/number/snapshot tests.
|
||||||
|
- Dependencies: CORE-001, CORE-003, SALE-001, ACC-001. Non-goals: email. Open questions: none.
|
||||||
|
|
||||||
|
### ACC-003 — Invoice issue accounting postings
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Post receivables, revenue, and VAT consequences when an invoice is issued.
|
||||||
|
- Scope: durable revenue-account mapping, invoice issue journal linkage, net/VAT/gross
|
||||||
|
postings, quotation conversion carry-over, credits, and issued-history stability.
|
||||||
|
- Acceptance criteria: issue creates one balanced journal (AR debit; income and VAT
|
||||||
|
credits as applicable); payments settle the resulting receivable; reports reflect
|
||||||
|
invoiced revenue; mappings remain stable after issue.
|
||||||
|
- Relevant code: invoice/quotation line models, sales services, migrations, reports.
|
||||||
|
- Validation: multi-line revenue classification, VAT/no-VAT, conversion, payment,
|
||||||
|
credit, snapshot, and migration tests.
|
||||||
|
- Dependencies: ACC-001, SALE-001, SALE-002. Non-goals: automated tax advice.
|
||||||
|
- Open questions: none; per-line mapping with an optional configured draft default was approved.
|
||||||
|
|
||||||
|
### ACC-004 — Audited manual journal workflow
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Expose the explicitly invoked advanced manual-journal workflow.
|
||||||
|
- Scope: separate service/CLI command, balanced Decimal lines, description and reason,
|
||||||
|
period locking, audit source and metadata.
|
||||||
|
- Acceptance criteria: balanced entries post; missing reason/unbalanced entries reject;
|
||||||
|
ordinary workflows remain distinct.
|
||||||
|
- Relevant code: journal/audit services and CLI.
|
||||||
|
- Validation: service and migrated-database CLI tests.
|
||||||
|
- Dependencies: ACC-001, ACC-002, CLI-003. Non-goals: casual ledger editing.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### SALE-003 — Quotation-to-invoice conversion
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Convert accepted quotations while preserving independent invoice history.
|
||||||
|
- Scope: conversion/linkage/carry-over.
|
||||||
|
- Acceptance criteria: only accepted quotes convert; invoice is stable.
|
||||||
|
- Relevant code: sales services.
|
||||||
|
- Validation: conversion/duplicate tests.
|
||||||
|
- Dependencies: SALE-001, SALE-002. Non-goals: automatic issue. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-004 — Invoice payments and receivables
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Support full/partial/multiple payment events and balances.
|
||||||
|
- Scope: allocations, lifecycle, actual payment dates.
|
||||||
|
- Acceptance criteria: exact balances; cash flow uses payment date.
|
||||||
|
- Relevant code: payments/sales services.
|
||||||
|
- Validation: payment consistency tests.
|
||||||
|
- Dependencies: SALE-002, CORE-002, ACC-001. Non-goals: matching. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-005 — Credit notes and bad debts
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Reduce/write off receivables without editing issued invoices.
|
||||||
|
- Scope: annual credit-note numbering/prefix, allocations, explicit write-off journal/reason.
|
||||||
|
- Acceptance criteria: original remains; no automatic write-off; balances/audit correct.
|
||||||
|
- Relevant code: sales/accounting services.
|
||||||
|
- Validation: credit/write-off/balance/audit tests.
|
||||||
|
- Dependencies: SALE-002, SALE-004, ACC-002. Non-goals: collections. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-006 — Supplier bills, payments, refunds, immediate purchases
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Support payables and convenient immediately-paid expenses.
|
||||||
|
- Scope: outstanding/partial/full bills, linked refunds, immediate path.
|
||||||
|
- Acceptance criteria: refunds do not rewrite original expense; journals balance.
|
||||||
|
- Relevant code: purchasing/payables services.
|
||||||
|
- Validation: bill/payment/refund tests.
|
||||||
|
- Dependencies: CORE-002, CORE-004, ACC-001. Non-goals: purchase orders. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-007 — Billable time and invoice selection
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Record and select eligible uninvoiced billable time.
|
||||||
|
- Scope: client/project/date/hours/description/rate/billable/invoiced.
|
||||||
|
- Acceptance criteria: only eligible entries selected; captured rates stable.
|
||||||
|
- Relevant code: time/billing services.
|
||||||
|
- Validation: eligibility/state/rate tests.
|
||||||
|
- Dependencies: CORE-001, CORE-003, SALE-002. Non-goals: monitoring. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-008 — Rechargeable expenses
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Discover linked uninvoiced rechargeable expenses during invoice creation.
|
||||||
|
- Scope: client/project links, flags, invoiced state.
|
||||||
|
- Acceptance criteria: eligible items discoverable and never double-invoiced.
|
||||||
|
- Relevant code: expense/sales services.
|
||||||
|
- Validation: selection/state tests.
|
||||||
|
- Dependencies: CORE-004, SALE-002. Non-goals: automatic charging. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-009 — Recurring invoice definitions
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Identify due definitions and prepare drafts only.
|
||||||
|
- Scope: recurrence, due detection, draft preparation, explicit approval.
|
||||||
|
- Acceptance criteria: no automatic issuance/posting.
|
||||||
|
- Relevant code: sales services.
|
||||||
|
- Validation: due/draft/no-issue tests.
|
||||||
|
- Dependencies: SALE-002. Non-goals: email. Open questions: none.
|
||||||
|
|
||||||
|
### SALE-010 — Recurring expense definitions
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Identify expected expenses without creating transactions.
|
||||||
|
- Scope: supplier/frequency/category/amount/reconciliation hints.
|
||||||
|
- Acceptance criteria: advisory detection never posts.
|
||||||
|
- Relevant code: purchasing/services.
|
||||||
|
- Validation: detection/no-create tests.
|
||||||
|
- Dependencies: CORE-002, CORE-004. Non-goals: auto-generation. Open questions: none.
|
||||||
|
|
||||||
|
## P1/P0 Controls
|
||||||
|
|
||||||
|
### CTRL-001 — Bank CSV import boundary
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Import bank rows through extensible parsers without posting silently.
|
||||||
|
- Scope: adapters, provenance, duplicate detection.
|
||||||
|
- Acceptance criteria: imported rows remain pending accounting action.
|
||||||
|
- Relevant code: `reconciliation/`, import services.
|
||||||
|
- Validation: parser/error/duplicate tests.
|
||||||
|
- Dependencies: FND-004, CORE-002. Non-goals: online banking. Open questions: bank mappings.
|
||||||
|
|
||||||
|
### CTRL-002 — Assisted matching and manual reconciliation
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Propose matches, require approval for ambiguity, separate reconciliation state.
|
||||||
|
- Scope: candidates, approval, rejection, manual workflow.
|
||||||
|
- Acceptance criteria: ambiguous matches never silently reconcile.
|
||||||
|
- Relevant code: reconciliation services/persistence.
|
||||||
|
- Validation: matching/approval/state tests.
|
||||||
|
- Dependencies: CTRL-001, ACC-001, SALE-004, SALE-006. Non-goals: direct bank links. Open questions: none.
|
||||||
|
|
||||||
|
### CTRL-003 — Multi-currency support
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Preserve original currency, applied rate, and EUR value.
|
||||||
|
- Scope: supported transaction fields/reports.
|
||||||
|
- Acceptance criteria: historical values never use current rates.
|
||||||
|
- Relevant code: money/currency domain.
|
||||||
|
- Validation: conversion/history tests.
|
||||||
|
- Dependencies: FND-003, ACC-001. Non-goals: live rate provider. Open questions: none.
|
||||||
|
|
||||||
|
### CTRL-004 — VAT-ready amounts and tax classification
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Store net/rate/VAT/gross/treatment and separate preparation classifications.
|
||||||
|
- Scope: enablement, treatment, ALLOWABLE/NON_ALLOWABLE/PARTIALLY_ALLOWABLE/CAPITAL/
|
||||||
|
PRE_TRADING/REVIEW.
|
||||||
|
- Acceptance criteria: disabled VAT works; uncertain treatment is REVIEW, never guessed.
|
||||||
|
- Relevant code: tax/money domain.
|
||||||
|
- Validation: VAT/classification tests.
|
||||||
|
- Dependencies: FND-003, FND-005, ACC-001, CORE-005. Non-goals: filing/advice. Open questions: none.
|
||||||
|
|
||||||
|
### CTRL-005 — Asset register
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Preserve asset and disposal data for later preparation.
|
||||||
|
- Scope: purchase/supplier/cost/currency/EUR/use/document/disposal/notes/treatment.
|
||||||
|
- Acceptance criteria: lifecycle/history complete; no automatic Irish capital allowances.
|
||||||
|
- Relevant code: asset domain/persistence.
|
||||||
|
- Validation: lifecycle/currency/document tests.
|
||||||
|
- Dependencies: CORE-002, CORE-006, CTRL-003. Non-goals: allowance engine. Open questions: none.
|
||||||
|
|
||||||
|
### CTRL-006 — Period close/reopen and safe backups
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Lock periods and provide SQLite-safe local timestamped backups.
|
||||||
|
- Scope: close/reopen audit, backup service/command, close-before-backup.
|
||||||
|
- Acceptance criteria: closed edits reject; reopen explicit/audited; backup collision-safe.
|
||||||
|
- Relevant code: periods/backup services and CLI.
|
||||||
|
- Validation: lock/reopen/backup/restore-read tests.
|
||||||
|
- Dependencies: FND-002, ACC-002. Non-goals: cloud backup. Open questions: none.
|
||||||
|
|
||||||
|
### CTRL-007 — Integrity checking
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Report SQLite/accounting/document invariants without mutation.
|
||||||
|
- Scope: balances, totals, payments, transfers, attachments, orphans, closed periods.
|
||||||
|
- Acceptance criteria: check reports seeded failures and never silently repairs.
|
||||||
|
- Relevant code: integrity services/CLI.
|
||||||
|
- Validation: valid/invalid fixture tests.
|
||||||
|
- Dependencies: ACC-001, ACC-002, CORE-006, SALE-004, CTRL-006. Non-goals: repair. Open questions: none.
|
||||||
|
|
||||||
|
## CLI and reporting
|
||||||
|
|
||||||
|
### CLI-001 — Shared interactive/non-interactive CLI foundation
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Dispatch commands through services with clear non-interactive failures.
|
||||||
|
- Scope: parsing, configuration paths, service wiring, mode handling.
|
||||||
|
- Acceptance criteria: both modes call shared services; missing values never unexpectedly prompt.
|
||||||
|
- Relevant code: `cli/`, package entry point.
|
||||||
|
- Validation: parsing/mode/error tests.
|
||||||
|
- Dependencies: FND-004, FND-005. Non-goals: all commands. Open questions: framework.
|
||||||
|
|
||||||
|
### CLI-002 — Database initialization and administration commands
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Make a new location-independent installation safely operable.
|
||||||
|
- Scope: migration-based initialization/upgrade, settings inspection/update, chart
|
||||||
|
inspection/maintenance, backup, and integrity entry points using XDG defaults.
|
||||||
|
- Acceptance criteria: a clean database can be initialized outside the checkout;
|
||||||
|
commands use services/migrations; non-interactive omissions fail clearly; secrets
|
||||||
|
are not written to project files.
|
||||||
|
- Relevant code: `cli/`, runtime configuration, packaged migrations.
|
||||||
|
- Validation: temporary XDG home command tests and installed-entry-point smoke tests.
|
||||||
|
- Dependencies: CLI-001, FND-005, CTRL-006, CTRL-007. Non-goals: transaction entry.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### CLI-003 — Core bookkeeping command surface
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Expose approved daily bookkeeping workflows through shared services.
|
||||||
|
- Scope: clients, suppliers, projects, financial accounts, expenses, transfers,
|
||||||
|
capital, drawings, personally paid and mixed-use expenses, attachments, tags.
|
||||||
|
- Acceptance criteria: interactive and non-interactive paths call the same services;
|
||||||
|
required missing non-interactive values fail; no destructive history commands.
|
||||||
|
- Relevant code: `cli/`, core services.
|
||||||
|
- Validation: command integration tests against temporary migrated databases.
|
||||||
|
- Dependencies: CLI-002, CORE-001 through CORE-007. Non-goals: sales/payables commands.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### CLI-004 — Sales and purchasing command surface
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Expose approved quotation, invoice, receipt, credit, bill, time, recharge,
|
||||||
|
and recurring-definition workflows.
|
||||||
|
- Scope: lifecycle commands and document generation without email delivery.
|
||||||
|
- Acceptance criteria: issued history/numbers remain stable; approval boundaries are
|
||||||
|
explicit; partial payments and outstanding balances are visible.
|
||||||
|
- Relevant code: `cli/`, sales/payables/document services.
|
||||||
|
- Validation: end-to-end CLI workflow tests on temporary databases.
|
||||||
|
- Dependencies: CLI-003, SALE-001 through SALE-010, DOC-003. Non-goals: email.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### CLI-005 — Controls, reporting, and export command surface
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Expose bank import/reconciliation, periods, assets, reports, and exports.
|
||||||
|
- Scope: explicit match approval, close/reopen, reports by range, CSV/ODS/PDF outputs.
|
||||||
|
- Acceptance criteria: controls preserve approval/non-mutation invariants; report
|
||||||
|
values come from reporting services; non-interactive operation is reliable.
|
||||||
|
- Relevant code: `cli/`, control/report/export services.
|
||||||
|
- Validation: command integration and representative output tests.
|
||||||
|
- Dependencies: CLI-004, CTRL-001 through CTRL-007, RPT-001 through RPT-004, DOC-004.
|
||||||
|
- Non-goals: online banking, tax filing, dashboard UI. Open questions: none.
|
||||||
|
|
||||||
|
### CLI-006 — Complete typed business-setting administration
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Make every approved non-secret business setting safely configurable.
|
||||||
|
- Scope: dates, Decimal rates, integer terms, booleans, prefixes/paths/contact/payment
|
||||||
|
fields and account defaults with validation.
|
||||||
|
- Acceptance criteria: typed values round-trip; invalid values fail; secrets remain
|
||||||
|
outside SQLite settings and repository files.
|
||||||
|
- Relevant code: settings service and CLI.
|
||||||
|
- Validation: migrated-database command tests.
|
||||||
|
- Dependencies: CLI-002, FND-005, DOC-001. Non-goals: secret management UI.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### SALE-011 — Invoice void and reversal workflow
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Void an eligible issued invoice without deleting or rewriting history.
|
||||||
|
- Scope: explicit reason/date, reversal journal, audit, lifecycle restrictions and
|
||||||
|
immutable issued lines.
|
||||||
|
- Acceptance criteria: original issue journal remains; balanced reversal is linked;
|
||||||
|
paid/credited/written-off invoices cannot be casually voided; status becomes VOID.
|
||||||
|
- Relevant code: invoice models/services/migration/CLI.
|
||||||
|
- Validation: reversal, audit, lifecycle, period-lock and CLI tests.
|
||||||
|
- Dependencies: ACC-003, ACC-002, CTRL-006. Non-goals: deleting invoices.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### CTRL-008 — Complete integrity invariant coverage
|
||||||
|
- Priority: P0; Status: COMPLETE
|
||||||
|
- Objective: Cover all explicitly required read-only integrity checks.
|
||||||
|
- Scope: quotation totals, invoice issue linkage, payment applications, transfers,
|
||||||
|
attachments, orphan/FK state, accounting periods and reversal consistency.
|
||||||
|
- Acceptance criteria: seeded corrupt fixtures are reported with stable codes and no
|
||||||
|
accounting data is mutated.
|
||||||
|
- Relevant code: integrity service/CLI tests.
|
||||||
|
- Validation: one valid and targeted invalid fixture per invariant family.
|
||||||
|
- Dependencies: CTRL-007, ACC-003, SALE-011. Non-goals: automatic repair.
|
||||||
|
- Open questions: none.
|
||||||
|
|
||||||
|
### RPT-001 — Ledgers and trial balance
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Report transaction/general ledgers and trial balance for arbitrary ranges.
|
||||||
|
- Scope: account/date filters, calendar-year support, authoritative values.
|
||||||
|
- Acceptance criteria: trial balance debit equals credit.
|
||||||
|
- Relevant code: reporting queries/services.
|
||||||
|
- Validation: fixture/date tests.
|
||||||
|
- Dependencies: ACC-001, CLI-001. Non-goals: PDF styling. Open questions: none.
|
||||||
|
|
||||||
|
### RPT-002 — P&L, Cash Flow, receivables, payables
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Provide operational reports with cash/accrual distinctions.
|
||||||
|
- Scope: P&L, payment-date Cash Flow, outstanding invoices/bills.
|
||||||
|
- Acceptance criteria: cash uses actual payment dates; incurred dates remain available.
|
||||||
|
- Relevant code: reporting services.
|
||||||
|
- Validation: cash/accrual/outstanding fixtures.
|
||||||
|
- Dependencies: SALE-004, SALE-006, RPT-001. Non-goals: filing. Open questions: none.
|
||||||
|
|
||||||
|
### RPT-003 — Asset, profitability, tax-preparation/review reports
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Produce structured preparation information and review queues.
|
||||||
|
- Scope: assets, client/project profitability, classifications, pre-trading, REVIEW.
|
||||||
|
- Acceptance criteria: uncertain treatment is not presented as advice.
|
||||||
|
- Relevant code: reporting services.
|
||||||
|
- Validation: classification/profitability fixtures.
|
||||||
|
- Dependencies: CORE-003, CORE-005, CTRL-004, CTRL-005. Non-goals: tax engine. Open questions: none.
|
||||||
|
|
||||||
|
### RPT-004 — CSV and ODS exports
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Export reports while SQLite remains authoritative.
|
||||||
|
- Scope: writers, field mappings, output paths.
|
||||||
|
- Acceptance criteria: exports reproduce report values and are not persistence inputs.
|
||||||
|
- Relevant code: `reporting/exports/`.
|
||||||
|
- Validation: fixture/content tests.
|
||||||
|
- Dependencies: RPT-001, RPT-002. Non-goals: ODS migration. Open questions: none.
|
||||||
|
|
||||||
|
### DOC-001 — Document contact and payment configuration
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Make all business identity, correspondence, and payment details used by generated documents configuration/data-driven.
|
||||||
|
- Scope: display/trading name, descriptor, website, general email, accounts email (default `accounts@roborto.net`), phone, postal address/location, applicable tax/VAT identifiers, and bank/payment instructions.
|
||||||
|
- Acceptance criteria: templates require structured configuration and contain no fictional reference-image data; invoices use the accounts address while quotations use the general address unless explicitly configured otherwise.
|
||||||
|
- Relevant code: business settings model/migration/services and tests.
|
||||||
|
- Validation: defaults, override, missing-data, and no-hard-coded-sample tests.
|
||||||
|
- Dependencies: FND-005. Non-goals: secrets, email sending, document rendering. Open questions: optional-detail omission policy.
|
||||||
|
|
||||||
|
### DOC-002 — Shared A4 print/PDF theme and rendering foundation
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Implement the approved reusable light-mode Roborto document identity.
|
||||||
|
- Scope: rendering-library selection, deterministic A4 output, margins, typography, `logo-light.svg`, colour tokens, headings, tables, totals, footer/page numbering, wrapping and page breaks.
|
||||||
|
- Acceptance criteria: one UI-independent theme serves every renderer; output is print-safe, greyscale-legible, deterministic, and contains no accounting logic.
|
||||||
|
- Relevant code: future `reporting/documents/`, `assets/branding/`, `docs/design/`.
|
||||||
|
- Validation: unit/layout tests plus generated representative multi-page PDF inspection.
|
||||||
|
- Dependencies: DOC-001. Non-goals: per-document themes, dashboards, gradients, shadows, proprietary fonts, Flask/React. Open questions: rendering library.
|
||||||
|
|
||||||
|
### DOC-003 — Branded invoice and quotation documents
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Render issued invoices and quotations using the canonical document family.
|
||||||
|
- Scope: numbers/dates/terms, snapshots, project/reference, lines, totals/VAT, notes, configured correspondence/payment details, and stored output metadata.
|
||||||
|
- Acceptance criteria: invoice-reference hierarchy is followed; quotation is a family adaptation; values come only from persisted snapshots/core calculations; no email.
|
||||||
|
- Relevant code: sales document renderers and managed-document metadata.
|
||||||
|
- Validation: content/snapshot, long-line and multi-page tests; generated PDF visual inspection.
|
||||||
|
- Dependencies: SALE-001, SALE-002, DOC-002. Non-goals: email, fictional data, template calculations. Open questions: none.
|
||||||
|
|
||||||
|
### DOC-004 — Branded accounting-report documents
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Apply the theme to Cash Flow, P&L, ledgers, trial balance, and approved professional reports.
|
||||||
|
- Scope: report headings/period metadata, restrained tables, repeated headers, totals, page numbers, configured header/footer.
|
||||||
|
- Acceptance criteria: report services supply values; Cash Flow/P&L use the approved family without dashboard UI; long reports paginate safely.
|
||||||
|
- Relevant code: reporting document renderers.
|
||||||
|
- Validation: value-regression tests and representative single/multi-page PDF inspection.
|
||||||
|
- Dependencies: DOC-002, RPT-001, RPT-002. Non-goals: charts/dashboards or calculations in templates. Open questions: none.
|
||||||
|
|
||||||
|
### DOC-005 — Visual-regression and sample-generation workflow
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Make representative document rendering repeatable and reviewable.
|
||||||
|
- Scope: deterministic fixtures/commands, PDF generation, comparison artifacts, clipping/overflow/footer/table checks.
|
||||||
|
- Acceptance criteria: documented commands generate invoice, quotation, Cash Flow, and P&L samples; output is inspected before parity is claimed.
|
||||||
|
- Relevant code: document test fixtures/scripts.
|
||||||
|
- Validation: commands succeed and representative pages are visually reviewed.
|
||||||
|
- Dependencies: DOC-003, DOC-004. Non-goals: production sample data or email. Open questions: visual-diff tolerance.
|
||||||
|
|
||||||
|
### DOC-FUTURE-001 — Apply theme to letters after workflow approval
|
||||||
|
- Priority: P2; Status: COMPLETE
|
||||||
|
- Objective: Reuse the shared theme for a future approved business-letter renderer.
|
||||||
|
- Scope: persisted draft with recipient snapshot, date, optional reference, subject and
|
||||||
|
body; explicit finalization to branded PDF and managed archive metadata.
|
||||||
|
- Acceptance criteria: finalized content is stable, uses configured general contact
|
||||||
|
details and shared theme, works outside the checkout, and never sends email.
|
||||||
|
- Relevant code: letter persistence/service/renderer/CLI.
|
||||||
|
- Validation: lifecycle, archive, deterministic multi-page PDF and visual inspection.
|
||||||
|
- Dependencies: DOC-001, DOC-002, CORE-006. Non-goals: email, mail merge, campaigns,
|
||||||
|
delivery tracking or correspondence automation. Open questions: none.
|
||||||
|
|
||||||
|
### DOC-006 — Operator setup and CLI guide
|
||||||
|
- Priority: P1; Status: COMPLETE
|
||||||
|
- Objective: Document installation, location-independent runtime storage, initialization,
|
||||||
|
safe command usage, line formats, reports/exports, backups, and recovery boundaries.
|
||||||
|
- Scope: concise root README and verified examples using implemented commands only.
|
||||||
|
- Acceptance criteria: a new operator can install, initialize, locate data, configure
|
||||||
|
the business, perform representative workflows, run checks/backups, and discover help.
|
||||||
|
- Relevant code: `README.md`, CLI parser, runtime configuration.
|
||||||
|
- Validation: commands/help and documented paths checked against source/tests.
|
||||||
|
- Dependencies: CLI-006, DOC-FUTURE-001. Non-goals: deployment automation or invented
|
||||||
|
workflows. Open questions: none.
|
||||||
|
|
||||||
|
## Backlog review
|
||||||
|
|
||||||
|
The approved specification is represented by tasks, acceptance criteria, decisions, or
|
||||||
|
permanent constraints above. Excluded features are explicit non-goals, not active work.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Roborto Print Document Design
|
||||||
|
|
||||||
|
Status: **Approved visual direction**
|
||||||
|
|
||||||
|
This is the normative specification for printable/PDF Roborto business documents.
|
||||||
|
Reference PNGs in `docs/design/references/` communicate visual intent; the invoice
|
||||||
|
reference is canonical. Sample names, addresses, rates, tax figures, and bank details
|
||||||
|
in those images are fictional and must never become production data.
|
||||||
|
|
||||||
|
## Scope and shared identity
|
||||||
|
|
||||||
|
Use one reusable theme for invoices, quotations, business letters, cash-flow and
|
||||||
|
Profit & Loss statements, transaction/accounting/year-end reports, and other
|
||||||
|
professional A4 output. Do not independently style each renderer.
|
||||||
|
|
||||||
|
- A4 portrait by default, white/light background, generous margins and whitespace.
|
||||||
|
- Use `assets/branding/logo-light.svg`; never put the dark logo panel on light pages.
|
||||||
|
- Roborto green `#7ee787`; Roborto dark `#0b0f14`; dark body text and light rules.
|
||||||
|
- Clean, non-proprietary sans-serif typography; monospace only sparingly.
|
||||||
|
- Strong dark titles with a short thin green accent, not full-width colour banners.
|
||||||
|
- Restrained tables with right-aligned explicit currency values and green emphasis
|
||||||
|
for important totals.
|
||||||
|
- Thin green footer rule and `roborto — Software Development`; page numbers on
|
||||||
|
multi-page reports where useful.
|
||||||
|
- Outputs must remain legible in greyscale and economical to print.
|
||||||
|
|
||||||
|
The shared rendering layer owns page size/margins, logo, colour and typography
|
||||||
|
tokens, headings, section labels, tables, totals, footer, and page numbering.
|
||||||
|
|
||||||
|
## Document-specific rules
|
||||||
|
|
||||||
|
Invoices include applicable number/date/due terms, bill-to snapshot, project/reference,
|
||||||
|
structured lines, subtotal, VAT/tax when applicable, total due, payment instructions,
|
||||||
|
and notes. Financial correspondence uses `accounts@roborto.net` unless configured
|
||||||
|
otherwise.
|
||||||
|
|
||||||
|
Quotations use the same family but the configured general/client-facing email.
|
||||||
|
Letters share the header/type/spacing/accent/footer and use the general email; no
|
||||||
|
letter-generation workflow is implied by this design specification.
|
||||||
|
|
||||||
|
Accounting reports share the invoice family. Do not add dashboard cards, charts,
|
||||||
|
gradients, shadows, illustrations, or app-style UI without explicit approval.
|
||||||
|
|
||||||
|
## Configuration and correctness
|
||||||
|
|
||||||
|
Trading/display name, descriptor, website, general email, accounts email, telephone,
|
||||||
|
postal address/location, tax/VAT identifiers, and bank/payment details are
|
||||||
|
configuration/data-driven. Do not hard-code fictional reference content.
|
||||||
|
|
||||||
|
Accounting values come from the accounting core/database. Formatting cannot perform
|
||||||
|
authoritative accounting calculations. Preserve deterministic output, correct
|
||||||
|
wrapping/alignment, repeated table headings where useful, page breaks, totals, and
|
||||||
|
footer placement. Test at A4 size for clipping, overflow, and orphaned totals.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Roborto Document Design Handoff
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
The approved direction is the minimalist light-mode Roborto A4 document family. The
|
||||||
|
invoice reference is canonical; quotation, letter, Cash Flow, and Profit & Loss
|
||||||
|
references show adaptations of the same family.
|
||||||
|
|
||||||
|
## Source-of-truth order
|
||||||
|
|
||||||
|
1. Current explicit user instruction.
|
||||||
|
2. `docs/design/DOCUMENT_DESIGN.md`.
|
||||||
|
3. `docs/design/references/invoice-reference.png`.
|
||||||
|
4. Other matching reference images.
|
||||||
|
5. Existing rendering implementation.
|
||||||
|
|
||||||
|
Reference-image content is fictional and may contain image-generation artefacts.
|
||||||
|
Never infer business data or reproduce text errors from it.
|
||||||
|
|
||||||
|
## Assets and references
|
||||||
|
|
||||||
|
- `assets/branding/logo-light.svg`: required light-document logo.
|
||||||
|
- `assets/branding/logo-dark.svg`: retained dark-mode asset, not for white A4 pages.
|
||||||
|
- `docs/design/references/invoice-reference.png`: canonical visual direction.
|
||||||
|
- Other PNGs: quotation, letter, Cash Flow, and Profit & Loss adaptations.
|
||||||
|
|
||||||
|
The print/PDF theme remains independent of CLI and future web UI layers. Any future
|
||||||
|
visual change should update the normative specification and canonical reference.
|
||||||
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1,28 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=68"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "roborto-accounting"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Local accounting application for roborto"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
dependencies = [
|
||||||
|
"alembic>=1.13",
|
||||||
|
"SQLAlchemy>=2.0",
|
||||||
|
"reportlab>=5.0",
|
||||||
|
"svglib>=2.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
test = ["pytest>=8.0"]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
accounts = "roborto_accounting.cli.main:main"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
addopts = "-ra"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
"""Core package for the roborto accounting application."""
|
||||||
|
|
||||||
|
__all__ = ["__version__"]
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Command-line interface adapters."""
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
"""Accounting controls, reporting, and export CLI adapter."""
|
||||||
|
from dataclasses import asdict
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import inspect,select
|
||||||
|
|
||||||
|
from roborto_accounting.persistence.models import AccountingPeriod,AssetRecord,BusinessSettings,ImportedBankTransaction,ReconciliationMatch
|
||||||
|
from roborto_accounting.reporting.documents.financial import render_cash_flow_pdf,render_profit_and_loss_pdf,render_transaction_ledger_pdf,render_trial_balance_pdf
|
||||||
|
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||||
|
from roborto_accounting.reporting.exports import export_csv,export_ods
|
||||||
|
from roborto_accounting.reporting.financial import cash_flow,outstanding_invoices,outstanding_supplier_bills,profit_and_loss_summary
|
||||||
|
from roborto_accounting.reporting.ledgers import transaction_ledger,trial_balance_summary
|
||||||
|
from roborto_accounting.reporting.preparation import asset_register,client_project_profitability,items_requiring_tax_review,tax_preparation_details
|
||||||
|
from roborto_accounting.services.assets import dispose_asset,record_asset
|
||||||
|
from roborto_accounting.services.bank_import import CsvMapping,MappedCsvParser,import_bank_csv
|
||||||
|
from roborto_accounting.services.currency import capture_currency_value
|
||||||
|
from roborto_accounting.services.periods import close_period,reopen_period
|
||||||
|
from roborto_accounting.services.reconciliation import approve_match,manually_reconcile,propose_match,reject_match
|
||||||
|
from roborto_accounting.services.tax import TaxClassification,record_tax_detail
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.config import default_logo_path
|
||||||
|
|
||||||
|
COMMANDS={"bank-import","bank-list","match-propose","match-approve","match-reject","reconcile-manual","currency-capture","tax-detail-add","asset-add","asset-dispose","asset-list","period-close","period-reopen","report"}
|
||||||
|
|
||||||
|
def register(sub)->None:
|
||||||
|
bank=sub.add_parser("bank-import");bank.add_argument("path",type=Path);bank.add_argument("--financial-account",required=True);bank.add_argument("--date-column",required=True);bank.add_argument("--description-column",required=True);bank.add_argument("--amount-column",required=True);bank.add_argument("--date-format",default="%Y-%m-%d");bank.add_argument("--currency-column");bank.add_argument("--currency",default="EUR");bank.add_argument("--format-name",default="mapped-csv")
|
||||||
|
sub.add_parser("bank-list")
|
||||||
|
proposed=sub.add_parser("match-propose");proposed.add_argument("import_id",type=int);proposed.add_argument("record_type");proposed.add_argument("record_id");proposed.add_argument("--score",type=int,required=True);proposed.add_argument("--reason")
|
||||||
|
for name in ("match-approve","match-reject"):
|
||||||
|
p=sub.add_parser(name);p.add_argument("id",type=int);p.add_argument("--reason",required=name=="match-reject")
|
||||||
|
manual=sub.add_parser("reconcile-manual");manual.add_argument("import_id",type=int);manual.add_argument("record_type");manual.add_argument("record_id");manual.add_argument("--reason",required=True)
|
||||||
|
currency=sub.add_parser("currency-capture");currency.add_argument("record_type");currency.add_argument("record_id");currency.add_argument("field_name");currency.add_argument("--amount",required=True);currency.add_argument("--currency",required=True);currency.add_argument("--rate",required=True)
|
||||||
|
tax=sub.add_parser("tax-detail-add");tax.add_argument("record_type");tax.add_argument("record_id");tax.add_argument("--net",required=True);tax.add_argument("--vat-enabled",action="store_true");tax.add_argument("--vat-rate",default="0");tax.add_argument("--vat-treatment",default="NONE");tax.add_argument("--classification",choices=[v.value for v in TaxClassification],default="REVIEW")
|
||||||
|
asset=sub.add_parser("asset-add");asset.add_argument("--date",required=True);asset.add_argument("--description",required=True);asset.add_argument("--cost",required=True);asset.add_argument("--currency",default="EUR");asset.add_argument("--eur-value",required=True);asset.add_argument("--business-use",default="100");asset.add_argument("--supplier-id",type=int);asset.add_argument("--attachment-id",type=int);asset.add_argument("--notes");asset.add_argument("--tax-treatment",choices=[v.value for v in TaxClassification],default="REVIEW")
|
||||||
|
disposal=sub.add_parser("asset-dispose");disposal.add_argument("id",type=int);disposal.add_argument("--date",required=True);disposal.add_argument("--proceeds",required=True)
|
||||||
|
assets=sub.add_parser("asset-list");assets.add_argument("--as-of",required=True)
|
||||||
|
close=sub.add_parser("period-close");close.add_argument("period");close.add_argument("--backups",type=Path,required=True)
|
||||||
|
reopen=sub.add_parser("period-reopen");reopen.add_argument("period");reopen.add_argument("--reason",required=True)
|
||||||
|
report=sub.add_parser("report");report.add_argument("name",choices=["ledger","trial-balance","profit-loss","cash-flow","receivables","payables","assets","profitability","tax","tax-review"]);report.add_argument("--start");report.add_argument("--end");report.add_argument("--as-of");report.add_argument("--client-id",type=int);report.add_argument("--project-id",type=int);report.add_argument("--account");report.add_argument("--format",choices=["text","csv","ods","pdf"],default="text");report.add_argument("--output",type=Path);report.add_argument("--logo",type=Path,default=default_logo_path())
|
||||||
|
|
||||||
|
def _rows(report):
|
||||||
|
if isinstance(report,list):return [asdict(row) if hasattr(row,"__dataclass_fields__") else {attribute.key:getattr(row,attribute.key) for attribute in inspect(row).mapper.column_attrs} for row in report]
|
||||||
|
if hasattr(report,"__dataclass_fields__"):return [asdict(report)]
|
||||||
|
return []
|
||||||
|
|
||||||
|
def dispatch(args,session,account_id,database_path:Path)->bool:
|
||||||
|
if args.command not in COMMANDS:return False
|
||||||
|
if args.command=="bank-import":
|
||||||
|
mapping=CsvMapping(args.date_column,args.description_column,args.amount_column,args.date_format,args.currency_column,args.currency);obj=import_bank_csv(session,path=args.path,financial_account_id=account_id(args.financial_account),parser=MappedCsvParser(args.format_name,mapping));session.commit();print(len(obj));return True
|
||||||
|
if args.command=="bank-list":
|
||||||
|
for row in session.scalars(select(ImportedBankTransaction).order_by(ImportedBankTransaction.transaction_date,ImportedBankTransaction.id)):print(f"{row.id}\t{row.transaction_date}\t{row.amount}\t{row.status}\t{row.description}")
|
||||||
|
return True
|
||||||
|
if args.command=="match-propose":obj=propose_match(session,imported=session.get(ImportedBankTransaction,args.import_id),record_type=args.record_type,record_id=args.record_id,score_ppm=args.score,reason=args.reason)
|
||||||
|
elif args.command=="match-approve":obj=session.get(ReconciliationMatch,args.id);approve_match(session,obj,reason=args.reason)
|
||||||
|
elif args.command=="match-reject":obj=session.get(ReconciliationMatch,args.id);reject_match(obj,reason=args.reason)
|
||||||
|
elif args.command=="reconcile-manual":obj=manually_reconcile(session,imported=session.get(ImportedBankTransaction,args.import_id),record_type=args.record_type,record_id=args.record_id,reason=args.reason)
|
||||||
|
elif args.command=="currency-capture":obj=capture_currency_value(session,record_type=args.record_type,record_id=args.record_id,field_name=args.field_name,original_amount=Decimal(args.amount),original_currency=args.currency,exchange_rate=Decimal(args.rate))
|
||||||
|
elif args.command=="tax-detail-add":obj=record_tax_detail(session,record_type=args.record_type,record_id=args.record_id,net_amount=Decimal(args.net),vat_enabled=args.vat_enabled,vat_rate=Decimal(args.vat_rate),vat_treatment=args.vat_treatment,classification=TaxClassification(args.classification))
|
||||||
|
elif args.command=="asset-add":obj=record_asset(session,purchase_date=date.fromisoformat(args.date),description=args.description,original_cost=Decimal(args.cost),original_currency=args.currency,eur_value=Decimal(args.eur_value),business_use_percent=Decimal(args.business_use),supplier_id=args.supplier_id,attachment_id=args.attachment_id,notes=args.notes,tax_treatment=TaxClassification(args.tax_treatment))
|
||||||
|
elif args.command=="asset-dispose":obj=session.get(AssetRecord,args.id);dispose_asset(obj,disposal_date=date.fromisoformat(args.date),proceeds=Decimal(args.proceeds))
|
||||||
|
elif args.command=="asset-list":
|
||||||
|
for row in asset_register(session,as_of=date.fromisoformat(args.as_of)):print(f"{row.id}\t{row.purchase_date}\t{row.eur_value}\t{row.description}")
|
||||||
|
return True
|
||||||
|
elif args.command in {"period-close","period-reopen"}:
|
||||||
|
year,month=(int(value) for value in args.period.split("-"))
|
||||||
|
if args.command=="period-close":obj=close_period(session,year=year,month=month,database_path=database_path,backup_dir=args.backups)
|
||||||
|
else:
|
||||||
|
obj=session.scalar(select(AccountingPeriod).where(AccountingPeriod.year==year,AccountingPeriod.month==month));reopen_period(session,obj,reason=args.reason)
|
||||||
|
else:return _report(args,session,account_id)
|
||||||
|
session.commit();print(getattr(obj,"id",None));return True
|
||||||
|
|
||||||
|
def _report(args,session,account_id)->bool:
|
||||||
|
range_reports={"ledger","trial-balance","profit-loss","cash-flow"}
|
||||||
|
if args.name in range_reports and (not args.start or not args.end):raise ValidationError("this report requires --start and --end")
|
||||||
|
if args.name in {"receivables","payables","assets"} and not (args.as_of or args.end):raise ValidationError("this report requires --as-of")
|
||||||
|
if args.name=="profitability" and args.client_id is None:raise ValidationError("profitability requires --client-id")
|
||||||
|
if args.format!="text" and args.output is None:raise ValidationError("export formats require --output")
|
||||||
|
if args.format=="pdf" and args.name not in range_reports:raise ValidationError("PDF is supported for ledger, trial-balance, profit-loss, and cash-flow")
|
||||||
|
start=date.fromisoformat(args.start) if args.start else None;end=date.fromisoformat(args.end) if args.end else None;as_of=date.fromisoformat(args.as_of) if args.as_of else end
|
||||||
|
if args.name=="ledger":report=transaction_ledger(session,start=start,end=end,account_id=account_id(args.account) if args.account else None)
|
||||||
|
elif args.name=="trial-balance":report=trial_balance_summary(session,start=start,end=end)
|
||||||
|
elif args.name=="profit-loss":report=profit_and_loss_summary(session,start=start,end=end)
|
||||||
|
elif args.name=="cash-flow":report=cash_flow(session,start=start,end=end)
|
||||||
|
elif args.name=="receivables":report=outstanding_invoices(session,as_of=as_of)
|
||||||
|
elif args.name=="payables":report=outstanding_supplier_bills(session,as_of=as_of)
|
||||||
|
elif args.name=="assets":report=asset_register(session,as_of=as_of)
|
||||||
|
elif args.name=="profitability":report=client_project_profitability(session,client_id=args.client_id,project_id=args.project_id)
|
||||||
|
elif args.name=="tax":report=tax_preparation_details(session)
|
||||||
|
else:report=items_requiring_tax_review(session)
|
||||||
|
rows=_rows(report)
|
||||||
|
if args.format=="text":
|
||||||
|
for row in rows:print("\t".join(f"{key}={value}" for key,value in row.items()))
|
||||||
|
elif args.format=="csv":print(export_csv(args.output,rows))
|
||||||
|
elif args.format=="ods":print(export_ods(args.output,rows,sheet_name=args.name))
|
||||||
|
else:
|
||||||
|
theme=DocumentTheme(args.logo);settings=session.get(BusinessSettings,1)
|
||||||
|
if args.name=="ledger":path=render_transaction_ledger_pdf(args.output,rows=report,start=start,end=end,settings=settings,theme=theme)
|
||||||
|
elif args.name=="trial-balance":path=render_trial_balance_pdf(args.output,report=report,start=start,end=end,settings=settings,theme=theme)
|
||||||
|
elif args.name=="profit-loss":path=render_profit_and_loss_pdf(args.output,report=report,start=start,end=end,settings=settings,theme=theme)
|
||||||
|
elif args.name=="cash-flow":path=render_cash_flow_pdf(args.output,summary=report,start=start,end=end,settings=settings,theme=theme)
|
||||||
|
else:raise AssertionError("validated PDF report type")
|
||||||
|
print(path)
|
||||||
|
return True
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
"""Thin command-line adapter over application services."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal,InvalidOperation
|
||||||
|
from pathlib import Path
|
||||||
|
from alembic import command
|
||||||
|
from alembic.config import Config
|
||||||
|
from sqlalchemy import select
|
||||||
|
from roborto_accounting.config import default_logo_path,runtime_paths
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.db import make_engine,make_session_factory,sqlite_url
|
||||||
|
from roborto_accounting.persistence.models import Account,AccountClass,BusinessLetter,BusinessSettings,Client,Project,Supplier
|
||||||
|
from roborto_accounting.services.chart import seed_default_accounts
|
||||||
|
from roborto_accounting.services.periods import backup_sqlite
|
||||||
|
from roborto_accounting.services.integrity import check_integrity
|
||||||
|
from roborto_accounting.reporting.documents.samples import generate_document_samples
|
||||||
|
from roborto_accounting.services.records import create_client,create_project,create_supplier
|
||||||
|
from roborto_accounting.services.expenses import record_expense,record_owner_movement,record_transfer
|
||||||
|
from roborto_accounting.services.documents import archive_document,DocumentCategory
|
||||||
|
from roborto_accounting.services.tags import add_tag
|
||||||
|
from roborto_accounting.services.journals import post_manual_journal
|
||||||
|
from roborto_accounting.services.settings import update_business_setting
|
||||||
|
from roborto_accounting.services.letters import create_letter,finalize_letter
|
||||||
|
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||||
|
from roborto_accounting.cli.sales import register as register_sales_commands,dispatch as dispatch_sales
|
||||||
|
from roborto_accounting.cli.controls import register as register_control_commands,dispatch as dispatch_controls
|
||||||
|
|
||||||
|
def require_value(value:str|None,*,label:str,non_interactive:bool,input_fn=input)->str:
|
||||||
|
if value:return value
|
||||||
|
if non_interactive:raise ValidationError(f"{label} is required in non-interactive mode")
|
||||||
|
entered=input_fn(f"{label}: ").strip()
|
||||||
|
if not entered:raise ValidationError(f"{label} is required")
|
||||||
|
return entered
|
||||||
|
|
||||||
|
def _decimal(value:str,label:str)->Decimal:
|
||||||
|
try:return Decimal(value)
|
||||||
|
except InvalidOperation as exc:raise ValidationError(f"{label} must be an exact decimal") from exc
|
||||||
|
|
||||||
|
def _core_args(command_parser:argparse.ArgumentParser)->None:
|
||||||
|
command_parser.add_argument("--non-interactive",action="store_true")
|
||||||
|
|
||||||
|
def build_parser()->argparse.ArgumentParser:
|
||||||
|
parser=argparse.ArgumentParser(prog="accounts")
|
||||||
|
parser.add_argument("--database",type=Path,default=runtime_paths().database)
|
||||||
|
sub=parser.add_subparsers(dest="command",required=True)
|
||||||
|
check=sub.add_parser("check",help="report accounting integrity issues")
|
||||||
|
check.add_argument("--archive",type=Path,default=runtime_paths().archive)
|
||||||
|
check.add_argument("--non-interactive",action="store_true")
|
||||||
|
samples=sub.add_parser("document-samples",help="generate deterministic PDFs for visual review")
|
||||||
|
samples.add_argument("--output",type=Path,required=True)
|
||||||
|
samples.add_argument("--logo",type=Path,default=default_logo_path())
|
||||||
|
sub.add_parser("init",help="initialize or upgrade the database and seed defaults")
|
||||||
|
sub.add_parser("settings-show",help="show non-secret business settings")
|
||||||
|
setting=sub.add_parser("settings-set",help="set a non-secret business setting")
|
||||||
|
setting.add_argument("field");setting.add_argument("value")
|
||||||
|
sub.add_parser("chart-list",help="list chart-of-account entries")
|
||||||
|
add=sub.add_parser("chart-add",help="add an account")
|
||||||
|
add.add_argument("--code",required=True);add.add_argument("--name",required=True)
|
||||||
|
add.add_argument("--class",dest="account_class",required=True,choices=[value.value for value in AccountClass])
|
||||||
|
add.add_argument("--financial",action="store_true")
|
||||||
|
rename=sub.add_parser("chart-rename",help="rename an account")
|
||||||
|
rename.add_argument("code");rename.add_argument("name")
|
||||||
|
disable=sub.add_parser("chart-disable",help="disable an account")
|
||||||
|
disable.add_argument("code")
|
||||||
|
backup=sub.add_parser("backup",help="create a SQLite-safe local backup")
|
||||||
|
backup.add_argument("--output",type=Path,default=runtime_paths().backups)
|
||||||
|
client_add=sub.add_parser("client-add",help="add a client");_core_args(client_add)
|
||||||
|
client_add.add_argument("--name");client_add.add_argument("--address");client_add.add_argument("--email");client_add.add_argument("--phone");client_add.add_argument("--contact");client_add.add_argument("--tax-id");client_add.add_argument("--terms",type=int);client_add.add_argument("--rate");client_add.add_argument("--notes")
|
||||||
|
sub.add_parser("client-list",help="list clients")
|
||||||
|
supplier_add=sub.add_parser("supplier-add",help="add a supplier");_core_args(supplier_add)
|
||||||
|
supplier_add.add_argument("--name");supplier_add.add_argument("--address");supplier_add.add_argument("--email");supplier_add.add_argument("--phone");supplier_add.add_argument("--tax-id");supplier_add.add_argument("--notes")
|
||||||
|
sub.add_parser("supplier-list",help="list suppliers")
|
||||||
|
project_add=sub.add_parser("project-add",help="add a client project");_core_args(project_add)
|
||||||
|
project_add.add_argument("--client-id",type=int);project_add.add_argument("--name");project_add.add_argument("--code");project_add.add_argument("--rate");project_add.add_argument("--notes")
|
||||||
|
sub.add_parser("project-list",help="list projects")
|
||||||
|
expense=sub.add_parser("expense-add",help="record an immediately paid expense");_core_args(expense)
|
||||||
|
for flag in ("date","description","amount","expense-account","payment-account"):expense.add_argument(f"--{flag}")
|
||||||
|
expense.add_argument("--business-use",default="100");expense.add_argument("--personal-portion-account");expense.add_argument("--supplier-id",type=int);expense.add_argument("--paid-personally",action="store_true");expense.add_argument("--basis");expense.add_argument("--client-id",type=int);expense.add_argument("--project-id",type=int);expense.add_argument("--rechargeable",action="store_true")
|
||||||
|
transfer=sub.add_parser("transfer",help="transfer between owned accounts");_core_args(transfer)
|
||||||
|
for flag in ("date","description","amount","from-account","to-account"):transfer.add_argument(f"--{flag}")
|
||||||
|
for name,drawings in (("capital-add",False),("drawings-add",True)):
|
||||||
|
movement=sub.add_parser(name);_core_args(movement)
|
||||||
|
for flag in ("date","description","amount","financial-account","equity-account"):movement.add_argument(f"--{flag}")
|
||||||
|
movement.set_defaults(drawings=drawings)
|
||||||
|
attachment=sub.add_parser("attachment-add",help="copy a file into the managed archive")
|
||||||
|
attachment.add_argument("source",type=Path);attachment.add_argument("--category",choices=[v.value for v in DocumentCategory],default=DocumentCategory.GENERAL.value);attachment.add_argument("--record-type");attachment.add_argument("--record-id");attachment.add_argument("--archive",type=Path,default=runtime_paths().archive)
|
||||||
|
tag=sub.add_parser("tag-add",help="tag a record");tag.add_argument("record_type");tag.add_argument("record_id");tag.add_argument("name")
|
||||||
|
manual=sub.add_parser("journal-manual",help="post an explicit balanced manual journal")
|
||||||
|
manual.add_argument("--date",required=True);manual.add_argument("--description",required=True);manual.add_argument("--reason",required=True)
|
||||||
|
manual.add_argument("--line",action="append",required=True,help="ACCOUNT_CODE|DEBIT|CREDIT")
|
||||||
|
letter=sub.add_parser("letter-create",help="create a business-letter draft")
|
||||||
|
letter.add_argument("--date",required=True);letter.add_argument("--recipient",required=True);letter.add_argument("--address",required=True);letter.add_argument("--email");letter.add_argument("--reference");letter.add_argument("--subject",required=True)
|
||||||
|
body=letter.add_mutually_exclusive_group(required=True);body.add_argument("--body");body.add_argument("--body-file",type=Path)
|
||||||
|
sub.add_parser("letter-list",help="list business letters")
|
||||||
|
finalize=sub.add_parser("letter-finalize",help="render and archive a letter draft");finalize.add_argument("id",type=int);finalize.add_argument("--archive",type=Path,default=runtime_paths().archive);finalize.add_argument("--logo",type=Path,default=default_logo_path())
|
||||||
|
register_sales_commands(sub)
|
||||||
|
register_control_commands(sub)
|
||||||
|
return parser
|
||||||
|
|
||||||
|
def _upgrade_database(path:Path)->None:
|
||||||
|
path.parent.mkdir(parents=True,exist_ok=True)
|
||||||
|
project_root=Path(__file__).resolve().parents[3]
|
||||||
|
config=Config(str(project_root/"alembic.ini"));config.set_main_option("script_location",str(project_root/"alembic"))
|
||||||
|
config.set_main_option("sqlalchemy.url",sqlite_url(path));command.upgrade(config,"head")
|
||||||
|
|
||||||
|
def _account_id(session,code:str)->int:
|
||||||
|
account=session.scalar(select(Account).where(Account.code==code,Account.is_active.is_(True)))
|
||||||
|
if account is None:raise ValidationError(f"active account {code!r} not found")
|
||||||
|
return account.id
|
||||||
|
|
||||||
|
def main(argv:list[str]|None=None)->int:
|
||||||
|
args=build_parser().parse_args(argv)
|
||||||
|
if args.command=="init":
|
||||||
|
_upgrade_database(args.database)
|
||||||
|
engine=make_engine(sqlite_url(args.database));session=make_session_factory(engine)()
|
||||||
|
try:
|
||||||
|
settings=session.get(BusinessSettings,1)
|
||||||
|
if settings is None:session.add(BusinessSettings(id=1))
|
||||||
|
seed_default_accounts(session);session.commit()
|
||||||
|
finally:session.close();engine.dispose()
|
||||||
|
print(args.database);return 0
|
||||||
|
if args.command=="check":
|
||||||
|
engine=make_engine(sqlite_url(args.database));session=make_session_factory(engine)()
|
||||||
|
try:issues=check_integrity(session,archive_root=args.archive)
|
||||||
|
finally:session.close();engine.dispose()
|
||||||
|
for issue in issues:print(f"{issue.code}: {issue.record_type} {issue.record_id}: {issue.message}")
|
||||||
|
return 1 if issues else 0
|
||||||
|
if args.command=="document-samples":
|
||||||
|
for path in generate_document_samples(args.output,logo_path=args.logo):print(path)
|
||||||
|
return 0
|
||||||
|
if args.command in {"settings-show","settings-set","chart-list","chart-add","chart-rename","chart-disable"}:
|
||||||
|
engine=make_engine(sqlite_url(args.database));session=make_session_factory(engine)()
|
||||||
|
try:
|
||||||
|
if args.command=="settings-show":
|
||||||
|
settings=session.get(BusinessSettings,1)
|
||||||
|
if settings is None:raise ValidationError("database is not initialized; run accounts init")
|
||||||
|
fields=("trading_name","commencement_date","base_currency","default_hourly_rate","default_payment_terms_days","vat_enabled","invoice_prefix","quotation_prefix","default_income_account_id","document_path","report_path","business_descriptor","website","general_email","accounts_email","telephone","postal_address","tax_identifier","bank_payment_instructions")
|
||||||
|
print(json.dumps({name:str(getattr(settings,name)) if getattr(settings,name) is not None else None for name in fields},indent=2,sort_keys=True))
|
||||||
|
elif args.command=="settings-set":
|
||||||
|
if args.field=="default_income_account":
|
||||||
|
settings=session.get(BusinessSettings,1);settings.default_income_account_id=_account_id(session,args.value);session.commit();print(args.field);return 0
|
||||||
|
settings=session.get(BusinessSettings,1)
|
||||||
|
if settings is None:raise ValidationError("database is not initialized; run accounts init")
|
||||||
|
update_business_setting(settings,field=args.field,value=args.value);session.commit();print(args.field)
|
||||||
|
elif args.command=="chart-list":
|
||||||
|
for account in session.scalars(select(Account).order_by(Account.code)):
|
||||||
|
print(f"{account.code}\t{account.account_class}\t{'active' if account.is_active else 'disabled'}\t{account.name}")
|
||||||
|
elif args.command=="chart-add":
|
||||||
|
session.add(Account(code=args.code,name=args.name,account_class=AccountClass(args.account_class),is_financial_account=args.financial));session.commit();print(args.code)
|
||||||
|
else:
|
||||||
|
account=session.scalar(select(Account).where(Account.code==args.code))
|
||||||
|
if account is None:raise ValidationError("account not found")
|
||||||
|
if args.command=="chart-rename":account.name=args.name
|
||||||
|
else:account.is_active=False
|
||||||
|
session.commit();print(args.code)
|
||||||
|
finally:session.close();engine.dispose()
|
||||||
|
return 0
|
||||||
|
if args.command=="backup":
|
||||||
|
print(backup_sqlite(args.database,args.output));return 0
|
||||||
|
core_commands={"client-add","client-list","supplier-add","supplier-list","project-add","project-list",
|
||||||
|
"expense-add","transfer","capital-add","drawings-add","attachment-add","tag-add","journal-manual","letter-create","letter-list","letter-finalize"}
|
||||||
|
if args.command in core_commands:
|
||||||
|
engine=make_engine(sqlite_url(args.database));session=make_session_factory(engine)()
|
||||||
|
try:
|
||||||
|
if args.command=="client-add":
|
||||||
|
name=require_value(args.name,label="Client name",non_interactive=args.non_interactive)
|
||||||
|
record=create_client(session,name=name,billing_address=args.address,email=args.email,phone=args.phone,
|
||||||
|
contact_person=args.contact,tax_identifier=args.tax_id,payment_terms_days=args.terms,
|
||||||
|
hourly_rate=_decimal(args.rate,"rate") if args.rate else None,notes=args.notes)
|
||||||
|
session.commit();print(record.id)
|
||||||
|
elif args.command=="client-list":
|
||||||
|
for row in session.scalars(select(Client).order_by(Client.name)):print(f"{row.id}\t{row.name}\t{row.email or ''}")
|
||||||
|
elif args.command=="supplier-add":
|
||||||
|
name=require_value(args.name,label="Supplier name",non_interactive=args.non_interactive)
|
||||||
|
record=create_supplier(session,name=name,billing_address=args.address,email=args.email,phone=args.phone,tax_identifier=args.tax_id,notes=args.notes)
|
||||||
|
session.commit();print(record.id)
|
||||||
|
elif args.command=="supplier-list":
|
||||||
|
for row in session.scalars(select(Supplier).order_by(Supplier.name)):print(f"{row.id}\t{row.name}\t{row.email or ''}")
|
||||||
|
elif args.command=="project-add":
|
||||||
|
client_id=int(require_value(str(args.client_id) if args.client_id else None,label="Client ID",non_interactive=args.non_interactive))
|
||||||
|
name=require_value(args.name,label="Project name",non_interactive=args.non_interactive)
|
||||||
|
record=create_project(session,client_id=client_id,name=name,code=args.code,hourly_rate=_decimal(args.rate,"rate") if args.rate else None,notes=args.notes)
|
||||||
|
session.commit();print(record.id)
|
||||||
|
elif args.command=="project-list":
|
||||||
|
for row in session.scalars(select(Project).order_by(Project.name)):print(f"{row.id}\t{row.client_id}\t{row.code or ''}\t{row.name}")
|
||||||
|
elif args.command=="attachment-add":
|
||||||
|
record=archive_document(session,source=args.source,archive_root=args.archive,category=DocumentCategory(args.category),record_type=args.record_type,record_id=args.record_id)
|
||||||
|
session.commit();print(record.stored_relative_path)
|
||||||
|
elif args.command=="tag-add":
|
||||||
|
record=add_tag(session,record_type=args.record_type,record_id=args.record_id,name=args.name,source="cli")
|
||||||
|
session.commit();print(record.id)
|
||||||
|
elif args.command=="journal-manual":
|
||||||
|
lines=[]
|
||||||
|
for raw in args.line:
|
||||||
|
parts=raw.split("|")
|
||||||
|
if len(parts)!=3:raise ValidationError("manual line format is ACCOUNT_CODE|DEBIT|CREDIT")
|
||||||
|
lines.append({"account_id":_account_id(session,parts[0]),"debit":_decimal(parts[1] or "0","debit"),"credit":_decimal(parts[2] or "0","credit")})
|
||||||
|
record=post_manual_journal(session,journal_date=date.fromisoformat(args.date),description=args.description,reason=args.reason,lines=lines,source="cli")
|
||||||
|
session.commit();print(record.id)
|
||||||
|
elif args.command=="letter-create":
|
||||||
|
body_text=args.body_file.read_text(encoding="utf-8") if args.body_file else args.body
|
||||||
|
record=create_letter(session,letter_date=date.fromisoformat(args.date),recipient_name=args.recipient,recipient_address=args.address.replace("\\n","\n"),recipient_email=args.email,reference=args.reference,subject=args.subject,body_text=body_text)
|
||||||
|
session.commit();print(record.id)
|
||||||
|
elif args.command=="letter-list":
|
||||||
|
for record in session.scalars(select(BusinessLetter).order_by(BusinessLetter.letter_date,BusinessLetter.id)):print(f"{record.id}\t{record.letter_date}\t{record.status}\t{record.recipient_name}\t{record.subject}")
|
||||||
|
elif args.command=="letter-finalize":
|
||||||
|
settings=session.get(BusinessSettings,1);letter=session.get(BusinessLetter,args.id)
|
||||||
|
record=finalize_letter(session,letter=letter,settings=settings,archive_root=args.archive,theme=DocumentTheme(args.logo));session.commit();print(record.stored_relative_path)
|
||||||
|
else:
|
||||||
|
values={name:require_value(getattr(args,name),label=name.replace("_"," ").title(),non_interactive=args.non_interactive)
|
||||||
|
for name in ({"date","description","amount","expense_account","payment_account"} if args.command=="expense-add" else
|
||||||
|
{"date","description","amount","from_account","to_account"} if args.command=="transfer" else
|
||||||
|
{"date","description","amount","financial_account","equity_account"})}
|
||||||
|
when=date.fromisoformat(values["date"]);amount=_decimal(values["amount"],"amount")
|
||||||
|
if args.command=="expense-add":
|
||||||
|
record=record_expense(session,expense_date=when,description=values["description"],actual_amount=amount,
|
||||||
|
business_use_percent=_decimal(args.business_use,"business use"),expense_account_id=_account_id(session,values["expense_account"]),
|
||||||
|
payment_account_id=_account_id(session,values["payment_account"]),personal_portion_account_id=_account_id(session,args.personal_portion_account) if args.personal_portion_account else None,
|
||||||
|
paid_personally=args.paid_personally,supplier_id=args.supplier_id,business_use_basis=args.basis,client_id=args.client_id,project_id=args.project_id,is_rechargeable=args.rechargeable)
|
||||||
|
elif args.command=="transfer":record=record_transfer(session,transfer_date=when,description=values["description"],amount=amount,from_account_id=_account_id(session,values["from_account"]),to_account_id=_account_id(session,values["to_account"]))
|
||||||
|
else:record=record_owner_movement(session,movement_date=when,description=values["description"],amount=amount,financial_account_id=_account_id(session,values["financial_account"]),equity_account_id=_account_id(session,values["equity_account"]),drawings=args.drawings)
|
||||||
|
session.commit();print(record.id)
|
||||||
|
except:session.rollback();raise
|
||||||
|
finally:session.close();engine.dispose()
|
||||||
|
return 0
|
||||||
|
engine=make_engine(sqlite_url(args.database));session=make_session_factory(engine)()
|
||||||
|
try:
|
||||||
|
if dispatch_sales(args,session,lambda code:_account_id(session,code)):return 0
|
||||||
|
if dispatch_controls(args,session,lambda code:_account_id(session,code),args.database):return 0
|
||||||
|
except:session.rollback();raise
|
||||||
|
finally:session.close();engine.dispose()
|
||||||
|
return 2
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""Sales and purchasing CLI adapter over application services."""
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal,InvalidOperation
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import BusinessSettings,Client,ClientPayment,Invoice,Quotation,SupplierBill,TimeEntry,Expense,Project,RecurringInvoiceDefinition
|
||||||
|
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||||
|
from roborto_accounting.services.credits import create_credit_note,write_off_bad_debt
|
||||||
|
from roborto_accounting.services.generated_documents import generate_invoice_document,generate_quotation_document
|
||||||
|
from roborto_accounting.services.invoices import create_invoice,invoice_from_quotation,issue_invoice,outstanding_balance,void_invoice
|
||||||
|
from roborto_accounting.services.payables import bill_outstanding,pay_supplier_bill,record_supplier_bill,record_supplier_refund
|
||||||
|
from roborto_accounting.services.payments import allocate_client_credit,record_invoice_payment
|
||||||
|
from roborto_accounting.services.quotations import accept_quotation,create_quotation,issue_quotation
|
||||||
|
from roborto_accounting.services.recharges import assign_recharges_to_invoice,uninvoiced_rechargeable_expenses
|
||||||
|
from roborto_accounting.services.time_entries import assign_time_to_invoice,record_time_entry,uninvoiced_billable_time
|
||||||
|
from roborto_accounting.services.recurring import create_recurring_expense_definition,create_recurring_invoice_definition,due_expense_definitions,due_invoice_definitions,prepare_recurring_invoice_draft
|
||||||
|
from roborto_accounting.config import default_logo_path
|
||||||
|
|
||||||
|
COMMANDS={"quotation-create","quotation-issue","quotation-accept","quotation-list","invoice-create","invoice-from-quotation","invoice-issue","invoice-void","invoice-list","invoice-payment","client-credit-allocate","credit-note","bad-debt","supplier-bill-add","supplier-bill-pay","supplier-refund","supplier-bill-list","time-add","time-list","time-assign","recharge-list","recharge-assign","sales-document-generate","recurring-invoice-add","recurring-invoice-due","recurring-invoice-prepare","recurring-expense-add","recurring-expense-due"}
|
||||||
|
|
||||||
|
def _d(value:str)->Decimal:
|
||||||
|
try:return Decimal(value)
|
||||||
|
except InvalidOperation as exc:raise ValidationError("amounts must be exact decimals") from exc
|
||||||
|
|
||||||
|
def _line(value:str)->dict[str,object]:
|
||||||
|
parts=value.split("|")
|
||||||
|
if len(parts)<4 or len(parts)>7:raise ValidationError("line format is DESCRIPTION|QUANTITY|UNIT|UNIT_PRICE[|VAT_AMOUNT|VAT_TREATMENT|INCOME_ACCOUNT]")
|
||||||
|
return {"description":parts[0],"quantity":_d(parts[1]),"unit":parts[2],"unit_price":_d(parts[3]),"vat_amount":_d(parts[4]) if len(parts)>4 and parts[4] else Decimal("0"),"vat_treatment":parts[5] if len(parts)>5 else "NONE","income_account_code":parts[6] if len(parts)>6 else None}
|
||||||
|
|
||||||
|
def _lines(values,account_id):
|
||||||
|
result=[]
|
||||||
|
for value in values:
|
||||||
|
item=_line(value);code=item.pop("income_account_code")
|
||||||
|
if code:item["income_account_id"]=account_id(code)
|
||||||
|
result.append(item)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def register(sub)->None:
|
||||||
|
q=sub.add_parser("quotation-create");q.add_argument("--client-id",type=int,required=True);q.add_argument("--date",required=True);q.add_argument("--project-id",type=int);q.add_argument("--line",action="append",required=True)
|
||||||
|
for name in ("quotation-issue","quotation-accept"):
|
||||||
|
p=sub.add_parser(name);p.add_argument("id",type=int)
|
||||||
|
sub.add_parser("quotation-list")
|
||||||
|
i=sub.add_parser("invoice-create");i.add_argument("--client-id",type=int,required=True);i.add_argument("--date",required=True);i.add_argument("--project-id",type=int);i.add_argument("--terms",type=int);i.add_argument("--line",action="append",required=True)
|
||||||
|
fq=sub.add_parser("invoice-from-quotation");fq.add_argument("quotation_id",type=int);fq.add_argument("--date",required=True);fq.add_argument("--terms",type=int)
|
||||||
|
ii=sub.add_parser("invoice-issue");ii.add_argument("id",type=int);ii.add_argument("--receivables-account",default="1100");ii.add_argument("--vat-account",default="2100")
|
||||||
|
iv=sub.add_parser("invoice-void");iv.add_argument("id",type=int);iv.add_argument("--date",required=True);iv.add_argument("--reason",required=True)
|
||||||
|
sub.add_parser("invoice-list")
|
||||||
|
pay=sub.add_parser("invoice-payment");pay.add_argument("invoice_id",type=int);pay.add_argument("--date",required=True);pay.add_argument("--amount",required=True);pay.add_argument("--financial-account",required=True);pay.add_argument("--receivables-account",default="1100");pay.add_argument("--credit-account",default="2110");pay.add_argument("--reference")
|
||||||
|
alloc=sub.add_parser("client-credit-allocate");alloc.add_argument("payment_id",type=int);alloc.add_argument("invoice_id",type=int);alloc.add_argument("--date",required=True);alloc.add_argument("--amount",required=True);alloc.add_argument("--receivables-account",default="1100");alloc.add_argument("--credit-account",default="2110")
|
||||||
|
for name in ("credit-note","bad-debt"):
|
||||||
|
p=sub.add_parser(name);p.add_argument("invoice_id",type=int);p.add_argument("--date",required=True);p.add_argument("--amount",required=True);p.add_argument("--reason",required=True);p.add_argument("--receivables-account",default="1100");p.add_argument("--contra-account",required=True)
|
||||||
|
bill=sub.add_parser("supplier-bill-add");bill.add_argument("--supplier-id",type=int,required=True);bill.add_argument("--date",required=True);bill.add_argument("--due-date");bill.add_argument("--description",required=True);bill.add_argument("--amount",required=True);bill.add_argument("--expense-account",required=True);bill.add_argument("--payable-account",default="2000");bill.add_argument("--reference")
|
||||||
|
bp=sub.add_parser("supplier-bill-pay");bp.add_argument("bill_id",type=int);bp.add_argument("--date",required=True);bp.add_argument("--amount",required=True);bp.add_argument("--payable-account",default="2000");bp.add_argument("--financial-account",required=True);bp.add_argument("--reference")
|
||||||
|
refund=sub.add_parser("supplier-refund");refund.add_argument("bill_id",type=int);refund.add_argument("--date",required=True);refund.add_argument("--amount",required=True);refund.add_argument("--financial-account",required=True);refund.add_argument("--reason",required=True)
|
||||||
|
sub.add_parser("supplier-bill-list")
|
||||||
|
time=sub.add_parser("time-add");time.add_argument("--client-id",type=int,required=True);time.add_argument("--project-id",type=int);time.add_argument("--date",required=True);time.add_argument("--hours",required=True);time.add_argument("--description",required=True);time.add_argument("--rate");time.add_argument("--non-billable",action="store_true")
|
||||||
|
tl=sub.add_parser("time-list");tl.add_argument("--client-id",type=int,required=True);tl.add_argument("--project-id",type=int)
|
||||||
|
ta=sub.add_parser("time-assign");ta.add_argument("invoice_id",type=int);ta.add_argument("entry_ids",type=int,nargs="+")
|
||||||
|
rl=sub.add_parser("recharge-list");rl.add_argument("--client-id",type=int,required=True);rl.add_argument("--project-id",type=int)
|
||||||
|
ra=sub.add_parser("recharge-assign");ra.add_argument("invoice_id",type=int);ra.add_argument("expense_ids",type=int,nargs="+")
|
||||||
|
doc=sub.add_parser("sales-document-generate");doc.add_argument("kind",choices=["invoice","quotation"]);doc.add_argument("id",type=int);doc.add_argument("--archive",type=Path,required=True);doc.add_argument("--logo",type=Path,default=default_logo_path())
|
||||||
|
ri=sub.add_parser("recurring-invoice-add");ri.add_argument("--client-id",type=int,required=True);ri.add_argument("--project-id",type=int);ri.add_argument("--frequency",required=True);ri.add_argument("--next-date",required=True);ri.add_argument("--line",action="append",required=True)
|
||||||
|
rid=sub.add_parser("recurring-invoice-due");rid.add_argument("--as-of",required=True)
|
||||||
|
rip=sub.add_parser("recurring-invoice-prepare");rip.add_argument("id",type=int);rip.add_argument("--date",required=True)
|
||||||
|
re=sub.add_parser("recurring-expense-add");re.add_argument("--supplier-id",type=int,required=True);re.add_argument("--frequency",required=True);re.add_argument("--next-date",required=True);re.add_argument("--category-account",required=True);re.add_argument("--amount");re.add_argument("--hints")
|
||||||
|
red=sub.add_parser("recurring-expense-due");red.add_argument("--as-of",required=True)
|
||||||
|
|
||||||
|
def dispatch(args,session,account_id)->bool:
|
||||||
|
if args.command not in COMMANDS:return False
|
||||||
|
settings=session.get(BusinessSettings,1)
|
||||||
|
if args.command=="quotation-create":obj=create_quotation(session,client=session.get(Client,args.client_id),quotation_date=date.fromisoformat(args.date),project_id=args.project_id,lines=_lines(args.line,account_id))
|
||||||
|
elif args.command=="quotation-issue":obj=issue_quotation(session,session.get(Quotation,args.id),session.get(Client,session.get(Quotation,args.id).client_id))
|
||||||
|
elif args.command=="quotation-accept":obj=accept_quotation(session,session.get(Quotation,args.id))
|
||||||
|
elif args.command=="quotation-list":
|
||||||
|
for q in session.scalars(select(Quotation).order_by(Quotation.quotation_date,Quotation.id)):print(f"{q.id}\t{q.number or 'DRAFT'}\t{q.status}\t{q.gross_total}")
|
||||||
|
return True
|
||||||
|
elif args.command=="invoice-create":obj=create_invoice(session,settings=settings,client=session.get(Client,args.client_id),invoice_date=date.fromisoformat(args.date),project_id=args.project_id,payment_terms_days=args.terms,lines=_lines(args.line,account_id))
|
||||||
|
elif args.command=="invoice-from-quotation":
|
||||||
|
q=session.get(Quotation,args.quotation_id);obj=invoice_from_quotation(session,settings=settings,client=session.get(Client,q.client_id),quotation=q,invoice_date=date.fromisoformat(args.date),payment_terms_days=args.terms)
|
||||||
|
elif args.command=="invoice-issue":
|
||||||
|
inv=session.get(Invoice,args.id);obj=issue_invoice(session,inv,session.get(Client,inv.client_id),receivables_account_id=account_id(args.receivables_account),vat_liability_account_id=account_id(args.vat_account) if inv.vat_total else None)
|
||||||
|
elif args.command=="invoice-void":obj=void_invoice(session,session.get(Invoice,args.id),void_date=date.fromisoformat(args.date),reason=args.reason)
|
||||||
|
elif args.command=="invoice-list":
|
||||||
|
for inv in session.scalars(select(Invoice).order_by(Invoice.invoice_date,Invoice.id)):print(f"{inv.id}\t{inv.number or 'DRAFT'}\t{inv.status}\t{inv.gross_total}\t{outstanding_balance(inv)}")
|
||||||
|
return True
|
||||||
|
elif args.command=="invoice-payment":obj=record_invoice_payment(session,invoice=session.get(Invoice,args.invoice_id),payment_date=date.fromisoformat(args.date),amount=_d(args.amount),financial_account_id=account_id(args.financial_account),receivables_account_id=account_id(args.receivables_account),client_credit_account_id=account_id(args.credit_account),reference=args.reference)
|
||||||
|
elif args.command=="client-credit-allocate":obj=allocate_client_credit(session,payment=session.get(ClientPayment,args.payment_id),invoice=session.get(Invoice,args.invoice_id),allocation_date=date.fromisoformat(args.date),amount=_d(args.amount),receivables_account_id=account_id(args.receivables_account),client_credit_account_id=account_id(args.credit_account))
|
||||||
|
elif args.command in {"credit-note","bad-debt"}:
|
||||||
|
fn=create_credit_note if args.command=="credit-note" else write_off_bad_debt;kw={"receivables_account_id":account_id(args.receivables_account),("sales_returns_account_id" if args.command=="credit-note" else "bad_debt_account_id"):account_id(args.contra_account)}
|
||||||
|
obj=fn(session,invoice=session.get(Invoice,args.invoice_id),**({"credit_date":date.fromisoformat(args.date)} if args.command=="credit-note" else {"write_off_date":date.fromisoformat(args.date)}),amount=_d(args.amount),reason=args.reason,**kw)
|
||||||
|
elif args.command=="supplier-bill-add":obj=record_supplier_bill(session,supplier_id=args.supplier_id,bill_date=date.fromisoformat(args.date),due_date=date.fromisoformat(args.due_date) if args.due_date else None,description=args.description,amount=_d(args.amount),expense_account_id=account_id(args.expense_account),payable_account_id=account_id(args.payable_account),supplier_reference=args.reference)
|
||||||
|
elif args.command=="supplier-bill-pay":obj=pay_supplier_bill(session,bill=session.get(SupplierBill,args.bill_id),payment_date=date.fromisoformat(args.date),amount=_d(args.amount),payable_account_id=account_id(args.payable_account),financial_account_id=account_id(args.financial_account),reference=args.reference)
|
||||||
|
elif args.command=="supplier-refund":obj=record_supplier_refund(session,bill=session.get(SupplierBill,args.bill_id),refund_date=date.fromisoformat(args.date),amount=_d(args.amount),financial_account_id=account_id(args.financial_account),reason=args.reason)
|
||||||
|
elif args.command=="supplier-bill-list":
|
||||||
|
for bill in session.scalars(select(SupplierBill).order_by(SupplierBill.bill_date,SupplierBill.id)):print(f"{bill.id}\t{bill.status}\t{bill.amount}\t{bill_outstanding(bill)}")
|
||||||
|
return True
|
||||||
|
elif args.command=="time-add":obj=record_time_entry(session,settings=settings,client=session.get(Client,args.client_id),project=session.get(Project,args.project_id) if args.project_id else None,entry_date=date.fromisoformat(args.date),hours=_d(args.hours),description=args.description,rate_override=_d(args.rate) if args.rate else None,is_billable=not args.non_billable)
|
||||||
|
elif args.command=="time-list":
|
||||||
|
for e in uninvoiced_billable_time(session,client_id=args.client_id,project_id=args.project_id):print(f"{e.id}\t{e.entry_date}\t{e.hours}\t{e.billing_rate}\t{e.description}")
|
||||||
|
return True
|
||||||
|
elif args.command=="time-assign":obj=session.get(Invoice,args.invoice_id);assign_time_to_invoice(session,invoice=obj,entries=[session.get(TimeEntry,i) for i in args.entry_ids])
|
||||||
|
elif args.command=="recharge-list":
|
||||||
|
for e in uninvoiced_rechargeable_expenses(session,client_id=args.client_id,project_id=args.project_id):print(f"{e.id}\t{e.expense_date}\t{e.business_amount}\t{e.description}")
|
||||||
|
return True
|
||||||
|
elif args.command=="recharge-assign":obj=session.get(Invoice,args.invoice_id);assign_recharges_to_invoice(session,invoice=obj,expenses=[session.get(Expense,i) for i in args.expense_ids])
|
||||||
|
elif args.command=="recurring-invoice-add":
|
||||||
|
lines=_lines(args.line,account_id)
|
||||||
|
for line in lines:
|
||||||
|
for key in ("quantity","unit_price","vat_amount"):line[key]=str(line[key])
|
||||||
|
obj=create_recurring_invoice_definition(session,client_id=args.client_id,project_id=args.project_id,frequency=args.frequency,next_due_date=date.fromisoformat(args.next_date),template_lines=lines)
|
||||||
|
elif args.command=="recurring-invoice-due":
|
||||||
|
for d in due_invoice_definitions(session,date.fromisoformat(args.as_of)):print(f"{d.id}\t{d.next_due_date}\t{d.frequency}\t{d.client_id}")
|
||||||
|
return True
|
||||||
|
elif args.command=="recurring-invoice-prepare":
|
||||||
|
definition=session.get(RecurringInvoiceDefinition,args.id);obj=prepare_recurring_invoice_draft(session,definition=definition,settings=settings,client=session.get(Client,definition.client_id),invoice_date=date.fromisoformat(args.date))
|
||||||
|
elif args.command=="recurring-expense-add":obj=create_recurring_expense_definition(session,supplier_id=args.supplier_id,frequency=args.frequency,next_expected_date=date.fromisoformat(args.next_date),category_account_id=account_id(args.category_account),expected_amount=_d(args.amount) if args.amount else None,reconciliation_hints=args.hints)
|
||||||
|
elif args.command=="recurring-expense-due":
|
||||||
|
for d in due_expense_definitions(session,date.fromisoformat(args.as_of)):print(f"{d.id}\t{d.next_expected_date}\t{d.frequency}\t{d.supplier_id}")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
theme=DocumentTheme(args.logo)
|
||||||
|
if args.kind=="invoice":obj=generate_invoice_document(session,invoice=session.get(Invoice,args.id),settings=settings,archive_root=args.archive,theme=theme)
|
||||||
|
else:obj=generate_quotation_document(session,quotation=session.get(Quotation,args.id),settings=settings,archive_root=args.archive,theme=theme)
|
||||||
|
session.commit();print(getattr(obj,"number",None) or getattr(obj,"id",None));return True
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Location-independent runtime paths following XDG conventions."""
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RuntimePaths:
|
||||||
|
config_dir:Path;data_dir:Path;state_dir:Path
|
||||||
|
@property
|
||||||
|
def database(self)->Path:return self.data_dir/"accounts.sqlite"
|
||||||
|
@property
|
||||||
|
def archive(self)->Path:return self.data_dir/"documents"
|
||||||
|
@property
|
||||||
|
def backups(self)->Path:return self.data_dir/"backups"
|
||||||
|
@property
|
||||||
|
def env_file(self)->Path:return self.config_dir/"env"
|
||||||
|
|
||||||
|
def runtime_paths(environ:dict[str,str]|None=None)->RuntimePaths:
|
||||||
|
env=os.environ if environ is None else environ
|
||||||
|
home=Path(env.get("HOME",str(Path.home())))
|
||||||
|
config=Path(env.get("XDG_CONFIG_HOME",home/".config"))/"roborto-accounting"
|
||||||
|
data=Path(env.get("XDG_DATA_HOME",home/".local/share"))/"roborto-accounting"
|
||||||
|
state=Path(env.get("XDG_STATE_HOME",home/".local/state"))/"roborto-accounting"
|
||||||
|
return RuntimePaths(config,data,state)
|
||||||
|
|
||||||
|
def default_logo_path()->Path:
|
||||||
|
"""Resolve the checked-in brand asset independently of the current directory."""
|
||||||
|
return Path(__file__).resolve().parents[2]/"assets"/"branding"/"logo-light.svg"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Accounting domain models and rules."""
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Immutable issue-time client snapshots."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from roborto_accounting.persistence.models import Client
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ClientSnapshot:
|
||||||
|
name: str
|
||||||
|
billing_address: str | None
|
||||||
|
email: str | None
|
||||||
|
phone: str | None
|
||||||
|
contact_person: str | None
|
||||||
|
tax_identifier: str | None
|
||||||
|
|
||||||
|
def snapshot_client(client: Client) -> ClientSnapshot:
|
||||||
|
return ClientSnapshot(name=client.name, billing_address=client.billing_address,
|
||||||
|
email=client.email, phone=client.phone,
|
||||||
|
contact_person=client.contact_person,
|
||||||
|
tax_identifier=client.tax_identifier)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"""Stable domain error types."""
|
||||||
|
class DomainError(Exception):
|
||||||
|
"""Base error for invalid accounting operations."""
|
||||||
|
class ValidationError(DomainError):
|
||||||
|
"""Input violates a domain invariant."""
|
||||||
|
class ConflictError(DomainError):
|
||||||
|
"""Operation conflicts with existing history or state."""
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Database access and persistence adapters."""
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
"""Declarative base shared by SQLAlchemy models."""
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
"""Base class for persistence models."""
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""SQLAlchemy engine and session configuration."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import Engine, create_engine
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
def make_engine(database_url: str = "sqlite:///accounts.db") -> Engine:
|
||||||
|
connect_args = {"check_same_thread": False} if database_url.startswith("sqlite") else {}
|
||||||
|
return create_engine(database_url, connect_args=connect_args, future=True)
|
||||||
|
|
||||||
|
def make_session_factory(engine: Engine) -> sessionmaker[Session]:
|
||||||
|
return sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def session_scope(factory: sessionmaker[Session]) -> Iterator[Session]:
|
||||||
|
session = factory()
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
session.commit()
|
||||||
|
except Exception:
|
||||||
|
session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
def sqlite_url(path: Path) -> str:
|
||||||
|
return "sqlite:///" + str(path.resolve())
|
||||||
@@ -0,0 +1,514 @@
|
|||||||
|
"""Foundational settings and chart-of-accounts persistence models."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from enum import StrEnum
|
||||||
|
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
from .base import Base
|
||||||
|
from .money import MoneyMicroUnits
|
||||||
|
|
||||||
|
class AccountClass(StrEnum):
|
||||||
|
ASSET = "ASSET"
|
||||||
|
LIABILITY = "LIABILITY"
|
||||||
|
EQUITY = "EQUITY"
|
||||||
|
INCOME = "INCOME"
|
||||||
|
EXPENSE = "EXPENSE"
|
||||||
|
|
||||||
|
class BusinessSettings(Base):
|
||||||
|
__tablename__ = "business_settings"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
|
||||||
|
trading_name: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
commencement_date: Mapped[date | None] = mapped_column(Date)
|
||||||
|
base_currency: Mapped[str] = mapped_column(String(3), default="EUR", nullable=False)
|
||||||
|
default_hourly_rate: Mapped[Decimal | None] = mapped_column("default_hourly_rate_micro", MoneyMicroUnits)
|
||||||
|
default_payment_terms_days: Mapped[int] = mapped_column(Integer, default=14, nullable=False)
|
||||||
|
vat_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
|
invoice_prefix: Mapped[str] = mapped_column(String(20), default="INV", nullable=False)
|
||||||
|
quotation_prefix: Mapped[str] = mapped_column(String(20), default="Q", nullable=False)
|
||||||
|
document_path: Mapped[str | None] = mapped_column(Text)
|
||||||
|
report_path: Mapped[str | None] = mapped_column(Text)
|
||||||
|
business_descriptor: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
website: Mapped[str | None] = mapped_column(String(300))
|
||||||
|
general_email: Mapped[str | None] = mapped_column(String(320))
|
||||||
|
accounts_email: Mapped[str] = mapped_column(String(320), default="accounts@roborto.net", nullable=False)
|
||||||
|
telephone: Mapped[str | None] = mapped_column(String(80))
|
||||||
|
postal_address: Mapped[str | None] = mapped_column(Text)
|
||||||
|
tax_identifier: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
bank_payment_instructions: Mapped[str | None] = mapped_column(Text)
|
||||||
|
default_income_account_id: Mapped[int | None] = mapped_column(ForeignKey("accounts.id"))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
def __init__(self, **kwargs: object) -> None:
|
||||||
|
kwargs.setdefault("base_currency", "EUR")
|
||||||
|
kwargs.setdefault("default_payment_terms_days", 14)
|
||||||
|
kwargs.setdefault("vat_enabled", False)
|
||||||
|
kwargs.setdefault("invoice_prefix", "INV")
|
||||||
|
kwargs.setdefault("quotation_prefix", "Q")
|
||||||
|
kwargs.setdefault("accounts_email", "accounts@roborto.net")
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
|
class Account(Base):
|
||||||
|
__tablename__ = "accounts"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
account_class: Mapped[AccountClass] = mapped_column(String(20), nullable=False)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
is_financial_account: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
|
financial_account_type: Mapped[str | None] = mapped_column(String(40))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
def __init__(self, **kwargs: object) -> None:
|
||||||
|
kwargs.setdefault("is_active", True)
|
||||||
|
kwargs.setdefault("is_financial_account", False)
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Journal(Base):
|
||||||
|
__tablename__ = "journals"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
journal_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
source: Mapped[str] = mapped_column(String(40), nullable=False, default="service")
|
||||||
|
is_posted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
lines: Mapped[list["JournalLine"]] = relationship(back_populates="journal", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class JournalLine(Base):
|
||||||
|
__tablename__ = "journal_lines"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
description: Mapped[str | None] = mapped_column(String(500))
|
||||||
|
debit: Mapped[Decimal] = mapped_column(MoneyMicroUnits, default=Decimal("0"), nullable=False)
|
||||||
|
credit: Mapped[Decimal] = mapped_column(MoneyMicroUnits, default=Decimal("0"), nullable=False)
|
||||||
|
journal: Mapped[Journal] = relationship(back_populates="lines")
|
||||||
|
|
||||||
|
|
||||||
|
class AuditEvent(Base):
|
||||||
|
__tablename__ = "audit_events"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
record_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
record_id: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
action: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
old_values: Mapped[str | None] = mapped_column(Text)
|
||||||
|
new_values: Mapped[str | None] = mapped_column(Text)
|
||||||
|
reason: Mapped[str | None] = mapped_column(Text)
|
||||||
|
source: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Client(Base):
|
||||||
|
__tablename__ = "clients"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
billing_address: Mapped[str | None] = mapped_column(Text)
|
||||||
|
email: Mapped[str | None] = mapped_column(String(320))
|
||||||
|
phone: Mapped[str | None] = mapped_column(String(80))
|
||||||
|
contact_person: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
tax_identifier: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
default_payment_terms_days: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
default_hourly_rate: Mapped[Decimal | None] = mapped_column("default_hourly_rate_micro", MoneyMicroUnits)
|
||||||
|
notes: Mapped[str | None] = mapped_column(Text)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Supplier(Base):
|
||||||
|
__tablename__ = "suppliers"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
billing_address: Mapped[str | None] = mapped_column(Text)
|
||||||
|
email: Mapped[str | None] = mapped_column(String(320))
|
||||||
|
phone: Mapped[str | None] = mapped_column(String(80))
|
||||||
|
tax_identifier: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
notes: Mapped[str | None] = mapped_column(Text)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
def __init__(self, **kwargs: object) -> None:
|
||||||
|
kwargs.setdefault("is_active", True)
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Project(Base):
|
||||||
|
__tablename__ = "projects"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
code: Mapped[str | None] = mapped_column(String(80), unique=True)
|
||||||
|
hourly_rate: Mapped[Decimal | None] = mapped_column("hourly_rate_micro", MoneyMicroUnits)
|
||||||
|
notes: Mapped[str | None] = mapped_column(Text)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
def __init__(self, **kwargs: object) -> None:
|
||||||
|
kwargs.setdefault("is_active", True)
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Expense(Base):
|
||||||
|
__tablename__ = "expenses"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
expense_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
supplier_id: Mapped[int | None] = mapped_column(ForeignKey("suppliers.id"))
|
||||||
|
expense_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
payment_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
actual_amount: Mapped[Decimal] = mapped_column("actual_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
business_amount: Mapped[Decimal] = mapped_column("business_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
business_use_ppm: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
business_use_basis: Mapped[str | None] = mapped_column(Text)
|
||||||
|
paid_personally: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||||
|
client_id: Mapped[int | None] = mapped_column(ForeignKey("clients.id"))
|
||||||
|
project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id"))
|
||||||
|
is_rechargeable: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||||
|
recharge_invoice_id: Mapped[int | None] = mapped_column(ForeignKey("invoices.id"))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Attachment(Base):
|
||||||
|
__tablename__ = "attachments"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
category: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
original_filename: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
stored_relative_path: Mapped[str] = mapped_column(String(1000), unique=True, nullable=False)
|
||||||
|
record_type: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
record_id: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Tag(Base):
|
||||||
|
__tablename__ = "tags"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class RecordTag(Base):
|
||||||
|
__tablename__ = "record_tags"
|
||||||
|
__table_args__ = (UniqueConstraint("tag_id", "record_type", "record_id"),)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
tag_id: Mapped[int] = mapped_column(ForeignKey("tags.id"), nullable=False)
|
||||||
|
record_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
record_id: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class DocumentCounter(Base):
|
||||||
|
__tablename__ = "document_counters"
|
||||||
|
__table_args__ = (UniqueConstraint("document_type", "calendar_year"),)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
document_type: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
calendar_year: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
next_number: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
|
||||||
|
|
||||||
|
|
||||||
|
class Quotation(Base):
|
||||||
|
__tablename__ = "quotations"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False)
|
||||||
|
project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id"))
|
||||||
|
quotation_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(String(30), nullable=False, default="DRAFT")
|
||||||
|
number: Mapped[str | None] = mapped_column(String(40), unique=True)
|
||||||
|
client_snapshot_json: Mapped[str | None] = mapped_column(Text)
|
||||||
|
net_total: Mapped[Decimal] = mapped_column("net_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_total: Mapped[Decimal] = mapped_column("vat_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
gross_total: Mapped[Decimal] = mapped_column("gross_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
lines: Mapped[list["QuotationLine"]] = relationship(back_populates="quotation", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class QuotationLine(Base):
|
||||||
|
__tablename__ = "quotation_lines"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
quotation_id: Mapped[int] = mapped_column(ForeignKey("quotations.id"), nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
quantity: Mapped[Decimal] = mapped_column("quantity_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
unit: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
unit_price: Mapped[Decimal] = mapped_column("unit_price_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_treatment: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||||
|
income_account_id: Mapped[int | None] = mapped_column(ForeignKey("accounts.id"))
|
||||||
|
net_total: Mapped[Decimal] = mapped_column("net_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_amount: Mapped[Decimal] = mapped_column("vat_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
gross_total: Mapped[Decimal] = mapped_column("gross_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
quotation: Mapped[Quotation] = relationship(back_populates="lines")
|
||||||
|
|
||||||
|
|
||||||
|
class Invoice(Base):
|
||||||
|
__tablename__ = "invoices"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False)
|
||||||
|
project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id"))
|
||||||
|
source_quotation_id: Mapped[int | None] = mapped_column(ForeignKey("quotations.id"))
|
||||||
|
invoice_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
due_date: Mapped[date | None] = mapped_column(Date)
|
||||||
|
status: Mapped[str] = mapped_column(String(30), nullable=False, default="DRAFT")
|
||||||
|
number: Mapped[str | None] = mapped_column(String(40), unique=True)
|
||||||
|
client_snapshot_json: Mapped[str | None] = mapped_column(Text)
|
||||||
|
issue_journal_id: Mapped[int | None] = mapped_column(ForeignKey("journals.id"))
|
||||||
|
void_journal_id: Mapped[int | None] = mapped_column(ForeignKey("journals.id"))
|
||||||
|
voided_on: Mapped[date | None] = mapped_column(Date)
|
||||||
|
net_total: Mapped[Decimal] = mapped_column("net_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_total: Mapped[Decimal] = mapped_column("vat_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
gross_total: Mapped[Decimal] = mapped_column("gross_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
paid_total: Mapped[Decimal] = mapped_column("paid_total_micro", MoneyMicroUnits, nullable=False, default=Decimal("0"))
|
||||||
|
credited_total: Mapped[Decimal] = mapped_column("credited_total_micro", MoneyMicroUnits, nullable=False, default=Decimal("0"))
|
||||||
|
written_off_total: Mapped[Decimal] = mapped_column("written_off_total_micro", MoneyMicroUnits, nullable=False, default=Decimal("0"))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
lines: Mapped[list["InvoiceLine"]] = relationship(back_populates="invoice", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceLine(Base):
|
||||||
|
__tablename__ = "invoice_lines"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
invoice_id: Mapped[int] = mapped_column(ForeignKey("invoices.id"), nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
quantity: Mapped[Decimal] = mapped_column("quantity_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
unit: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
unit_price: Mapped[Decimal] = mapped_column("unit_price_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_treatment: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||||
|
income_account_id: Mapped[int | None] = mapped_column(ForeignKey("accounts.id"))
|
||||||
|
net_total: Mapped[Decimal] = mapped_column("net_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_amount: Mapped[Decimal] = mapped_column("vat_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
gross_total: Mapped[Decimal] = mapped_column("gross_total_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
invoice: Mapped[Invoice] = relationship(back_populates="lines")
|
||||||
|
|
||||||
|
|
||||||
|
class ClientPayment(Base):
|
||||||
|
__tablename__ = "client_payments"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False)
|
||||||
|
payment_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
unapplied_amount: Mapped[Decimal] = mapped_column("unapplied_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
financial_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
receipt_journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
reference: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
notes: Mapped[str | None] = mapped_column(Text)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
allocations: Mapped[list["PaymentAllocation"]] = relationship(back_populates="payment", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentAllocation(Base):
|
||||||
|
__tablename__ = "payment_allocations"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
payment_id: Mapped[int] = mapped_column(ForeignKey("client_payments.id"), nullable=False)
|
||||||
|
invoice_id: Mapped[int] = mapped_column(ForeignKey("invoices.id"), nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
allocation_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
journal_id: Mapped[int | None] = mapped_column(ForeignKey("journals.id"))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
payment: Mapped[ClientPayment] = relationship(back_populates="allocations")
|
||||||
|
|
||||||
|
|
||||||
|
class CreditNote(Base):
|
||||||
|
__tablename__ = "credit_notes"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
invoice_id: Mapped[int] = mapped_column(ForeignKey("invoices.id"), nullable=False)
|
||||||
|
number: Mapped[str] = mapped_column(String(40), unique=True, nullable=False)
|
||||||
|
credit_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class BadDebtWriteOff(Base):
|
||||||
|
__tablename__ = "bad_debt_write_offs"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
invoice_id: Mapped[int] = mapped_column(ForeignKey("invoices.id"), nullable=False)
|
||||||
|
write_off_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class SupplierBill(Base):
|
||||||
|
__tablename__ = "supplier_bills"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
supplier_id: Mapped[int] = mapped_column(ForeignKey("suppliers.id"), nullable=False)
|
||||||
|
bill_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
due_date: Mapped[date | None] = mapped_column(Date)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
paid_total: Mapped[Decimal] = mapped_column("paid_total_micro", MoneyMicroUnits, nullable=False, default=Decimal("0"))
|
||||||
|
status: Mapped[str] = mapped_column(String(30), nullable=False, default="OUTSTANDING")
|
||||||
|
expense_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
supplier_reference: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class SupplierPayment(Base):
|
||||||
|
__tablename__ = "supplier_payments"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
bill_id: Mapped[int] = mapped_column(ForeignKey("supplier_bills.id"), nullable=False)
|
||||||
|
payment_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
financial_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
reference: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class SupplierRefund(Base):
|
||||||
|
__tablename__ = "supplier_refunds"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
bill_id: Mapped[int] = mapped_column(ForeignKey("supplier_bills.id"), nullable=False)
|
||||||
|
refund_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
financial_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
journal_id: Mapped[int] = mapped_column(ForeignKey("journals.id"), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class TimeEntry(Base):
|
||||||
|
__tablename__ = "time_entries"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False)
|
||||||
|
project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id"))
|
||||||
|
entry_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
hours: Mapped[Decimal] = mapped_column("hours_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
billing_rate: Mapped[Decimal] = mapped_column("billing_rate_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
is_billable: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||||
|
invoice_id: Mapped[int | None] = mapped_column(ForeignKey("invoices.id"))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class RecurringInvoiceDefinition(Base):
|
||||||
|
__tablename__ = "recurring_invoice_definitions"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False)
|
||||||
|
project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id"))
|
||||||
|
frequency: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
next_due_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
template_lines_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class RecurringExpenseDefinition(Base):
|
||||||
|
__tablename__ = "recurring_expense_definitions"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
supplier_id: Mapped[int] = mapped_column(ForeignKey("suppliers.id"), nullable=False)
|
||||||
|
frequency: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
next_expected_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
category_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
expected_amount: Mapped[Decimal | None] = mapped_column("expected_amount_micro", MoneyMicroUnits)
|
||||||
|
reconciliation_hints: Mapped[str | None] = mapped_column(Text)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ImportedBankTransaction(Base):
|
||||||
|
__tablename__ = "imported_bank_transactions"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
financial_account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
transaction_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(1000), nullable=False)
|
||||||
|
amount: Mapped[Decimal] = mapped_column("amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
currency: Mapped[str] = mapped_column(String(3), nullable=False, default="EUR")
|
||||||
|
source_format: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
source_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||||
|
raw_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(String(30), nullable=False, default="PENDING")
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ReconciliationMatch(Base):
|
||||||
|
__tablename__ = "reconciliation_matches"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
imported_transaction_id: Mapped[int] = mapped_column(ForeignKey("imported_bank_transactions.id"), nullable=False)
|
||||||
|
record_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
record_id: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
score_ppm: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
status: Mapped[str] = mapped_column(String(30), nullable=False, default="PROPOSED")
|
||||||
|
reason: Mapped[str | None] = mapped_column(Text)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
decided_at: Mapped[datetime | None] = mapped_column(DateTime)
|
||||||
|
|
||||||
|
|
||||||
|
class CurrencySnapshot(Base):
|
||||||
|
__tablename__ = "currency_snapshots"
|
||||||
|
__table_args__ = (UniqueConstraint("record_type","record_id","field_name"),)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
record_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
record_id: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
field_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
original_amount: Mapped[Decimal] = mapped_column("original_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
original_currency: Mapped[str] = mapped_column(String(3), nullable=False)
|
||||||
|
exchange_rate: Mapped[Decimal] = mapped_column("exchange_rate_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
eur_amount: Mapped[Decimal] = mapped_column("eur_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class TaxDetail(Base):
|
||||||
|
__tablename__ = "tax_details"
|
||||||
|
__table_args__ = (UniqueConstraint("record_type","record_id"),)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
record_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
record_id: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
net_amount: Mapped[Decimal] = mapped_column("net_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_rate: Mapped[Decimal] = mapped_column("vat_rate_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_amount: Mapped[Decimal] = mapped_column("vat_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
gross_amount: Mapped[Decimal] = mapped_column("gross_amount_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
vat_treatment: Mapped[str] = mapped_column(String(60), nullable=False)
|
||||||
|
tax_classification: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class AssetRecord(Base):
|
||||||
|
__tablename__ = "asset_records"
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
purchase_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
supplier_id: Mapped[int | None] = mapped_column(ForeignKey("suppliers.id"))
|
||||||
|
original_cost: Mapped[Decimal] = mapped_column("original_cost_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
original_currency: Mapped[str] = mapped_column(String(3), nullable=False)
|
||||||
|
eur_value: Mapped[Decimal] = mapped_column("eur_value_micro", MoneyMicroUnits, nullable=False)
|
||||||
|
business_use_ppm: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
attachment_id: Mapped[int | None] = mapped_column(ForeignKey("attachments.id"))
|
||||||
|
disposal_date: Mapped[date | None] = mapped_column(Date)
|
||||||
|
disposal_proceeds: Mapped[Decimal | None] = mapped_column("disposal_proceeds_micro", MoneyMicroUnits)
|
||||||
|
notes: Mapped[str | None] = mapped_column(Text)
|
||||||
|
tax_treatment: Mapped[str] = mapped_column(String(40), nullable=False, default="REVIEW")
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountingPeriod(Base):
|
||||||
|
__tablename__ = "accounting_periods"
|
||||||
|
__table_args__ = (UniqueConstraint("year","month"),)
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
year: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
month: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(String(20), nullable=False, default="OPEN")
|
||||||
|
closed_at: Mapped[datetime | None] = mapped_column(DateTime)
|
||||||
|
reopened_at: Mapped[datetime | None] = mapped_column(DateTime)
|
||||||
|
backup_path: Mapped[str | None] = mapped_column(Text)
|
||||||
|
|
||||||
|
|
||||||
|
class BusinessLetter(Base):
|
||||||
|
__tablename__="business_letters"
|
||||||
|
id:Mapped[int]=mapped_column(Integer,primary_key=True)
|
||||||
|
letter_date:Mapped[date]=mapped_column(Date,nullable=False)
|
||||||
|
recipient_name:Mapped[str]=mapped_column(String(200),nullable=False)
|
||||||
|
recipient_address:Mapped[str]=mapped_column(Text,nullable=False)
|
||||||
|
recipient_email:Mapped[str|None]=mapped_column(String(320))
|
||||||
|
reference:Mapped[str|None]=mapped_column(String(200))
|
||||||
|
subject:Mapped[str]=mapped_column(String(300),nullable=False)
|
||||||
|
body_text:Mapped[str]=mapped_column(Text,nullable=False)
|
||||||
|
status:Mapped[str]=mapped_column(String(30),nullable=False,default="DRAFT")
|
||||||
|
attachment_id:Mapped[int|None]=mapped_column(ForeignKey("attachments.id"))
|
||||||
|
finalized_at:Mapped[datetime|None]=mapped_column(DateTime)
|
||||||
|
created_at:Mapped[datetime]=mapped_column(DateTime,default=datetime.utcnow,nullable=False)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Exact monetary storage helpers using integer micro-units."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||||
|
from sqlalchemy.types import Integer, TypeDecorator
|
||||||
|
SCALE = 6
|
||||||
|
_FACTOR = Decimal(10) ** SCALE
|
||||||
|
_QUANTUM = Decimal(1) / _FACTOR
|
||||||
|
|
||||||
|
def to_minor_units(value: Decimal) -> int:
|
||||||
|
if not isinstance(value, Decimal):
|
||||||
|
raise TypeError("monetary values must be Decimal instances")
|
||||||
|
try:
|
||||||
|
quantized = value.quantize(_QUANTUM, rounding=ROUND_HALF_UP)
|
||||||
|
except (InvalidOperation, ValueError) as exc:
|
||||||
|
raise ValueError("invalid monetary value") from exc
|
||||||
|
return int(quantized * _FACTOR)
|
||||||
|
|
||||||
|
def from_minor_units(value: int) -> Decimal:
|
||||||
|
if not isinstance(value, int):
|
||||||
|
raise TypeError("stored monetary values must be integers")
|
||||||
|
return (Decimal(value) / _FACTOR).quantize(_QUANTUM)
|
||||||
|
|
||||||
|
class MoneyMicroUnits(TypeDecorator[Decimal]):
|
||||||
|
"""Decimal facade backed by an INTEGER column."""
|
||||||
|
impl = Integer
|
||||||
|
cache_ok = True
|
||||||
|
def process_bind_param(self, value: Decimal | None, dialect) -> int | None:
|
||||||
|
return None if value is None else to_minor_units(value)
|
||||||
|
def process_result_value(self, value: int | None, dialect) -> Decimal | None:
|
||||||
|
return None if value is None else from_minor_units(value)
|
||||||
@@ -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)))
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Application services shared by interfaces."""
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Asset-register recording without automatic allowance advice."""
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal,ROUND_HALF_UP
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import AssetRecord
|
||||||
|
from roborto_accounting.services.tax import TaxClassification
|
||||||
|
|
||||||
|
def record_asset(session:Session,*,purchase_date:date,description:str,original_cost:Decimal,
|
||||||
|
original_currency:str,eur_value:Decimal,business_use_percent:Decimal,
|
||||||
|
supplier_id:int|None=None,attachment_id:int|None=None,notes:str|None=None,
|
||||||
|
tax_treatment:TaxClassification=TaxClassification.REVIEW)->AssetRecord:
|
||||||
|
if not description.strip():raise ValidationError("asset description is required")
|
||||||
|
if not all(isinstance(v,Decimal) for v in (original_cost,eur_value,business_use_percent)):
|
||||||
|
raise ValidationError("asset amounts and percentage must be Decimal")
|
||||||
|
if original_cost<0 or eur_value<0 or business_use_percent<0 or business_use_percent>100:
|
||||||
|
raise ValidationError("asset values or business-use percentage are invalid")
|
||||||
|
currency=original_currency.upper()
|
||||||
|
if len(currency)!=3:raise ValidationError("currency must be a three-letter code")
|
||||||
|
ppm=int((business_use_percent*Decimal("10000")).quantize(Decimal("1"),rounding=ROUND_HALF_UP))
|
||||||
|
asset=AssetRecord(purchase_date=purchase_date,description=description,supplier_id=supplier_id,
|
||||||
|
original_cost=original_cost,original_currency=currency,eur_value=eur_value,business_use_ppm=ppm,
|
||||||
|
attachment_id=attachment_id,notes=notes,tax_treatment=tax_treatment.value)
|
||||||
|
session.add(asset);session.flush();return asset
|
||||||
|
|
||||||
|
def dispose_asset(asset:AssetRecord,*,disposal_date:date,proceeds:Decimal)->None:
|
||||||
|
if asset.disposal_date is not None:raise ValidationError("asset is already disposed")
|
||||||
|
if disposal_date<asset.purchase_date or not isinstance(proceeds,Decimal) or proceeds<0:
|
||||||
|
raise ValidationError("asset disposal details are invalid")
|
||||||
|
asset.disposal_date=disposal_date;asset.disposal_proceeds=proceeds
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""Durable audit event recording."""
|
||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import AuditEvent
|
||||||
|
|
||||||
|
def record_audit(session: Session, *, record_type: str, record_id: str | int,
|
||||||
|
action: str, source: str, reason: str | None = None,
|
||||||
|
old_values: Mapping[str, object] | None = None,
|
||||||
|
new_values: Mapping[str, object] | None = None) -> AuditEvent:
|
||||||
|
if not record_type or not action or not source:
|
||||||
|
raise ValidationError("audit record type, action, and source are required")
|
||||||
|
event = AuditEvent(record_type=record_type, record_id=str(record_id), action=action,
|
||||||
|
source=source, reason=reason,
|
||||||
|
old_values=json.dumps(old_values, sort_keys=True, default=str) if old_values else None,
|
||||||
|
new_values=json.dumps(new_values, sort_keys=True, default=str) if new_values else None)
|
||||||
|
session.add(event)
|
||||||
|
session.flush()
|
||||||
|
return event
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Extensible bank CSV parsing and pending import persistence."""
|
||||||
|
import csv,hashlib,json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Protocol
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import ImportedBankTransaction
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CsvMapping:
|
||||||
|
date_column:str;description_column:str;amount_column:str
|
||||||
|
date_format:str="%Y-%m-%d";currency_column:str|None=None;default_currency:str="EUR"
|
||||||
|
|
||||||
|
class BankParser(Protocol):
|
||||||
|
name:str
|
||||||
|
def parse(self,path:Path)->list[dict[str,str]]:...
|
||||||
|
|
||||||
|
class MappedCsvParser:
|
||||||
|
def __init__(self,name:str,mapping:CsvMapping):self.name=name;self.mapping=mapping
|
||||||
|
def parse(self,path:Path)->list[dict[str,str]]:
|
||||||
|
with path.open(newline="",encoding="utf-8-sig") as handle:return list(csv.DictReader(handle))
|
||||||
|
|
||||||
|
def import_bank_csv(session:Session,*,path:Path,financial_account_id:int,
|
||||||
|
parser:MappedCsvParser)->list[ImportedBankTransaction]:
|
||||||
|
if not path.is_file():raise ValidationError("bank CSV does not exist")
|
||||||
|
created=[];mapping=parser.mapping
|
||||||
|
for row in parser.parse(path):
|
||||||
|
try:
|
||||||
|
tx_date=datetime.strptime(row[mapping.date_column],mapping.date_format).date()
|
||||||
|
amount=Decimal(row[mapping.amount_column])
|
||||||
|
description=row[mapping.description_column].strip()
|
||||||
|
currency=(row[mapping.currency_column] if mapping.currency_column else mapping.default_currency).upper()
|
||||||
|
except (KeyError,ValueError) as exc:raise ValidationError("bank CSV row does not match mapping") from exc
|
||||||
|
raw=json.dumps(row,sort_keys=True);digest=hashlib.sha256(f"{financial_account_id}|{parser.name}|{raw}".encode()).hexdigest()
|
||||||
|
if session.scalar(select(ImportedBankTransaction.id).where(ImportedBankTransaction.source_hash==digest)) is not None:continue
|
||||||
|
item=ImportedBankTransaction(financial_account_id=financial_account_id,transaction_date=tx_date,
|
||||||
|
description=description,amount=amount,currency=currency,source_format=parser.name,
|
||||||
|
source_hash=digest,raw_json=raw,status="PENDING")
|
||||||
|
session.add(item);session.flush();created.append(item)
|
||||||
|
return created
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Initial chart of accounts for a sole-trader software business."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.persistence.models import Account, AccountClass
|
||||||
|
|
||||||
|
DEFAULT_ACCOUNTS = (
|
||||||
|
("1000", "Business bank", AccountClass.ASSET),
|
||||||
|
("1010", "Cash", AccountClass.ASSET),
|
||||||
|
("1020", "PayPal", AccountClass.ASSET),
|
||||||
|
("1030", "Credit card", AccountClass.LIABILITY),
|
||||||
|
("1100", "Accounts receivable", AccountClass.ASSET),
|
||||||
|
("1200", "Equipment and assets", AccountClass.ASSET),
|
||||||
|
("2000", "Accounts payable", AccountClass.LIABILITY),
|
||||||
|
("2100", "VAT/tax liability", AccountClass.LIABILITY),
|
||||||
|
("2110", "Unapplied client credits", AccountClass.LIABILITY),
|
||||||
|
("3000", "Capital introduced", AccountClass.EQUITY),
|
||||||
|
("3100", "Drawings", AccountClass.EQUITY),
|
||||||
|
("4000", "Software development income", AccountClass.INCOME),
|
||||||
|
("4010", "Hosting and maintenance income", AccountClass.INCOME),
|
||||||
|
("4090", "Other income", AccountClass.INCOME),
|
||||||
|
("5000", "Hosting", AccountClass.EXPENSE),
|
||||||
|
("5010", "Domains", AccountClass.EXPENSE),
|
||||||
|
("5020", "Software subscriptions", AccountClass.EXPENSE),
|
||||||
|
("5030", "Equipment and small tools", AccountClass.EXPENSE),
|
||||||
|
("5040", "Advertising", AccountClass.EXPENSE),
|
||||||
|
("5050", "Professional fees", AccountClass.EXPENSE),
|
||||||
|
("5060", "Bank charges", AccountClass.EXPENSE),
|
||||||
|
("5070", "Phone and internet", AccountClass.EXPENSE),
|
||||||
|
("5080", "Travel", AccountClass.EXPENSE),
|
||||||
|
("5090", "Other expenses", AccountClass.EXPENSE),
|
||||||
|
)
|
||||||
|
|
||||||
|
def seed_default_accounts(session: Session) -> list[Account]:
|
||||||
|
existing = {code for (code,) in session.execute(select(Account.code))}
|
||||||
|
created = []
|
||||||
|
for code, name, account_class in DEFAULT_ACCOUNTS:
|
||||||
|
if code not in existing:
|
||||||
|
account = Account(code=code, name=name, account_class=account_class)
|
||||||
|
session.add(account)
|
||||||
|
created.append(account)
|
||||||
|
return created
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Contracts shared by interfaces and application services."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Protocol, TypeVar
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
T = TypeVar("T")
|
||||||
|
class Service(Protocol[T]):
|
||||||
|
def __call__(self, session: Session, **kwargs: object) -> T: ...
|
||||||
|
SessionFactory = Callable[[], Session]
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""Credit-note and explicit bad-debt adjustment services."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import BadDebtWriteOff, CreditNote, DocumentCounter, Invoice
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
from roborto_accounting.services.invoices import outstanding_balance
|
||||||
|
from roborto_accounting.services.journals import post_journal
|
||||||
|
|
||||||
|
def _validate_adjustment(invoice: Invoice, amount: Decimal, reason: str) -> None:
|
||||||
|
if invoice.status not in {"ISSUED", "PARTIALLY_PAID"}:
|
||||||
|
raise ValidationError("adjustments require an issued invoice")
|
||||||
|
if not isinstance(amount, Decimal) or amount <= 0 or amount > outstanding_balance(invoice):
|
||||||
|
raise ValidationError("adjustment must be a positive Decimal within the outstanding balance")
|
||||||
|
if not reason.strip():
|
||||||
|
raise ValidationError("an adjustment reason is required")
|
||||||
|
|
||||||
|
def create_credit_note(session: Session, *, invoice: Invoice, credit_date: date,
|
||||||
|
amount: Decimal, reason: str, receivables_account_id: int,
|
||||||
|
sales_returns_account_id: int) -> CreditNote:
|
||||||
|
_validate_adjustment(invoice, amount, reason)
|
||||||
|
counter=session.scalar(select(DocumentCounter).where(DocumentCounter.document_type=="credit_note",
|
||||||
|
DocumentCounter.calendar_year==credit_date.year))
|
||||||
|
if counter is None:
|
||||||
|
counter=DocumentCounter(document_type="credit_note",calendar_year=credit_date.year,next_number=1)
|
||||||
|
session.add(counter);session.flush()
|
||||||
|
number=f"CN-{credit_date.year}-{counter.next_number:03d}";counter.next_number+=1
|
||||||
|
journal=post_journal(session,journal_date=credit_date,description=f"Credit note {number}: {reason}",
|
||||||
|
lines=[{"account_id":sales_returns_account_id,"debit":amount},
|
||||||
|
{"account_id":receivables_account_id,"credit":amount}],source="credit_note")
|
||||||
|
note=CreditNote(invoice_id=invoice.id,number=number,credit_date=credit_date,
|
||||||
|
amount=amount,reason=reason,journal_id=journal.id)
|
||||||
|
session.add(note);invoice.credited_total+=amount;session.flush()
|
||||||
|
record_audit(session,record_type="invoice",record_id=invoice.id,action="credit_note_issued",
|
||||||
|
source="service",reason=reason,new_values={"credit_note":number,"amount":amount})
|
||||||
|
return note
|
||||||
|
|
||||||
|
def write_off_bad_debt(session: Session, *, invoice: Invoice, write_off_date: date,
|
||||||
|
amount: Decimal, reason: str, receivables_account_id: int,
|
||||||
|
bad_debt_account_id: int) -> BadDebtWriteOff:
|
||||||
|
_validate_adjustment(invoice, amount, reason)
|
||||||
|
journal=post_journal(session,journal_date=write_off_date,description=f"Bad debt: {reason}",
|
||||||
|
lines=[{"account_id":bad_debt_account_id,"debit":amount},
|
||||||
|
{"account_id":receivables_account_id,"credit":amount}],source="bad_debt")
|
||||||
|
event=BadDebtWriteOff(invoice_id=invoice.id,write_off_date=write_off_date,
|
||||||
|
amount=amount,reason=reason,journal_id=journal.id)
|
||||||
|
session.add(event);invoice.written_off_total+=amount;session.flush()
|
||||||
|
record_audit(session,record_type="invoice",record_id=invoice.id,action="bad_debt_written_off",
|
||||||
|
source="service",reason=reason,new_values={"amount":amount})
|
||||||
|
return event
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Historical foreign-currency conversion snapshots."""
|
||||||
|
from decimal import Decimal,ROUND_HALF_UP
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import CurrencySnapshot
|
||||||
|
|
||||||
|
def capture_currency_value(session:Session,*,record_type:str,record_id:str|int,field_name:str,
|
||||||
|
original_amount:Decimal,original_currency:str,
|
||||||
|
exchange_rate:Decimal)->CurrencySnapshot:
|
||||||
|
if not isinstance(original_amount,Decimal) or not isinstance(exchange_rate,Decimal):
|
||||||
|
raise ValidationError("currency amounts and rates must be Decimal")
|
||||||
|
if original_amount<0 or exchange_rate<=0:raise ValidationError("amount cannot be negative and rate must be positive")
|
||||||
|
currency=original_currency.upper()
|
||||||
|
if len(currency)!=3:raise ValidationError("currency must be a three-letter code")
|
||||||
|
eur=(original_amount*exchange_rate).quantize(Decimal("0.000001"),rounding=ROUND_HALF_UP)
|
||||||
|
snapshot=CurrencySnapshot(record_type=record_type,record_id=str(record_id),field_name=field_name,
|
||||||
|
original_amount=original_amount,original_currency=currency,exchange_rate=exchange_rate,eur_amount=eur)
|
||||||
|
session.add(snapshot);session.flush();return snapshot
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Managed supporting-document archive."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from enum import StrEnum
|
||||||
|
from pathlib import Path
|
||||||
|
from shutil import copy2
|
||||||
|
from uuid import uuid4
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Attachment
|
||||||
|
|
||||||
|
class DocumentCategory(StrEnum):
|
||||||
|
RECEIPT = "receipts"
|
||||||
|
SUPPLIER_INVOICE = "supplier_invoices"
|
||||||
|
CLIENT_INVOICE = "client_invoices"
|
||||||
|
CLIENT_QUOTATION = "client_quotations"
|
||||||
|
BANK_STATEMENT = "bank_statements"
|
||||||
|
GENERAL = "general_attachments"
|
||||||
|
BUSINESS_LETTER = "business_letters"
|
||||||
|
|
||||||
|
def archive_document(session: Session, *, source: Path, archive_root: Path,
|
||||||
|
category: DocumentCategory, record_type: str | None = None,
|
||||||
|
record_id: str | int | None = None) -> Attachment:
|
||||||
|
if not source.is_file():
|
||||||
|
raise ValidationError("supporting document does not exist or is not a file")
|
||||||
|
target_dir = archive_root / category.value
|
||||||
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
safe_suffix = source.suffix.lower()[:20]
|
||||||
|
stored_name = f"{uuid4().hex}{safe_suffix}"
|
||||||
|
target = target_dir / stored_name
|
||||||
|
copy2(source, target)
|
||||||
|
attachment = Attachment(category=category.value, original_filename=source.name,
|
||||||
|
stored_relative_path=str(Path(category.value) / stored_name),
|
||||||
|
record_type=record_type,
|
||||||
|
record_id=str(record_id) if record_id is not None else None)
|
||||||
|
session.add(attachment)
|
||||||
|
session.flush()
|
||||||
|
return attachment
|
||||||
|
|
||||||
|
def attachment_exists(attachment: Attachment, archive_root: Path) -> bool:
|
||||||
|
return (archive_root / attachment.stored_relative_path).is_file()
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Core expense, owner-funding, drawings, and transfer workflows."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal, ROUND_HALF_UP
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Expense, Journal
|
||||||
|
from roborto_accounting.services.journals import post_journal
|
||||||
|
|
||||||
|
def _percent_to_ppm(percent: Decimal) -> int:
|
||||||
|
if not isinstance(percent, Decimal) or percent < 0 or percent > 100:
|
||||||
|
raise ValidationError("business-use percentage must be a Decimal from 0 to 100")
|
||||||
|
return int((percent * Decimal("10000")).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
def record_expense(session: Session, *, expense_date: date, description: str,
|
||||||
|
actual_amount: Decimal, business_use_percent: Decimal,
|
||||||
|
expense_account_id: int, payment_account_id: int,
|
||||||
|
personal_portion_account_id: int | None = None,
|
||||||
|
paid_personally: bool = False, supplier_id: int | None = None,
|
||||||
|
business_use_basis: str | None = None, client_id: int | None = None,
|
||||||
|
project_id: int | None = None, is_rechargeable: bool = False) -> Expense:
|
||||||
|
if not isinstance(actual_amount, Decimal) or actual_amount <= 0:
|
||||||
|
raise ValidationError("expense amount must be a positive Decimal")
|
||||||
|
ppm = _percent_to_ppm(business_use_percent)
|
||||||
|
business_amount = (actual_amount * business_use_percent / Decimal("100")).quantize(Decimal("0.000001"), rounding=ROUND_HALF_UP)
|
||||||
|
personal_amount = actual_amount - business_amount
|
||||||
|
if personal_amount and personal_portion_account_id is None:
|
||||||
|
raise ValidationError("mixed-use expenses require a personal-portion account")
|
||||||
|
lines = [{"account_id": expense_account_id, "debit": business_amount}]
|
||||||
|
if personal_amount:
|
||||||
|
lines.append({"account_id": personal_portion_account_id, "debit": personal_amount})
|
||||||
|
lines.append({"account_id": payment_account_id, "credit": actual_amount})
|
||||||
|
journal = post_journal(session, journal_date=expense_date, description=description, lines=lines,
|
||||||
|
source="personal_funds" if paid_personally else "expense")
|
||||||
|
expense = Expense(expense_date=expense_date, description=description,
|
||||||
|
supplier_id=supplier_id, expense_account_id=expense_account_id,
|
||||||
|
payment_account_id=payment_account_id, journal_id=journal.id,
|
||||||
|
actual_amount=actual_amount, business_amount=business_amount,
|
||||||
|
business_use_ppm=ppm, business_use_basis=business_use_basis,
|
||||||
|
paid_personally=paid_personally,client_id=client_id,project_id=project_id,
|
||||||
|
is_rechargeable=is_rechargeable,recharge_invoice_id=None)
|
||||||
|
session.add(expense)
|
||||||
|
session.flush()
|
||||||
|
return expense
|
||||||
|
|
||||||
|
def record_transfer(session: Session, *, transfer_date: date, description: str,
|
||||||
|
amount: Decimal, from_account_id: int, to_account_id: int) -> Journal:
|
||||||
|
if from_account_id == to_account_id:
|
||||||
|
raise ValidationError("transfer accounts must differ")
|
||||||
|
return post_journal(session, journal_date=transfer_date, description=description,
|
||||||
|
lines=[{"account_id": to_account_id, "debit": amount},
|
||||||
|
{"account_id": from_account_id, "credit": amount}], source="transfer")
|
||||||
|
|
||||||
|
def record_owner_movement(session: Session, *, movement_date: date, description: str,
|
||||||
|
amount: Decimal, financial_account_id: int,
|
||||||
|
equity_account_id: int, drawings: bool) -> Journal:
|
||||||
|
lines = ([{"account_id": equity_account_id, "debit": amount},
|
||||||
|
{"account_id": financial_account_id, "credit": amount}]
|
||||||
|
if drawings else
|
||||||
|
[{"account_id": financial_account_id, "debit": amount},
|
||||||
|
{"account_id": equity_account_id, "credit": amount}])
|
||||||
|
return post_journal(session, journal_date=movement_date, description=description,
|
||||||
|
lines=lines, source="drawings" if drawings else "capital")
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Application services for rendering and registering generated sales PDFs."""
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from roborto_accounting.persistence.models import Attachment, BusinessSettings, Invoice, Quotation
|
||||||
|
from roborto_accounting.reporting.documents.sales import render_invoice_pdf, render_quotation_pdf
|
||||||
|
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||||
|
from roborto_accounting.services.documents import DocumentCategory
|
||||||
|
|
||||||
|
|
||||||
|
def _target(archive_root: Path, category: DocumentCategory) -> tuple[Path, Path]:
|
||||||
|
relative = Path(category.value) / f"{uuid4().hex}.pdf"
|
||||||
|
path = archive_root / relative
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
return path, relative
|
||||||
|
|
||||||
|
|
||||||
|
def generate_invoice_document(
|
||||||
|
session: Session, *, invoice: Invoice, settings: BusinessSettings,
|
||||||
|
archive_root: Path, theme: DocumentTheme,
|
||||||
|
) -> Attachment:
|
||||||
|
path, relative = _target(archive_root, DocumentCategory.CLIENT_INVOICE)
|
||||||
|
render_invoice_pdf(path, invoice=invoice, settings=settings, theme=theme)
|
||||||
|
attachment = Attachment(
|
||||||
|
category=DocumentCategory.CLIENT_INVOICE.value,
|
||||||
|
original_filename=f"{invoice.number}.pdf",
|
||||||
|
stored_relative_path=str(relative), record_type="invoice", record_id=str(invoice.id),
|
||||||
|
)
|
||||||
|
session.add(attachment); session.flush(); return attachment
|
||||||
|
|
||||||
|
|
||||||
|
def generate_quotation_document(
|
||||||
|
session: Session, *, quotation: Quotation, settings: BusinessSettings,
|
||||||
|
archive_root: Path, theme: DocumentTheme,
|
||||||
|
) -> Attachment:
|
||||||
|
path, relative = _target(archive_root, DocumentCategory.CLIENT_QUOTATION)
|
||||||
|
render_quotation_pdf(path, quotation=quotation, settings=settings, theme=theme)
|
||||||
|
attachment = Attachment(
|
||||||
|
category=DocumentCategory.CLIENT_QUOTATION.value,
|
||||||
|
original_filename=f"{quotation.number}.pdf",
|
||||||
|
stored_relative_path=str(relative), record_type="quotation", record_id=str(quotation.id),
|
||||||
|
)
|
||||||
|
session.add(attachment); session.flush(); return attachment
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Read-only integrity checks; never repairs accounting data."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.persistence.models import AccountingPeriod,Account,Attachment,ClientPayment,Invoice,Journal,PaymentAllocation,Quotation,SupplierBill,SupplierPayment
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class IntegrityIssue:
|
||||||
|
code:str;record_type:str;record_id:str;message:str
|
||||||
|
|
||||||
|
def check_integrity(session:Session,*,archive_root:Path|None=None)->list[IntegrityIssue]:
|
||||||
|
issues=[]
|
||||||
|
result=session.execute(text("PRAGMA integrity_check")).scalar()
|
||||||
|
if result!="ok":issues.append(IntegrityIssue("SQLITE_INTEGRITY","database","sqlite",str(result)))
|
||||||
|
for row in session.execute(text("PRAGMA foreign_key_check")):
|
||||||
|
issues.append(IntegrityIssue("ORPHANED_FOREIGN_KEY",str(row[0]),str(row[1]),f"foreign key {row[3]}"))
|
||||||
|
for journal in session.query(Journal).all():
|
||||||
|
debits=sum((line.debit for line in journal.lines),Decimal("0"));credits=sum((line.credit for line in journal.lines),Decimal("0"))
|
||||||
|
if debits!=credits:issues.append(IntegrityIssue("UNBALANCED_JOURNAL","journal",str(journal.id),f"debits {debits} != credits {credits}"))
|
||||||
|
for invoice in session.query(Invoice).all():
|
||||||
|
net=sum((line.net_total for line in invoice.lines),Decimal("0"));vat=sum((line.vat_amount for line in invoice.lines),Decimal("0"));gross=sum((line.gross_total for line in invoice.lines),Decimal("0"))
|
||||||
|
if (net,vat,gross)!=(invoice.net_total,invoice.vat_total,invoice.gross_total):
|
||||||
|
issues.append(IntegrityIssue("INVOICE_TOTAL_MISMATCH","invoice",str(invoice.id),"header totals differ from lines"))
|
||||||
|
if invoice.status in {"ISSUED","PARTIALLY_PAID","PAID","VOID"} and invoice.issue_journal_id is None:
|
||||||
|
issues.append(IntegrityIssue("INVOICE_ISSUE_JOURNAL_MISSING","invoice",str(invoice.id),"issued invoice has no issue journal"))
|
||||||
|
allocated=session.query(PaymentAllocation).filter_by(invoice_id=invoice.id).all()
|
||||||
|
if sum((item.amount for item in allocated),Decimal("0"))!=invoice.paid_total:
|
||||||
|
issues.append(IntegrityIssue("INVOICE_PAID_TOTAL_MISMATCH","invoice",str(invoice.id),"payment allocations differ from paid total"))
|
||||||
|
if invoice.status=="VOID":
|
||||||
|
issue=session.get(Journal,invoice.issue_journal_id);reversal=session.get(Journal,invoice.void_journal_id)
|
||||||
|
if issue is None or reversal is None or sorted((line.account_id,line.debit,line.credit) for line in issue.lines)!=sorted((line.account_id,line.credit,line.debit) for line in reversal.lines):
|
||||||
|
issues.append(IntegrityIssue("INVOICE_VOID_REVERSAL_MISMATCH","invoice",str(invoice.id),"void reversal does not mirror issue journal"))
|
||||||
|
for quote in session.query(Quotation).all():
|
||||||
|
net=sum((line.net_total for line in quote.lines),Decimal("0"));vat=sum((line.vat_amount for line in quote.lines),Decimal("0"));gross=sum((line.gross_total for line in quote.lines),Decimal("0"))
|
||||||
|
if (net,vat,gross)!=(quote.net_total,quote.vat_total,quote.gross_total):issues.append(IntegrityIssue("QUOTATION_TOTAL_MISMATCH","quotation",str(quote.id),"header totals differ from lines"))
|
||||||
|
for payment in session.query(ClientPayment).all():
|
||||||
|
allocated=sum((allocation.amount for allocation in payment.allocations),Decimal("0"))
|
||||||
|
if allocated+payment.unapplied_amount!=payment.amount:
|
||||||
|
issues.append(IntegrityIssue("PAYMENT_ALLOCATION_MISMATCH","client_payment",str(payment.id),"allocations plus unapplied credit differ from receipt"))
|
||||||
|
for bill in session.query(SupplierBill).all():
|
||||||
|
paid=sum((payment.amount for payment in session.query(SupplierPayment).filter_by(bill_id=bill.id)),Decimal("0"))
|
||||||
|
if paid!=bill.paid_total:issues.append(IntegrityIssue("SUPPLIER_BILL_PAID_TOTAL_MISMATCH","supplier_bill",str(bill.id),"payments differ from paid total"))
|
||||||
|
accounts={account.id:account for account in session.query(Account).all()}
|
||||||
|
for journal in session.query(Journal).filter_by(source="transfer"):
|
||||||
|
if len(journal.lines)!=2 or any(not accounts.get(line.account_id) or not accounts[line.account_id].is_financial_account for line in journal.lines):issues.append(IntegrityIssue("TRANSFER_CONSISTENCY","journal",str(journal.id),"transfer must contain two financial-account lines"))
|
||||||
|
for period in session.query(AccountingPeriod).filter_by(status="CLOSED"):
|
||||||
|
if not period.backup_path or not Path(period.backup_path).is_file():issues.append(IntegrityIssue("CLOSED_PERIOD_BACKUP_MISSING","accounting_period",f"{period.year:04d}-{period.month:02d}","closed period backup is missing"))
|
||||||
|
if archive_root is not None:
|
||||||
|
for attachment in session.query(Attachment).all():
|
||||||
|
if not (archive_root/attachment.stored_relative_path).is_file():
|
||||||
|
issues.append(IntegrityIssue("ATTACHMENT_MISSING","attachment",str(attachment.id),attachment.stored_relative_path))
|
||||||
|
return issues
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""Invoice drafting, issue snapshots, terms, and derived state."""
|
||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from dataclasses import asdict
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.clients import snapshot_client
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Account,AccountClass,BusinessSettings, Client, DocumentCounter, Invoice, InvoiceLine, Journal,Quotation
|
||||||
|
from roborto_accounting.services.journals import post_journal
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
|
||||||
|
def create_invoice(session: Session, *, settings: BusinessSettings, client: Client,
|
||||||
|
invoice_date: date, lines: list[dict[str, object]], project_id: int | None = None,
|
||||||
|
payment_terms_days: int | None = None, source_quotation_id: int | None = None) -> Invoice:
|
||||||
|
if not lines: raise ValidationError("invoice requires at least one line")
|
||||||
|
terms = payment_terms_days if payment_terms_days is not None else (
|
||||||
|
client.default_payment_terms_days if client.default_payment_terms_days is not None
|
||||||
|
else settings.default_payment_terms_days)
|
||||||
|
if terms < 0: raise ValidationError("payment terms cannot be negative")
|
||||||
|
invoice = Invoice(client_id=client.id, project_id=project_id, source_quotation_id=source_quotation_id,
|
||||||
|
invoice_date=invoice_date, due_date=invoice_date + timedelta(days=terms), status="DRAFT",
|
||||||
|
net_total=Decimal("0"), vat_total=Decimal("0"), gross_total=Decimal("0"), paid_total=Decimal("0"))
|
||||||
|
for item in lines:
|
||||||
|
quantity=item["quantity"]; unit_price=item["unit_price"]; vat_amount=item.get("vat_amount", Decimal("0"))
|
||||||
|
if not all(isinstance(v, Decimal) for v in (quantity, unit_price, vat_amount)):
|
||||||
|
raise ValidationError("invoice quantities and amounts must be Decimal")
|
||||||
|
if quantity <= 0 or unit_price < 0 or vat_amount < 0: raise ValidationError("invoice line values are invalid")
|
||||||
|
net=quantity*unit_price; gross=net+vat_amount
|
||||||
|
invoice.lines.append(InvoiceLine(description=str(item["description"]), quantity=quantity,
|
||||||
|
unit=str(item["unit"]), unit_price=unit_price, vat_treatment=str(item.get("vat_treatment", "NONE")),
|
||||||
|
income_account_id=item.get("income_account_id",settings.default_income_account_id),
|
||||||
|
net_total=net, vat_amount=vat_amount, gross_total=gross))
|
||||||
|
invoice.net_total += net; invoice.vat_total += vat_amount; invoice.gross_total += gross
|
||||||
|
session.add(invoice); session.flush(); return invoice
|
||||||
|
|
||||||
|
def issue_invoice(session: Session, invoice: Invoice, client: Client,*,receivables_account_id:int,
|
||||||
|
vat_liability_account_id:int|None=None) -> Invoice:
|
||||||
|
if invoice.status != "DRAFT" or invoice.number is not None: raise ValidationError("only an unnumbered draft invoice can be issued")
|
||||||
|
if any(line.income_account_id is None for line in invoice.lines):raise ValidationError("every invoice line requires an income account")
|
||||||
|
income_accounts={a.id:a for a in session.scalars(select(Account).where(Account.id.in_([line.income_account_id for line in invoice.lines])))}
|
||||||
|
if len(income_accounts)!=len({line.income_account_id for line in invoice.lines}) or any(a.account_class!=AccountClass.INCOME for a in income_accounts.values()):raise ValidationError("invoice line accounts must be income accounts")
|
||||||
|
receivables=session.get(Account,receivables_account_id)
|
||||||
|
if receivables is None or receivables.account_class!=AccountClass.ASSET:raise ValidationError("receivables account must be an asset")
|
||||||
|
if invoice.vat_total and vat_liability_account_id is None:raise ValidationError("VAT invoices require a VAT liability account")
|
||||||
|
year=invoice.invoice_date.year
|
||||||
|
counter=session.scalar(select(DocumentCounter).where(DocumentCounter.document_type=="invoice", DocumentCounter.calendar_year==year))
|
||||||
|
if counter is None:
|
||||||
|
counter=DocumentCounter(document_type="invoice", calendar_year=year, next_number=1); session.add(counter); session.flush()
|
||||||
|
invoice.number=f"INV-{year}-{counter.next_number:03d}"; counter.next_number += 1
|
||||||
|
invoice.client_snapshot_json=json.dumps(asdict(snapshot_client(client)), sort_keys=True); invoice.status="ISSUED"
|
||||||
|
totals:dict[int,Decimal]={}
|
||||||
|
for line in invoice.lines:totals[line.income_account_id]=totals.get(line.income_account_id,Decimal("0"))+line.net_total
|
||||||
|
lines=[{"account_id":receivables_account_id,"debit":invoice.gross_total}]+[{"account_id":account_id,"credit":amount} for account_id,amount in totals.items()]
|
||||||
|
if invoice.vat_total:lines.append({"account_id":vat_liability_account_id,"credit":invoice.vat_total})
|
||||||
|
invoice.issue_journal_id=post_journal(session,journal_date=invoice.invoice_date,description=f"Invoice {invoice.number}",lines=lines,source="invoice").id
|
||||||
|
session.flush(); return invoice
|
||||||
|
|
||||||
|
def outstanding_balance(invoice: Invoice) -> Decimal:
|
||||||
|
return invoice.gross_total - invoice.paid_total - invoice.credited_total - invoice.written_off_total
|
||||||
|
|
||||||
|
def is_overdue(invoice: Invoice, today: date) -> bool:
|
||||||
|
return invoice.status in {"ISSUED", "PARTIALLY_PAID"} and outstanding_balance(invoice) > 0 and invoice.due_date is not None and today > invoice.due_date
|
||||||
|
|
||||||
|
def void_invoice(session:Session,invoice:Invoice,*,void_date:date,reason:str)->Invoice:
|
||||||
|
if invoice.status!="ISSUED" or invoice.issue_journal_id is None:raise ValidationError("only an issued, unadjusted invoice can be voided")
|
||||||
|
if invoice.paid_total or invoice.credited_total or invoice.written_off_total:raise ValidationError("an adjusted invoice cannot be voided")
|
||||||
|
if not reason.strip():raise ValidationError("invoice void reason is required")
|
||||||
|
issue=session.get(Journal,invoice.issue_journal_id)
|
||||||
|
reversal=post_journal(session,journal_date=void_date,description=f"Void {invoice.number}: {reason}",
|
||||||
|
lines=[{"account_id":line.account_id,"debit":line.credit,"credit":line.debit,"description":line.description} for line in issue.lines],source="invoice_void")
|
||||||
|
invoice.status="VOID";invoice.void_journal_id=reversal.id;invoice.voided_on=void_date
|
||||||
|
record_audit(session,record_type="invoice",record_id=invoice.id,action="voided",source="service",reason=reason,new_values={"void_journal_id":reversal.id})
|
||||||
|
session.flush();return invoice
|
||||||
|
|
||||||
|
def invoice_from_quotation(session: Session, *, settings: BusinessSettings, client: Client,
|
||||||
|
quotation: Quotation, invoice_date: date,
|
||||||
|
payment_terms_days: int | None = None) -> Invoice:
|
||||||
|
if quotation.status != "ACCEPTED":
|
||||||
|
raise ValidationError("only an accepted quotation can be converted")
|
||||||
|
existing = session.scalar(select(Invoice).where(Invoice.source_quotation_id == quotation.id))
|
||||||
|
if existing is not None:
|
||||||
|
raise ValidationError("quotation has already been converted")
|
||||||
|
lines = [{"description": line.description, "quantity": line.quantity,
|
||||||
|
"unit": line.unit, "unit_price": line.unit_price,
|
||||||
|
"vat_treatment": line.vat_treatment, "vat_amount": line.vat_amount}
|
||||||
|
| {"income_account_id":line.income_account_id}
|
||||||
|
for line in quotation.lines]
|
||||||
|
return create_invoice(session, settings=settings, client=client,
|
||||||
|
invoice_date=invoice_date, lines=lines,
|
||||||
|
project_id=quotation.project_id,
|
||||||
|
payment_terms_days=payment_terms_days,
|
||||||
|
source_quotation_id=quotation.id)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Application service for balanced double-entry journal posting."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Account, Journal, JournalLine
|
||||||
|
from roborto_accounting.services.periods import ensure_period_open
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
|
||||||
|
def post_journal(session: Session, *, journal_date: date, description: str,
|
||||||
|
lines: list[dict[str, object]], source: str = "service") -> Journal:
|
||||||
|
ensure_period_open(session, journal_date)
|
||||||
|
if not description.strip():
|
||||||
|
raise ValidationError("journal description is required")
|
||||||
|
if len(lines) < 2:
|
||||||
|
raise ValidationError("a journal requires at least two lines")
|
||||||
|
account_ids = {int(line["account_id"]) for line in lines}
|
||||||
|
accounts = {account.id: account for account in session.scalars(select(Account).where(Account.id.in_(account_ids)))}
|
||||||
|
if len(accounts) != len(account_ids) or any(not account.is_active for account in accounts.values()):
|
||||||
|
raise ValidationError("journal references a missing or inactive account")
|
||||||
|
total_debit = Decimal("0")
|
||||||
|
total_credit = Decimal("0")
|
||||||
|
journal = Journal(journal_date=journal_date, description=description, source=source, is_posted=True)
|
||||||
|
for item in lines:
|
||||||
|
debit = item.get("debit", Decimal("0"))
|
||||||
|
credit = item.get("credit", Decimal("0"))
|
||||||
|
if not isinstance(debit, Decimal) or not isinstance(credit, Decimal):
|
||||||
|
raise ValidationError("journal amounts must be Decimal values")
|
||||||
|
if debit < 0 or credit < 0 or (debit and credit):
|
||||||
|
raise ValidationError("each line must contain either a non-negative debit or credit")
|
||||||
|
if not debit and not credit:
|
||||||
|
raise ValidationError("journal lines must contain an amount")
|
||||||
|
total_debit += debit
|
||||||
|
total_credit += credit
|
||||||
|
journal.lines.append(JournalLine(account_id=int(item["account_id"]), description=item.get("description"), debit=debit, credit=credit))
|
||||||
|
if total_debit != total_credit:
|
||||||
|
raise ValidationError("journal debits and credits must balance")
|
||||||
|
session.add(journal)
|
||||||
|
session.flush()
|
||||||
|
return journal
|
||||||
|
|
||||||
|
def post_manual_journal(session:Session,*,journal_date:date,description:str,reason:str,
|
||||||
|
lines:list[dict[str,object]],source:str="cli")->Journal:
|
||||||
|
if not reason.strip():raise ValidationError("manual journal reason is required")
|
||||||
|
journal=post_journal(session,journal_date=journal_date,description=description,lines=lines,source="manual_journal")
|
||||||
|
record_audit(session,record_type="journal",record_id=journal.id,action="manual_journal_posted",
|
||||||
|
source=source,reason=reason,new_values={"description":description})
|
||||||
|
return journal
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Persist, finalize, and archive stable business letters."""
|
||||||
|
from datetime import date,datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Attachment,BusinessLetter,BusinessSettings
|
||||||
|
from roborto_accounting.reporting.documents.letters import render_letter_pdf
|
||||||
|
from roborto_accounting.reporting.documents.theme import DocumentTheme
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
from roborto_accounting.services.documents import DocumentCategory
|
||||||
|
|
||||||
|
def create_letter(session:Session,*,letter_date:date,recipient_name:str,recipient_address:str,
|
||||||
|
subject:str,body_text:str,recipient_email:str|None=None,
|
||||||
|
reference:str|None=None)->BusinessLetter:
|
||||||
|
if not all(value.strip() for value in (recipient_name,recipient_address,subject,body_text)):raise ValidationError("letter recipient, address, subject, and body are required")
|
||||||
|
letter=BusinessLetter(letter_date=letter_date,recipient_name=recipient_name.strip(),recipient_address=recipient_address.strip(),recipient_email=recipient_email,reference=reference,subject=subject.strip(),body_text=body_text.strip(),status="DRAFT")
|
||||||
|
session.add(letter);session.flush();return letter
|
||||||
|
|
||||||
|
def finalize_letter(session:Session,*,letter:BusinessLetter,settings:BusinessSettings,
|
||||||
|
archive_root:Path,theme:DocumentTheme)->Attachment:
|
||||||
|
if letter.status!="DRAFT" or letter.attachment_id is not None:raise ValidationError("only an unfinalized letter draft can be finalized")
|
||||||
|
relative=Path(DocumentCategory.BUSINESS_LETTER.value)/f"{uuid4().hex}.pdf";target=archive_root/relative
|
||||||
|
render_letter_pdf(target,letter=letter,settings=settings,theme=theme)
|
||||||
|
attachment=Attachment(category=DocumentCategory.BUSINESS_LETTER.value,original_filename=f"letter-{letter.id}.pdf",stored_relative_path=str(relative),record_type="business_letter",record_id=str(letter.id))
|
||||||
|
session.add(attachment);session.flush();letter.attachment_id=attachment.id;letter.status="FINALIZED";letter.finalized_at=datetime.utcnow()
|
||||||
|
record_audit(session,record_type="business_letter",record_id=letter.id,action="finalized",source="service",new_values={"attachment_id":attachment.id})
|
||||||
|
session.flush();return attachment
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Supplier bill, payment, and linked refund workflows."""
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import SupplierBill,SupplierPayment,SupplierRefund
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
from roborto_accounting.services.journals import post_journal
|
||||||
|
|
||||||
|
def bill_outstanding(bill: SupplierBill) -> Decimal:
|
||||||
|
return bill.amount-bill.paid_total
|
||||||
|
|
||||||
|
def record_supplier_bill(session: Session, *, supplier_id: int, bill_date: date,
|
||||||
|
description: str, amount: Decimal, expense_account_id: int,
|
||||||
|
payable_account_id: int, due_date: date | None = None,
|
||||||
|
supplier_reference: str | None = None) -> SupplierBill:
|
||||||
|
if not isinstance(amount,Decimal) or amount<=0: raise ValidationError("bill amount must be a positive Decimal")
|
||||||
|
if not description.strip(): raise ValidationError("bill description is required")
|
||||||
|
journal=post_journal(session,journal_date=bill_date,description=description,
|
||||||
|
lines=[{"account_id":expense_account_id,"debit":amount},{"account_id":payable_account_id,"credit":amount}],source="supplier_bill")
|
||||||
|
bill=SupplierBill(supplier_id=supplier_id,bill_date=bill_date,due_date=due_date,
|
||||||
|
description=description,amount=amount,paid_total=Decimal("0"),status="OUTSTANDING",
|
||||||
|
expense_account_id=expense_account_id,journal_id=journal.id,supplier_reference=supplier_reference)
|
||||||
|
session.add(bill);session.flush();return bill
|
||||||
|
|
||||||
|
def pay_supplier_bill(session: Session, *, bill: SupplierBill, payment_date: date,
|
||||||
|
amount: Decimal, payable_account_id: int,
|
||||||
|
financial_account_id: int, reference: str | None = None) -> SupplierPayment:
|
||||||
|
if not isinstance(amount,Decimal) or amount<=0 or amount>bill_outstanding(bill):
|
||||||
|
raise ValidationError("payment must be positive and no more than the bill balance")
|
||||||
|
journal=post_journal(session,journal_date=payment_date,description=f"Supplier payment for bill {bill.id}",
|
||||||
|
lines=[{"account_id":payable_account_id,"debit":amount},{"account_id":financial_account_id,"credit":amount}],source="supplier_payment")
|
||||||
|
payment=SupplierPayment(bill_id=bill.id,payment_date=payment_date,amount=amount,
|
||||||
|
financial_account_id=financial_account_id,journal_id=journal.id,reference=reference)
|
||||||
|
session.add(payment);bill.paid_total+=amount
|
||||||
|
bill.status="PAID" if bill_outstanding(bill)==0 else "PARTIALLY_PAID"
|
||||||
|
session.flush();return payment
|
||||||
|
|
||||||
|
def record_supplier_refund(session: Session, *, bill: SupplierBill, refund_date: date,
|
||||||
|
amount: Decimal, financial_account_id: int, reason: str) -> SupplierRefund:
|
||||||
|
if not isinstance(amount,Decimal) or amount<=0 or amount>bill.paid_total:
|
||||||
|
raise ValidationError("refund must be positive and no more than paid total")
|
||||||
|
if not reason.strip(): raise ValidationError("refund reason is required")
|
||||||
|
journal=post_journal(session,journal_date=refund_date,description=f"Supplier refund: {reason}",
|
||||||
|
lines=[{"account_id":financial_account_id,"debit":amount},{"account_id":bill.expense_account_id,"credit":amount}],source="supplier_refund")
|
||||||
|
refund=SupplierRefund(bill_id=bill.id,refund_date=refund_date,amount=amount,
|
||||||
|
financial_account_id=financial_account_id,reason=reason,journal_id=journal.id)
|
||||||
|
session.add(refund);session.flush()
|
||||||
|
record_audit(session,record_type="supplier_bill",record_id=bill.id,action="refund_recorded",
|
||||||
|
source="service",reason=reason,new_values={"amount":amount})
|
||||||
|
return refund
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""Client cash receipts, invoice allocations, and unapplied credit."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import ClientPayment, Invoice, PaymentAllocation
|
||||||
|
from roborto_accounting.services.invoices import outstanding_balance
|
||||||
|
from roborto_accounting.services.journals import post_journal
|
||||||
|
|
||||||
|
def _positive_amount(amount: Decimal) -> None:
|
||||||
|
if not isinstance(amount, Decimal) or amount <= 0:
|
||||||
|
raise ValidationError("payment amount must be a positive Decimal")
|
||||||
|
|
||||||
|
def _update_invoice_state(invoice: Invoice) -> None:
|
||||||
|
balance = outstanding_balance(invoice)
|
||||||
|
if balance == 0:
|
||||||
|
invoice.status = "PAID"
|
||||||
|
elif invoice.paid_total > 0:
|
||||||
|
invoice.status = "PARTIALLY_PAID"
|
||||||
|
|
||||||
|
def record_invoice_payment(session: Session, *, invoice: Invoice, payment_date: date,
|
||||||
|
amount: Decimal, financial_account_id: int,
|
||||||
|
receivables_account_id: int, client_credit_account_id: int,
|
||||||
|
reference: str | None = None, notes: str | None = None) -> ClientPayment:
|
||||||
|
_positive_amount(amount)
|
||||||
|
if invoice.status not in {"ISSUED", "PARTIALLY_PAID"}:
|
||||||
|
raise ValidationError("payments require an issued invoice with an outstanding balance")
|
||||||
|
balance = outstanding_balance(invoice)
|
||||||
|
if balance <= 0:
|
||||||
|
raise ValidationError("invoice has no outstanding balance")
|
||||||
|
allocated = min(amount, balance)
|
||||||
|
unapplied = amount - allocated
|
||||||
|
lines: list[dict[str, object]] = [{"account_id": financial_account_id, "debit": amount}]
|
||||||
|
if allocated:
|
||||||
|
lines.append({"account_id": receivables_account_id, "credit": allocated})
|
||||||
|
if unapplied:
|
||||||
|
lines.append({"account_id": client_credit_account_id, "credit": unapplied})
|
||||||
|
journal = post_journal(session, journal_date=payment_date,
|
||||||
|
description=f"Client payment for {invoice.number or invoice.id}",
|
||||||
|
lines=lines, source="client_payment")
|
||||||
|
payment = ClientPayment(client_id=invoice.client_id, payment_date=payment_date,
|
||||||
|
amount=amount, unapplied_amount=unapplied,
|
||||||
|
financial_account_id=financial_account_id,
|
||||||
|
receipt_journal_id=journal.id, reference=reference, notes=notes)
|
||||||
|
session.add(payment); session.flush()
|
||||||
|
payment.allocations.append(PaymentAllocation(payment_id=payment.id, invoice_id=invoice.id,
|
||||||
|
amount=allocated, allocation_date=payment_date, journal_id=journal.id))
|
||||||
|
invoice.paid_total += allocated
|
||||||
|
_update_invoice_state(invoice)
|
||||||
|
session.flush()
|
||||||
|
return payment
|
||||||
|
|
||||||
|
def allocate_client_credit(session: Session, *, payment: ClientPayment, invoice: Invoice,
|
||||||
|
allocation_date: date, amount: Decimal,
|
||||||
|
receivables_account_id: int, client_credit_account_id: int) -> PaymentAllocation:
|
||||||
|
_positive_amount(amount)
|
||||||
|
if payment.client_id != invoice.client_id:
|
||||||
|
raise ValidationError("client credit can only be allocated to the same client")
|
||||||
|
if invoice.status not in {"ISSUED", "PARTIALLY_PAID"}:
|
||||||
|
raise ValidationError("credit requires an issued invoice with an outstanding balance")
|
||||||
|
if amount > payment.unapplied_amount or amount > outstanding_balance(invoice):
|
||||||
|
raise ValidationError("credit allocation exceeds available credit or invoice balance")
|
||||||
|
journal = post_journal(session, journal_date=allocation_date,
|
||||||
|
description=f"Apply client credit to {invoice.number or invoice.id}",
|
||||||
|
lines=[{"account_id": client_credit_account_id, "debit": amount},
|
||||||
|
{"account_id": receivables_account_id, "credit": amount}], source="client_credit")
|
||||||
|
allocation = PaymentAllocation(payment_id=payment.id, invoice_id=invoice.id,
|
||||||
|
amount=amount, allocation_date=allocation_date,
|
||||||
|
journal_id=journal.id)
|
||||||
|
session.add(allocation)
|
||||||
|
payment.unapplied_amount -= amount
|
||||||
|
invoice.paid_total += amount
|
||||||
|
_update_invoice_state(invoice)
|
||||||
|
session.flush()
|
||||||
|
return allocation
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Accounting period locks with SQLite-safe pre-close backups."""
|
||||||
|
from datetime import date,datetime
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3,uuid
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import AccountingPeriod
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
|
||||||
|
def backup_sqlite(source:Path,backup_dir:Path)->Path:
|
||||||
|
if not source.is_file():raise ValidationError("SQLite database file does not exist")
|
||||||
|
backup_dir.mkdir(parents=True,exist_ok=True)
|
||||||
|
target=backup_dir/f"accounts-{datetime.utcnow():%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:8]}.sqlite"
|
||||||
|
with sqlite3.connect(source) as src,sqlite3.connect(target) as dst:src.backup(dst)
|
||||||
|
return target
|
||||||
|
|
||||||
|
def ensure_period_open(session:Session,transaction_date:date)->None:
|
||||||
|
period=session.scalar(select(AccountingPeriod).where(AccountingPeriod.year==transaction_date.year,
|
||||||
|
AccountingPeriod.month==transaction_date.month))
|
||||||
|
if period is not None and period.status=="CLOSED":raise ValidationError("accounting period is closed")
|
||||||
|
|
||||||
|
def close_period(session:Session,*,year:int,month:int,database_path:Path,backup_dir:Path)->AccountingPeriod:
|
||||||
|
if month<1 or month>12:raise ValidationError("month must be from 1 to 12")
|
||||||
|
period=session.scalar(select(AccountingPeriod).where(AccountingPeriod.year==year,AccountingPeriod.month==month))
|
||||||
|
if period is not None and period.status=="CLOSED":raise ValidationError("accounting period is already closed")
|
||||||
|
backup=backup_sqlite(database_path,backup_dir)
|
||||||
|
if period is None:period=AccountingPeriod(year=year,month=month);session.add(period);session.flush()
|
||||||
|
period.status="CLOSED";period.closed_at=datetime.utcnow();period.backup_path=str(backup)
|
||||||
|
record_audit(session,record_type="accounting_period",record_id=f"{year:04d}-{month:02d}",
|
||||||
|
action="closed",source="service",new_values={"backup_path":str(backup)})
|
||||||
|
return period
|
||||||
|
|
||||||
|
def reopen_period(session:Session,period:AccountingPeriod,*,reason:str)->None:
|
||||||
|
if period.status!="CLOSED" or not reason.strip():raise ValidationError("closed period and reopen reason required")
|
||||||
|
period.status="OPEN";period.reopened_at=datetime.utcnow()
|
||||||
|
record_audit(session,record_type="accounting_period",record_id=f"{period.year:04d}-{period.month:02d}",
|
||||||
|
action="reopened",source="service",reason=reason)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""Pre-trading classification without tax-advice assumptions."""
|
||||||
|
from datetime import date
|
||||||
|
from sqlalchemy import Select, select
|
||||||
|
from roborto_accounting.persistence.models import BusinessSettings, Expense
|
||||||
|
|
||||||
|
def is_pre_trading(transaction_date: date, commencement_date: date | None) -> bool:
|
||||||
|
return commencement_date is not None and transaction_date < commencement_date
|
||||||
|
|
||||||
|
def pre_trading_expenses(settings: BusinessSettings) -> Select[tuple[Expense]]:
|
||||||
|
if settings.commencement_date is None:
|
||||||
|
return select(Expense).where(False)
|
||||||
|
return select(Expense).where(Expense.expense_date < settings.commencement_date)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Quotation drafting, numbering, and issue snapshots."""
|
||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from dataclasses import asdict
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.clients import snapshot_client
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Client, DocumentCounter, Quotation, QuotationLine
|
||||||
|
|
||||||
|
def create_quotation(session: Session, *, client: Client, quotation_date: date,
|
||||||
|
lines: list[dict[str, object]], project_id: int | None = None) -> Quotation:
|
||||||
|
if not lines:
|
||||||
|
raise ValidationError("quotation requires at least one line")
|
||||||
|
quote = Quotation(client_id=client.id, project_id=project_id, quotation_date=quotation_date,
|
||||||
|
status="DRAFT", net_total=Decimal("0"), vat_total=Decimal("0"), gross_total=Decimal("0"))
|
||||||
|
for item in lines:
|
||||||
|
quantity = item["quantity"]; unit_price = item["unit_price"]
|
||||||
|
vat_amount = item.get("vat_amount", Decimal("0"))
|
||||||
|
if not all(isinstance(value, Decimal) for value in (quantity, unit_price, vat_amount)):
|
||||||
|
raise ValidationError("quotation quantities and amounts must be Decimal")
|
||||||
|
if quantity <= 0 or unit_price < 0 or vat_amount < 0:
|
||||||
|
raise ValidationError("quotation line values are invalid")
|
||||||
|
net = quantity * unit_price; gross = net + vat_amount
|
||||||
|
line = QuotationLine(description=str(item["description"]), quantity=quantity,
|
||||||
|
unit=str(item["unit"]), unit_price=unit_price,
|
||||||
|
income_account_id=item.get("income_account_id"),
|
||||||
|
vat_treatment=str(item.get("vat_treatment", "NONE")), net_total=net,
|
||||||
|
vat_amount=vat_amount, gross_total=gross)
|
||||||
|
quote.lines.append(line); quote.net_total += net; quote.vat_total += vat_amount; quote.gross_total += gross
|
||||||
|
session.add(quote); session.flush(); return quote
|
||||||
|
|
||||||
|
def issue_quotation(session: Session, quote: Quotation, client: Client) -> Quotation:
|
||||||
|
if quote.status != "DRAFT" or quote.number is not None:
|
||||||
|
raise ValidationError("only an unnumbered draft quotation can be issued")
|
||||||
|
year = quote.quotation_date.year
|
||||||
|
counter = session.scalar(select(DocumentCounter).where(
|
||||||
|
DocumentCounter.document_type == "quotation", DocumentCounter.calendar_year == year))
|
||||||
|
if counter is None:
|
||||||
|
counter = DocumentCounter(document_type="quotation", calendar_year=year, next_number=1)
|
||||||
|
session.add(counter); session.flush()
|
||||||
|
quote.number = f"Q-{year}-{counter.next_number:03d}"
|
||||||
|
counter.next_number += 1
|
||||||
|
quote.client_snapshot_json = json.dumps(asdict(snapshot_client(client)), sort_keys=True)
|
||||||
|
quote.status = "ISSUED"
|
||||||
|
session.flush(); return quote
|
||||||
|
|
||||||
|
def accept_quotation(session:Session,quote:Quotation)->Quotation:
|
||||||
|
if quote.status!="ISSUED":raise ValidationError("only an issued quotation can be accepted")
|
||||||
|
quote.status="ACCEPTED";session.flush();return quote
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""Billing-rate resolution shared by time and sales workflows."""
|
||||||
|
from decimal import Decimal
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import BusinessSettings, Client, Project
|
||||||
|
|
||||||
|
def resolve_billing_rate(*, settings: BusinessSettings, client: Client,
|
||||||
|
project: Project | None = None,
|
||||||
|
entry_override: Decimal | None = None) -> Decimal:
|
||||||
|
candidates = (entry_override,
|
||||||
|
project.hourly_rate if project is not None else None,
|
||||||
|
client.default_hourly_rate,
|
||||||
|
settings.default_hourly_rate)
|
||||||
|
rate = next((value for value in candidates if value is not None), None)
|
||||||
|
if rate is None:
|
||||||
|
raise ValidationError("no billing rate is configured")
|
||||||
|
if not isinstance(rate, Decimal):
|
||||||
|
raise ValidationError("billing rates must be Decimal values")
|
||||||
|
if rate < 0:
|
||||||
|
raise ValidationError("billing rates cannot be negative")
|
||||||
|
return Decimal(rate)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""Rechargeable-expense discovery and invoice assignment."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Expense,Invoice
|
||||||
|
|
||||||
|
def uninvoiced_rechargeable_expenses(session: Session, *, client_id: int,
|
||||||
|
project_id: int | None = None) -> list[Expense]:
|
||||||
|
query=select(Expense).where(Expense.client_id==client_id,Expense.is_rechargeable.is_(True),
|
||||||
|
Expense.recharge_invoice_id.is_(None))
|
||||||
|
if project_id is not None: query=query.where(Expense.project_id==project_id)
|
||||||
|
return list(session.scalars(query.order_by(Expense.expense_date,Expense.id)))
|
||||||
|
|
||||||
|
def assign_recharges_to_invoice(session: Session, *, invoice: Invoice,
|
||||||
|
expenses: list[Expense]) -> None:
|
||||||
|
if invoice.status!="DRAFT": raise ValidationError("recharges can only be assigned to a draft invoice")
|
||||||
|
if any(not expense.is_rechargeable or expense.recharge_invoice_id is not None or expense.client_id!=invoice.client_id for expense in expenses):
|
||||||
|
raise ValidationError("expense is not eligible for this invoice")
|
||||||
|
for expense in expenses: expense.recharge_invoice_id=invoice.id
|
||||||
|
session.flush()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Explicit bank matching and reconciliation state."""
|
||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import ImportedBankTransaction,ReconciliationMatch
|
||||||
|
from roborto_accounting.services.audit import record_audit
|
||||||
|
|
||||||
|
def propose_match(session:Session,*,imported:ImportedBankTransaction,record_type:str,
|
||||||
|
record_id:str|int,score_ppm:int,reason:str|None=None)->ReconciliationMatch:
|
||||||
|
if score_ppm<0 or score_ppm>1_000_000:raise ValidationError("match score must be between 0 and 1,000,000")
|
||||||
|
match=ReconciliationMatch(imported_transaction_id=imported.id,record_type=record_type,
|
||||||
|
record_id=str(record_id),score_ppm=score_ppm,status="PROPOSED",reason=reason)
|
||||||
|
session.add(match);session.flush();return match
|
||||||
|
|
||||||
|
def approve_match(session:Session,match:ReconciliationMatch,*,reason:str|None=None)->None:
|
||||||
|
if match.status!="PROPOSED":raise ValidationError("only proposed matches can be approved")
|
||||||
|
imported=session.get(ImportedBankTransaction,match.imported_transaction_id)
|
||||||
|
if imported is None or imported.status=="RECONCILED":raise ValidationError("transaction is already reconciled or missing")
|
||||||
|
approved=session.scalar(select(ReconciliationMatch.id).where(
|
||||||
|
ReconciliationMatch.imported_transaction_id==match.imported_transaction_id,
|
||||||
|
ReconciliationMatch.status=="APPROVED"))
|
||||||
|
if approved is not None:raise ValidationError("transaction already has an approved match")
|
||||||
|
match.status="APPROVED";match.reason=reason or match.reason;match.decided_at=datetime.utcnow();imported.status="RECONCILED"
|
||||||
|
record_audit(session,record_type="bank_import",record_id=imported.id,action="reconciled",source="service",
|
||||||
|
reason=match.reason,new_values={"record_type":match.record_type,"record_id":match.record_id})
|
||||||
|
|
||||||
|
def reject_match(match:ReconciliationMatch,*,reason:str)->None:
|
||||||
|
if match.status!="PROPOSED" or not reason.strip():raise ValidationError("proposed match and rejection reason required")
|
||||||
|
match.status="REJECTED";match.reason=reason;match.decided_at=datetime.utcnow()
|
||||||
|
|
||||||
|
def manually_reconcile(session:Session,*,imported:ImportedBankTransaction,record_type:str,
|
||||||
|
record_id:str|int,reason:str)->ReconciliationMatch:
|
||||||
|
if not reason.strip():raise ValidationError("manual reconciliation reason is required")
|
||||||
|
match=propose_match(session,imported=imported,record_type=record_type,record_id=record_id,
|
||||||
|
score_ppm=1_000_000,reason=reason)
|
||||||
|
approve_match(session,match,reason=reason);return match
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Reusable application services for core business-record maintenance."""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import Client, Project, Supplier
|
||||||
|
|
||||||
|
|
||||||
|
def create_client(session: Session, *, name: str, billing_address: str | None = None,
|
||||||
|
email: str | None = None, phone: str | None = None,
|
||||||
|
contact_person: str | None = None, tax_identifier: str | None = None,
|
||||||
|
payment_terms_days: int | None = None, hourly_rate: Decimal | None = None,
|
||||||
|
notes: str | None = None) -> Client:
|
||||||
|
if not name.strip(): raise ValidationError("client name is required")
|
||||||
|
if payment_terms_days is not None and payment_terms_days < 0: raise ValidationError("payment terms cannot be negative")
|
||||||
|
client=Client(name=name.strip(),billing_address=billing_address,email=email,phone=phone,
|
||||||
|
contact_person=contact_person,tax_identifier=tax_identifier,
|
||||||
|
default_payment_terms_days=payment_terms_days,default_hourly_rate=hourly_rate,notes=notes)
|
||||||
|
session.add(client);session.flush();return client
|
||||||
|
|
||||||
|
|
||||||
|
def create_supplier(session: Session, *, name: str, billing_address: str | None = None,
|
||||||
|
email: str | None = None, phone: str | None = None,
|
||||||
|
tax_identifier: str | None = None, notes: str | None = None) -> Supplier:
|
||||||
|
if not name.strip(): raise ValidationError("supplier name is required")
|
||||||
|
supplier=Supplier(name=name.strip(),billing_address=billing_address,email=email,phone=phone,
|
||||||
|
tax_identifier=tax_identifier,notes=notes)
|
||||||
|
session.add(supplier);session.flush();return supplier
|
||||||
|
|
||||||
|
|
||||||
|
def create_project(session: Session, *, client_id: int, name: str, code: str | None = None,
|
||||||
|
hourly_rate: Decimal | None = None, notes: str | None = None) -> Project:
|
||||||
|
if not name.strip(): raise ValidationError("project name is required")
|
||||||
|
if session.get(Client,client_id) is None: raise ValidationError("client not found")
|
||||||
|
project=Project(client_id=client_id,name=name.strip(),code=code,hourly_rate=hourly_rate,notes=notes)
|
||||||
|
session.add(project);session.flush();return project
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Advisory recurring definitions; never automatic financial events."""
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from roborto_accounting.persistence.models import BusinessSettings,Client,RecurringExpenseDefinition,RecurringInvoiceDefinition
|
||||||
|
from roborto_accounting.services.invoices import create_invoice
|
||||||
|
|
||||||
|
def create_recurring_invoice_definition(session:Session,*,client_id:int,next_due_date:date,
|
||||||
|
frequency:str,template_lines:list[dict[str,str]],project_id:int|None=None)->RecurringInvoiceDefinition:
|
||||||
|
definition=RecurringInvoiceDefinition(client_id=client_id,project_id=project_id,frequency=frequency,
|
||||||
|
next_due_date=next_due_date,template_lines_json=json.dumps(template_lines,sort_keys=True),is_active=True)
|
||||||
|
session.add(definition);session.flush();return definition
|
||||||
|
|
||||||
|
def create_recurring_expense_definition(session:Session,*,supplier_id:int,next_expected_date:date,
|
||||||
|
frequency:str,category_account_id:int,expected_amount:Decimal|None=None,
|
||||||
|
reconciliation_hints:str|None=None)->RecurringExpenseDefinition:
|
||||||
|
definition=RecurringExpenseDefinition(supplier_id=supplier_id,frequency=frequency,next_expected_date=next_expected_date,
|
||||||
|
category_account_id=category_account_id,expected_amount=expected_amount,reconciliation_hints=reconciliation_hints,is_active=True)
|
||||||
|
session.add(definition);session.flush();return definition
|
||||||
|
|
||||||
|
def due_invoice_definitions(session: Session, as_of: date) -> list[RecurringInvoiceDefinition]:
|
||||||
|
return list(session.scalars(select(RecurringInvoiceDefinition).where(
|
||||||
|
RecurringInvoiceDefinition.is_active.is_(True),RecurringInvoiceDefinition.next_due_date<=as_of)))
|
||||||
|
|
||||||
|
def prepare_recurring_invoice_draft(session: Session, *, definition: RecurringInvoiceDefinition,
|
||||||
|
settings: BusinessSettings, client: Client, invoice_date: date):
|
||||||
|
raw=json.loads(definition.template_lines_json)
|
||||||
|
lines=[{**line,"quantity":Decimal(line["quantity"]),"unit_price":Decimal(line["unit_price"]),
|
||||||
|
"vat_amount":Decimal(line.get("vat_amount","0"))} for line in raw]
|
||||||
|
return create_invoice(session,settings=settings,client=client,invoice_date=invoice_date,
|
||||||
|
lines=lines,project_id=definition.project_id)
|
||||||
|
|
||||||
|
def due_expense_definitions(session: Session, as_of: date) -> list[RecurringExpenseDefinition]:
|
||||||
|
return list(session.scalars(select(RecurringExpenseDefinition).where(
|
||||||
|
RecurringExpenseDefinition.is_active.is_(True),RecurringExpenseDefinition.next_expected_date<=as_of)))
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Typed, non-secret business-setting updates."""
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal,InvalidOperation
|
||||||
|
|
||||||
|
from roborto_accounting.domain.errors import ValidationError
|
||||||
|
from roborto_accounting.persistence.models import BusinessSettings
|
||||||
|
|
||||||
|
TEXT_FIELDS={"trading_name","business_descriptor","website","general_email","accounts_email","telephone","postal_address","tax_identifier","bank_payment_instructions","document_path","report_path","invoice_prefix","quotation_prefix"}
|
||||||
|
|
||||||
|
def update_business_setting(settings:BusinessSettings,*,field:str,value:str)->None:
|
||||||
|
if field in TEXT_FIELDS:
|
||||||
|
if field in {"accounts_email","invoice_prefix","quotation_prefix"} and not value.strip():raise ValidationError(f"{field} cannot be empty")
|
||||||
|
setattr(settings,field,value or None);return
|
||||||
|
if field=="commencement_date":
|
||||||
|
try:settings.commencement_date=None if value.lower() in {"unset","none",""} else date.fromisoformat(value)
|
||||||
|
except ValueError as exc:raise ValidationError("commencement_date must be YYYY-MM-DD or unset") from exc
|
||||||
|
return
|
||||||
|
if field=="default_hourly_rate":
|
||||||
|
try:rate=Decimal(value)
|
||||||
|
except InvalidOperation as exc:raise ValidationError("default_hourly_rate must be an exact decimal") from exc
|
||||||
|
if rate<0:raise ValidationError("default_hourly_rate cannot be negative")
|
||||||
|
settings.default_hourly_rate=rate;return
|
||||||
|
if field=="default_payment_terms_days":
|
||||||
|
try:terms=int(value)
|
||||||
|
except ValueError as exc:raise ValidationError("payment terms must be an integer") from exc
|
||||||
|
if terms<0:raise ValidationError("payment terms cannot be negative")
|
||||||
|
settings.default_payment_terms_days=terms;return
|
||||||
|
if field=="vat_enabled":
|
||||||
|
normalized=value.lower()
|
||||||
|
if normalized not in {"true","false","yes","no","1","0"}:raise ValidationError("vat_enabled must be true or false")
|
||||||
|
settings.vat_enabled=normalized in {"true","yes","1"};return
|
||||||
|
if field=="base_currency":
|
||||||
|
if value.upper()!="EUR":raise ValidationError("v1 base currency must remain EUR")
|
||||||
|
settings.base_currency="EUR";return
|
||||||
|
raise ValidationError("setting is not editable with this command")
|
||||||