Skip to content
Merged

dev #2283

Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
90fd1d7
feat(billing): unify license quantity sync webhooks
johnyeocx Jul 16, 2026
48a9b61
feat(licenses): support license plan customization
johnyeocx Jul 17, 2026
e9e387f
Merge remote-tracking branch 'origin/dev' into license-plan-customize
johnyeocx Jul 17, 2026
9807024
Merge pull request #2280 from useautumn/license-plan-customize
johnyeocx Jul 17, 2026
f16f009
fix(licenses): scope custom stripe prices to parent products
johnyeocx Jul 17, 2026
a80de2d
fix(migrations): serialize concurrent customer migrations
og2701 Jul 17, 2026
68b31c7
Merge pull request #2281 from useautumn/license-plan-customize
johnyeocx Jul 17, 2026
39dca95
chore: 🤖 merge main into dev
johnyeocx Jul 17, 2026
ef281ec
fix: unit tests
johnyeocx Jul 17, 2026
7267818
merge from main
johnyeocx Jul 17, 2026
61dc59f
Merge branch 'dev' of https://github.com/useautumn/autumn into dev
johnyeocx Jul 17, 2026
efdf5fd
fix: bun lock
johnyeocx Jul 17, 2026
bc5dbb3
fix(migrations): bound lazy lock wait
og2701 Jul 17, 2026
70522cb
chore: merge dev and refresh bun lock
og2701 Jul 17, 2026
90273f6
Merge pull request #2282 from useautumn/fix/cross-migration-customer-…
og2701 Jul 17, 2026
d2d2043
fix(sync): preserve matched plan version
charlietlamb Jul 17, 2026
f1a49c6
feat(licenses): 🎸 support catalog license plan updates
johnyeocx Jul 17, 2026
c29524e
Merge pull request #2288 from useautumn/license-plan-customize
johnyeocx Jul 17, 2026
fcc09de
fix(dashboard): resolve pinned license plan version
charlietlamb Jul 17, 2026
d7d52a6
Merge pull request #2291 from useautumn/charlie/licneses-config-fixes
charlietlamb Jul 17, 2026
940bfad
Merge pull request #2284 from useautumn/charlie/sync-plan-version
charlietlamb Jul 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ai
Submodule ai updated from bca809 to bce748
1,546 changes: 676 additions & 870 deletions bun.lock

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,10 @@ import { billingActions } from "@/internal/billing/v2/actions";
import { canAutoSync } from "@/internal/billing/v2/actions/sync/canAutoSync/index.js";
import { buildIncrementalSyncParams } from "@/internal/billing/v2/actions/sync/scope/buildIncrementalSyncParams.js";
import { subscriptionToSyncParams } from "@/internal/billing/v2/actions/sync/subscriptionToSyncParams";
import type { SyncV2Result } from "@/internal/billing/v2/actions/sync/syncV2";
import { isAutumnManagedSubscriptionMetadata } from "@/internal/billing/v2/providers/stripe/utils/common/autumnStripeMetadata";
import { CusProductService } from "@/internal/customers/cusProducts/CusProductService";
import type { StripeWebhookContext } from "../../../webhookMiddlewares/stripeWebhookContext";
import {
trackCustomerProductInsertion,
trackCustomerProductUpdate,
} from "../../common/trackCustomerProductUpdate";
import { trackCustomerProductUpdate } from "../../common/trackCustomerProductUpdate";
import type { StripeSubscriptionUpdatedContext } from "../stripeSubscriptionUpdatedContext";

const stripeProductId = (
Expand Down Expand Up @@ -49,53 +45,6 @@ const priceOrProductChanged = ({
});
};

const trackSyncResult = async ({
ctx,
subscriptionUpdatedContext,
result,
linkedCustomerProducts,
}: {
ctx: StripeWebhookContext;
subscriptionUpdatedContext: StripeSubscriptionUpdatedContext;
result: SyncV2Result;
linkedCustomerProducts: FullCusProduct[];
}) => {
const { customerProducts, fullCustomer } = subscriptionUpdatedContext;

for (const id of result.expired_cus_product_ids) {
const customerProduct =
customerProducts.find((cp) => cp.id === id) ??
linkedCustomerProducts.find((cp) => cp.id === id);
const syncedProduct = await CusProductService.getFull({ db: ctx.db, id });
if (!customerProduct || !syncedProduct) continue;

trackCustomerProductUpdate({
eventContext: subscriptionUpdatedContext,
customerProduct,
updates: {
status: syncedProduct.status,
canceled: syncedProduct.canceled,
canceled_at: syncedProduct.canceled_at,
ended_at: syncedProduct.ended_at,
},
});
}

for (const id of result.inserted_cus_product_ids) {
const customerProduct = await CusProductService.getFull({ db: ctx.db, id });
if (!customerProduct) continue;

if (!fullCustomer.customer_products.some((cp) => cp.id === id)) {
fullCustomer.customer_products.push(customerProduct);
}

trackCustomerProductInsertion({
eventContext: subscriptionUpdatedContext,
customerProduct,
});
}
};

const expireRemovedCustomerProducts = async ({
ctx,
subscriptionUpdatedContext,
Expand Down Expand Up @@ -189,14 +138,6 @@ export const autoSyncUpdatedSubscription = async ({
return;
}

await billingActions.syncLicenseQuantities({
ctx,
params: {
customerId,
licenseQuantityDrifts: incremental.licenseQuantityDrifts,
},
});

await expireRemovedCustomerProducts({
ctx,
subscriptionUpdatedContext,
Expand All @@ -205,20 +146,15 @@ export const autoSyncUpdatedSubscription = async ({

if (!incremental.params) {
logger.info(
`sub.updated auto-sync applied ${stripeSubscription.id}: removed=${incremental.removedCustomerProducts.length}, licensePools=${incremental.licenseQuantityDrifts.length}`,
`sub.updated auto-sync applied ${stripeSubscription.id}: removed=${incremental.removedCustomerProducts.length}`,
);
return;
}

const result = await billingActions.syncV2({
ctx,
params: incremental.params,
});
await trackSyncResult({
ctx,
subscriptionUpdatedContext,
result,
linkedCustomerProducts,
tags: ["sync:customer.subscription.updated"],
});
logger.info(
`sub.updated auto-sync applied ${stripeSubscription.id}: expired=${result.expired_cus_product_ids.length}, inserted=${result.inserted_cus_product_ids.length}, removed=${incremental.removedCustomerProducts.length}`,
Expand Down
2 changes: 0 additions & 2 deletions server/src/internal/billing/v2/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { sync } from "@/internal/billing/v2/actions/sync/sync";
import { syncProposals } from "@/internal/billing/v2/actions/sync/syncProposals";
import { syncProposalsV2 } from "@/internal/billing/v2/actions/sync/syncProposalsV2";
import { syncV2 } from "@/internal/billing/v2/actions/sync/syncV2";
import { syncLicenseQuantities } from "@/internal/billing/v2/actions/syncLicenseQuantities/syncLicenseQuantities";
import { updateSubscription } from "@/internal/billing/v2/actions/updateSubscription/updateSubscription";
import { verify } from "@/internal/billing/v2/actions/verify/verify";

Expand All @@ -36,7 +35,6 @@ export const billingActions = {
previewRestore: previewRestore,
sync: sync,
syncV2: syncV2,
syncLicenseQuantities: syncLicenseQuantities,
syncProposals: syncProposals,
syncProposalsV2: syncProposalsV2,
verify: verify,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
type AutumnBillingPlan,
type CustomerLicenseUpdate,
CusProductStatus,
type Entitlement,
type FullCusProduct,
Expand All @@ -8,6 +9,7 @@ import {
type SyncBillingContext,
} from "@autumn/shared";
import type { AutumnContext } from "@/honoUtils/HonoEnv";
import { computeCustomerLicenseQuantityChanges } from "@/internal/billing/v2/compute/computeCustomerLicenseQuantityChanges";
import { resolveSyncExistingUsagesConfig } from "@/internal/billing/v2/utils/handleCarryOvers/resolveSyncExistingUsagesConfig";
import { initImmediateSyncCustomerProduct } from "./initImmediateSyncCustomerProduct";

Expand All @@ -21,6 +23,7 @@ export type ImmediatePhaseResult = {
customPrices: Price[];
customEntitlements: Entitlement[];
insertPlanLicenses: InsertPlanLicenseSpec[];
customerLicenseUpdates: CustomerLicenseUpdate[];
};

const expireCustomerProduct = ({
Expand Down Expand Up @@ -68,6 +71,7 @@ export const computeSyncImmediatePhase = ({
customPrices: [],
customEntitlements: [],
insertPlanLicenses: [],
customerLicenseUpdates: [],
};
}

Expand All @@ -76,14 +80,29 @@ export const computeSyncImmediatePhase = ({
const customPrices: Price[] = [];
const customEntitlements: Entitlement[] = [];
const insertPlanLicenses: InsertPlanLicenseSpec[] = [];
const customerLicenseUpdates: CustomerLicenseUpdate[] = [];

for (const productContext of immediatePhase.productContexts) {
const currentCustomerProduct = productContext.currentCustomerProduct;
if (currentCustomerProduct?.product_id === productContext.fullProduct.id) {
const licenseQuantityChanges = computeCustomerLicenseQuantityChanges({
customerProduct: currentCustomerProduct,
customerLicenseQuantities: productContext.customerLicenseQuantities,
});
if (licenseQuantityChanges.length > 0) {
customerLicenseUpdates.push(
...licenseQuantityChanges.map(({ update }) => update),
);
Comment on lines +83 to +95

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 continue skips all product-level sync work when seat counts drift

When licenseQuantityChanges.length > 0 for a product context, the loop continues before reaching the initImmediateSyncCustomerProduct path. buildIncrementalSyncParams guarantees these paths are mutually exclusive for DIFFERENT plans (product-id changed → early-return before seat check). However, both a seat drift AND a full-product re-sync can be needed for the same Autumn plan id in the version-upgrade case, since the gate in buildIncrementalSyncParams compares product.id (public ID, stable across versions) not internal_id. If a new product version with changed items is also accompanied by a Stripe seat-quantity change, the version upgrade would be silently skipped here.

Prompt To Fix With AI
This is a comment left during a code review.
Path: server/src/internal/billing/v2/actions/sync/compute/computeSyncImmediatePhase.ts
Line: 83-95

Comment:
**`continue` skips all product-level sync work when seat counts drift**

When `licenseQuantityChanges.length > 0` for a product context, the loop `continue`s before reaching the `initImmediateSyncCustomerProduct` path. `buildIncrementalSyncParams` guarantees these paths are mutually exclusive for DIFFERENT plans (product-id changed → early-return before seat check). However, both a seat drift AND a full-product re-sync can be needed for the same Autumn plan id in the version-upgrade case, since the gate in `buildIncrementalSyncParams` compares `product.id` (public ID, stable across versions) not `internal_id`. If a new product version with changed items is also accompanied by a Stripe seat-quantity change, the version upgrade would be silently skipped here.

How can I resolve this? If you propose a fix, please make it concise.

continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: A mixed sync can silently lose custom license/item changes when any existing license quantity also changes, because this continue bypasses product initialization and collection of customPrices, customEntitlements, and insertPlanLicenses. The optimization should only short-circuit a truly quantity-only context; otherwise preserve the normal initialization path while applying the in-place quantity updates.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At server/src/internal/billing/v2/actions/sync/compute/computeSyncImmediatePhase.ts, line 96:

<comment>A mixed sync can silently lose custom license/item changes when any existing license quantity also changes, because this `continue` bypasses product initialization and collection of `customPrices`, `customEntitlements`, and `insertPlanLicenses`. The optimization should only short-circuit a truly quantity-only context; otherwise preserve the normal initialization path while applying the in-place quantity updates.</comment>

<file context>
@@ -76,14 +80,29 @@ export const computeSyncImmediatePhase = ({
+				customerLicenseUpdates.push(
+					...licenseQuantityChanges.map(({ update }) => update),
+				);
+				continue;
+			}
+		}
</file context>

}
}

const existingUsagesConfig =
carryOverUsage && productContext.currentCustomerProduct
carryOverUsage && currentCustomerProduct
? resolveSyncExistingUsagesConfig({
ctx,
carryOverUsages,
currentCustomerProduct: productContext.currentCustomerProduct,
currentCustomerProduct,
})
: undefined;

Expand Down Expand Up @@ -117,5 +136,6 @@ export const computeSyncImmediatePhase = ({
customPrices,
customEntitlements,
insertPlanLicenses,
customerLicenseUpdates,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export const computeSyncPlan = ({
immediate.insertPlanLicenses.length > 0
? immediate.insertPlanLicenses
: undefined,
customerLicenseUpdates:
immediate.customerLicenseUpdates.length > 0
? immediate.customerLicenseUpdates
: undefined,
lockCustomerCurrency: syncContextToCurrencyLock({ syncContext }),
upsertSubscription,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ import {
type SyncPlanInstance,
} from "@autumn/shared";
import type { MatchedPlan, SubscriptionMatch } from "../detect/types";
import {
findLicenseQuantityDrifts,
type LicenseQuantityDrift,
} from "./findLicenseQuantityDrifts";
import { findLicenseQuantityDrifts } from "./findLicenseQuantityDrifts";
import {
linkedCustomerProductsToTargetGroupMap,
matchedPlanToTargetGroupLink,
Expand All @@ -30,9 +27,6 @@ export type IncrementalSyncParamsResult =
params: SyncParamsV1 | null;
/** Linked add-on cusProducts whose Stripe items were removed. */
removedCustomerProducts: FullCusProduct[];
/** Pools whose seat quantities drifted — converged in place, never
* via expire+replace (seats stay anchored to the pool's link). */
licenseQuantityDrifts: LicenseQuantityDrift[];
}
| { shouldSync: false; reason: IncrementalSyncSkipReason };

Expand Down Expand Up @@ -177,7 +171,6 @@ export const buildIncrementalSyncParams = ({
}

const changedPlans: SyncPlanInstance[] = [];
const licenseQuantityDrifts: LicenseQuantityDrift[] = [];
for (const syncPlan of phase.plans) {
const matchedPlan = matchedPlanMap.plansByProductId.get(syncPlan.plan_id);
if (!matchedPlan) {
Expand Down Expand Up @@ -236,12 +229,11 @@ export const buildIncrementalSyncParams = ({

// Same product still attached — seat quantity changes converge the
// pool in place instead of re-attaching the parent.
licenseQuantityDrifts.push(
...findLicenseQuantityDrifts({
linkedCustomerProduct: linkedProduct,
syncPlan,
}),
);
const licenseQuantityDrifts = findLicenseQuantityDrifts({
linkedCustomerProduct: linkedProduct,
syncPlan,
});
if (licenseQuantityDrifts.length > 0) changedPlans.push(syncPlan);
}

// Linked add-ons whose Stripe items disappeared from the sub get expired.
Expand All @@ -264,11 +256,7 @@ export const buildIncrementalSyncParams = ({
!matchedPlanIds.has(linkedProduct.product.id),
);

if (
changedPlans.length === 0 &&
removedCustomerProducts.length === 0 &&
licenseQuantityDrifts.length === 0
) {
if (changedPlans.length === 0 && removedCustomerProducts.length === 0) {
return {
shouldSync: false,
reason: "no_changed_targets",
Expand All @@ -282,6 +270,5 @@ export const buildIncrementalSyncParams = ({
? { ...params, phases: [{ ...phase, plans: changedPlans }] }
: null,
removedCustomerProducts,
licenseQuantityDrifts,
};
};
57 changes: 27 additions & 30 deletions server/src/internal/billing/v2/actions/sync/syncV2.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { SyncParamsV1 } from "@autumn/shared";
import { CusProductStatus, type SyncParamsV1 } from "@autumn/shared";
import type { AutumnContext } from "@/honoUtils/HonoEnv";
import { persistCreateSchedule } from "@/internal/billing/v2/actions/createSchedule/utils/persistCreateSchedule";
import { executeAutumnBillingPlan } from "@/internal/billing/v2/execute/executeAutumnBillingPlan";
import { sendBillingUpdatedWebhook } from "@/internal/billing/v2/workflows/sendBillingUpdatedWebhook/sendBillingUpdatedWebhook";
import { reconcileLicenseStateForCustomer } from "@/internal/licenses/actions/reconcile/reconcileLicenseState";
import { computeSyncPlan } from "./compute/computeSyncPlan";
import { handleSyncErrors } from "./errors/handleSyncErrors";
import { logSyncContext } from "./logs/logSyncContext";
Expand All @@ -27,28 +28,15 @@ export type SyncV2Result = {

/**
* Sync a Stripe subscription/schedule into Autumn state.
*
* Mirrors the v2 action convention used by createSchedule.ts:
* 1. setup — fetch sub, schedule, customer, products
* 2. errors — validate inputs against detection result
* 3. compute — apply caller overrides and produce an AutumnBillingPlan
* 4. execute — run the billing plan (cusProduct inserts/updates)
* 5. persist — write any scheduled phase rows (reuses createSchedule's
* `persistCreateSchedule` so the schedule + schedule_phases
* tables are written identically across actions)
*
* Webhook emission is opt-in via `webhook` so Stripe auto-sync callers
* (which already emit billing.updated from the originating action) don't
* double-send.
*/
export const syncV2 = async ({
ctx,
params,
webhook,
tags,
}: {
ctx: AutumnContext;
params: SyncParamsV1;
webhook?: { tags?: string[] };
tags?: string[];
}): Promise<SyncV2Result> => {
// 1. Setup
const syncContext = await setupSyncContext({ ctx, params });
Expand All @@ -63,6 +51,13 @@ export const syncV2 = async ({

// 4. Execute
await executeAutumnBillingPlan({ ctx, autumnBillingPlan });
if ((autumnBillingPlan.customerLicenseUpdates?.length ?? 0) > 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Licensed syncs that replace the current product do not reconcile license state: those plans have inserted/expired customer products but no customerLicenseUpdates, so this condition is false. The old license assignments can remain attached to the expired parent and produce stale seat access; the trigger should cover all sync mutations that add or expire license-bearing customer products, not only quantity updates.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At server/src/internal/billing/v2/actions/sync/syncV2.ts, line 54:

<comment>Licensed syncs that replace the current product do not reconcile license state: those plans have inserted/expired customer products but no `customerLicenseUpdates`, so this condition is false. The old license assignments can remain attached to the expired parent and produce stale seat access; the trigger should cover all sync mutations that add or expire license-bearing customer products, not only quantity updates.</comment>

<file context>
@@ -63,6 +51,13 @@ export const syncV2 = async ({
 
 	// 4. Execute
 	await executeAutumnBillingPlan({ ctx, autumnBillingPlan });
+	if ((autumnBillingPlan.customerLicenseUpdates?.length ?? 0) > 0) {
+		await reconcileLicenseStateForCustomer({
+			ctx,
</file context>

await reconcileLicenseStateForCustomer({
ctx,
idOrInternalId: syncContext.customer_id,
deleteCache: true,
});
}

// 5. Persist scheduled phases (only when sync produced more than one phase)
let scheduleId: string | null = null;
Expand All @@ -79,14 +74,20 @@ export const syncV2 = async ({
scheduledPhases = persisted.insertedPhases;
}

if (webhook) {
void sendBillingUpdatedWebhook({
ctx,
autumnBillingPlan,
originalFullCustomer: syncContext.fullCustomer,
tags: webhook.tags,
});
}
void sendBillingUpdatedWebhook({
ctx,
autumnBillingPlan,
originalFullCustomer: syncContext.fullCustomer,
tags,
});

const customerProductUpdates = (
Comment on lines +77 to +84

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Unconditional webhook now doubles events in handleStripeSubscriptionUpdated

syncV2 previously guarded sendBillingUpdatedWebhook behind an opt-in webhook param. The old code comment said explicitly: "Webhook emission is opt-in via webhook so Stripe auto-sync callers (which already emit billing.updated from the originating action) don't double-send." That guard is now gone.

handleStripeSubscriptionUpdated calls autoSyncUpdatedSubscription (which runs syncV2 → emits webhook #1 with tags: ["sync:customer.subscription.updated"]), then calls emitBillingChangeWebhook unconditionally at line 94. Whenever expireRemovedCustomerProducts, syncCustomerProductStatus, handleStripeSubscriptionCanceled, or handleStripeSubscriptionRenewed track any change into the event context, the second emission fires and customers receive two billing.updated events for one Stripe event. The same issue affects autoSyncFromSubscription (subscription.created path) which now also fires a webhook where it previously fired none.

Prompt To Fix With AI
This is a comment left during a code review.
Path: server/src/internal/billing/v2/actions/sync/syncV2.ts
Line: 77-84

Comment:
**Unconditional webhook now doubles events in `handleStripeSubscriptionUpdated`**

`syncV2` previously guarded `sendBillingUpdatedWebhook` behind an opt-in `webhook` param. The old code comment said explicitly: _"Webhook emission is opt-in via `webhook` so Stripe auto-sync callers (which already emit billing.updated from the originating action) don't double-send."_ That guard is now gone.

`handleStripeSubscriptionUpdated` calls `autoSyncUpdatedSubscription` (which runs `syncV2` → emits webhook #1 with `tags: ["sync:customer.subscription.updated"]`), then calls `emitBillingChangeWebhook` unconditionally at line 94. Whenever `expireRemovedCustomerProducts`, `syncCustomerProductStatus`, `handleStripeSubscriptionCanceled`, or `handleStripeSubscriptionRenewed` track any change into the event context, the second emission fires and customers receive two `billing.updated` events for one Stripe event. The same issue affects `autoSyncFromSubscription` (subscription.created path) which now also fires a webhook where it previously fired none.

How can I resolve this? If you propose a fix, please make it concise.

autumnBillingPlan.updateCustomerProducts ?? []
).concat(
autumnBillingPlan.updateCustomerProduct
? [autumnBillingPlan.updateCustomerProduct]
: [],
);

return {
customer_id: syncContext.customer_id,
Expand All @@ -95,12 +96,8 @@ export const syncV2 = async ({
inserted_cus_product_ids: autumnBillingPlan.insertCustomerProducts.map(
(cp) => cp.id,
),
expired_cus_product_ids: (autumnBillingPlan.updateCustomerProducts ?? [])
.concat(
autumnBillingPlan.updateCustomerProduct
? [autumnBillingPlan.updateCustomerProduct]
: [],
)
expired_cus_product_ids: customerProductUpdates
.filter(({ updates }) => updates.status === CusProductStatus.Expired)
.map((u) => u.customerProduct.id),
schedule_id: scheduleId,
scheduled_phases: scheduledPhases,
Expand Down
Loading
Loading