@buffcore/affiliates 0.0.0-stage → 0.8.40

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.
package/LICENSE ADDED
@@ -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.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ BuffApe
2
+ Copyright © 2026 BuffApe
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # Partners and affiliates
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@buffcore/affiliates` is a server extension requiring `@buffcore/payments` (AFF0's paid lines).
4
+ It arrives off. Silent mode defaults to `true`: it gathers clicks, attribution and commissions,
5
+ provides Owner-only review, sends no messages, exposes no affiliate portal and refuses payouts.
6
+ There are no screens in this slice.
7
+
8
+ Add both extensions to the product's composition and grant affiliates `reads: ['contact']`,
9
+ `hosts: []`. Configure it in the composition's `settings`:
10
+
11
+ ```ts
12
+ affiliates: {
13
+ silent: true,
14
+ rates: { plan: 1250, seat: 1000 }, // basis points, product-defined line types
15
+ durationMonths: 12,
16
+ landingPath: '/pricing',
17
+ }
18
+ ```
19
+
20
+ Register the exported `affiliateRedirects` in the **product's** HTTP plugin. An extension cannot
21
+ register raw HTTP; this bridge turns the validated click action's answer into HTTP 302, a cookie
22
+ and `Cache-Control: no-store`. Other requests are unchanged. For example, the product module can
23
+ declare `plugin: affiliateRedirects`, or call `await affiliateRedirects(server, app)` from its
24
+ existing plugin. Register it before serving requests. Keep the redirect and sign-up API on the
25
+ same first-party host so the host-only cookie reaches sign-up. Without this bridge, the click
26
+ route returns its transport envelope as JSON and must not be used as a public navigation link.
27
+
28
+ The Owner publishes the configured terms before collecting referrals, creates affiliates and
29
+ tagged links, and shares the returned URL. All routes are schemas in `@buffcore/affiliates/contract`:
30
+
31
+ | Door under `/v1/admin/ext/affiliates` | Purpose |
32
+ |---|---|
33
+ | `POST /affiliates` | Create with `email` and optional `accountId` |
34
+ | `POST /affiliates/:affiliateId/close` | Stop new referrals and earnings |
35
+ | `POST /affiliates/:affiliateId/links` | Create a code with a `placement` slug |
36
+ | `POST /terms/publish` | Publish configuration for future sellers |
37
+ | `POST /affiliates/:affiliateId/clients` | Set an existing client's seller once |
38
+ | `GET /affiliates/:affiliateId/statement?month=YYYY-MM` | UTC totals by line type and currency |
39
+ | `GET /payouts/export?month=YYYY-MM` | CSV totals in integer minor units; pays nothing |
40
+ | `POST /affiliates/:affiliateId/payouts` | Approve `{ month, currency }` for manual payment |
41
+
42
+ Creation, closure, links, terms and client registration are always-human actions: machine/agent
43
+ proposals wait for the Owner when Automation is installed, otherwise they are refused. Contact
44
+ input additionally requires the product to let `contact` out. Statement/export reads and payout
45
+ approval are closed to machines, agents, members and non-Owner operators. Payout approval is
46
+ refused in silent mode, and records a positive monthly total once per affiliate/currency/month;
47
+ it does not transfer money. The CSV is a review aid, includes no customer names or contact data,
48
+ and may include negative balances for a person to carry forward.
49
+
50
+ `GET /v1/ext/affiliates/links/:code` counts a click and sets a signed, host-only `HttpOnly`,
51
+ `SameSite=Lax` cookie for 90 days (`Secure` on HTTPS). One constant, `WINDOW` in `links.ts`,
52
+ sets both cookie lifetime and attribution validity; it is not a setting. Optional `to` is a local app path;
53
+ outside URLs are refused. Each placement has its own link code. The browser's latest click
54
+ replaces its cookie. At sign-up, identity's additive `onSignup` hook receives parsed non-auth
55
+ cookies, with every identity cookie removed. Each subscriber has its own savepoint: failure is
56
+ logged without cookie values, and the account stands. Affiliates records the seller once. Old, future, invalid and closed links
57
+ are ignored. Without published terms there is no attribution. Operator client registration
58
+ starts the duration at registration. Duration uses UTC calendar months, clamped to month end;
59
+ paid lines on or after expiry earn nothing. Existing sellers retain their published rates.
60
+ Refunds retain the original rate, even after closure or expiry. Event IDs are unique and paid
61
+ lines accrue once; delivery before the paid subscriber backfills that line's original accrual.
62
+ No customer-leaving clawback is invented: this slice consumes actual refund/dispute line events;
63
+ a separate clawback policy and event would need an agreed window.
64
+
65
+ Referred customers' privacy exports include only whether and when they were referred, without
66
+ affiliate IDs, rates or commission amounts. Affiliates' own exports keep their records, links,
67
+ payouts and ledger entries, omitting other customers' account IDs. Deletion removes contacts and
68
+ links, detaches the deleted account/affiliate from retained ledger and payout amounts, and
69
+ removes the account's seller. The business keeps its books. Cookies never enter events or logs.
70
+ There is no payout provider, announcement, notification, tax form or affiliate-facing screen.
71
+
72
+ ## License
73
+
74
+ Apache-2.0. Copyright © 2026 BuffApe. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,190 @@
1
+ import { z } from 'zod';
2
+ export declare const month: z.ZodString;
3
+ export declare const StatementRow: z.ZodObject<{
4
+ affiliateId: z.ZodNullable<z.ZodUUID>;
5
+ lineType: z.ZodString;
6
+ currency: z.ZodString;
7
+ accrued: z.ZodNumber;
8
+ reversed: z.ZodNumber;
9
+ total: z.ZodNumber;
10
+ }, z.core.$strip>;
11
+ export declare const click: {
12
+ readonly method: "GET";
13
+ readonly path: "/v1/ext/affiliates/links/:code";
14
+ readonly access: "public";
15
+ readonly limit: {
16
+ readonly tries: 30;
17
+ readonly seconds: 60;
18
+ };
19
+ readonly params: z.ZodObject<{
20
+ code: z.ZodString;
21
+ }, z.core.$strip>;
22
+ readonly query: z.ZodObject<{
23
+ to: z.ZodOptional<z.ZodString>;
24
+ }, z.core.$strip>;
25
+ readonly response: z.ZodObject<{
26
+ location: z.ZodString;
27
+ cookie: z.ZodString;
28
+ }, z.core.$strip>;
29
+ readonly name: "click";
30
+ readonly description: "Count a browser click, set its signed referral cookie and redirect to the product app.";
31
+ readonly closedBecause: "A browser navigation, with a first-party referral cookie.";
32
+ };
33
+ export declare const createAffiliate: {
34
+ readonly roles: readonly ['owner'];
35
+ readonly action: {
36
+ readonly risk: 'high';
37
+ readonly alwaysHuman: true;
38
+ };
39
+ readonly mcp: true;
40
+ readonly method: "POST";
41
+ readonly path: "/v1/admin/ext/affiliates/affiliates";
42
+ readonly body: z.ZodObject<{
43
+ email: z.ZodEmail;
44
+ accountId: z.ZodOptional<z.ZodUUID>;
45
+ }, z.core.$strip>;
46
+ readonly response: z.ZodObject<{
47
+ id: z.ZodUUID;
48
+ }, z.core.$strip>;
49
+ readonly carries: readonly ["contact"];
50
+ readonly name: "create_affiliate";
51
+ readonly description: "Create an affiliate from their contact address and optional account. A person must approve this action.";
52
+ };
53
+ export declare const closeAffiliate: {
54
+ readonly roles: readonly ['owner'];
55
+ readonly action: {
56
+ readonly risk: 'high';
57
+ readonly alwaysHuman: true;
58
+ };
59
+ readonly mcp: true;
60
+ readonly method: "POST";
61
+ readonly path: "/v1/admin/ext/affiliates/affiliates/:affiliateId/close";
62
+ readonly params: z.ZodObject<{
63
+ affiliateId: z.ZodUUID;
64
+ }, z.core.$strip>;
65
+ readonly response: z.ZodObject<{
66
+ ok: z.ZodLiteral<true>;
67
+ }, z.core.$strip>;
68
+ readonly name: "close_affiliate";
69
+ readonly description: "Close an affiliate to new referrals and commissions. Existing refund reversals remain in the books.";
70
+ };
71
+ export declare const createLink: {
72
+ readonly roles: readonly ['owner'];
73
+ readonly action: {
74
+ readonly risk: 'high';
75
+ readonly alwaysHuman: true;
76
+ };
77
+ readonly mcp: true;
78
+ readonly method: "POST";
79
+ readonly path: "/v1/admin/ext/affiliates/affiliates/:affiliateId/links";
80
+ readonly params: z.ZodObject<{
81
+ affiliateId: z.ZodUUID;
82
+ }, z.core.$strip>;
83
+ readonly body: z.ZodObject<{
84
+ placement: z.ZodString;
85
+ }, z.core.$strip>;
86
+ readonly response: z.ZodObject<{
87
+ code: z.ZodString;
88
+ url: z.ZodString;
89
+ }, z.core.$strip>;
90
+ readonly name: "create_link";
91
+ readonly description: "Make a tagged link for an active affiliate. Returns its code and the product API navigation URL.";
92
+ };
93
+ export declare const publishTerms: {
94
+ readonly roles: readonly ['owner'];
95
+ readonly action: {
96
+ readonly risk: 'high';
97
+ readonly alwaysHuman: true;
98
+ };
99
+ readonly mcp: true;
100
+ readonly method: "POST";
101
+ readonly path: "/v1/admin/ext/affiliates/terms/publish";
102
+ readonly response: z.ZodObject<{
103
+ id: z.ZodUUID;
104
+ }, z.core.$strip>;
105
+ readonly name: "publish_terms";
106
+ readonly description: "Publish the configured rates and duration for future referrals. Existing sellers keep their agreed rates.";
107
+ };
108
+ export declare const registerClient: {
109
+ readonly roles: readonly ['owner'];
110
+ readonly action: {
111
+ readonly risk: 'high';
112
+ readonly alwaysHuman: true;
113
+ };
114
+ readonly mcp: true;
115
+ readonly method: "POST";
116
+ readonly path: "/v1/admin/ext/affiliates/affiliates/:affiliateId/clients";
117
+ readonly params: z.ZodObject<{
118
+ affiliateId: z.ZodUUID;
119
+ }, z.core.$strip>;
120
+ readonly body: z.ZodObject<{
121
+ accountId: z.ZodUUID;
122
+ }, z.core.$strip>;
123
+ readonly response: z.ZodObject<{
124
+ ok: z.ZodLiteral<true>;
125
+ }, z.core.$strip>;
126
+ readonly name: "register_client";
127
+ readonly description: "Assign an existing account to an affiliate as seller of record once, after a person approves it.";
128
+ };
129
+ export declare const getStatement: {
130
+ readonly roles: readonly ['owner'];
131
+ readonly closedBecause: 'Affiliate personal data and money are for the Owner in the console.';
132
+ readonly audit: "sensitive-read";
133
+ readonly method: "GET";
134
+ readonly path: "/v1/admin/ext/affiliates/affiliates/:affiliateId/statement";
135
+ readonly params: z.ZodObject<{
136
+ affiliateId: z.ZodUUID;
137
+ }, z.core.$strip>;
138
+ readonly query: z.ZodObject<{
139
+ month: z.ZodString;
140
+ }, z.core.$strip>;
141
+ readonly response: z.ZodObject<{
142
+ rows: z.ZodArray<z.ZodObject<{
143
+ affiliateId: z.ZodNullable<z.ZodUUID>;
144
+ lineType: z.ZodString;
145
+ currency: z.ZodString;
146
+ accrued: z.ZodNumber;
147
+ reversed: z.ZodNumber;
148
+ total: z.ZodNumber;
149
+ }, z.core.$strip>>;
150
+ }, z.core.$strip>;
151
+ readonly name: "get_statement";
152
+ readonly description: "Read one affiliate monthly statement in UTC, grouped by line type and currency, without customer names.";
153
+ };
154
+ export declare const exportPayouts: {
155
+ readonly roles: readonly ['owner'];
156
+ readonly closedBecause: 'Affiliate personal data and money are for the Owner in the console.';
157
+ readonly audit: "sensitive-read";
158
+ readonly method: "GET";
159
+ readonly path: "/v1/admin/ext/affiliates/payouts/export";
160
+ readonly query: z.ZodObject<{
161
+ month: z.ZodString;
162
+ }, z.core.$strip>;
163
+ readonly response: z.ZodObject<{
164
+ csv: z.ZodString;
165
+ }, z.core.$strip>;
166
+ readonly name: "export_payouts";
167
+ readonly description: "Export monthly affiliate totals as CSV for the Owner to review before manual payment. Sends no money.";
168
+ };
169
+ export declare const approvePayout: {
170
+ readonly roles: readonly ['owner'];
171
+ readonly closedBecause: 'Affiliate personal data and money are for the Owner in the console.';
172
+ readonly method: "POST";
173
+ readonly path: "/v1/admin/ext/affiliates/affiliates/:affiliateId/payouts";
174
+ readonly action: {
175
+ readonly risk: "high";
176
+ readonly alwaysHuman: true;
177
+ };
178
+ readonly params: z.ZodObject<{
179
+ affiliateId: z.ZodUUID;
180
+ }, z.core.$strip>;
181
+ readonly body: z.ZodObject<{
182
+ month: z.ZodString;
183
+ currency: z.ZodString;
184
+ }, z.core.$strip>;
185
+ readonly response: z.ZodObject<{
186
+ ok: z.ZodLiteral<true>;
187
+ }, z.core.$strip>;
188
+ readonly name: "approve_payout";
189
+ readonly description: "Record the Owner approval of a monthly payout for manual payment. Silent mode refuses every approval.";
190
+ };
@@ -0,0 +1,113 @@
1
+ import { ok, route, zId } from '@buffcore/contracts';
2
+ import { z } from 'zod';
3
+ import { localPath } from './settings.js';
4
+ const admin = {
5
+ roles: ['owner'],
6
+ closedBecause: 'Affiliate personal data and money are for the Owner in the console.',
7
+ };
8
+ const human = { roles: ['owner'], action: { risk: 'high', alwaysHuman: true }, mcp: true };
9
+ const affiliateId = z.object({ affiliateId: zId });
10
+ export const month = z
11
+ .string()
12
+ .regex(/^\d{4}-(0[1-9]|1[0-2])$/)
13
+ .refine((v) => !v.startsWith('0000'));
14
+ const period = z.object({ month });
15
+ export const StatementRow = z.object({
16
+ affiliateId: zId.nullable(),
17
+ lineType: z.string(),
18
+ currency: z.string(),
19
+ accrued: z.number().int(),
20
+ reversed: z.number().int(),
21
+ total: z.number().int(),
22
+ });
23
+ export const click = route({
24
+ method: 'GET',
25
+ path: '/v1/ext/affiliates/links/:code',
26
+ access: 'public',
27
+ limit: { tries: 30, seconds: 60 },
28
+ params: z.object({ code: z.string().regex(/^[a-zA-Z0-9_-]{8,64}$/) }),
29
+ query: z.object({ to: localPath.optional() }),
30
+ response: z.object({ location: z.string(), cookie: z.string() }),
31
+ name: 'click',
32
+ description: 'Count a browser click, set its signed referral cookie and redirect to the product app.',
33
+ closedBecause: 'A browser navigation, with a first-party referral cookie.',
34
+ });
35
+ export const createAffiliate = route({
36
+ ...human,
37
+ method: 'POST',
38
+ path: '/v1/admin/ext/affiliates/affiliates',
39
+ body: z.object({ email: z.email().max(254), accountId: zId.optional() }),
40
+ response: z.object({ id: zId }),
41
+ carries: ['contact'],
42
+ name: 'create_affiliate',
43
+ description: 'Create an affiliate from their contact address and optional account. A person must approve this action.',
44
+ });
45
+ export const closeAffiliate = route({
46
+ ...human,
47
+ method: 'POST',
48
+ path: '/v1/admin/ext/affiliates/affiliates/:affiliateId/close',
49
+ params: affiliateId,
50
+ response: ok,
51
+ name: 'close_affiliate',
52
+ description: 'Close an affiliate to new referrals and commissions. Existing refund reversals remain in the books.',
53
+ });
54
+ export const createLink = route({
55
+ ...human,
56
+ method: 'POST',
57
+ path: '/v1/admin/ext/affiliates/affiliates/:affiliateId/links',
58
+ params: affiliateId,
59
+ body: z.object({ placement: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/) }),
60
+ response: z.object({ code: z.string(), url: z.string() }),
61
+ name: 'create_link',
62
+ description: 'Make a tagged link for an active affiliate. Returns its code and the product API navigation URL.',
63
+ });
64
+ export const publishTerms = route({
65
+ ...human,
66
+ method: 'POST',
67
+ path: '/v1/admin/ext/affiliates/terms/publish',
68
+ response: z.object({ id: zId }),
69
+ name: 'publish_terms',
70
+ description: 'Publish the configured rates and duration for future referrals. Existing sellers keep their agreed rates.',
71
+ });
72
+ export const registerClient = route({
73
+ ...human,
74
+ method: 'POST',
75
+ path: '/v1/admin/ext/affiliates/affiliates/:affiliateId/clients',
76
+ params: affiliateId,
77
+ body: z.object({ accountId: zId }),
78
+ response: ok,
79
+ name: 'register_client',
80
+ description: 'Assign an existing account to an affiliate as seller of record once, after a person approves it.',
81
+ });
82
+ export const getStatement = route({
83
+ ...admin,
84
+ audit: 'sensitive-read',
85
+ method: 'GET',
86
+ path: '/v1/admin/ext/affiliates/affiliates/:affiliateId/statement',
87
+ params: affiliateId,
88
+ query: period,
89
+ response: z.object({ rows: z.array(StatementRow) }),
90
+ name: 'get_statement',
91
+ description: 'Read one affiliate monthly statement in UTC, grouped by line type and currency, without customer names.',
92
+ });
93
+ export const exportPayouts = route({
94
+ ...admin,
95
+ audit: 'sensitive-read',
96
+ method: 'GET',
97
+ path: '/v1/admin/ext/affiliates/payouts/export',
98
+ query: period,
99
+ response: z.object({ csv: z.string() }),
100
+ name: 'export_payouts',
101
+ description: 'Export monthly affiliate totals as CSV for the Owner to review before manual payment. Sends no money.',
102
+ });
103
+ export const approvePayout = route({
104
+ ...admin,
105
+ method: 'POST',
106
+ path: '/v1/admin/ext/affiliates/affiliates/:affiliateId/payouts',
107
+ action: { risk: 'high', alwaysHuman: true },
108
+ params: affiliateId,
109
+ body: z.object({ month, currency: z.string().regex(/^[a-z]{3}$/) }),
110
+ response: ok,
111
+ name: 'approve_payout',
112
+ description: 'Record the Owner approval of a monthly payout for manual payment. Silent mode refuses every approval.',
113
+ });