feat(commerce): implement monthly reset invoice numbering format INV-MMM-YYYY-00001
This commit is contained in:
parent
694ab9b01b
commit
50538bb64f
|
|
@ -0,0 +1,41 @@
|
|||
"""add invoice monthly sequences table
|
||||
|
||||
Revision ID: 0003_add_invoice_monthly_sequences
|
||||
Revises: 0002_add_template_search_flags
|
||||
Create Date: 2026-10-20
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "0003_add_invoice_monthly_sequences"
|
||||
down_revision: str | None = "0002_add_template_search_flags"
|
||||
branch_labels: Sequence[str] | None = None
|
||||
depends_on: Sequence[str] | None = None
|
||||
|
||||
COMMERCE_SCHEMA = "commerce"
|
||||
TABLE_NAME = "invoice_monthly_sequences"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
tables = inspector.get_table_names(schema=COMMERCE_SCHEMA)
|
||||
if TABLE_NAME not in tables:
|
||||
op.create_table(
|
||||
TABLE_NAME,
|
||||
sa.Column("year_month", sa.String(length=7), nullable=False),
|
||||
sa.Column("last_serial", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
|
||||
sa.PrimaryKeyConstraint("year_month"),
|
||||
schema=COMMERCE_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table(TABLE_NAME, schema=COMMERCE_SCHEMA)
|
||||
|
|
@ -41,6 +41,7 @@ from .commerce import (
|
|||
Coupon,
|
||||
PaymentTransaction,
|
||||
Invoice,
|
||||
InvoiceMonthlySequence,
|
||||
CouponRedemption,
|
||||
RefundDecision,
|
||||
)
|
||||
|
|
@ -95,6 +96,7 @@ __all__ = [
|
|||
"Coupon",
|
||||
"PaymentTransaction",
|
||||
"Invoice",
|
||||
"InvoiceMonthlySequence",
|
||||
"CouponRedemption",
|
||||
"RefundDecision",
|
||||
"UserActivityLog",
|
||||
|
|
|
|||
|
|
@ -279,6 +279,15 @@ class Invoice(Base):
|
|||
applied_coupon: Mapped[Coupon | None] = relationship()
|
||||
|
||||
|
||||
class InvoiceMonthlySequence(Base):
|
||||
__tablename__ = "invoice_monthly_sequences"
|
||||
__table_args__ = {"schema": COMMERCE_SCHEMA}
|
||||
|
||||
year_month: Mapped[str] = mapped_column(String(7), primary_key=True)
|
||||
last_serial: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
|
||||
|
||||
|
||||
class CouponRedemption(Base):
|
||||
__tablename__ = "coupon_redemptions"
|
||||
__table_args__ = (UniqueConstraint("coupon_id", "user_id", name="uq_coupon_user"), {"schema": COMMERCE_SCHEMA})
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ from app.db.models import (
|
|||
)
|
||||
from ..schema import AdminRefundRequest, AdminRefundResponse, AdminSyncResponse
|
||||
from app.features.email import send_invoice_email
|
||||
from app.features.payments import get_razorpay_service
|
||||
from app.features.payments import generate_next_invoice_number, get_razorpay_service
|
||||
|
||||
|
||||
class AdminPaymentService:
|
||||
|
|
@ -173,10 +173,11 @@ class AdminPaymentService:
|
|||
discount = Decimal(str(meta.get("total_discounts", 0)))
|
||||
user = (await self.session.execute(select(AppUser).where(AppUser.id == sub.user_id))).scalar_one()
|
||||
|
||||
invoice_number = await generate_next_invoice_number(self.session, dt=now)
|
||||
self.session.add(
|
||||
Invoice(
|
||||
payment_transaction_id=tx.id,
|
||||
invoice_number=f"INV-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}",
|
||||
invoice_number=invoice_number,
|
||||
billing_name=user.display_name or user.email,
|
||||
billing_email=user.email,
|
||||
billing_address="Synced from Razorpay",
|
||||
|
|
@ -298,16 +299,15 @@ class AdminPaymentService:
|
|||
except Exception:
|
||||
pass
|
||||
|
||||
if not inv_id:
|
||||
inv_id = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
|
||||
|
||||
# Always return our internal branded Acupedia Tax Invoice view URL
|
||||
url = f"/api/admin/payments/{payment_id}/invoice/view"
|
||||
|
||||
if invoice:
|
||||
if not invoice.invoice_number or invoice.invoice_number.startswith("Tx:"):
|
||||
invoice.invoice_number = inv_id
|
||||
invoice.invoice_number = await generate_next_invoice_number(self.session)
|
||||
inv_number = invoice.invoice_number
|
||||
else:
|
||||
inv_number = await generate_next_invoice_number(self.session)
|
||||
amount = Decimal(str(payment.get("amount", 0))) / 100
|
||||
curr = str(payment.get("currency", "INR")).upper()
|
||||
taxable = (amount / Decimal("1.0236") * Decimal("0.02")).quantize(Decimal("0.01")) if curr == "INR" else (amount / Decimal("1.03") * Decimal("0.03")).quantize(Decimal("0.01"))
|
||||
|
|
@ -316,7 +316,7 @@ class AdminPaymentService:
|
|||
self.session.add(
|
||||
Invoice(
|
||||
payment_transaction_id=tx.id,
|
||||
invoice_number=inv_id,
|
||||
invoice_number=inv_number,
|
||||
billing_name=customer["name"],
|
||||
billing_email=customer["email"],
|
||||
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}" if profile else "Not Configured",
|
||||
|
|
@ -331,7 +331,7 @@ class AdminPaymentService:
|
|||
)
|
||||
)
|
||||
await self.session.commit()
|
||||
return url, inv_id, customer["email"]
|
||||
return url, inv_number, customer["email"]
|
||||
|
||||
async def share_invoice(self, payment_id: str) -> dict:
|
||||
url, num, email = await self.get_or_create_invoice(payment_id)
|
||||
|
|
@ -379,8 +379,9 @@ class AdminPaymentService:
|
|||
|
||||
cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else (user.country if user and user.country else "Digital Access")
|
||||
|
||||
inv_number = (invoice.invoice_number if invoice else None) or f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
|
||||
inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else (tx.created_at.strftime("%B %d, %Y") if tx and tx.created_at else datetime.now(timezone.utc).strftime("%B %d, %Y"))
|
||||
now = datetime.now(timezone.utc)
|
||||
inv_number = (invoice.invoice_number if invoice else None) or f"INV-{now.strftime('%b').upper()}-{now.strftime('%Y')}-PREVIEW"
|
||||
inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else (tx.created_at.strftime("%B %d, %Y") if tx and tx.created_at else now.strftime("%B %d, %Y"))
|
||||
|
||||
currency = (invoice.currency_code if invoice else None) or (tx.currency if tx else None) or str(rzp_payment.get("currency", "USD")).upper()
|
||||
curr_symbol = "$" if currency == "USD" else ("₹" if currency == "INR" else f"{currency} ")
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from app.db.models import AccessPlan, AccessPlanModule, AppUser, Invoice, Paymen
|
|||
from app.features.cart.repository import CartRepository
|
||||
from app.features.cart.schema import CartCalculationRequest
|
||||
from app.features.cart.service import CartService
|
||||
from app.features.payments import get_razorpay_service
|
||||
from app.features.payments import generate_next_invoice_number, get_razorpay_service
|
||||
from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest
|
||||
|
||||
class CheckoutService:
|
||||
|
|
@ -129,7 +129,7 @@ class CheckoutService:
|
|||
|
||||
async def _create_invoice(self, rzp, tx: PaymentTransaction, profile: UserBillingProfile, payment: dict, plan_names: list[str], meta: dict) -> tuple[str, str | None]:
|
||||
currency = tx.currency.upper()
|
||||
inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{tx.gateway_transaction_id[-6:].upper()}"
|
||||
inv_number = await generate_next_invoice_number(self.session)
|
||||
try:
|
||||
rzp.client.invoice.create(data={"type":"invoice","customer":{"name":profile.billing_name,"email":profile.billing_email, **({"contact": profile.billing_phone} if profile.billing_phone else {})},"line_items":[{"name": (", ".join(plan_names) or "Access Subscription")[:250],"amount": int(Decimal(tx.amount)*100),"currency":currency,"quantity":1}],"email_notify":False,"sms_notify":False,"notes":{"payment_id":tx.gateway_transaction_id}})
|
||||
except Exception:
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
from .razorpay import RazorpayService, get_razorpay_service
|
||||
from .pricing import PricingEngine, PricingItem, PricingCoupon
|
||||
from .invoice_service import generate_next_invoice_number
|
||||
|
||||
__all__ = ["RazorpayService", "get_razorpay_service", "PricingEngine", "PricingItem", "PricingCoupon", "generate_next_invoice_number"]
|
||||
|
||||
__all__ = ["RazorpayService", "get_razorpay_service", "PricingEngine", "PricingItem", "PricingCoupon"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
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}"
|
||||
|
|
@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
|
||||
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
|
||||
from app.db.models import AccessPlan, AccessPlanModule, Invoice, PaymentTransaction, UserEntitlement, UserSubscription
|
||||
from app.features.payments import generate_next_invoice_number
|
||||
|
||||
|
||||
class RazorpayWebhookService:
|
||||
|
|
@ -94,7 +95,7 @@ class RazorpayWebhookService:
|
|||
gst = Decimal(str(meta.get("gst_amount", "0")))
|
||||
base = Decimal(str(meta.get("base_subtotal", amount)))
|
||||
discount = Decimal(str(meta.get("total_discounts", "0")))
|
||||
invoice_number = f"INV-{now.strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
|
||||
invoice_number = await generate_next_invoice_number(self.session, dt=now)
|
||||
self.session.add(Invoice(
|
||||
payment_transaction_id=transaction.id,
|
||||
invoice_number=invoice_number,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,63 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from app.features.payments.invoice_service import generate_next_invoice_number
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_next_invoice_number_format_and_padding() -> None:
|
||||
session = AsyncMock()
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one = MagicMock(return_value=1)
|
||||
session.execute = AsyncMock(return_value=mock_result)
|
||||
|
||||
dt = datetime(2026, 10, 15, 12, 0, 0, tzinfo=timezone.utc)
|
||||
inv_number = await generate_next_invoice_number(session, dt=dt)
|
||||
|
||||
assert inv_number == "INV-OCT-2026-00001"
|
||||
|
||||
# Verify query and parameters
|
||||
call_args = session.execute.call_args
|
||||
assert call_args is not None
|
||||
assert call_args[0][1] == {"ym": "2026-10"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_next_invoice_number_higher_serial() -> None:
|
||||
session = AsyncMock()
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one = MagicMock(return_value=42)
|
||||
session.execute = AsyncMock(return_value=mock_result)
|
||||
|
||||
dt = datetime(2026, 10, 20, 14, 0, 0, tzinfo=timezone.utc)
|
||||
inv_number = await generate_next_invoice_number(session, dt=dt)
|
||||
|
||||
assert inv_number == "INV-OCT-2026-00042"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_next_invoice_number_monthly_reset() -> None:
|
||||
session = AsyncMock()
|
||||
|
||||
# In November, sequence starts at 1
|
||||
mock_result_nov = MagicMock()
|
||||
mock_result_nov.scalar_one = MagicMock(return_value=1)
|
||||
session.execute = AsyncMock(return_value=mock_result_nov)
|
||||
|
||||
dt_nov = datetime(2026, 11, 1, 0, 0, 0, tzinfo=timezone.utc)
|
||||
inv_number_nov = await generate_next_invoice_number(session, dt=dt_nov)
|
||||
assert inv_number_nov == "INV-NOV-2026-00001"
|
||||
assert session.execute.call_args[0][1] == {"ym": "2026-11"}
|
||||
|
||||
# In January next year
|
||||
mock_result_jan = MagicMock()
|
||||
mock_result_jan.scalar_one = MagicMock(return_value=1)
|
||||
session.execute = AsyncMock(return_value=mock_result_jan)
|
||||
|
||||
dt_jan = datetime(2027, 1, 15, 0, 0, 0, tzinfo=timezone.utc)
|
||||
inv_number_jan = await generate_next_invoice_number(session, dt=dt_jan)
|
||||
assert inv_number_jan == "INV-JAN-2027-00001"
|
||||
assert session.execute.call_args[0][1] == {"ym": "2027-01"}
|
||||
Loading…
Reference in New Issue