Skip to content

Commit 02adc42

Browse files
cheddarfoxclaude
andcommitted
feat(db): add CreditLedgerEntry model and migration [REN-75]
Add credit_ledger_entries table for tracking user credit transactions. Includes TransactionDirection and TransactionSource PostgreSQL native ENUM types, idempotency constraint (reference_id + direction), and non-negative balance CHECK constraint. - Add CreditLedgerEntry SQLAlchemy model to core/models/base.py - Add Alembic migration 0002 (revision chain: 0001_baseline -> 0002_credit_ledger) - Export new model and enums from core/models/__init__.py - Indexes on user_id and reference_id for query performance Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 27d174a commit 02adc42

3 files changed

Lines changed: 263 additions & 5 deletions

File tree

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
# Copyright 2025 ByBren, LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Add credit_ledger_entries table.
16+
17+
Revision ID: 0002_credit_ledger
18+
Revises: 0001_baseline
19+
Create Date: 2026-03-09
20+
"""
21+
22+
from collections.abc import Sequence
23+
24+
import sqlalchemy as sa
25+
26+
from alembic import op
27+
28+
# revision identifiers, used by Alembic.
29+
revision: str = "0002_credit_ledger"
30+
down_revision: str | None = "0001_baseline"
31+
branch_labels: str | Sequence[str] | None = None
32+
depends_on: str | Sequence[str] | None = None
33+
34+
# PostgreSQL native ENUM types
35+
transaction_direction = sa.Enum(
36+
"CREDIT",
37+
"DEBIT",
38+
name="transaction_direction",
39+
)
40+
transaction_source = sa.Enum(
41+
"STRIPE",
42+
"USAGE",
43+
"ADJUSTMENT",
44+
"REFUND",
45+
name="transaction_source",
46+
)
47+
48+
49+
def upgrade() -> None:
50+
"""Create credit_ledger_entries table with enum types and constraints."""
51+
# -- enum types -----------------------------------------------------------
52+
transaction_direction.create(op.get_bind(), checkfirst=True)
53+
transaction_source.create(op.get_bind(), checkfirst=True)
54+
55+
# -- credit_ledger_entries ------------------------------------------------
56+
op.create_table(
57+
"credit_ledger_entries",
58+
sa.Column(
59+
"id",
60+
sa.Uuid(),
61+
primary_key=True,
62+
server_default=sa.text("gen_random_uuid()"),
63+
nullable=False,
64+
),
65+
sa.Column(
66+
"user_id",
67+
sa.Uuid(),
68+
sa.ForeignKey("users.id", ondelete="CASCADE"),
69+
nullable=False,
70+
),
71+
sa.Column(
72+
"amount",
73+
sa.Numeric(precision=12, scale=4),
74+
nullable=False,
75+
),
76+
sa.Column(
77+
"direction",
78+
transaction_direction,
79+
nullable=False,
80+
),
81+
sa.Column(
82+
"source",
83+
transaction_source,
84+
nullable=False,
85+
),
86+
sa.Column(
87+
"reference_id",
88+
sa.String(length=255),
89+
nullable=False,
90+
),
91+
sa.Column(
92+
"balance_after",
93+
sa.Numeric(precision=12, scale=4),
94+
nullable=False,
95+
),
96+
sa.Column(
97+
"description",
98+
sa.Text(),
99+
nullable=True,
100+
),
101+
sa.Column(
102+
"created_at",
103+
sa.DateTime(timezone=True),
104+
server_default=sa.text("now()"),
105+
nullable=False,
106+
),
107+
sa.Column(
108+
"updated_at",
109+
sa.DateTime(timezone=True),
110+
server_default=sa.text("now()"),
111+
nullable=False,
112+
),
113+
sa.UniqueConstraint(
114+
"reference_id",
115+
"direction",
116+
name="uq_ledger_reference_direction",
117+
),
118+
sa.CheckConstraint(
119+
"balance_after >= 0",
120+
name="ck_ledger_balance_non_negative",
121+
),
122+
)
123+
op.create_index(
124+
"ix_credit_ledger_entries_user_id",
125+
"credit_ledger_entries",
126+
["user_id"],
127+
)
128+
op.create_index(
129+
"ix_credit_ledger_entries_reference_id",
130+
"credit_ledger_entries",
131+
["reference_id"],
132+
)
133+
134+
135+
def downgrade() -> None:
136+
"""Drop credit_ledger_entries table and enum types."""
137+
op.drop_index(
138+
"ix_credit_ledger_entries_reference_id",
139+
table_name="credit_ledger_entries",
140+
)
141+
op.drop_index(
142+
"ix_credit_ledger_entries_user_id",
143+
table_name="credit_ledger_entries",
144+
)
145+
op.drop_table("credit_ledger_entries")
146+
transaction_source.drop(op.get_bind(), checkfirst=True)
147+
transaction_direction.drop(op.get_bind(), checkfirst=True)

‎core/models/__init__.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,20 @@
1818
"""
1919

2020
from core.database import Base, BaseModel
21-
from core.models.base import Project, User
21+
from core.models.base import (
22+
CreditLedgerEntry,
23+
Project,
24+
TransactionDirection,
25+
TransactionSource,
26+
User,
27+
)
2228

23-
__all__ = ["Base", "BaseModel", "Project", "User"]
29+
__all__ = [
30+
"Base",
31+
"BaseModel",
32+
"CreditLedgerEntry",
33+
"Project",
34+
"TransactionDirection",
35+
"TransactionSource",
36+
"User",
37+
]

‎core/models/base.py‎

Lines changed: 100 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,24 @@
1414

1515
"""Core domain models for RenderTrust.
1616
17-
Defines the foundational User and Project models.
17+
Defines the foundational User, Project, and CreditLedgerEntry models.
1818
All models use UUID primary keys and include created_at/updated_at timestamps.
1919
"""
2020

21+
import enum
2122
import uuid
22-
23-
from sqlalchemy import Boolean, ForeignKey, String, Text
23+
from decimal import Decimal
24+
25+
from sqlalchemy import (
26+
Boolean,
27+
CheckConstraint,
28+
Enum,
29+
ForeignKey,
30+
Numeric,
31+
String,
32+
Text,
33+
UniqueConstraint,
34+
)
2435
from sqlalchemy.orm import Mapped, mapped_column, relationship
2536

2637
from core.database import BaseModel
@@ -108,3 +119,89 @@ class Project(BaseModel):
108119

109120
def __repr__(self) -> str:
110121
return f"<Project(id={self.id}, name={self.name})>"
122+
123+
124+
class TransactionDirection(enum.Enum):
125+
"""Direction of a credit ledger transaction."""
126+
127+
CREDIT = "CREDIT"
128+
DEBIT = "DEBIT"
129+
130+
131+
class TransactionSource(enum.Enum):
132+
"""Source/reason for a credit ledger transaction."""
133+
134+
STRIPE = "STRIPE"
135+
USAGE = "USAGE"
136+
ADJUSTMENT = "ADJUSTMENT"
137+
REFUND = "REFUND"
138+
139+
140+
class CreditLedgerEntry(BaseModel):
141+
"""Credit ledger entry tracking user credit transactions.
142+
143+
Implements double-entry style tracking with idempotency via
144+
UNIQUE(reference_id, direction) constraint.
145+
146+
Attributes:
147+
user_id: FK to the owning User.
148+
amount: Transaction amount (positive value).
149+
direction: CREDIT or DEBIT.
150+
source: Origin of the transaction (STRIPE, USAGE, ADJUSTMENT, REFUND).
151+
reference_id: External reference for idempotency (e.g. Stripe charge ID).
152+
balance_after: User's credit balance after this transaction.
153+
description: Optional human-readable description.
154+
user: Relationship to the User who owns this entry.
155+
"""
156+
157+
__tablename__ = "credit_ledger_entries"
158+
__table_args__ = (
159+
UniqueConstraint(
160+
"reference_id",
161+
"direction",
162+
name="uq_ledger_reference_direction",
163+
),
164+
CheckConstraint(
165+
"balance_after >= 0",
166+
name="ck_ledger_balance_non_negative",
167+
),
168+
)
169+
170+
user_id: Mapped[uuid.UUID] = mapped_column(
171+
ForeignKey("users.id", ondelete="CASCADE"),
172+
nullable=False,
173+
index=True,
174+
)
175+
amount: Mapped[Decimal] = mapped_column(
176+
Numeric(12, 4),
177+
nullable=False,
178+
)
179+
direction: Mapped[TransactionDirection] = mapped_column(
180+
Enum(TransactionDirection, name="transaction_direction"),
181+
nullable=False,
182+
)
183+
source: Mapped[TransactionSource] = mapped_column(
184+
Enum(TransactionSource, name="transaction_source"),
185+
nullable=False,
186+
)
187+
reference_id: Mapped[str] = mapped_column(
188+
String(255),
189+
nullable=False,
190+
index=True,
191+
)
192+
balance_after: Mapped[Decimal] = mapped_column(
193+
Numeric(12, 4),
194+
nullable=False,
195+
)
196+
description: Mapped[str | None] = mapped_column(
197+
Text,
198+
nullable=True,
199+
)
200+
201+
user: Mapped["User"] = relationship("User")
202+
203+
def __repr__(self) -> str:
204+
return (
205+
f"<CreditLedgerEntry(id={self.id}, user_id={self.user_id}, "
206+
f"amount={self.amount}, direction={self.direction.value})>"
207+
)

0 commit comments

Comments
 (0)