sandloom-billing 0.7.0a1__tar.gz

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.
Files changed (61) hide show
  1. sandloom_billing-0.7.0a1/.gitignore +4 -0
  2. sandloom_billing-0.7.0a1/CHANGELOG.md +36 -0
  3. sandloom_billing-0.7.0a1/LICENSE +202 -0
  4. sandloom_billing-0.7.0a1/NOTICE +8 -0
  5. sandloom_billing-0.7.0a1/PKG-INFO +52 -0
  6. sandloom_billing-0.7.0a1/README.md +34 -0
  7. sandloom_billing-0.7.0a1/pyproject.toml +37 -0
  8. sandloom_billing-0.7.0a1/sandloom_billing/__init__.py +95 -0
  9. sandloom_billing-0.7.0a1/sandloom_billing/access.py +165 -0
  10. sandloom_billing-0.7.0a1/sandloom_billing/admin.py +462 -0
  11. sandloom_billing-0.7.0a1/sandloom_billing/api/__init__.py +12 -0
  12. sandloom_billing-0.7.0a1/sandloom_billing/api/billing.py +212 -0
  13. sandloom_billing-0.7.0a1/sandloom_billing/api/platform.py +338 -0
  14. sandloom_billing-0.7.0a1/sandloom_billing/api/webhooks.py +42 -0
  15. sandloom_billing-0.7.0a1/sandloom_billing/claims.py +37 -0
  16. sandloom_billing-0.7.0a1/sandloom_billing/contracts.py +133 -0
  17. sandloom_billing-0.7.0a1/sandloom_billing/contracts.snapshot.json +309 -0
  18. sandloom_billing-0.7.0a1/sandloom_billing/credits.py +123 -0
  19. sandloom_billing-0.7.0a1/sandloom_billing/entitlements.py +83 -0
  20. sandloom_billing-0.7.0a1/sandloom_billing/events.py +98 -0
  21. sandloom_billing-0.7.0a1/sandloom_billing/exceptions.py +75 -0
  22. sandloom_billing-0.7.0a1/sandloom_billing/migrations/env.py +24 -0
  23. sandloom_billing-0.7.0a1/sandloom_billing/migrations/script.py.mako +28 -0
  24. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/.gitkeep +0 -0
  25. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0001_billing_billing_tables.py +126 -0
  26. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0002_billing_hardening.py +107 -0
  27. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0003_billing_drop_duplicate_ledger_index.py +37 -0
  28. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0004_billing_operation_intents.py +97 -0
  29. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0005_billing_subscription_origin.py +71 -0
  30. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0006_billing_subscription_intent.py +45 -0
  31. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0007_billing_intent_reconcile.py +59 -0
  32. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0008_billing_credit_grants.py +111 -0
  33. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0009_billing_intent_issued_at.py +35 -0
  34. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0010_billing_reconciler_indexes.py +56 -0
  35. sandloom_billing-0.7.0a1/sandloom_billing/migrations/versions/0011_billing_timestamps_default_to_clock_timestamp.py +43 -0
  36. sandloom_billing-0.7.0a1/sandloom_billing/models/__init__.py +99 -0
  37. sandloom_billing-0.7.0a1/sandloom_billing/models/catalog.py +81 -0
  38. sandloom_billing-0.7.0a1/sandloom_billing/models/credits.py +181 -0
  39. sandloom_billing-0.7.0a1/sandloom_billing/models/customer.py +44 -0
  40. sandloom_billing-0.7.0a1/sandloom_billing/models/intent.py +148 -0
  41. sandloom_billing-0.7.0a1/sandloom_billing/models/stripe_event.py +24 -0
  42. sandloom_billing-0.7.0a1/sandloom_billing/models/subscription.py +226 -0
  43. sandloom_billing-0.7.0a1/sandloom_billing/module.snapshot.json +392 -0
  44. sandloom_billing-0.7.0a1/sandloom_billing/psp/__init__.py +112 -0
  45. sandloom_billing-0.7.0a1/sandloom_billing/psp/fake.py +183 -0
  46. sandloom_billing-0.7.0a1/sandloom_billing/psp/port.py +197 -0
  47. sandloom_billing-0.7.0a1/sandloom_billing/psp/stripe_http.py +347 -0
  48. sandloom_billing-0.7.0a1/sandloom_billing/routes.snapshot.json +407 -0
  49. sandloom_billing-0.7.0a1/sandloom_billing/schemas/__init__.py +27 -0
  50. sandloom_billing-0.7.0a1/sandloom_billing/schemas/billing.py +84 -0
  51. sandloom_billing-0.7.0a1/sandloom_billing/schemas/platform.py +144 -0
  52. sandloom_billing-0.7.0a1/sandloom_billing/schemas/reads.py +39 -0
  53. sandloom_billing-0.7.0a1/sandloom_billing/services/__init__.py +7 -0
  54. sandloom_billing-0.7.0a1/sandloom_billing/services/billing_service.py +946 -0
  55. sandloom_billing-0.7.0a1/sandloom_billing/services/intent_reconciler.py +488 -0
  56. sandloom_billing-0.7.0a1/sandloom_billing/services/operation_intents.py +700 -0
  57. sandloom_billing-0.7.0a1/sandloom_billing/services/operations.py +85 -0
  58. sandloom_billing-0.7.0a1/sandloom_billing/services/platform_service.py +364 -0
  59. sandloom_billing-0.7.0a1/sandloom_billing/services/tenant_resolver.py +331 -0
  60. sandloom_billing-0.7.0a1/sandloom_billing/services/webhook_service.py +1487 -0
  61. sandloom_billing-0.7.0a1/sandloom_billing/tasks.py +67 -0
@@ -0,0 +1,4 @@
1
+ # Build artifacts from `uv build` — not committed.
2
+ dist/
3
+ build/
4
+ *.egg-info/
@@ -0,0 +1,36 @@
1
+ # Changelog — sandloom-billing
2
+
3
+ All notable changes to the `sandloom-billing` distribution are documented here.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+ Per-package entries are aggregated in the repository-level [docs/changelog.md](../../docs/changelog.md).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.7.0a1] — 2026-10-28
11
+
12
+ Initial public alpha preparation; earlier version headings describe internal development.
13
+
14
+ - Breaking (packaging): an ecosystem module distribution. The import package
15
+ is `sandloom_billing` (formerly `sandloom.billing`); it registers the
16
+ `sandloom.modules` entry point `billing = "sandloom_billing"` and depends on
17
+ `sandloom>=0.7,<0.8` instead of `sandloom-framework` + `sandloom-shared`.
18
+ Its contract DTOs, stubs and event schemas stay in `sandloom.shared`
19
+ (shipped with `sandloom`, SANDLOOM-C012).
20
+
21
+ ## [0.7.0] — 2026-10-13
22
+
23
+ First prepared release version; public publication is pending. While the framework is `0.x`, every Sandloom
24
+ distribution is released in lockstep with the framework release line
25
+ (see [Versioning & Stability](../../docs/contributing/versioning.md));
26
+ the change list since 0.6.0 is in [CHANGELOG.md](../../CHANGELOG.md)
27
+ and the current source API upgrade steps are in
28
+ [Upgrading to Public API 1.0](../../docs/guides/upgrading-1.0.md).
29
+ The historical 0.7 migration guide remains in the preparation archive.
30
+
31
+ ### Fixed
32
+ - Source distributions include the package sources and build independently of the monorepo.
33
+
34
+ ### Added
35
+ - Billing module: plans, subscriptions, the credits ledger and the Stripe
36
+ provider, shipped as a standalone wheel over `sandloom-framework` + `sandloom-shared`.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ Sandloom
2
+ Copyright 2026 Vasyl Cherniavskyi
3
+
4
+ The original Sandloom framework code, documentation and examples are licensed
5
+ under the Apache License, Version 2.0. See LICENSE for the full terms.
6
+
7
+ Third-party components and assets retain their own copyright notices and
8
+ licenses. This notice does not replace or modify those terms.
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.5
2
+ Name: sandloom-billing
3
+ Version: 0.7.0a1
4
+ Summary: Sandloom billing module: plans, subscriptions, credits ledger, Stripe.
5
+ Project-URL: Homepage, https://sandloom.dev/
6
+ Project-URL: Documentation, https://sandloom.dev/docs/
7
+ Project-URL: Repository, https://github.com/Sandloom-dev/sandloom
8
+ Project-URL: Issues, https://github.com/Sandloom-dev/sandloom/issues
9
+ Project-URL: Changelog, https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-billing/CHANGELOG.md
10
+ Author: Vasyl Cherniavskyi
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: sandloom<0.8,>=0.7.0a1
17
+ Description-Content-Type: text/markdown
18
+
19
+ # sandloom-billing
20
+
21
+ The Sandloom billing module: plans, subscriptions, the credits ledger and the
22
+ Stripe integration (with a `fake` PSP default). Import package
23
+ `sandloom_billing`; it registers the `sandloom.modules` entry point
24
+ `billing = "sandloom_billing"`, so its module name is `billing` (tables
25
+ `billing_*`, migration chain `alembic_version_billing`, channels and contracts
26
+ `billing.*`). Depends on `sandloom>=0.7.0a1,<0.8`; on no other module.
27
+
28
+ ```bash
29
+ pip install "sandloom[redis,celery]==0.7.0a1" sandloom-billing==0.7.0a1
30
+ ```
31
+
32
+ `sandloom.main:app` composes it once installed; an app selects it with
33
+ `SANDLOOM_MODULES=billing` (or `sandloom new <app> --with billing`). Other
34
+ modules call it through its contracts; their DTOs, stubs and event schemas
35
+ live in `sandloom.shared` and ship with `sandloom`.
36
+
37
+ Source of truth lives in the monorepo at `src/sandloom_billing`; this package
38
+ builds the wheel and source archive.
39
+
40
+ ## Project links
41
+
42
+ [Source](https://github.com/Sandloom-dev/sandloom) ·
43
+ [Documentation](https://sandloom.dev/docs/) ·
44
+ [Changelog](https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-billing/CHANGELOG.md)
45
+
46
+ This is the initial `0.7.0a1` alpha distribution. The canonical source
47
+ repository is private and awaiting transfer; the documentation website is
48
+ not deployed yet. The project links above are the planned public locations.
49
+
50
+ ## License
51
+
52
+ Apache-2.0. Copyright 2026 Vasyl Cherniavskyi. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,34 @@
1
+ # sandloom-billing
2
+
3
+ The Sandloom billing module: plans, subscriptions, the credits ledger and the
4
+ Stripe integration (with a `fake` PSP default). Import package
5
+ `sandloom_billing`; it registers the `sandloom.modules` entry point
6
+ `billing = "sandloom_billing"`, so its module name is `billing` (tables
7
+ `billing_*`, migration chain `alembic_version_billing`, channels and contracts
8
+ `billing.*`). Depends on `sandloom>=0.7.0a1,<0.8`; on no other module.
9
+
10
+ ```bash
11
+ pip install "sandloom[redis,celery]==0.7.0a1" sandloom-billing==0.7.0a1
12
+ ```
13
+
14
+ `sandloom.main:app` composes it once installed; an app selects it with
15
+ `SANDLOOM_MODULES=billing` (or `sandloom new <app> --with billing`). Other
16
+ modules call it through its contracts; their DTOs, stubs and event schemas
17
+ live in `sandloom.shared` and ship with `sandloom`.
18
+
19
+ Source of truth lives in the monorepo at `src/sandloom_billing`; this package
20
+ builds the wheel and source archive.
21
+
22
+ ## Project links
23
+
24
+ [Source](https://github.com/Sandloom-dev/sandloom) ·
25
+ [Documentation](https://sandloom.dev/docs/) ·
26
+ [Changelog](https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-billing/CHANGELOG.md)
27
+
28
+ This is the initial `0.7.0a1` alpha distribution. The canonical source
29
+ repository is private and awaiting transfer; the documentation website is
30
+ not deployed yet. The project links above are the planned public locations.
31
+
32
+ ## License
33
+
34
+ Apache-2.0. Copyright 2026 Vasyl Cherniavskyi. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "sandloom-billing"
3
+ version = "0.7.0a1"
4
+ classifiers = ["Development Status :: 3 - Alpha"]
5
+ description = "Sandloom billing module: plans, subscriptions, credits ledger, Stripe."
6
+ readme = "README.md"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ authors = [{ name = "Vasyl Cherniavskyi" }]
10
+ requires-python = ">=3.11"
11
+ # An ecosystem module like any third party's: a compatible framework range,
12
+ # never an exact pin. Contract calls to other modules are bound at runtime
13
+ # and use the consumer's own generated stubs: no module depends on another.
14
+ dependencies = [
15
+ "sandloom>=0.7.0a1,<0.8",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://sandloom.dev/"
20
+ Documentation = "https://sandloom.dev/docs/"
21
+ Repository = "https://github.com/Sandloom-dev/sandloom"
22
+ Issues = "https://github.com/Sandloom-dev/sandloom/issues"
23
+ Changelog = "https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-billing/CHANGELOG.md"
24
+
25
+ # The module name (`billing`: tables, migration chain, channels, contracts) and
26
+ # its import path; SANDLOOM_MODULES may name it by either.
27
+ [project.entry-points."sandloom.modules"]
28
+ billing = "sandloom_billing"
29
+
30
+ [build-system]
31
+ requires = [
32
+ "hatchling>=1.27",
33
+ ]
34
+ build-backend = "hatchling.build"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["sandloom_billing"]
@@ -0,0 +1,95 @@
1
+ """Billing module: monetization (plans, subscriptions, credits, Stripe).
2
+
3
+ Monolith-first, microservice-ready (BILLING_SPEC.md). Registered via the core
4
+ plugin system; exposes:
5
+
6
+ - `billing.entitlements.v1` — read contract for cross-domain guards
7
+ - `billing.credits.v1` — command contract: spend a tenant's credits
8
+ - `billing.claims.v1` — token-claims contributor (auto-registered)
9
+ - `billing.facts.v1` — its access facts (``subscription.active``,
10
+ ``organization.subscription.active``) for processes without billing
11
+ (auto-registered with the facts)
12
+
13
+ Consumes (``ModuleDescriptor.consumes``): ``tenancy.membership.v1`` (optional).
14
+
15
+ Contract semantics: contract methods take no session; each call runs in
16
+ billing's own Unit of Work on billing's database (identically in-process and
17
+ over internal RPC). ``billing.credits.v1.spend`` is a command: idempotent on
18
+ its ``operation_key`` and NOT atomic with the caller's transaction (saga).
19
+ """
20
+
21
+ from sandloom.sdk import define_module
22
+ from sandloom.sdk.infra import settings
23
+ from sandloom.sdk.module import ContractRequirement, ModuleAPI
24
+
25
+ from . import psp
26
+ from .access import ORG_SUBSCRIPTION_ACTIVE_FACT, SUBSCRIPTION_ACTIVE_FACT
27
+ from .claims import contribute_billing_claims
28
+ from .services.operations import OPERATIONS
29
+
30
+ ENTITLEMENTS_SERVICE_V1 = "billing.entitlements.v1"
31
+ CREDITS_SERVICE_V1 = "billing.credits.v1"
32
+ FACTS_SERVICE_V1 = "billing.facts.v1"
33
+ MEMBERSHIP_SERVICE_V1 = "tenancy.membership.v1"
34
+
35
+
36
+ def _setup(core: ModuleAPI) -> None:
37
+ core.add_shutdown_task(psp.close_psp_client)
38
+
39
+ # Production must never run on the fake PSP (fake checkouts; forged-event
40
+ # risk). A CRITICAL startup task aborts the lifespan instead of serving.
41
+ config_error = psp.psp_configuration_error(settings)
42
+ if config_error is not None:
43
+ core.logger.error("billing: %s", config_error)
44
+
45
+ async def _refuse_fake_psp_in_prod() -> None:
46
+ raise RuntimeError(config_error)
47
+
48
+ core.add_startup_task(_refuse_fake_psp_in_prod, critical=True)
49
+
50
+ # The PSP client is billing-INTERNAL (it can create checkout sessions and
51
+ # verifies webhooks with billing's secrets): never a public service
52
+ # contract, so no other module or RPC caller can reach it.
53
+ psp.install_psp_client(psp.build_psp_client())
54
+
55
+ # Subscription/plan claims baked into minted access tokens.
56
+ core.add_claims_contributor(contribute_billing_claims)
57
+
58
+ # Configurable access facts: Entitled("subscription.active") (personal
59
+ # tenant; claim / live / auto per the ACCESS setting) and
60
+ # Entitled("organization.subscription.active") (request's org; live).
61
+ core.register_access_fact(SUBSCRIPTION_ACTIVE_FACT)
62
+ core.register_access_fact(ORG_SUBSCRIPTION_ACTIVE_FACT)
63
+
64
+ # Declared reads of GET /subscription and GET /credits (execution
65
+ # planner; planned at startup, a schema error fails the boot).
66
+ core.register_operations(*OPERATIONS)
67
+
68
+
69
+ # Discovered (sandloom.sdk define_module): the routers of ``api.__all__``, the
70
+ # producer classes of ``events`` and the ``@contract`` providers of
71
+ # ``contracts`` (billing.entitlements.v1, billing.credits.v1).
72
+ register = define_module(
73
+ __name__,
74
+ version="1.0.0",
75
+ capabilities=["database", "eventbus"],
76
+ consumes=[
77
+ # Organization billing context. Optional: a personal-only deployment
78
+ # (no tenancy anywhere) runs without it; when the token shows tenancy
79
+ # IS deployed, billing answers 501 instead of silently using the
80
+ # personal tenant (services/tenant_resolver).
81
+ ContractRequirement(
82
+ MEMBERSHIP_SERVICE_V1,
83
+ required=False,
84
+ reason="organization billing context / org subscription fact",
85
+ ),
86
+ ],
87
+ setup=_setup,
88
+ )
89
+
90
+ __all__ = [
91
+ "register",
92
+ "ENTITLEMENTS_SERVICE_V1",
93
+ "CREDITS_SERVICE_V1",
94
+ "FACTS_SERVICE_V1",
95
+ ]
@@ -0,0 +1,165 @@
1
+ """Billing's access facts — configurable claim/live resolution.
2
+
3
+ Two facts, one per billing tenant kind:
4
+
5
+ - ``subscription.active`` — the subject's PERSONAL tenant. Answerable from the
6
+ claim contributor (token ``subscription_status``) or live via
7
+ ``billing.entitlements.v1`` with ``("user", subject.user_id)``. Both modes use
8
+ the same predicate (period + past_due grace policy), so the deployment can
9
+ pick claim (cheap) / live (fresh) / auto via ``ACCESS`` without an edit.
10
+ - ``organization.subscription.active`` — the ORGANIZATION the request targets.
11
+ Live only (the token carries no per-organization billing claim). The
12
+ organization comes from the request (``org_id`` path or query parameter),
13
+ else the bound tenant (``TenantScope``); the subject must be a member of it
14
+ (``tenancy.membership.v1``), otherwise it denies 403 (``FactDenied``
15
+ ``not_a_member``). No organization in context ⇒ 403 ``organization_required``
16
+ (fail closed). An org without an active subscription ⇒ 402 (both facts
17
+ declare ``deny_category=PAYMENT_REQUIRED``, like ``Subscribed`` /
18
+ ``SubscriptionActive`` / ``Credits``). Tenancy not deployed ⇒ ``FactUnavailable``
19
+ (501, misconfiguration — never a silent allow).
20
+
21
+ Both facts are part of billing's PUBLIC contract: registering them exposes
22
+ ``billing.facts.v1`` (``describe`` / ``evaluate``), so a process WITHOUT
23
+ billing that binds it resolves ``Entitled(...)`` /
24
+ ``Subscribed(of=Account.user())`` exactly
25
+ like the monolith (claim read with :func:`subscription_claim_rule`, live
26
+ answered by billing).
27
+
28
+ The fixed-tier ``Subscribed`` (claim, personal) / ``SubscriptionActive`` (live)
29
+ atoms remain for callers that want to pin a mode explicitly.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from typing import TYPE_CHECKING
35
+ from uuid import UUID
36
+
37
+ from sandloom.sdk.authz import (
38
+ ACTIVE_SUBSCRIPTION_STATUSES,
39
+ MODE_LIVE,
40
+ AccessFact,
41
+ Category,
42
+ ClaimRule,
43
+ FactDenied,
44
+ FactUnavailable,
45
+ )
46
+ from sandloom.sdk.errors import ServiceNotFound
47
+ from sandloom.sdk.infra import settings
48
+ from sandloom.sdk.tenant import current_tenant_id_optional
49
+ from sandloom_billing.entitlements import ENTITLEMENTS_SERVICE_V1
50
+
51
+ if TYPE_CHECKING: # pragma: no cover - typing only
52
+ from sandloom.sdk.authz import AuthzContext
53
+
54
+ MEMBERSHIP_SERVICE_V1 = "tenancy.membership.v1"
55
+ ORG_PARAM = "org_id"
56
+ _PAST_DUE = "past_due"
57
+
58
+
59
+ async def _live_subscription_active(service: object, ctx: AuthzContext) -> bool:
60
+ return bool(
61
+ await service.check_subscription_active( # type: ignore[attr-defined]
62
+ "user", ctx.subject.user_id
63
+ )
64
+ )
65
+
66
+
67
+ def subscription_claim_rule() -> ClaimRule:
68
+ """The DECLARATIVE claim rule of ``subscription.active`` (single source).
69
+
70
+ Same predicate as the live check: ``active`` / ``trialing`` grant access,
71
+ and ``past_due`` does during the grace period unless
72
+ ``BILLING_DENY_ON_PAST_DUE``. Evaluated with billing's settings — locally,
73
+ and at ``billing.facts.v1.describe()`` time for consumers in other
74
+ processes (so they interpret the claim exactly like billing does).
75
+ """
76
+ statuses = set(ACTIVE_SUBSCRIPTION_STATUSES)
77
+ if not settings.billing_deny_on_past_due:
78
+ statuses.add(_PAST_DUE)
79
+ return ClaimRule.one_of(statuses)
80
+
81
+
82
+ def _parse_uuid(raw: object) -> UUID | None:
83
+ if raw is None:
84
+ return None
85
+ if isinstance(raw, UUID):
86
+ return raw
87
+ try:
88
+ return UUID(str(raw))
89
+ except (TypeError, ValueError):
90
+ return None
91
+
92
+
93
+ def context_org_id(ctx: AuthzContext) -> UUID | None:
94
+ """The organization this evaluation targets, or ``None``.
95
+
96
+ Request ``org_id`` path param → ``org_id`` query param → bound tenant.
97
+ """
98
+ request = ctx.request
99
+ if request is not None:
100
+ org_id = _parse_uuid(request.path_params.get(ORG_PARAM))
101
+ if org_id is None:
102
+ org_id = _parse_uuid(request.query_params.get(ORG_PARAM))
103
+ if org_id is not None:
104
+ return org_id
105
+ return current_tenant_id_optional()
106
+
107
+
108
+ async def _live_org_subscription_active(service: object, ctx: AuthzContext) -> bool:
109
+ org_id = context_org_id(ctx)
110
+ if org_id is None:
111
+ # Fail closed, but as "forbidden" (403): there is nothing to pay for.
112
+ raise FactDenied("no organization in context", code="organization_required")
113
+ core = ctx.core()
114
+ if core is None:
115
+ raise FactUnavailable(
116
+ "fact 'organization.subscription.active': no core bound to resolve "
117
+ f"{MEMBERSHIP_SERVICE_V1!r}"
118
+ )
119
+ # Local provider OR the SERVICE_BINDINGS RPC proxy (tenancy deployed as a
120
+ # separate service) — never a local-registry-only probe.
121
+ try:
122
+ membership = core.get_service(MEMBERSHIP_SERVICE_V1)
123
+ except ServiceNotFound as exc: # incl. ServiceUnavailableInDeployment
124
+ raise FactUnavailable(
125
+ "fact 'organization.subscription.active': "
126
+ f"{MEMBERSHIP_SERVICE_V1!r} is not configured"
127
+ ) from exc
128
+ # A caller-supplied org id is only a selector: never answer for an
129
+ # organization the subject does not belong to.
130
+ if await membership.get_role(org_id, ctx.subject.user_id) is None:
131
+ raise FactDenied(
132
+ "subject is not a member of the organization", code="not_a_member"
133
+ )
134
+ return bool(
135
+ await service.check_subscription_active( # type: ignore[attr-defined]
136
+ "organization", org_id
137
+ )
138
+ )
139
+
140
+
141
+ SUBSCRIPTION_ACTIVE_FACT = AccessFact(
142
+ name="subscription.active",
143
+ owner_module="billing",
144
+ claim_key="subscription_status",
145
+ # Declarative, so it travels to consumers via billing.facts.v1.
146
+ claim_rule=subscription_claim_rule,
147
+ live_service=ENTITLEMENTS_SERVICE_V1,
148
+ live_resolver=_live_subscription_active,
149
+ min_freshness="claim",
150
+ default_mode="auto",
151
+ # Same 402 as Subscribed / SubscriptionActive / Credits.
152
+ deny_category=Category.PAYMENT_REQUIRED,
153
+ )
154
+
155
+ ORG_SUBSCRIPTION_ACTIVE_FACT = AccessFact(
156
+ name="organization.subscription.active",
157
+ owner_module="billing",
158
+ live_service=ENTITLEMENTS_SERVICE_V1,
159
+ live_resolver=_live_org_subscription_active,
160
+ min_freshness=MODE_LIVE,
161
+ default_mode=MODE_LIVE,
162
+ # 402 when the org simply has no active subscription; no org in context /
163
+ # not a member deny 403 (FactDenied in the resolver).
164
+ deny_category=Category.PAYMENT_REQUIRED,
165
+ )