allowances 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,90 @@
1
+ """
2
+ Read-mostly admin for inspecting the ledger.
3
+
4
+ Balances are meant to move through :mod:`allowances_django.shortcuts`, which writes a transaction
5
+ for every change. Editing a balance directly in the admin leaves no trace of why it moved, so the
6
+ transaction and archive tables are registered read-only — visible for support work, not editable.
7
+ """
8
+
9
+ from django.contrib import admin
10
+
11
+ from allowances.types import SubjectRef
12
+ from allowances_django.models import (
13
+ FulfillmentRecord,
14
+ LicenseModifier,
15
+ Transaction,
16
+ TransactionArchive,
17
+ Wallet,
18
+ WalletArchive,
19
+ )
20
+ from allowances_django.subjects import resolve
21
+
22
+
23
+ class SubjectDisplayMixin:
24
+ @admin.display(description="Subject")
25
+ def subject(self, obj):
26
+ resolved = resolve(SubjectRef(obj.subject_type, obj.subject_id))
27
+ return resolved if resolved is not None else f"{obj.subject_type}:{obj.subject_id} (missing)"
28
+
29
+
30
+ @admin.register(Wallet)
31
+ class WalletAdmin(SubjectDisplayMixin, admin.ModelAdmin):
32
+ list_display = ("id", "subject", "wallet_type", "currency", "balance", "valid_from", "valid_until")
33
+ list_filter = ("wallet_type", "currency")
34
+ search_fields = ("subject_type", "subject_id", "currency")
35
+ date_hierarchy = "created_at"
36
+
37
+
38
+ @admin.register(FulfillmentRecord)
39
+ class FulfillmentRecordAdmin(admin.ModelAdmin):
40
+ list_display = ("guid", "created_at")
41
+ search_fields = ("guid",)
42
+ date_hierarchy = "created_at"
43
+
44
+
45
+ @admin.register(Transaction)
46
+ class TransactionAdmin(admin.ModelAdmin):
47
+ list_display = ("id", "wallet", "kind", "amount", "feature", "created_at")
48
+ list_filter = ("kind", "feature")
49
+ search_fields = ("feature", "object_type", "object_id")
50
+ date_hierarchy = "created_at"
51
+
52
+ def has_add_permission(self, request):
53
+ return False
54
+
55
+ def has_change_permission(self, request, obj=None):
56
+ return False
57
+
58
+
59
+ @admin.register(LicenseModifier)
60
+ class LicenseModifierAdmin(SubjectDisplayMixin, admin.ModelAdmin):
61
+ list_display = ("id", "subject", "feature", "factor", "valid_from", "valid_until")
62
+ list_filter = ("feature",)
63
+ search_fields = ("subject_type", "subject_id", "feature")
64
+
65
+
66
+ @admin.register(WalletArchive)
67
+ class WalletArchiveAdmin(SubjectDisplayMixin, admin.ModelAdmin):
68
+ list_display = ("id", "original_wallet_id", "subject", "currency", "final_balance", "archived_at")
69
+ list_filter = ("wallet_type", "currency")
70
+ search_fields = ("subject_type", "subject_id", "currency")
71
+ date_hierarchy = "archived_at"
72
+
73
+ def has_add_permission(self, request):
74
+ return False
75
+
76
+ def has_change_permission(self, request, obj=None):
77
+ return False
78
+
79
+
80
+ @admin.register(TransactionArchive)
81
+ class TransactionArchiveAdmin(admin.ModelAdmin):
82
+ list_display = ("id", "original_transaction_id", "original_wallet_id", "kind", "amount", "archived_at")
83
+ list_filter = ("kind", "feature")
84
+ date_hierarchy = "archived_at"
85
+
86
+ def has_add_permission(self, request):
87
+ return False
88
+
89
+ def has_change_permission(self, request, obj=None):
90
+ return False
@@ -0,0 +1,15 @@
1
+ from django.apps import AppConfig
2
+ from django.core.checks import register
3
+
4
+
5
+ class AllowancesConfig(AppConfig):
6
+ name = "allowances_django"
7
+ # Tables come out as `allowances_wallet` rather than `allowances_django_wallet`.
8
+ label = "allowances"
9
+ verbose_name = "Allowances"
10
+ default_auto_field = "django.db.models.BigAutoField"
11
+
12
+ def ready(self):
13
+ from allowances_django.checks import check_sqlite_transaction_mode
14
+
15
+ register(check_sqlite_transaction_mode)
@@ -0,0 +1,48 @@
1
+ """
2
+ Deployment checks specific to this app.
3
+
4
+ There is exactly one, and it exists because SQLite is supported but has a single configuration
5
+ switch that decides whether concurrent fulfillment waits or raises.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from django.conf import settings
11
+ from django.core.checks import Warning as CheckWarning
12
+
13
+ #: Modes that make ``atomic()`` take SQLite's write lock at ``BEGIN`` rather than on first write.
14
+ SAFE_TRANSACTION_MODES = {"IMMEDIATE", "EXCLUSIVE"}
15
+
16
+ HINT = (
17
+ 'DATABASES["{alias}"]["OPTIONS"] = {{"transaction_mode": "IMMEDIATE", "timeout": 20, '
18
+ '"init_command": "PRAGMA journal_mode=WAL;"}}'
19
+ )
20
+
21
+
22
+ def check_sqlite_transaction_mode(app_configs, **kwargs):
23
+ """
24
+ SQLite has no ``SELECT ... FOR UPDATE``; it serialises writers instead. A ``DEFERRED``
25
+ transaction — Django's default — only takes that write lock when it first writes, by which
26
+ point it may have read a balance another transaction has already changed underneath it.
27
+
28
+ SQLite catches that itself and fails the write rather than committing a stale balance, so
29
+ the ledger stays correct either way. But the failure surfaces as ``OperationalError:
30
+ database is locked`` in the middle of a ``fulfill``, which is not a thing to discover in
31
+ production. ``IMMEDIATE`` takes the lock up front, so the second caller waits its turn.
32
+ """
33
+ problems = []
34
+ for alias, config in settings.DATABASES.items():
35
+ if not config.get("ENGINE", "").endswith("sqlite3"):
36
+ continue
37
+ mode = (config.get("OPTIONS") or {}).get("transaction_mode") or ""
38
+ if mode.upper() in SAFE_TRANSACTION_MODES:
39
+ continue
40
+ problems.append(
41
+ CheckWarning(
42
+ f'The SQLite database "{alias}" does not use IMMEDIATE transactions, so concurrent '
43
+ f"fulfillment can raise OperationalError instead of waiting for its turn.",
44
+ hint=HINT.format(alias=alias),
45
+ id="allowances.W001",
46
+ )
47
+ )
48
+ return problems
@@ -0,0 +1,125 @@
1
+ # Generated by Django 5.2.17 on 2026-08-07 09:27
2
+
3
+ import django.db.models.deletion
4
+ import django.utils.timezone
5
+ import uuid
6
+ from django.db import migrations, models
7
+
8
+
9
+ class Migration(migrations.Migration):
10
+
11
+ initial = True
12
+
13
+ dependencies = [
14
+ ]
15
+
16
+ operations = [
17
+ migrations.CreateModel(
18
+ name='FulfillmentRecord',
19
+ fields=[
20
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
21
+ ('guid', models.UUIDField(default=uuid.uuid4, unique=True)),
22
+ ('created_at', models.DateTimeField(default=django.utils.timezone.now)),
23
+ ('updated_at', models.DateTimeField(auto_now=True)),
24
+ ],
25
+ ),
26
+ migrations.CreateModel(
27
+ name='LicenseModifier',
28
+ fields=[
29
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
30
+ ('subject_type', models.CharField(help_text="Lowercased 'app_label.modelname' of the subject, e.g. 'auth.user'.", max_length=100)),
31
+ ('subject_id', models.CharField(help_text='Primary key of the subject, as text — so integer, UUID and slug keys all work.', max_length=64)),
32
+ ('feature', models.CharField(max_length=100)),
33
+ ('factor', models.DecimalField(decimal_places=6, max_digits=10)),
34
+ ('valid_from', models.DateTimeField(blank=True, null=True)),
35
+ ('valid_until', models.DateTimeField(blank=True, null=True)),
36
+ ('created_at', models.DateTimeField(default=django.utils.timezone.now)),
37
+ ],
38
+ options={
39
+ 'indexes': [models.Index(fields=['subject_type', 'subject_id'], name='allowances__subject_48f323_idx'), models.Index(fields=['feature'], name='allowances__feature_e36882_idx'), models.Index(fields=['valid_from', 'valid_until'], name='allowances__valid_f_5e4364_idx')],
40
+ },
41
+ ),
42
+ migrations.CreateModel(
43
+ name='Wallet',
44
+ fields=[
45
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
46
+ ('subject_type', models.CharField(help_text="Lowercased 'app_label.modelname' of the subject, e.g. 'auth.user'.", max_length=100)),
47
+ ('subject_id', models.CharField(help_text='Primary key of the subject, as text — so integer, UUID and slug keys all work.', max_length=64)),
48
+ ('wallet_type', models.CharField(choices=[('grant', 'Grant'), ('consumable', 'Consumable')], max_length=16)),
49
+ ('currency', models.CharField(help_text="Name of a currency declared in settings.ALLOWANCES['currencies'].", max_length=100)),
50
+ ('balance', models.DecimalField(decimal_places=6, default=0, max_digits=20)),
51
+ ('valid_from', models.DateTimeField(blank=True, null=True)),
52
+ ('valid_until', models.DateTimeField(blank=True, null=True)),
53
+ ('overdraft_limit', models.DecimalField(blank=True, decimal_places=6, help_text='How far below zero this wallet may go. Null means no overdraft at all.', max_digits=20, null=True)),
54
+ ('first_overdraft_at', models.DateTimeField(blank=True, help_text='When the balance first went negative. Set by the engine, never cleared.', null=True)),
55
+ ('reset_config', models.JSONField(blank=True, help_text="Sliding-window configuration: {'time': ...} daily, {'day_of_week', 'time'} weekly, {'day_of_month', 'time'} monthly, {'window_seconds': N} rolling. Null means the balance is a plain stored amount that does not replenish.", null=True)),
56
+ ('created_at', models.DateTimeField(default=django.utils.timezone.now)),
57
+ ('updated_at', models.DateTimeField(auto_now=True)),
58
+ ],
59
+ options={
60
+ 'indexes': [models.Index(fields=['subject_type', 'subject_id'], name='allowances__subject_516dbf_idx'), models.Index(fields=['currency'], name='allowances__currenc_d42bb5_idx'), models.Index(fields=['wallet_type'], name='allowances__wallet__9d1fb2_idx'), models.Index(fields=['valid_from', 'valid_until'], name='allowances__valid_f_68c3db_idx'), models.Index(fields=['subject_type', 'subject_id', 'wallet_type', 'currency'], name='allowances__subject_d909d7_idx')],
61
+ },
62
+ ),
63
+ migrations.CreateModel(
64
+ name='WalletArchive',
65
+ fields=[
66
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
67
+ ('subject_type', models.CharField(help_text="Lowercased 'app_label.modelname' of the subject, e.g. 'auth.user'.", max_length=100)),
68
+ ('subject_id', models.CharField(help_text='Primary key of the subject, as text — so integer, UUID and slug keys all work.', max_length=64)),
69
+ ('original_wallet_id', models.BigIntegerField()),
70
+ ('wallet_type', models.CharField(choices=[('grant', 'Grant'), ('consumable', 'Consumable')], max_length=16)),
71
+ ('currency', models.CharField(max_length=100)),
72
+ ('final_balance', models.DecimalField(decimal_places=6, max_digits=20)),
73
+ ('valid_from', models.DateTimeField(blank=True, null=True)),
74
+ ('valid_until', models.DateTimeField(blank=True, null=True)),
75
+ ('overdraft_limit', models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True)),
76
+ ('first_overdraft_at', models.DateTimeField(blank=True, null=True)),
77
+ ('reset_config', models.JSONField(blank=True, null=True)),
78
+ ('original_created_at', models.DateTimeField()),
79
+ ('archived_at', models.DateTimeField(default=django.utils.timezone.now)),
80
+ ],
81
+ options={
82
+ 'indexes': [models.Index(fields=['subject_type', 'subject_id'], name='allowances__subject_c83fb3_idx'), models.Index(fields=['original_wallet_id'], name='allowances__origina_c0a0aa_idx'), models.Index(fields=['currency'], name='allowances__currenc_1829a8_idx')],
83
+ },
84
+ ),
85
+ migrations.CreateModel(
86
+ name='Transaction',
87
+ fields=[
88
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
89
+ ('kind', models.CharField(choices=[('grant', 'Grant'), ('consumption', 'Consumption'), ('storno', 'Storno')], max_length=16)),
90
+ ('amount', models.DecimalField(decimal_places=6, max_digits=20)),
91
+ ('feature', models.CharField(blank=True, max_length=100)),
92
+ ('object_type', models.CharField(blank=True, max_length=100)),
93
+ ('object_id', models.CharField(blank=True, max_length=64)),
94
+ ('created_at', models.DateTimeField(default=django.utils.timezone.now)),
95
+ ('record', models.ForeignKey(blank=True, help_text='Null for ad-hoc entries such as a manual admin correction, which need no record.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transactions', to='allowances.fulfillmentrecord')),
96
+ ('storno_of', models.ForeignKey(blank=True, help_text='The entry this one reverses.', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='storno_transactions', to='allowances.transaction')),
97
+ ('wallet', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='allowances.wallet')),
98
+ ],
99
+ options={
100
+ 'indexes': [models.Index(fields=['wallet'], name='allowances__wallet__e5e370_idx'), models.Index(fields=['record'], name='allowances__record__ec43d4_idx'), models.Index(fields=['object_type', 'object_id'], name='allowances__object__316c93_idx'), models.Index(fields=['kind'], name='allowances__kind_c2291c_idx'), models.Index(fields=['wallet', 'created_at'], name='allowances__wallet__8799e3_idx')],
101
+ 'constraints': [models.UniqueConstraint(condition=models.Q(('storno_of__isnull', False)), fields=('storno_of',), name='allowances_transaction_storno_of_unique')],
102
+ },
103
+ ),
104
+ migrations.CreateModel(
105
+ name='TransactionArchive',
106
+ fields=[
107
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
108
+ ('original_transaction_id', models.BigIntegerField()),
109
+ ('original_wallet_id', models.BigIntegerField()),
110
+ ('kind', models.CharField(choices=[('grant', 'Grant'), ('consumption', 'Consumption'), ('storno', 'Storno')], max_length=16)),
111
+ ('amount', models.DecimalField(decimal_places=6, max_digits=20)),
112
+ ('feature', models.CharField(blank=True, max_length=100)),
113
+ ('object_type', models.CharField(blank=True, max_length=100)),
114
+ ('object_id', models.CharField(blank=True, max_length=64)),
115
+ ('original_created_at', models.DateTimeField()),
116
+ ('archived_at', models.DateTimeField(default=django.utils.timezone.now)),
117
+ ('record', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='archived_transactions', to='allowances.fulfillmentrecord')),
118
+ ('storno_of', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='storno_transactions', to='allowances.transactionarchive')),
119
+ ('wallet_archive', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='allowances.walletarchive')),
120
+ ],
121
+ options={
122
+ 'indexes': [models.Index(fields=['wallet_archive'], name='allowances__wallet__87044d_idx'), models.Index(fields=['original_wallet_id'], name='allowances__origina_196586_idx'), models.Index(fields=['record'], name='allowances__record__e4d56a_idx'), models.Index(fields=['kind'], name='allowances__kind_15bfcc_idx')],
123
+ },
124
+ ),
125
+ ]
File without changes
@@ -0,0 +1,279 @@
1
+ """
2
+ Relational storage for the ``allowances`` core.
3
+
4
+ These models are a persistence detail, not the library's vocabulary — the engine never imports
5
+ them and never sees an instance. ``allowances_django.store.DjangoStore`` converts rows into the
6
+ core's frozen value types on the way out and back on the way in.
7
+
8
+ **Subjects are stored as two plain strings, not a GenericForeignKey.** ``subject_type`` holds
9
+ ``"app_label.modelname"`` and ``subject_id`` the primary key as text. This buys three things a
10
+ ``ContentType`` FK cannot: the core stays free of Django, subjects with UUID or slug primary keys
11
+ work (a ``PositiveBigIntegerField`` object id rules those out), and a schema-per-tenant deployment
12
+ stops fighting the shared ``django_content_type`` table — a real FK from a per-tenant table to it
13
+ is legal to create but breaks ``TRUNCATE`` once a second schema exists, which is why the old schema
14
+ had to carry ``db_constraint=False`` everywhere.
15
+
16
+ The cost is that ``select_related`` cannot follow a subject and a dangling reference is not caught
17
+ by the database. ``allowances_django.subjects.resolve()`` fetches the object when you need it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import uuid
23
+
24
+ from django.db import models
25
+ from django.utils import timezone
26
+
27
+ # Ledger amounts are Decimal throughout. 20 digits with 6 decimal places covers fractional
28
+ # consumables (0.5 credits) and large balances without ever reaching for a float.
29
+ AMOUNT_MAX_DIGITS = 20
30
+ AMOUNT_DECIMAL_PLACES = 6
31
+
32
+ # A modifier's factor is a multiplier (0.5, 3.27), not a currency amount, so it gets its own,
33
+ # smaller precision.
34
+ FACTOR_MAX_DIGITS = 10
35
+ FACTOR_DECIMAL_PLACES = 6
36
+
37
+ NAME_MAX_LENGTH = 100
38
+ # Long enough for a UUID in any formatting, a numeric pk, or a slug.
39
+ SUBJECT_ID_MAX_LENGTH = 64
40
+
41
+
42
+ class WalletType(models.TextChoices):
43
+ GRANT = "grant", "Grant"
44
+ CONSUMABLE = "consumable", "Consumable"
45
+
46
+
47
+ class TransactionKind(models.TextChoices):
48
+ GRANT = "grant", "Grant"
49
+ CONSUMPTION = "consumption", "Consumption"
50
+ STORNO = "storno", "Storno"
51
+
52
+
53
+ class SubjectFields(models.Model):
54
+ """The two columns that identify whoever holds a record."""
55
+
56
+ subject_type = models.CharField(
57
+ max_length=NAME_MAX_LENGTH,
58
+ help_text="Lowercased 'app_label.modelname' of the subject, e.g. 'auth.user'.",
59
+ )
60
+ subject_id = models.CharField(
61
+ max_length=SUBJECT_ID_MAX_LENGTH,
62
+ help_text="Primary key of the subject, as text — so integer, UUID and slug keys all work.",
63
+ )
64
+
65
+ class Meta:
66
+ abstract = True
67
+
68
+
69
+ class Wallet(SubjectFields):
70
+ """
71
+ A subject's holding of one currency.
72
+
73
+ For a wallet with a ``reset_config``, ``balance`` is the per-window allotment and never moves;
74
+ the balance that governs decisions is computed from the transactions inside the current window.
75
+ """
76
+
77
+ wallet_type = models.CharField(max_length=16, choices=WalletType.choices)
78
+ currency = models.CharField(
79
+ max_length=NAME_MAX_LENGTH,
80
+ help_text="Name of a currency declared in settings.ALLOWANCES['currencies'].",
81
+ )
82
+ balance = models.DecimalField(max_digits=AMOUNT_MAX_DIGITS, decimal_places=AMOUNT_DECIMAL_PLACES, default=0)
83
+ valid_from = models.DateTimeField(null=True, blank=True)
84
+ valid_until = models.DateTimeField(null=True, blank=True)
85
+ overdraft_limit = models.DecimalField(
86
+ max_digits=AMOUNT_MAX_DIGITS,
87
+ decimal_places=AMOUNT_DECIMAL_PLACES,
88
+ null=True,
89
+ blank=True,
90
+ help_text="How far below zero this wallet may go. Null means no overdraft at all.",
91
+ )
92
+ first_overdraft_at = models.DateTimeField(
93
+ null=True,
94
+ blank=True,
95
+ help_text="When the balance first went negative. Set by the engine, never cleared.",
96
+ )
97
+ reset_config = models.JSONField(
98
+ null=True,
99
+ blank=True,
100
+ help_text=(
101
+ "Sliding-window configuration: {'time': ...} daily, {'day_of_week', 'time'} weekly, "
102
+ "{'day_of_month', 'time'} monthly, {'window_seconds': N} rolling. Null means the "
103
+ "balance is a plain stored amount that does not replenish."
104
+ ),
105
+ )
106
+ # Not auto_now_add: the store sets it, so a backfill or a test can place a wallet in the past.
107
+ created_at = models.DateTimeField(default=timezone.now)
108
+ updated_at = models.DateTimeField(auto_now=True)
109
+
110
+ class Meta:
111
+ indexes = [
112
+ models.Index(fields=["subject_type", "subject_id"]),
113
+ models.Index(fields=["currency"]),
114
+ models.Index(fields=["wallet_type"]),
115
+ models.Index(fields=["valid_from", "valid_until"]),
116
+ # Candidate lookups always filter on this whole combination, then order by created_at.
117
+ models.Index(fields=["subject_type", "subject_id", "wallet_type", "currency"]),
118
+ ]
119
+
120
+ def __str__(self):
121
+ return f"Wallet({self.wallet_type}, {self.currency}, {self.subject_type}:{self.subject_id}, {self.balance})"
122
+
123
+
124
+ class FulfillmentRecord(models.Model):
125
+ """Groups every transaction belonging to one business operation."""
126
+
127
+ guid = models.UUIDField(default=uuid.uuid4, unique=True, editable=True)
128
+ created_at = models.DateTimeField(default=timezone.now)
129
+ updated_at = models.DateTimeField(auto_now=True)
130
+
131
+ def __str__(self):
132
+ return f"FulfillmentRecord({self.guid})"
133
+
134
+
135
+ class Transaction(models.Model):
136
+ """
137
+ One signed ledger entry: negative for consumption, positive for a grant or a storno.
138
+
139
+ ``object_type``/``object_id`` are written in a second step. The transaction is created when the
140
+ quota is consumed; the domain object it paid for is attached once that operation actually
141
+ succeeds. A transaction left unattached is therefore a usable signal that something failed in
142
+ between.
143
+ """
144
+
145
+ wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE, related_name="transactions")
146
+ record = models.ForeignKey(
147
+ FulfillmentRecord,
148
+ on_delete=models.SET_NULL,
149
+ null=True,
150
+ blank=True,
151
+ related_name="transactions",
152
+ help_text="Null for ad-hoc entries such as a manual admin correction, which need no record.",
153
+ )
154
+ kind = models.CharField(max_length=16, choices=TransactionKind.choices)
155
+ amount = models.DecimalField(max_digits=AMOUNT_MAX_DIGITS, decimal_places=AMOUNT_DECIMAL_PLACES)
156
+ feature = models.CharField(max_length=NAME_MAX_LENGTH, blank=True)
157
+ storno_of = models.ForeignKey(
158
+ "self",
159
+ on_delete=models.PROTECT,
160
+ null=True,
161
+ blank=True,
162
+ related_name="storno_transactions",
163
+ help_text="The entry this one reverses.",
164
+ )
165
+ object_type = models.CharField(max_length=NAME_MAX_LENGTH, blank=True)
166
+ object_id = models.CharField(max_length=SUBJECT_ID_MAX_LENGTH, blank=True)
167
+ created_at = models.DateTimeField(default=timezone.now)
168
+
169
+ class Meta:
170
+ indexes = [
171
+ models.Index(fields=["wallet"]),
172
+ models.Index(fields=["record"]),
173
+ models.Index(fields=["object_type", "object_id"]),
174
+ models.Index(fields=["kind"]),
175
+ # Sliding-window balances sum a wallet's entries over a time range on every fulfillment.
176
+ models.Index(fields=["wallet", "created_at"]),
177
+ ]
178
+ constraints = [
179
+ models.UniqueConstraint(
180
+ fields=["storno_of"],
181
+ condition=models.Q(storno_of__isnull=False),
182
+ name="allowances_transaction_storno_of_unique",
183
+ ),
184
+ ]
185
+
186
+ def __str__(self):
187
+ return f"Transaction({self.kind}, {self.amount}, wallet={self.wallet_id})"
188
+
189
+
190
+ class LicenseModifier(SubjectFields):
191
+ """A time-limited factor adjusting what one unit of a feature costs a given subject."""
192
+
193
+ feature = models.CharField(max_length=NAME_MAX_LENGTH)
194
+ factor = models.DecimalField(max_digits=FACTOR_MAX_DIGITS, decimal_places=FACTOR_DECIMAL_PLACES)
195
+ valid_from = models.DateTimeField(null=True, blank=True)
196
+ valid_until = models.DateTimeField(null=True, blank=True)
197
+ created_at = models.DateTimeField(default=timezone.now)
198
+
199
+ class Meta:
200
+ indexes = [
201
+ models.Index(fields=["subject_type", "subject_id"]),
202
+ models.Index(fields=["feature"]),
203
+ models.Index(fields=["valid_from", "valid_until"]),
204
+ ]
205
+
206
+ def __str__(self):
207
+ return f"LicenseModifier({self.feature}, ×{self.factor}, {self.subject_type}:{self.subject_id})"
208
+
209
+
210
+ class WalletArchive(SubjectFields):
211
+ """
212
+ A wallet that has been spent out or has expired, moved here so the live tables only hold
213
+ wallets that can still pay for something.
214
+
215
+ Deliberately not a foreign key back to :class:`Wallet` — the live row is gone by the time this
216
+ one exists, so a real FK would either dangle or force cascade bookkeeping that defeats the
217
+ point. ``original_wallet_id`` is a plain reference, the way an audit table's is.
218
+ """
219
+
220
+ original_wallet_id = models.BigIntegerField()
221
+ wallet_type = models.CharField(max_length=16, choices=WalletType.choices)
222
+ currency = models.CharField(max_length=NAME_MAX_LENGTH)
223
+ final_balance = models.DecimalField(max_digits=AMOUNT_MAX_DIGITS, decimal_places=AMOUNT_DECIMAL_PLACES)
224
+ valid_from = models.DateTimeField(null=True, blank=True)
225
+ valid_until = models.DateTimeField(null=True, blank=True)
226
+ overdraft_limit = models.DecimalField(
227
+ max_digits=AMOUNT_MAX_DIGITS, decimal_places=AMOUNT_DECIMAL_PLACES, null=True, blank=True
228
+ )
229
+ first_overdraft_at = models.DateTimeField(null=True, blank=True)
230
+ reset_config = models.JSONField(null=True, blank=True)
231
+ original_created_at = models.DateTimeField()
232
+ archived_at = models.DateTimeField(default=timezone.now)
233
+
234
+ class Meta:
235
+ indexes = [
236
+ models.Index(fields=["subject_type", "subject_id"]),
237
+ models.Index(fields=["original_wallet_id"]),
238
+ models.Index(fields=["currency"]),
239
+ ]
240
+
241
+ def __str__(self):
242
+ return f"WalletArchive(wallet={self.original_wallet_id}, {self.currency})"
243
+
244
+
245
+ class TransactionArchive(models.Model):
246
+ """
247
+ An archived transaction, moved out alongside its wallet. ``original_wallet_id`` is kept as well
248
+ as the archive FK, so the link survives even if a transaction is archived without its wallet.
249
+ """
250
+
251
+ original_transaction_id = models.BigIntegerField()
252
+ wallet_archive = models.ForeignKey(
253
+ WalletArchive, on_delete=models.CASCADE, null=True, blank=True, related_name="transactions"
254
+ )
255
+ original_wallet_id = models.BigIntegerField()
256
+ record = models.ForeignKey(
257
+ FulfillmentRecord, on_delete=models.SET_NULL, null=True, blank=True, related_name="archived_transactions"
258
+ )
259
+ kind = models.CharField(max_length=16, choices=TransactionKind.choices)
260
+ amount = models.DecimalField(max_digits=AMOUNT_MAX_DIGITS, decimal_places=AMOUNT_DECIMAL_PLACES)
261
+ feature = models.CharField(max_length=NAME_MAX_LENGTH, blank=True)
262
+ storno_of = models.ForeignKey(
263
+ "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="storno_transactions"
264
+ )
265
+ object_type = models.CharField(max_length=NAME_MAX_LENGTH, blank=True)
266
+ object_id = models.CharField(max_length=SUBJECT_ID_MAX_LENGTH, blank=True)
267
+ original_created_at = models.DateTimeField()
268
+ archived_at = models.DateTimeField(default=timezone.now)
269
+
270
+ class Meta:
271
+ indexes = [
272
+ models.Index(fields=["wallet_archive"]),
273
+ models.Index(fields=["original_wallet_id"]),
274
+ models.Index(fields=["record"]),
275
+ models.Index(fields=["kind"]),
276
+ ]
277
+
278
+ def __str__(self):
279
+ return f"TransactionArchive(transaction={self.original_transaction_id}, {self.amount})"
@@ -0,0 +1,25 @@
1
+ """Reading feature and currency definitions out of Django settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django.conf import settings
6
+
7
+ from allowances.definitions import DictProvider
8
+
9
+ SETTINGS_KEY = "ALLOWANCES"
10
+
11
+
12
+ class SettingsProvider(DictProvider):
13
+ """
14
+ Reads ``settings.ALLOWANCES``.
15
+
16
+ A ``config`` dict may be passed instead, bypassing settings entirely — useful in tests, and for
17
+ applications whose definitions are narrower than a global settings module: per-tenant
18
+ configuration assembled at request time, or a plan fetched from a remote service and cached.
19
+ """
20
+
21
+ @property
22
+ def config(self) -> dict:
23
+ if self._config is not None:
24
+ return self._config
25
+ return getattr(settings, SETTINGS_KEY, {})