@fantastic.dev/better-stripe 0.23.1 → 0.24.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.
- package/CHANGELOG.md +26 -2
- package/README.md +40 -5
- package/dist/client/affiliateRecovery/disputes.d.ts +18 -0
- package/dist/client/affiliateRecovery/disputes.d.ts.map +1 -0
- package/dist/client/affiliateRecovery/disputes.js +33 -0
- package/dist/client/affiliateRecovery/disputes.js.map +1 -0
- package/dist/client/affiliateRecovery/engine.d.ts +29 -0
- package/dist/client/affiliateRecovery/engine.d.ts.map +1 -0
- package/dist/client/affiliateRecovery/engine.js +116 -0
- package/dist/client/affiliateRecovery/engine.js.map +1 -0
- package/dist/client/affiliateRecovery/payoutGate.d.ts +24 -0
- package/dist/client/affiliateRecovery/payoutGate.d.ts.map +1 -0
- package/dist/client/affiliateRecovery/payoutGate.js +30 -0
- package/dist/client/affiliateRecovery/payoutGate.js.map +1 -0
- package/dist/client/affiliateRecovery/provider.d.ts +14 -0
- package/dist/client/affiliateRecovery/provider.d.ts.map +1 -0
- package/dist/client/affiliateRecovery/provider.js +96 -0
- package/dist/client/affiliateRecovery/provider.js.map +1 -0
- package/dist/client/affiliateRecovery/review.d.ts +28 -0
- package/dist/client/affiliateRecovery/review.d.ts.map +1 -0
- package/dist/client/affiliateRecovery/review.js +86 -0
- package/dist/client/affiliateRecovery/review.js.map +1 -0
- package/dist/client/affiliateRecovery/validators.d.ts +402 -0
- package/dist/client/affiliateRecovery/validators.d.ts.map +1 -0
- package/dist/client/affiliateRecovery/validators.js +27 -0
- package/dist/client/affiliateRecovery/validators.js.map +1 -0
- package/dist/client/affiliateRecovery.d.ts +131 -0
- package/dist/client/affiliateRecovery.d.ts.map +1 -0
- package/dist/client/affiliateRecovery.js +69 -0
- package/dist/client/affiliateRecovery.js.map +1 -0
- package/dist/client/connect/commissionReceipts.d.ts +4 -0
- package/dist/client/connect/commissionReceipts.d.ts.map +1 -0
- package/dist/client/connect/commissionReceipts.js +17 -0
- package/dist/client/connect/commissionReceipts.js.map +1 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +536 -2
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSync.d.ts +32 -0
- package/dist/client/connect/payoutSync.d.ts.map +1 -0
- package/dist/client/connect/payoutSync.js +48 -0
- package/dist/client/connect/payoutSync.js.map +1 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +1509 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -0
- package/dist/client/connect/payoutSyncTestHelpers.js +62 -0
- package/dist/client/connect/payoutSyncTestHelpers.js.map +1 -0
- package/dist/client/connect/payoutSyncValidation.d.ts +16 -0
- package/dist/client/connect/payoutSyncValidation.d.ts.map +1 -0
- package/dist/client/connect/payoutSyncValidation.js +54 -0
- package/dist/client/connect/payoutSyncValidation.js.map +1 -0
- package/dist/client/connect/payouts.d.ts +3 -1
- package/dist/client/connect/payouts.d.ts.map +1 -1
- package/dist/client/connect/payouts.js +45 -12
- package/dist/client/connect/payouts.js.map +1 -1
- package/dist/client/connect/refundPrincipal.d.ts +4 -0
- package/dist/client/connect/refundPrincipal.d.ts.map +1 -0
- package/dist/client/connect/refundPrincipal.js +21 -0
- package/dist/client/connect/refundPrincipal.js.map +1 -0
- package/dist/client/connect/reversalExecution.d.ts +47 -0
- package/dist/client/connect/reversalExecution.d.ts.map +1 -0
- package/dist/client/connect/reversalExecution.js +84 -0
- package/dist/client/connect/reversalExecution.js.map +1 -0
- package/dist/client/connect/transfers.d.ts +8 -4
- package/dist/client/connect/transfers.d.ts.map +1 -1
- package/dist/client/connect/transfers.js +52 -57
- package/dist/client/connect/transfers.js.map +1 -1
- package/dist/client/index.d.ts +29 -9
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +9 -6
- package/dist/client/index.js.map +1 -1
- package/dist/client/readContracts.d.ts +8 -0
- package/dist/client/readContracts.d.ts.map +1 -1
- package/dist/client/readContracts.js +7 -0
- package/dist/client/readContracts.js.map +1 -1
- package/dist/client/settlement/execution.d.ts.map +1 -1
- package/dist/client/settlement/execution.js +30 -3
- package/dist/client/settlement/execution.js.map +1 -1
- package/dist/client/settlement/reconciliation.d.ts.map +1 -1
- package/dist/client/settlement/reconciliation.js +16 -2
- package/dist/client/settlement/reconciliation.js.map +1 -1
- package/dist/client/webhooks/disputeRecovery.d.ts +4 -0
- package/dist/client/webhooks/disputeRecovery.d.ts.map +1 -0
- package/dist/client/webhooks/disputeRecovery.js +40 -0
- package/dist/client/webhooks/disputeRecovery.js.map +1 -0
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +14 -29
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/component/_generated/component.d.ts +560 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/affiliateEarnings/mutations.d.ts +22 -0
- package/dist/component/affiliateEarnings/mutations.d.ts.map +1 -0
- package/dist/component/affiliateEarnings/mutations.js +160 -0
- package/dist/component/affiliateEarnings/mutations.js.map +1 -0
- package/dist/component/affiliatePayouts/mutations.d.ts +25 -0
- package/dist/component/affiliatePayouts/mutations.d.ts.map +1 -0
- package/dist/component/affiliatePayouts/mutations.js +104 -0
- package/dist/component/affiliatePayouts/mutations.js.map +1 -0
- package/dist/component/affiliatePayouts/queries.d.ts +23 -0
- package/dist/component/affiliatePayouts/queries.d.ts.map +1 -0
- package/dist/component/affiliatePayouts/queries.js +23 -0
- package/dist/component/affiliatePayouts/queries.js.map +1 -0
- package/dist/component/affiliatePayouts/recipientGuard.d.ts +12 -0
- package/dist/component/affiliatePayouts/recipientGuard.d.ts.map +1 -0
- package/dist/component/affiliatePayouts/recipientGuard.js +26 -0
- package/dist/component/affiliatePayouts/recipientGuard.js.map +1 -0
- package/dist/component/affiliateRecovery/accounting.d.ts +28 -0
- package/dist/component/affiliateRecovery/accounting.d.ts.map +1 -0
- package/dist/component/affiliateRecovery/accounting.js +71 -0
- package/dist/component/affiliateRecovery/accounting.js.map +1 -0
- package/dist/component/affiliateRecovery/mutations.d.ts +65 -0
- package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -0
- package/dist/component/affiliateRecovery/mutations.js +250 -0
- package/dist/component/affiliateRecovery/mutations.js.map +1 -0
- package/dist/component/affiliateRecovery/queries.d.ts +305 -0
- package/dist/component/affiliateRecovery/queries.d.ts.map +1 -0
- package/dist/component/affiliateRecovery/queries.js +113 -0
- package/dist/component/affiliateRecovery/queries.js.map +1 -0
- package/dist/component/affiliateRecovery/schema.d.ts +171 -0
- package/dist/component/affiliateRecovery/schema.d.ts.map +1 -0
- package/dist/component/affiliateRecovery/schema.js +71 -0
- package/dist/component/affiliateRecovery/schema.js.map +1 -0
- package/dist/component/connect/mutations.d.ts +36 -23
- package/dist/component/connect/mutations.d.ts.map +1 -1
- package/dist/component/connect/mutations.js +11 -151
- package/dist/component/connect/mutations.js.map +1 -1
- package/dist/component/connect/payoutWrites.d.ts +21 -0
- package/dist/component/connect/payoutWrites.d.ts.map +1 -0
- package/dist/component/connect/payoutWrites.js +19 -0
- package/dist/component/connect/payoutWrites.js.map +1 -0
- package/dist/component/connect/queries.d.ts +10 -0
- package/dist/component/connect/queries.d.ts.map +1 -1
- package/dist/component/connect/queries.js +3 -40
- package/dist/component/connect/queries.js.map +1 -1
- package/dist/component/connect/reversalClaims.d.ts +169 -0
- package/dist/component/connect/reversalClaims.d.ts.map +1 -0
- package/dist/component/connect/reversalClaims.js +176 -0
- package/dist/component/connect/reversalClaims.js.map +1 -0
- package/dist/component/connect/reversalDiagnostics.d.ts +59 -0
- package/dist/component/connect/reversalDiagnostics.d.ts.map +1 -0
- package/dist/component/connect/reversalDiagnostics.js +50 -0
- package/dist/component/connect/reversalDiagnostics.js.map +1 -0
- package/dist/component/connect/reversalReceipts.d.ts +27 -0
- package/dist/component/connect/reversalReceipts.d.ts.map +1 -0
- package/dist/component/connect/reversalReceipts.js +85 -0
- package/dist/component/connect/reversalReceipts.js.map +1 -0
- package/dist/component/connect/schema.d.ts +31 -1
- package/dist/component/connect/schema.d.ts.map +1 -1
- package/dist/component/connect/schema.js +3 -1
- package/dist/component/connect/schema.js.map +1 -1
- package/dist/component/connect/validators.d.ts +49 -1
- package/dist/component/connect/validators.d.ts.map +1 -1
- package/dist/component/connect/validators.js +2 -0
- package/dist/component/connect/validators.js.map +1 -1
- package/dist/component/earnings/triggers.d.ts +454 -2
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/mutations.d.ts.map +1 -1
- package/dist/component/payoutRelease/mutations.js +6 -0
- package/dist/component/payoutRelease/mutations.js.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.js +3 -1
- package/dist/component/payoutRelease/queries.js.map +1 -1
- package/dist/component/payoutSync/helpers.d.ts +44 -0
- package/dist/component/payoutSync/helpers.d.ts.map +1 -0
- package/dist/component/payoutSync/helpers.js +60 -0
- package/dist/component/payoutSync/helpers.js.map +1 -0
- package/dist/component/payoutSync/mutations.d.ts +51 -0
- package/dist/component/payoutSync/mutations.d.ts.map +1 -0
- package/dist/component/payoutSync/mutations.js +88 -0
- package/dist/component/payoutSync/mutations.js.map +1 -0
- package/dist/component/payoutSync/queries.d.ts +16 -0
- package/dist/component/payoutSync/queries.d.ts.map +1 -0
- package/dist/component/payoutSync/queries.js +11 -0
- package/dist/component/payoutSync/queries.js.map +1 -0
- package/dist/component/payoutSync/schema.d.ts +46 -0
- package/dist/component/payoutSync/schema.d.ts.map +1 -0
- package/dist/component/payoutSync/schema.js +22 -0
- package/dist/component/payoutSync/schema.js.map +1 -0
- package/dist/component/payoutSync/validators.d.ts +137 -0
- package/dist/component/payoutSync/validators.d.ts.map +1 -0
- package/dist/component/payoutSync/validators.js +19 -0
- package/dist/component/payoutSync/validators.js.map +1 -0
- package/dist/component/schema.d.ts +268 -1
- package/dist/component/schema.js +11 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/settlement/clawbackSchema.d.ts +161 -0
- package/dist/component/settlement/clawbackSchema.d.ts.map +1 -0
- package/dist/component/settlement/clawbackSchema.js +73 -0
- package/dist/component/settlement/clawbackSchema.js.map +1 -0
- package/dist/component/settlement/clawbacks.d.ts +55 -0
- package/dist/component/settlement/clawbacks.d.ts.map +1 -0
- package/dist/component/settlement/clawbacks.js +146 -0
- package/dist/component/settlement/clawbacks.js.map +1 -0
- package/dist/component/settlement/mutations.d.ts +16 -0
- package/dist/component/settlement/mutations.d.ts.map +1 -1
- package/dist/component/settlement/mutations.js +48 -0
- package/dist/component/settlement/mutations.js.map +1 -1
- package/dist/component/settlement/queries.d.ts +53 -0
- package/dist/component/settlement/queries.d.ts.map +1 -1
- package/dist/component/settlement/queries.js +26 -0
- package/dist/component/settlement/queries.js.map +1 -1
- package/dist/react/workflows/AffiliateRecovery.d.ts +46 -0
- package/dist/react/workflows/AffiliateRecovery.d.ts.map +1 -0
- package/dist/react/workflows/AffiliateRecovery.js +84 -0
- package/dist/react/workflows/AffiliateRecovery.js.map +1 -0
- package/dist/react/workflows/index.d.ts +2 -0
- package/dist/react/workflows/index.d.ts.map +1 -1
- package/dist/react/workflows/index.js +1 -0
- package/dist/react/workflows/index.js.map +1 -1
- package/dist/testing/affiliate-recovery.d.ts +10 -0
- package/dist/testing/affiliate-recovery.d.ts.map +1 -0
- package/dist/testing/affiliate-recovery.js +126 -0
- package/dist/testing/affiliate-recovery.js.map +1 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +1 -0
- package/dist/testing/index.js.map +1 -1
- package/docs/affiliate-clawbacks.md +306 -0
- package/docs/read-contracts.md +40 -5
- package/docs/settlement.md +17 -0
- package/package.json +2 -1
- package/src/client/affiliateRecovery/disputes.ts +62 -0
- package/src/client/affiliateRecovery/engine.ts +196 -0
- package/src/client/affiliateRecovery/payoutGate.ts +65 -0
- package/src/client/affiliateRecovery/provider.ts +127 -0
- package/src/client/affiliateRecovery/review.ts +117 -0
- package/src/client/affiliateRecovery/validators.ts +38 -0
- package/src/client/affiliateRecovery.ts +173 -0
- package/src/client/connect/commissionReceipts.test.ts +157 -0
- package/src/client/connect/commissionReceipts.ts +23 -0
- package/src/client/connect/payoutSync.test.ts +313 -0
- package/src/client/connect/payoutSync.ts +93 -0
- package/src/client/connect/payoutSyncTestHelpers.ts +82 -0
- package/src/client/connect/payoutSyncValidation.ts +74 -0
- package/src/client/connect/payouts.ts +75 -15
- package/src/client/connect/refundPrincipal.test.ts +46 -0
- package/src/client/connect/refundPrincipal.ts +26 -0
- package/src/client/connect/reversalExecution.ts +130 -0
- package/src/client/connect/transfers.test.ts +3 -3
- package/src/client/connect/transfers.ts +93 -92
- package/src/client/index.ts +20 -18
- package/src/client/readContracts.ts +12 -0
- package/src/client/settlement/execution.test.ts +5 -0
- package/src/client/settlement/execution.ts +50 -3
- package/src/client/settlement/reconciliation.ts +20 -2
- package/src/client/webhooks/disputeRecovery.ts +74 -0
- package/src/client/webhooks/processors.test.ts +36 -53
- package/src/client/webhooks/processors.ts +18 -31
- package/src/component/_generated/api.ts +34 -0
- package/src/component/_generated/component.ts +696 -1
- package/src/component/affiliate-clawbacks.test.ts +370 -0
- package/src/component/affiliate-component-pagination.test.ts +83 -0
- package/src/component/affiliate-direct-payout.test.ts +160 -0
- package/src/component/affiliate-recovery-lifecycle.test.ts +587 -0
- package/src/component/affiliateEarnings/mutations.ts +196 -0
- package/src/component/affiliatePayouts/mutations.ts +121 -0
- package/src/component/affiliatePayouts/queries.ts +28 -0
- package/src/component/affiliatePayouts/recipientGuard.ts +42 -0
- package/src/component/affiliateRecovery/accounting.ts +111 -0
- package/src/component/affiliateRecovery/mutations.ts +275 -0
- package/src/component/affiliateRecovery/queries.ts +138 -0
- package/src/component/affiliateRecovery/schema.ts +86 -0
- package/src/component/connect/mutations.ts +13 -190
- package/src/component/connect/payoutWrites.ts +25 -0
- package/src/component/connect/queries.ts +4 -47
- package/src/component/connect/reversalClaims.ts +232 -0
- package/src/component/connect/reversalDiagnostics.ts +61 -0
- package/src/component/connect/reversalReceipts.ts +147 -0
- package/src/component/connect/schema.ts +3 -3
- package/src/component/connect/validators.ts +2 -0
- package/src/component/payout-recovery-integration.test.ts +172 -0
- package/src/component/payout-sync.test.ts +117 -0
- package/src/component/payoutRelease/mutations.ts +9 -0
- package/src/component/payoutRelease/queries.ts +3 -1
- package/src/component/payoutSync/helpers.ts +86 -0
- package/src/component/payoutSync/mutations.ts +102 -0
- package/src/component/payoutSync/queries.ts +10 -0
- package/src/component/payoutSync/schema.ts +25 -0
- package/src/component/payoutSync/validators.ts +21 -0
- package/src/component/schema.ts +20 -0
- package/src/component/settlement/clawbackSchema.ts +78 -0
- package/src/component/settlement/clawbacks.ts +233 -0
- package/src/component/settlement/mutations.ts +54 -0
- package/src/component/settlement/queries.ts +35 -0
- package/src/component/summary-arithmetic.test.ts +9 -4
- package/src/react/workflows/AffiliateRecovery.test.tsx +106 -0
- package/src/react/workflows/AffiliateRecovery.tsx +273 -0
- package/src/react/workflows/index.ts +9 -0
- package/src/testing/affiliate-recovery.ts +137 -0
- package/src/testing/index.ts +2 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { commissionExposureValidator } from "../settlement/clawbackSchema.js";
|
|
2
|
+
import { applyObligationExposure } from "../settlement/clawbacks.js";
|
|
3
|
+
import { v } from "convex/values";
|
|
4
|
+
import { mutation } from "../earnings/triggers.js";
|
|
5
|
+
import { balance, updateObligation, due, credit } from "./accounting.js";
|
|
6
|
+
import { operationFields, recoveryState } from "./schema.js";
|
|
7
|
+
import { deriveReversalState } from "../lib/reversals.js";
|
|
8
|
+
const operationDoc = v.object({
|
|
9
|
+
...operationFields,
|
|
10
|
+
_id: v.id("affiliateRecoveryOperations"),
|
|
11
|
+
_creationTime: v.number(),
|
|
12
|
+
});
|
|
13
|
+
export const reserveOperation = mutation({
|
|
14
|
+
args: {
|
|
15
|
+
obligationId: v.id("affiliateObligations"),
|
|
16
|
+
kind: v.union(v.literal("recovery"), v.literal("restoration")),
|
|
17
|
+
now: v.number(),
|
|
18
|
+
},
|
|
19
|
+
returns: v.union(operationDoc, v.null()),
|
|
20
|
+
handler: async (ctx, args) => {
|
|
21
|
+
const row = await ctx.db.get("affiliateObligations", args.obligationId);
|
|
22
|
+
if (!row) throw new Error("Affiliate obligation not found.");
|
|
23
|
+
if (row.needsReconciliation) return null;
|
|
24
|
+
if (
|
|
25
|
+
(await balance(ctx, row.affiliateAccountId, row.currency))
|
|
26
|
+
?.activePayoutKey
|
|
27
|
+
)
|
|
28
|
+
throw new Error("Affiliate payout is pending reconciliation.");
|
|
29
|
+
if (row.activeOperationId)
|
|
30
|
+
return ctx.db.get("affiliateRecoveryOperations", row.activeOperationId);
|
|
31
|
+
const originalTransfer = row.stripeTransferId
|
|
32
|
+
? await ctx.db
|
|
33
|
+
.query("transfers")
|
|
34
|
+
.withIndex("by_stripe_transfer_id", (q) =>
|
|
35
|
+
q.eq("stripeTransferId", row.stripeTransferId!),
|
|
36
|
+
)
|
|
37
|
+
.unique()
|
|
38
|
+
: null;
|
|
39
|
+
const reversible = originalTransfer
|
|
40
|
+
? originalTransfer.amount - (originalTransfer.reversedAmount ?? 0)
|
|
41
|
+
: 0;
|
|
42
|
+
const amount =
|
|
43
|
+
args.kind === "recovery"
|
|
44
|
+
? Math.min(due(row), Math.max(0, reversible))
|
|
45
|
+
: credit(row);
|
|
46
|
+
if (amount <= 0 || (args.kind === "recovery" && !row.stripeTransferId)) {
|
|
47
|
+
if (args.kind === "recovery" && due(row) > 0)
|
|
48
|
+
await updateObligation(ctx, row, {
|
|
49
|
+
lastState: "offset_required",
|
|
50
|
+
lastError:
|
|
51
|
+
"Original transfer has no reversible funds; recover from eligible future commissions.",
|
|
52
|
+
});
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const id = await ctx.db.insert("affiliateRecoveryOperations", {
|
|
56
|
+
obligationId: row._id,
|
|
57
|
+
sourceEventId:
|
|
58
|
+
args.kind === "restoration"
|
|
59
|
+
? row.disputeId
|
|
60
|
+
: (row.lastRefundId ?? row.disputeId),
|
|
61
|
+
kind: args.kind,
|
|
62
|
+
amount,
|
|
63
|
+
state: "pending",
|
|
64
|
+
attempted: false,
|
|
65
|
+
providerBaseline: originalTransfer?.reversedAmount ?? 0,
|
|
66
|
+
createdAt: args.now,
|
|
67
|
+
});
|
|
68
|
+
await updateObligation(ctx, row, {
|
|
69
|
+
activeOperationId: id,
|
|
70
|
+
[args.kind === "recovery" ? "reservedRecovery" : "reservedRestoration"]:
|
|
71
|
+
amount,
|
|
72
|
+
lastState: "pending",
|
|
73
|
+
lastError: undefined,
|
|
74
|
+
});
|
|
75
|
+
return (await ctx.db.get("affiliateRecoveryOperations", id))!;
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
/** Persist intent before contacting Stripe. Retries keep the exact operation ID. */
|
|
79
|
+
export const beginOperation = mutation({
|
|
80
|
+
args: { operationId: v.id("affiliateRecoveryOperations") },
|
|
81
|
+
returns: operationDoc,
|
|
82
|
+
handler: async (ctx, { operationId }) => {
|
|
83
|
+
const op = await ctx.db.get("affiliateRecoveryOperations", operationId);
|
|
84
|
+
if (!op) throw new Error("Affiliate operation not found.");
|
|
85
|
+
const row = (await ctx.db.get("affiliateObligations", op.obligationId))!;
|
|
86
|
+
if (
|
|
87
|
+
!op.attempted &&
|
|
88
|
+
(op.kind === "recovery" ? due(row) : credit(row)) < op.amount
|
|
89
|
+
) {
|
|
90
|
+
await ctx.db.patch("affiliateRecoveryOperations", op._id, {
|
|
91
|
+
state: "canceled",
|
|
92
|
+
});
|
|
93
|
+
await updateObligation(ctx, row, {
|
|
94
|
+
activeOperationId: undefined,
|
|
95
|
+
reservedRecovery: 0,
|
|
96
|
+
reservedRestoration: 0,
|
|
97
|
+
lastState: "canceled",
|
|
98
|
+
});
|
|
99
|
+
return { ...op, state: "canceled" as const };
|
|
100
|
+
}
|
|
101
|
+
if (op.state === "pending" && !op.attempted)
|
|
102
|
+
await ctx.db.patch("affiliateRecoveryOperations", op._id, {
|
|
103
|
+
attempted: true,
|
|
104
|
+
});
|
|
105
|
+
return { ...op, attempted: true };
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
export const completeOperation = mutation({
|
|
109
|
+
args: {
|
|
110
|
+
operationId: v.id("affiliateRecoveryOperations"),
|
|
111
|
+
state: recoveryState,
|
|
112
|
+
receiptId: v.optional(v.string()),
|
|
113
|
+
confirmedTransferReversed: v.optional(v.number()),
|
|
114
|
+
error: v.optional(v.string()),
|
|
115
|
+
},
|
|
116
|
+
returns: v.null(),
|
|
117
|
+
handler: async (ctx, args) => {
|
|
118
|
+
const op = await ctx.db.get(
|
|
119
|
+
"affiliateRecoveryOperations",
|
|
120
|
+
args.operationId,
|
|
121
|
+
);
|
|
122
|
+
if (!op) throw new Error("Affiliate operation not found.");
|
|
123
|
+
if (op.state === "succeeded") {
|
|
124
|
+
if (args.state === "succeeded" && op.receiptId !== args.receiptId)
|
|
125
|
+
throw new Error("Affiliate receipt identity cannot change.");
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
const row = (await ctx.db.get("affiliateObligations", op.obligationId))!;
|
|
129
|
+
if (args.state === "succeeded" && !args.receiptId)
|
|
130
|
+
throw new Error("Confirmed affiliate recovery requires a receipt.");
|
|
131
|
+
const pending = args.state === "pending" || args.state === "unknown";
|
|
132
|
+
const patch = {
|
|
133
|
+
lastState: args.state,
|
|
134
|
+
lastError: args.error,
|
|
135
|
+
activeOperationId: pending ? op._id : undefined,
|
|
136
|
+
reservedRecovery: op.kind === "recovery" && pending ? op.amount : 0,
|
|
137
|
+
reservedRestoration: op.kind === "restoration" && pending ? op.amount : 0,
|
|
138
|
+
};
|
|
139
|
+
if (args.state === "succeeded") {
|
|
140
|
+
if (op.kind === "recovery") {
|
|
141
|
+
if (!row.stripeTransferId)
|
|
142
|
+
throw new Error("Recovery has no original Connect transfer.");
|
|
143
|
+
const transfer = await ctx.db
|
|
144
|
+
.query("transfers")
|
|
145
|
+
.withIndex("by_stripe_transfer_id", (q) =>
|
|
146
|
+
q.eq("stripeTransferId", row.stripeTransferId!),
|
|
147
|
+
)
|
|
148
|
+
.unique();
|
|
149
|
+
if (!transfer) throw new Error("Original transfer not found.");
|
|
150
|
+
const total = row.recoveredAmount + op.amount;
|
|
151
|
+
if (total > transfer.amount)
|
|
152
|
+
throw new Error("Recovery exceeds original transfer.");
|
|
153
|
+
const aggregate = args.confirmedTransferReversed;
|
|
154
|
+
if (
|
|
155
|
+
aggregate === undefined ||
|
|
156
|
+
!Number.isSafeInteger(aggregate) ||
|
|
157
|
+
aggregate < total ||
|
|
158
|
+
aggregate > transfer.amount
|
|
159
|
+
)
|
|
160
|
+
throw new Error(
|
|
161
|
+
"A confirmed provider transfer aggregate is required.",
|
|
162
|
+
);
|
|
163
|
+
await ctx.db.patch(
|
|
164
|
+
"transfers",
|
|
165
|
+
transfer._id,
|
|
166
|
+
deriveReversalState(
|
|
167
|
+
transfer.amount,
|
|
168
|
+
Math.max(aggregate, transfer.reversedAmount ?? 0),
|
|
169
|
+
transfer.status,
|
|
170
|
+
),
|
|
171
|
+
);
|
|
172
|
+
const duplicate = await ctx.db
|
|
173
|
+
.query("affiliateReversalReceipts")
|
|
174
|
+
.withIndex("by_receipt", (q) =>
|
|
175
|
+
q.eq("stripeReversalId", args.receiptId!),
|
|
176
|
+
)
|
|
177
|
+
.unique();
|
|
178
|
+
if (duplicate)
|
|
179
|
+
throw new Error(
|
|
180
|
+
"Affiliate reversal receipt has already been attributed.",
|
|
181
|
+
);
|
|
182
|
+
await ctx.db.insert("affiliateReversalReceipts", {
|
|
183
|
+
stripeReversalId: args.receiptId!,
|
|
184
|
+
stripeTransferId: row.stripeTransferId,
|
|
185
|
+
operationId: op._id,
|
|
186
|
+
amount: op.amount,
|
|
187
|
+
});
|
|
188
|
+
await updateObligation(ctx, row, { ...patch, recoveredAmount: total });
|
|
189
|
+
} else {
|
|
190
|
+
await ctx.db.insert("transfers", {
|
|
191
|
+
stripeTransferId: args.receiptId!,
|
|
192
|
+
sourceChargeId: row.sourceChargeId,
|
|
193
|
+
sourceInvoiceId: row.sourceInvoiceId,
|
|
194
|
+
destinationAccountId: row.affiliateAccountId,
|
|
195
|
+
currency: row.currency,
|
|
196
|
+
amount: op.amount,
|
|
197
|
+
role: "affiliate",
|
|
198
|
+
status: "paid",
|
|
199
|
+
reinstatement: true,
|
|
200
|
+
metadata: { bsRecoveryOperation: op._id },
|
|
201
|
+
});
|
|
202
|
+
await updateObligation(ctx, row, {
|
|
203
|
+
...patch,
|
|
204
|
+
restoredAmount: (row.restoredAmount ?? 0) + op.amount,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
} else await updateObligation(ctx, row, patch);
|
|
208
|
+
await ctx.db.patch("affiliateRecoveryOperations", op._id, {
|
|
209
|
+
state: args.state,
|
|
210
|
+
receiptId: args.receiptId,
|
|
211
|
+
error: args.error,
|
|
212
|
+
});
|
|
213
|
+
return null;
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
/** Trusted operator API; the client verifies provider facts before this write. */
|
|
218
|
+
export const reviewLegacy = mutation({
|
|
219
|
+
args: {
|
|
220
|
+
obligationId: v.id("affiliateObligations"),
|
|
221
|
+
recoveredAmount: v.number(),
|
|
222
|
+
restoredAmount: v.number(),
|
|
223
|
+
receipts: v.array(v.object({ id: v.string(), amount: v.number() })),
|
|
224
|
+
restorationIds: v.array(v.string()),
|
|
225
|
+
note: v.string(),
|
|
226
|
+
exposure: commissionExposureValidator,
|
|
227
|
+
},
|
|
228
|
+
returns: v.null(),
|
|
229
|
+
handler: async (ctx, args) => {
|
|
230
|
+
const row = await ctx.db.get("affiliateObligations", args.obligationId);
|
|
231
|
+
if (!row || !row.needsReconciliation || row.activeOperationId)
|
|
232
|
+
throw new Error("Obligation is not eligible for legacy review.");
|
|
233
|
+
if (
|
|
234
|
+
!args.note.trim() ||
|
|
235
|
+
args.receipts.length > 100 ||
|
|
236
|
+
new Set(args.receipts.map((r) => r.id)).size !== args.receipts.length ||
|
|
237
|
+
![
|
|
238
|
+
args.recoveredAmount,
|
|
239
|
+
args.restoredAmount,
|
|
240
|
+
...args.receipts.map((r) => r.amount),
|
|
241
|
+
].every((n) => Number.isSafeInteger(n) && n >= 0) ||
|
|
242
|
+
args.recoveredAmount > row.originalCommission ||
|
|
243
|
+
args.restoredAmount > args.recoveredAmount ||
|
|
244
|
+
args.receipts.reduce((n, r) => n + r.amount, 0) !== args.recoveredAmount
|
|
245
|
+
)
|
|
246
|
+
throw new Error("Legacy review does not reconcile.");
|
|
247
|
+
await applyObligationExposure(ctx, row, args.exposure);
|
|
248
|
+
const observed = (await ctx.db.get("affiliateObligations", row._id))!;
|
|
249
|
+
for (const receipt of args.receipts) {
|
|
250
|
+
const existing = await ctx.db
|
|
251
|
+
.query("affiliateReversalReceipts")
|
|
252
|
+
.withIndex("by_receipt", (q) => q.eq("stripeReversalId", receipt.id))
|
|
253
|
+
.unique();
|
|
254
|
+
if (existing && existing.stripeTransferId !== row.stripeTransferId)
|
|
255
|
+
throw new Error("Legacy receipt belongs to another original transfer.");
|
|
256
|
+
if (!existing)
|
|
257
|
+
await ctx.db.insert("affiliateReversalReceipts", {
|
|
258
|
+
stripeReversalId: receipt.id,
|
|
259
|
+
stripeTransferId: row.stripeTransferId!,
|
|
260
|
+
operationId: `review:${row._id}`,
|
|
261
|
+
amount: receipt.amount,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
await updateObligation(ctx, observed, {
|
|
265
|
+
recoveredAmount: args.recoveredAmount,
|
|
266
|
+
restoredAmount: args.restoredAmount,
|
|
267
|
+
needsReconciliation: false,
|
|
268
|
+
legacyReceiptIds: args.receipts.map((r) => r.id),
|
|
269
|
+
legacyRestorationIds: args.restorationIds,
|
|
270
|
+
operatorNote: args.note,
|
|
271
|
+
lastState: "reviewed",
|
|
272
|
+
});
|
|
273
|
+
return null;
|
|
274
|
+
},
|
|
275
|
+
});
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { paginator } from "convex-helpers/server/pagination";
|
|
2
|
+
import schema from "../schema.js";
|
|
3
|
+
import {
|
|
4
|
+
paginationOptsValidator,
|
|
5
|
+
paginationResultValidator,
|
|
6
|
+
} from "convex/server";
|
|
7
|
+
import { v } from "convex/values";
|
|
8
|
+
import { query } from "../_generated/server.js";
|
|
9
|
+
import { obligationFields } from "../settlement/clawbackSchema.js";
|
|
10
|
+
import { balanceFields, operationFields, earningFields } from "./schema.js";
|
|
11
|
+
export const obligationDoc = v.object({
|
|
12
|
+
...obligationFields,
|
|
13
|
+
_id: v.id("affiliateObligations"),
|
|
14
|
+
_creationTime: v.number(),
|
|
15
|
+
});
|
|
16
|
+
export const getObligation = query({
|
|
17
|
+
args: { obligationId: v.id("affiliateObligations") },
|
|
18
|
+
returns: v.union(obligationDoc, v.null()),
|
|
19
|
+
handler: (ctx, args) => ctx.db.get("affiliateObligations", args.obligationId),
|
|
20
|
+
});
|
|
21
|
+
export const chargeObligations = query({
|
|
22
|
+
args: { sourceChargeId: v.string() },
|
|
23
|
+
returns: v.array(obligationDoc),
|
|
24
|
+
handler: async (ctx, args) => {
|
|
25
|
+
const rows = await ctx.db
|
|
26
|
+
.query("affiliateObligations")
|
|
27
|
+
.withIndex("by_charge", (q) =>
|
|
28
|
+
q.eq("sourceChargeId", args.sourceChargeId),
|
|
29
|
+
)
|
|
30
|
+
.take(1001);
|
|
31
|
+
if (rows.length > 1000)
|
|
32
|
+
throw new Error("Affiliate charge recovery limit exceeded.");
|
|
33
|
+
return rows;
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
export const getEarning = query({
|
|
37
|
+
args: { sourceChargeId: v.string(), affiliateAccountId: v.string() },
|
|
38
|
+
returns: v.union(
|
|
39
|
+
v.object({
|
|
40
|
+
...earningFields,
|
|
41
|
+
_id: v.id("affiliateEarnings"),
|
|
42
|
+
_creationTime: v.number(),
|
|
43
|
+
}),
|
|
44
|
+
v.null(),
|
|
45
|
+
),
|
|
46
|
+
handler: (ctx, args) =>
|
|
47
|
+
ctx.db
|
|
48
|
+
.query("affiliateEarnings")
|
|
49
|
+
.withIndex("by_charge_affiliate", (q) =>
|
|
50
|
+
q
|
|
51
|
+
.eq("sourceChargeId", args.sourceChargeId)
|
|
52
|
+
.eq("affiliateAccountId", args.affiliateAccountId),
|
|
53
|
+
)
|
|
54
|
+
.unique(),
|
|
55
|
+
});
|
|
56
|
+
export const recoverySnapshot = query({
|
|
57
|
+
args: {
|
|
58
|
+
affiliateAccountId: v.string(),
|
|
59
|
+
currency: v.string(),
|
|
60
|
+
paginationOpts: paginationOptsValidator,
|
|
61
|
+
},
|
|
62
|
+
returns: v.object({
|
|
63
|
+
balance: v.union(
|
|
64
|
+
v.object({
|
|
65
|
+
...balanceFields,
|
|
66
|
+
_id: v.id("affiliateRecoveryBalances"),
|
|
67
|
+
_creationTime: v.number(),
|
|
68
|
+
}),
|
|
69
|
+
v.null(),
|
|
70
|
+
),
|
|
71
|
+
obligations: paginationResultValidator(obligationDoc),
|
|
72
|
+
}),
|
|
73
|
+
handler: async (ctx, args) => ({
|
|
74
|
+
balance: await ctx.db
|
|
75
|
+
.query("affiliateRecoveryBalances")
|
|
76
|
+
.withIndex("by_affiliate_currency", (q) =>
|
|
77
|
+
q
|
|
78
|
+
.eq("affiliateAccountId", args.affiliateAccountId)
|
|
79
|
+
.eq("currency", args.currency),
|
|
80
|
+
)
|
|
81
|
+
.unique(),
|
|
82
|
+
obligations: await paginator(ctx.db, schema)
|
|
83
|
+
.query("affiliateObligations")
|
|
84
|
+
.withIndex("by_affiliate_currency", (q) =>
|
|
85
|
+
q
|
|
86
|
+
.eq("affiliateAccountId", args.affiliateAccountId)
|
|
87
|
+
.eq("currency", args.currency),
|
|
88
|
+
)
|
|
89
|
+
.paginate({
|
|
90
|
+
...args.paginationOpts,
|
|
91
|
+
numItems: Math.min(100, args.paginationOpts.numItems),
|
|
92
|
+
}),
|
|
93
|
+
}),
|
|
94
|
+
});
|
|
95
|
+
export const operationHistory = query({
|
|
96
|
+
args: {
|
|
97
|
+
obligationId: v.id("affiliateObligations"),
|
|
98
|
+
paginationOpts: paginationOptsValidator,
|
|
99
|
+
},
|
|
100
|
+
returns: paginationResultValidator(
|
|
101
|
+
v.object({
|
|
102
|
+
...operationFields,
|
|
103
|
+
_id: v.id("affiliateRecoveryOperations"),
|
|
104
|
+
_creationTime: v.number(),
|
|
105
|
+
}),
|
|
106
|
+
),
|
|
107
|
+
handler: (ctx, args) =>
|
|
108
|
+
paginator(ctx.db, schema)
|
|
109
|
+
.query("affiliateRecoveryOperations")
|
|
110
|
+
.withIndex("by_obligation", (q) =>
|
|
111
|
+
q.eq("obligationId", args.obligationId),
|
|
112
|
+
)
|
|
113
|
+
.paginate({
|
|
114
|
+
...args.paginationOpts,
|
|
115
|
+
numItems: Math.min(100, args.paginationOpts.numItems),
|
|
116
|
+
}),
|
|
117
|
+
});
|
|
118
|
+
export const pendingOperations = query({
|
|
119
|
+
args: {
|
|
120
|
+
paginationOpts: paginationOptsValidator,
|
|
121
|
+
state: v.union(v.literal("pending"), v.literal("unknown")),
|
|
122
|
+
},
|
|
123
|
+
returns: paginationResultValidator(
|
|
124
|
+
v.object({
|
|
125
|
+
...operationFields,
|
|
126
|
+
_id: v.id("affiliateRecoveryOperations"),
|
|
127
|
+
_creationTime: v.number(),
|
|
128
|
+
}),
|
|
129
|
+
),
|
|
130
|
+
handler: (ctx, args) =>
|
|
131
|
+
paginator(ctx.db, schema)
|
|
132
|
+
.query("affiliateRecoveryOperations")
|
|
133
|
+
.withIndex("by_state", (q) => q.eq("state", args.state))
|
|
134
|
+
.paginate({
|
|
135
|
+
...args.paginationOpts,
|
|
136
|
+
numItems: Math.min(50, args.paginationOpts.numItems),
|
|
137
|
+
}),
|
|
138
|
+
});
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { defineTable } from "convex/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
export const recoveryState = v.union(
|
|
4
|
+
v.literal("pending"),
|
|
5
|
+
v.literal("unknown"),
|
|
6
|
+
v.literal("insufficient_balance"),
|
|
7
|
+
v.literal("unsupported"),
|
|
8
|
+
v.literal("failed"),
|
|
9
|
+
v.literal("succeeded"),
|
|
10
|
+
v.literal("canceled"),
|
|
11
|
+
);
|
|
12
|
+
export const operationFields = {
|
|
13
|
+
obligationId: v.id("affiliateObligations"),
|
|
14
|
+
sourceEventId: v.optional(v.string()),
|
|
15
|
+
kind: v.union(v.literal("recovery"), v.literal("restoration")),
|
|
16
|
+
amount: v.number(),
|
|
17
|
+
state: recoveryState,
|
|
18
|
+
receiptId: v.optional(v.string()),
|
|
19
|
+
error: v.optional(v.string()),
|
|
20
|
+
attempted: v.boolean(),
|
|
21
|
+
providerBaseline: v.optional(v.number()),
|
|
22
|
+
createdAt: v.number(),
|
|
23
|
+
};
|
|
24
|
+
export const operationsTable = defineTable(operationFields)
|
|
25
|
+
.index("by_obligation", ["obligationId"])
|
|
26
|
+
.index("by_state", ["state"]);
|
|
27
|
+
export const earningFields = {
|
|
28
|
+
sourceChargeId: v.string(),
|
|
29
|
+
affiliateAccountId: v.string(),
|
|
30
|
+
currency: v.string(),
|
|
31
|
+
originalCommission: v.number(),
|
|
32
|
+
withheldAmount: v.number(),
|
|
33
|
+
releaseAmount: v.number(),
|
|
34
|
+
sourceInvoiceId: v.optional(v.string()),
|
|
35
|
+
paymentIntentId: v.optional(v.string()),
|
|
36
|
+
stripeTransferId: v.optional(v.string()),
|
|
37
|
+
status: v.union(v.literal("reserved"), v.literal("paid")),
|
|
38
|
+
};
|
|
39
|
+
export const earningsTable = defineTable(earningFields)
|
|
40
|
+
.index("by_charge_affiliate", ["sourceChargeId", "affiliateAccountId"])
|
|
41
|
+
.index("by_affiliate_currency", ["affiliateAccountId", "currency"]);
|
|
42
|
+
export const offsetsTable = defineTable({
|
|
43
|
+
earningId: v.id("affiliateEarnings"),
|
|
44
|
+
obligationId: v.id("affiliateObligations"),
|
|
45
|
+
amount: v.number(),
|
|
46
|
+
})
|
|
47
|
+
.index("by_earning", ["earningId"])
|
|
48
|
+
.index("by_obligation", ["obligationId"]);
|
|
49
|
+
export const balanceFields = {
|
|
50
|
+
activePayoutKey: v.optional(v.string()),
|
|
51
|
+
pendingPayoutAmount: v.optional(v.number()),
|
|
52
|
+
affiliateAccountId: v.string(),
|
|
53
|
+
currency: v.string(),
|
|
54
|
+
originalCommission: v.number(),
|
|
55
|
+
recoveredAmount: v.number(),
|
|
56
|
+
offsetAmount: v.number(),
|
|
57
|
+
restoredAmount: v.number(),
|
|
58
|
+
outstandingDebt: v.number(),
|
|
59
|
+
reservedRecovery: v.number(),
|
|
60
|
+
reservedRestoration: v.number(),
|
|
61
|
+
restorationDue: v.number(),
|
|
62
|
+
withheldAmount: v.number(),
|
|
63
|
+
netPayable: v.number(),
|
|
64
|
+
};
|
|
65
|
+
export const balancesTable = defineTable(balanceFields).index(
|
|
66
|
+
"by_affiliate_currency",
|
|
67
|
+
["affiliateAccountId", "currency"],
|
|
68
|
+
);
|
|
69
|
+
export const payoutReleaseFields = {
|
|
70
|
+
affiliateAccountId: v.string(),
|
|
71
|
+
currency: v.string(),
|
|
72
|
+
operationKey: v.string(),
|
|
73
|
+
amount: v.number(),
|
|
74
|
+
minimumAmount: v.number(),
|
|
75
|
+
state: v.union(
|
|
76
|
+
v.literal("pending"),
|
|
77
|
+
v.literal("unknown"),
|
|
78
|
+
v.literal("submitted"),
|
|
79
|
+
v.literal("failed"),
|
|
80
|
+
),
|
|
81
|
+
stripePayoutId: v.optional(v.string()),
|
|
82
|
+
createdAt: v.number(),
|
|
83
|
+
};
|
|
84
|
+
export const payoutReleasesTable = defineTable(payoutReleaseFields)
|
|
85
|
+
.index("by_key", ["operationKey"])
|
|
86
|
+
.index("by_state", ["state"]);
|