32 lines
1.1 KiB
Python
32 lines
1.1 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
async def generate_next_invoice_number(session: AsyncSession, dt: datetime | None = None) -> str:
|
|
"""Generate the next sequential invoice number for the month.
|
|
|
|
Format: INV-{MONTH}-{YEAR}-{SERIAL} (e.g., INV-OCT-2026-00001).
|
|
The serial number is 5 digits zero-padded and resets to 00001 every month.
|
|
"""
|
|
now = dt or datetime.now(timezone.utc)
|
|
year_month = now.strftime("%Y-%m")
|
|
month_abbr = now.strftime("%b").upper()
|
|
year_str = now.strftime("%Y")
|
|
|
|
stmt = text(
|
|
"""
|
|
INSERT INTO commerce.invoice_monthly_sequences (year_month, last_serial, updated_at)
|
|
VALUES (:ym, 1, now())
|
|
ON CONFLICT (year_month)
|
|
DO UPDATE SET last_serial = commerce.invoice_monthly_sequences.last_serial + 1,
|
|
updated_at = now()
|
|
RETURNING last_serial;
|
|
"""
|
|
)
|
|
result = await session.execute(stmt, {"ym": year_month})
|
|
serial = result.scalar_one()
|
|
return f"INV-{month_abbr}-{year_str}-{serial:05d}"
|