@btst/plugin-affiliate 0.0.0-stage → 1.0.0

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 (79) hide show
  1. package/LICENSE.md +17 -0
  2. package/dist/api/getters.cjs +182 -0
  3. package/dist/api/getters.mjs +166 -0
  4. package/dist/api/index.cjs +49 -0
  5. package/dist/api/index.d.cts +975 -0
  6. package/dist/api/index.d.mts +975 -0
  7. package/dist/api/index.d.ts +975 -0
  8. package/dist/api/index.mjs +7 -0
  9. package/dist/api/mutations.cjs +362 -0
  10. package/dist/api/mutations.mjs +352 -0
  11. package/dist/api/operations.cjs +328 -0
  12. package/dist/api/operations.mjs +326 -0
  13. package/dist/api/plugin.cjs +146 -0
  14. package/dist/api/plugin.mjs +144 -0
  15. package/dist/attribution.cjs +92 -0
  16. package/dist/attribution.d.cts +20 -0
  17. package/dist/attribution.d.mts +20 -0
  18. package/dist/attribution.d.ts +20 -0
  19. package/dist/attribution.mjs +82 -0
  20. package/dist/client/components/index.cjs +12 -0
  21. package/dist/client/components/index.d.cts +13 -0
  22. package/dist/client/components/index.d.mts +13 -0
  23. package/dist/client/components/index.d.ts +13 -0
  24. package/dist/client/components/index.mjs +1 -0
  25. package/dist/client/components/pages/affiliate-apply-page.internal.cjs +59 -0
  26. package/dist/client/components/pages/affiliate-apply-page.internal.mjs +57 -0
  27. package/dist/client/components/pages/affiliate-detail-page.internal.cjs +112 -0
  28. package/dist/client/components/pages/affiliate-detail-page.internal.mjs +110 -0
  29. package/dist/client/components/pages/affiliate-portal-page.internal.cjs +252 -0
  30. package/dist/client/components/pages/affiliate-portal-page.internal.mjs +250 -0
  31. package/dist/client/components/pages/affiliates-page.internal.cjs +160 -0
  32. package/dist/client/components/pages/affiliates-page.internal.mjs +158 -0
  33. package/dist/client/components/pages/commissions-page.internal.cjs +151 -0
  34. package/dist/client/components/pages/commissions-page.internal.mjs +149 -0
  35. package/dist/client/components/pages/payouts-page.internal.cjs +230 -0
  36. package/dist/client/components/pages/payouts-page.internal.mjs +228 -0
  37. package/dist/client/components/pages.cjs +145 -0
  38. package/dist/client/components/pages.mjs +138 -0
  39. package/dist/client/components/shared.cjs +331 -0
  40. package/dist/client/components/shared.mjs +316 -0
  41. package/dist/client/constants.cjs +5 -0
  42. package/dist/client/constants.mjs +3 -0
  43. package/dist/client/hooks/index.cjs +77 -0
  44. package/dist/client/hooks/index.d.cts +39 -0
  45. package/dist/client/hooks/index.d.mts +39 -0
  46. package/dist/client/hooks/index.d.ts +39 -0
  47. package/dist/client/hooks/index.mjs +61 -0
  48. package/dist/client/index.cjs +7 -0
  49. package/dist/client/index.d.cts +110 -0
  50. package/dist/client/index.d.mts +110 -0
  51. package/dist/client/index.d.ts +110 -0
  52. package/dist/client/index.mjs +1 -0
  53. package/dist/client/plugin.cjs +77 -0
  54. package/dist/client/plugin.mjs +75 -0
  55. package/dist/client.css +311 -0
  56. package/dist/commission.cjs +24 -0
  57. package/dist/commission.mjs +22 -0
  58. package/dist/db.cjs +74 -0
  59. package/dist/db.mjs +72 -0
  60. package/dist/permissions.cjs +53 -0
  61. package/dist/permissions.d.cts +78 -0
  62. package/dist/permissions.d.mts +78 -0
  63. package/dist/permissions.d.ts +78 -0
  64. package/dist/permissions.mjs +51 -0
  65. package/dist/query-keys.cjs +152 -0
  66. package/dist/query-keys.d.cts +394 -0
  67. package/dist/query-keys.d.mts +394 -0
  68. package/dist/query-keys.d.ts +394 -0
  69. package/dist/query-keys.mjs +149 -0
  70. package/dist/schemas.cjs +95 -0
  71. package/dist/schemas.mjs +77 -0
  72. package/dist/style.css +313 -0
  73. package/dist/types.cjs +2 -0
  74. package/dist/types.d.cts +176 -0
  75. package/dist/types.d.mts +176 -0
  76. package/dist/types.d.ts +176 -0
  77. package/dist/types.mjs +1 -0
  78. package/package.json +159 -3
  79. package/README.md +0 -3
package/LICENSE.md ADDED
@@ -0,0 +1,17 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2025 - present, olliethedev
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
5
+ and associated documentation files (the "Software"), to deal in the Software without restriction,
6
+ including without limitation the rights to use, copy, modify, merge, publish, distribute,
7
+ sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
8
+ is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or
11
+ substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
14
+ BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+
3
+ const api = require('@btst/stack/plugins/api');
4
+
5
+ function serializeAffiliateRecord(record) {
6
+ const { lockVersion: _lockVersion, ...result } = record;
7
+ for (const field of ["createdAt", "updatedAt", "paidAt"]) {
8
+ const value = result[field];
9
+ if (value instanceof Date) result[field] = value.toISOString();
10
+ }
11
+ return result;
12
+ }
13
+ async function byField(adapter, model, field, value) {
14
+ const row = await adapter.findOne({
15
+ model,
16
+ where: [{ field, value, operator: "eq" }]
17
+ });
18
+ return row ? serializeAffiliateRecord(row) : null;
19
+ }
20
+ const getAffiliate = (adapter, id) => byField(adapter, "affiliate", "id", id);
21
+ const getAffiliateByUserId = (adapter, userId) => byField(adapter, "affiliate", "userId", userId);
22
+ const getAffiliateByCode = (adapter, code) => byField(adapter, "affiliate", "code", code);
23
+ const getReferralClick = (adapter, id) => byField(adapter, "referralClick", "id", id);
24
+ const getCommission = (adapter, id) => byField(adapter, "affiliateCommission", "id", id);
25
+ const getPayout = (adapter, id) => byField(adapter, "affiliatePayout", "id", id);
26
+ const getConversionByExternalRef = (adapter, externalRef) => byField(
27
+ adapter,
28
+ "affiliateConversion",
29
+ "externalRef",
30
+ externalRef
31
+ );
32
+ async function list(adapter, model, params = {}) {
33
+ const where = [];
34
+ for (const field of ["affiliateId", "status", "currency"]) {
35
+ const value = params[field];
36
+ if (value) where.push({ field, value, operator: "eq" });
37
+ }
38
+ const limit = params.limit ?? 50;
39
+ const offset = params.offset ?? 0;
40
+ const [rows, total] = await Promise.all([
41
+ adapter.findMany({
42
+ model,
43
+ where,
44
+ limit,
45
+ offset,
46
+ sortBy: { field: "createdAt", direction: "desc" }
47
+ }),
48
+ adapter.count({ model, where })
49
+ ]);
50
+ return {
51
+ items: rows.map((row) => serializeAffiliateRecord(row)),
52
+ total,
53
+ limit,
54
+ offset
55
+ };
56
+ }
57
+ const listAffiliates = (adapter, params) => list(adapter, "affiliate", {
58
+ limit: params?.limit,
59
+ offset: params?.offset,
60
+ status: params?.status
61
+ });
62
+ const listCommissions = (adapter, params) => list(adapter, "affiliateCommission", params);
63
+ const listPayouts = (adapter, params) => list(adapter, "affiliatePayout", params);
64
+ async function allRows(adapter, model, where = []) {
65
+ const items = [];
66
+ for (let offset = 0; ; offset += 100) {
67
+ const rows = await adapter.findMany({
68
+ model,
69
+ where,
70
+ limit: 100,
71
+ offset,
72
+ sortBy: { field: "id", direction: "asc" }
73
+ });
74
+ items.push(...rows.map((row) => serializeAffiliateRecord(row)));
75
+ if (rows.length < 100) return items;
76
+ }
77
+ }
78
+ async function getAffiliateStats(adapter, affiliateId) {
79
+ const where = [
80
+ { field: "affiliateId", value: affiliateId, operator: "eq" }
81
+ ];
82
+ const [clicks, conversions, commissions] = await Promise.all([
83
+ adapter.count({ model: "referralClick", where }),
84
+ adapter.count({ model: "affiliateConversion", where }),
85
+ allRows(adapter, "affiliateCommission", where)
86
+ ]);
87
+ const currencies = /* @__PURE__ */ new Map();
88
+ for (const commission of commissions) {
89
+ const total = currencies.get(commission.currency) ?? {
90
+ currency: commission.currency,
91
+ pending: 0,
92
+ approved: 0,
93
+ paid: 0,
94
+ voided: 0
95
+ };
96
+ const next = BigInt(total[commission.status]) + BigInt(commission.amount);
97
+ if (next > BigInt(Number.MAX_SAFE_INTEGER))
98
+ throw new api.OperationHttpError(
99
+ 409,
100
+ "Commission total exceeds safe integer range",
101
+ "AFFILIATE_AMOUNT_OVERFLOW"
102
+ );
103
+ total[commission.status] = Number(next);
104
+ currencies.set(commission.currency, total);
105
+ }
106
+ return {
107
+ clicks,
108
+ conversions,
109
+ totals: [...currencies.values()].sort(
110
+ (a, b) => a.currency.localeCompare(b.currency)
111
+ )
112
+ };
113
+ }
114
+ async function getPortal(adapter, userId, assets = []) {
115
+ const affiliate = await getAffiliateByUserId(adapter, userId);
116
+ if (!affiliate)
117
+ return {
118
+ affiliate: null,
119
+ stats: { clicks: 0, conversions: 0, totals: [] },
120
+ commissions: [],
121
+ payouts: [],
122
+ assets
123
+ };
124
+ const [stats, commissions, payouts] = await Promise.all([
125
+ getAffiliateStats(adapter, affiliate.id),
126
+ listCommissions(adapter, { affiliateId: affiliate.id, limit: 100 }),
127
+ listPayouts(adapter, { affiliateId: affiliate.id, limit: 100 })
128
+ ]);
129
+ const { notes: _notes, ...profile } = affiliate;
130
+ return {
131
+ affiliate: profile,
132
+ stats,
133
+ commissions: commissions.items,
134
+ payouts: payouts.items,
135
+ assets
136
+ };
137
+ }
138
+ function csvCell(value) {
139
+ let text = value == null ? "" : String(value);
140
+ if (/^[\s]*[=+\-@\t\r\n]/.test(text)) text = `'${text}`;
141
+ return `"${text.replace(/"/g, '""')}"`;
142
+ }
143
+ async function exportPayouts(adapter, params = {}) {
144
+ const where = [];
145
+ for (const field of ["affiliateId", "status", "currency"]) {
146
+ const value = params[field];
147
+ if (value) where.push({ field, value, operator: "eq" });
148
+ }
149
+ const payouts = await allRows(adapter, "affiliatePayout", where);
150
+ const fields = [
151
+ "id",
152
+ "affiliateId",
153
+ "amount",
154
+ "currency",
155
+ "status",
156
+ "reference",
157
+ "paidAt",
158
+ "createdAt"
159
+ ];
160
+ return [
161
+ fields.map(csvCell).join(","),
162
+ ...payouts.map(
163
+ (row) => fields.map((field) => csvCell(row[field])).join(",")
164
+ )
165
+ ].join("\r\n");
166
+ }
167
+
168
+ exports.allRows = allRows;
169
+ exports.exportPayouts = exportPayouts;
170
+ exports.getAffiliate = getAffiliate;
171
+ exports.getAffiliateByCode = getAffiliateByCode;
172
+ exports.getAffiliateByUserId = getAffiliateByUserId;
173
+ exports.getAffiliateStats = getAffiliateStats;
174
+ exports.getCommission = getCommission;
175
+ exports.getConversionByExternalRef = getConversionByExternalRef;
176
+ exports.getPayout = getPayout;
177
+ exports.getPortal = getPortal;
178
+ exports.getReferralClick = getReferralClick;
179
+ exports.listAffiliates = listAffiliates;
180
+ exports.listCommissions = listCommissions;
181
+ exports.listPayouts = listPayouts;
182
+ exports.serializeAffiliateRecord = serializeAffiliateRecord;
@@ -0,0 +1,166 @@
1
+ import { OperationHttpError } from '@btst/stack/plugins/api';
2
+
3
+ function serializeAffiliateRecord(record) {
4
+ const { lockVersion: _lockVersion, ...result } = record;
5
+ for (const field of ["createdAt", "updatedAt", "paidAt"]) {
6
+ const value = result[field];
7
+ if (value instanceof Date) result[field] = value.toISOString();
8
+ }
9
+ return result;
10
+ }
11
+ async function byField(adapter, model, field, value) {
12
+ const row = await adapter.findOne({
13
+ model,
14
+ where: [{ field, value, operator: "eq" }]
15
+ });
16
+ return row ? serializeAffiliateRecord(row) : null;
17
+ }
18
+ const getAffiliate = (adapter, id) => byField(adapter, "affiliate", "id", id);
19
+ const getAffiliateByUserId = (adapter, userId) => byField(adapter, "affiliate", "userId", userId);
20
+ const getAffiliateByCode = (adapter, code) => byField(adapter, "affiliate", "code", code);
21
+ const getReferralClick = (adapter, id) => byField(adapter, "referralClick", "id", id);
22
+ const getCommission = (adapter, id) => byField(adapter, "affiliateCommission", "id", id);
23
+ const getPayout = (adapter, id) => byField(adapter, "affiliatePayout", "id", id);
24
+ const getConversionByExternalRef = (adapter, externalRef) => byField(
25
+ adapter,
26
+ "affiliateConversion",
27
+ "externalRef",
28
+ externalRef
29
+ );
30
+ async function list(adapter, model, params = {}) {
31
+ const where = [];
32
+ for (const field of ["affiliateId", "status", "currency"]) {
33
+ const value = params[field];
34
+ if (value) where.push({ field, value, operator: "eq" });
35
+ }
36
+ const limit = params.limit ?? 50;
37
+ const offset = params.offset ?? 0;
38
+ const [rows, total] = await Promise.all([
39
+ adapter.findMany({
40
+ model,
41
+ where,
42
+ limit,
43
+ offset,
44
+ sortBy: { field: "createdAt", direction: "desc" }
45
+ }),
46
+ adapter.count({ model, where })
47
+ ]);
48
+ return {
49
+ items: rows.map((row) => serializeAffiliateRecord(row)),
50
+ total,
51
+ limit,
52
+ offset
53
+ };
54
+ }
55
+ const listAffiliates = (adapter, params) => list(adapter, "affiliate", {
56
+ limit: params?.limit,
57
+ offset: params?.offset,
58
+ status: params?.status
59
+ });
60
+ const listCommissions = (adapter, params) => list(adapter, "affiliateCommission", params);
61
+ const listPayouts = (adapter, params) => list(adapter, "affiliatePayout", params);
62
+ async function allRows(adapter, model, where = []) {
63
+ const items = [];
64
+ for (let offset = 0; ; offset += 100) {
65
+ const rows = await adapter.findMany({
66
+ model,
67
+ where,
68
+ limit: 100,
69
+ offset,
70
+ sortBy: { field: "id", direction: "asc" }
71
+ });
72
+ items.push(...rows.map((row) => serializeAffiliateRecord(row)));
73
+ if (rows.length < 100) return items;
74
+ }
75
+ }
76
+ async function getAffiliateStats(adapter, affiliateId) {
77
+ const where = [
78
+ { field: "affiliateId", value: affiliateId, operator: "eq" }
79
+ ];
80
+ const [clicks, conversions, commissions] = await Promise.all([
81
+ adapter.count({ model: "referralClick", where }),
82
+ adapter.count({ model: "affiliateConversion", where }),
83
+ allRows(adapter, "affiliateCommission", where)
84
+ ]);
85
+ const currencies = /* @__PURE__ */ new Map();
86
+ for (const commission of commissions) {
87
+ const total = currencies.get(commission.currency) ?? {
88
+ currency: commission.currency,
89
+ pending: 0,
90
+ approved: 0,
91
+ paid: 0,
92
+ voided: 0
93
+ };
94
+ const next = BigInt(total[commission.status]) + BigInt(commission.amount);
95
+ if (next > BigInt(Number.MAX_SAFE_INTEGER))
96
+ throw new OperationHttpError(
97
+ 409,
98
+ "Commission total exceeds safe integer range",
99
+ "AFFILIATE_AMOUNT_OVERFLOW"
100
+ );
101
+ total[commission.status] = Number(next);
102
+ currencies.set(commission.currency, total);
103
+ }
104
+ return {
105
+ clicks,
106
+ conversions,
107
+ totals: [...currencies.values()].sort(
108
+ (a, b) => a.currency.localeCompare(b.currency)
109
+ )
110
+ };
111
+ }
112
+ async function getPortal(adapter, userId, assets = []) {
113
+ const affiliate = await getAffiliateByUserId(adapter, userId);
114
+ if (!affiliate)
115
+ return {
116
+ affiliate: null,
117
+ stats: { clicks: 0, conversions: 0, totals: [] },
118
+ commissions: [],
119
+ payouts: [],
120
+ assets
121
+ };
122
+ const [stats, commissions, payouts] = await Promise.all([
123
+ getAffiliateStats(adapter, affiliate.id),
124
+ listCommissions(adapter, { affiliateId: affiliate.id, limit: 100 }),
125
+ listPayouts(adapter, { affiliateId: affiliate.id, limit: 100 })
126
+ ]);
127
+ const { notes: _notes, ...profile } = affiliate;
128
+ return {
129
+ affiliate: profile,
130
+ stats,
131
+ commissions: commissions.items,
132
+ payouts: payouts.items,
133
+ assets
134
+ };
135
+ }
136
+ function csvCell(value) {
137
+ let text = value == null ? "" : String(value);
138
+ if (/^[\s]*[=+\-@\t\r\n]/.test(text)) text = `'${text}`;
139
+ return `"${text.replace(/"/g, '""')}"`;
140
+ }
141
+ async function exportPayouts(adapter, params = {}) {
142
+ const where = [];
143
+ for (const field of ["affiliateId", "status", "currency"]) {
144
+ const value = params[field];
145
+ if (value) where.push({ field, value, operator: "eq" });
146
+ }
147
+ const payouts = await allRows(adapter, "affiliatePayout", where);
148
+ const fields = [
149
+ "id",
150
+ "affiliateId",
151
+ "amount",
152
+ "currency",
153
+ "status",
154
+ "reference",
155
+ "paidAt",
156
+ "createdAt"
157
+ ];
158
+ return [
159
+ fields.map(csvCell).join(","),
160
+ ...payouts.map(
161
+ (row) => fields.map((field) => csvCell(row[field])).join(",")
162
+ )
163
+ ].join("\r\n");
164
+ }
165
+
166
+ export { allRows, exportPayouts, getAffiliate, getAffiliateByCode, getAffiliateByUserId, getAffiliateStats, getCommission, getConversionByExternalRef, getPayout, getPortal, getReferralClick, listAffiliates, listCommissions, listPayouts, serializeAffiliateRecord };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const plugin = require('./plugin.cjs');
4
+ const db = require('../db.cjs');
5
+ const permissions = require('../permissions.cjs');
6
+ const getters = require('./getters.cjs');
7
+ const mutations = require('./mutations.cjs');
8
+ const attribution = require('../attribution.cjs');
9
+ const commission = require('../commission.cjs');
10
+
11
+
12
+
13
+ exports.affiliateBackendPlugin = plugin.affiliateBackendPlugin;
14
+ exports.affiliateSchema = db.affiliateSchema;
15
+ exports.affiliatePermissions = permissions.affiliatePermissions;
16
+ exports.allRows = getters.allRows;
17
+ exports.exportPayouts = getters.exportPayouts;
18
+ exports.getAffiliate = getters.getAffiliate;
19
+ exports.getAffiliateByCode = getters.getAffiliateByCode;
20
+ exports.getAffiliateByUserId = getters.getAffiliateByUserId;
21
+ exports.getAffiliateStats = getters.getAffiliateStats;
22
+ exports.getCommission = getters.getCommission;
23
+ exports.getConversionByExternalRef = getters.getConversionByExternalRef;
24
+ exports.getPayout = getters.getPayout;
25
+ exports.getPortal = getters.getPortal;
26
+ exports.getReferralClick = getters.getReferralClick;
27
+ exports.listAffiliates = getters.listAffiliates;
28
+ exports.listCommissions = getters.listCommissions;
29
+ exports.listPayouts = getters.listPayouts;
30
+ exports.serializeAffiliateRecord = getters.serializeAffiliateRecord;
31
+ exports.createAffiliate = mutations.createAffiliate;
32
+ exports.createConversion = mutations.createConversion;
33
+ exports.createPayout = mutations.createPayout;
34
+ exports.deleteAffiliate = mutations.deleteAffiliate;
35
+ exports.trackClick = mutations.trackClick;
36
+ exports.updateAffiliate = mutations.updateAffiliate;
37
+ exports.updateCommission = mutations.updateCommission;
38
+ exports.updatePayout = mutations.updatePayout;
39
+ exports.withAffiliateTransaction = mutations.withAffiliateTransaction;
40
+ exports.AFFILIATE_COOKIE_NAME = attribution.AFFILIATE_COOKIE_NAME;
41
+ exports.attributionFromRequest = attribution.attributionFromRequest;
42
+ exports.createReferralLink = attribution.createReferralLink;
43
+ exports.createTrackingLink = attribution.createTrackingLink;
44
+ exports.getReferralRedirect = attribution.getReferralRedirect;
45
+ exports.isClickWithinWindow = attribution.isClickWithinWindow;
46
+ exports.referralCodeFromURL = attribution.referralCodeFromURL;
47
+ exports.safeLandingPath = attribution.safeLandingPath;
48
+ exports.selectAttributionClick = attribution.selectAttributionClick;
49
+ exports.calculateCommission = commission.calculateCommission;