snapshot of https://github.com/twentyhq/twenty.git (main, 2026-09-17; blobs > 131072B omitted)
Some checks failed
App Prod-Parity E2E Dispatch / dispatch (push) Failing after 10s
CD Storybook UI / build (push) Failing after 3m25s
CD Storybook UI / dispatch (push) Has been skipped
CD deploy main / website-changed-files (push) Successful in 18m8s
CI Agent Skills / changed-files-check (push) Successful in 18m9s
CI Create App E2E minimal / changed-files-check (push) Successful in 24s
CI Create App / changed-files-check (push) Successful in 26s
CI Docs / changed-files-check (push) Successful in 26s
CI Emails / changed-files-check (push) Successful in 28s
CI Example App Hello World / changed-files-check (push) Successful in 23s
CI Front / changed-files-check (push) Has been skipped
CI Example App Postcard / changed-files-check (push) Successful in 27s
CI UI / changed-files-check (push) Has been skipped
CI Utils Test / changed-files-check (push) Successful in 45s
CI Twenty Apps / discover (push) Successful in 1m3s
CD deploy main / deploy-main (push) Failing after 3s
CI Agent Skills / agent-skills-validate (push) Has been skipped
CI Create App / create-app-test (lint) (push) Has been skipped
CI Emails / emails-test (push) Has been skipped
CI Front / front-task (lingui:compile) (push) Has been skipped
CI Front / front-task (lint) (push) Has been skipped
CI Example App Postcard / example-app-postcard (push) Has been skipped
CI UI / ui-task (lint) (push) Has been skipped
CI UI / ui-task (pack-size) (push) Has been skipped
CI UI / ui-task (size) (push) Has been skipped
CI UI / ui-task (test) (push) Has been skipped
CI UI / ui-task (typecheck) (push) Has been skipped
CI Utils Test / utils-test (push) Has been skipped
CI Twenty Apps / ${{ matrix.app.name }} (push) Has been skipped
CI Emails / ci-emails-status-check (push) Successful in 2s
CI Example App Hello World / ci-example-app-hello-world-status-check (push) Successful in 2s
CI Example App Postcard / ci-example-app-postcard-status-check (push) Successful in 3s
CI UI / ui-sb-test (push) Has been skipped
CI Utils Test / ci-utils-test-status-check (push) Successful in 2s
CI Twenty Apps / ci-twenty-apps-status-check (push) Successful in 2s
CI UI / ci-ui-status-check (push) Successful in 2s
CI Desktop / desktop (push) Failing after 1m8s
Push docs to Crowdin / Push documentation to Crowdin (push) Failing after 55s
Push translations to Crowdin / Extract and upload translations (push) Failing after 5s
Push website translations to Crowdin / Extract and upload website translations (push) Failing after 5s
CI Create App / create-app-test (test) (push) Has been skipped
CI Create App / create-app-test (typecheck) (push) Has been skipped
CI Docs / docs-lint (push) Has been skipped
CI Example App Hello World / example-app-hello-world (push) Has been skipped
CI Front / front-task (lingui:extract) (push) Has been skipped
CI Front / front-task (test) (push) Has been skipped
CI Front / front-task (typecheck) (push) Has been skipped
CI UI / ui-sb-build (push) Failing after 1m32s
CI Twenty Apps / ${{ matrix.app.name }} (${{ matrix.server-source }}) (push) Has been skipped
CI Agent Skills / agent-skills-publish (push) Has been skipped
CI Create App / ci-create-app-status-check (push) Successful in 2s
CI Agent Skills / agent-skills-remote-source (push) Has been skipped
CI Create App E2E minimal / create-app-e2e-minimal (push) Has been cancelled
CI E2E Main / e2e-test (push) Has been cancelled
CI Front / front-sb-build (push) Has been cancelled
CI Front / front-build (push) Has been cancelled
CI Create App E2E minimal / ci-create-app-e2e-minimal-status-check (push) Has been cancelled
CI E2E Main / ci-e2e-main-status-check (push) Has been cancelled
CI E2E Main / notify-main-ci-failure (push) Has been cancelled
CI E2E Main / qa-scout-comment (push) Has been cancelled
CI Front / front-sb-test (push) Has been cancelled
CI Front / front-sb-screenshots (push) Has been cancelled
CI Front / ci-front-status-check (push) Has been cancelled
DPA Sub-Processor Sync / sync-subprocessors (push) Failing after 3s
AI Catalog Sync / sync-catalog (push) Failing after 2s

This commit is contained in:
upstream-mirror
2026-09-17 23:28:13 +05:00
commit e7da97194a
32688 changed files with 4208681 additions and 0 deletions

View File

@@ -0,0 +1,112 @@
import request from 'supertest';
import { createMockStripeEntitlementUpdatedData } from 'test/integration/billing/utils/create-mock-stripe-entitlement-updated-data.util';
import { createMockStripePriceCreatedData } from 'test/integration/billing/utils/create-mock-stripe-price-created-data.util';
import { createMockStripeProductUpdatedData } from 'test/integration/billing/utils/create-mock-stripe-product-updated-data.util';
import { createMockStripeSubscriptionCreatedData } from 'test/integration/billing/utils/create-mock-stripe-subscription-created-data.util';
const client = request(`http://localhost:${APP_PORT}`);
describe('BillingController (integration)', () => {
it('should handle product.updated and price.created webhook events', async () => {
const productUpdatedPayload = {
type: 'product.updated',
data: createMockStripeProductUpdatedData(),
};
const priceCreatedPayload = {
type: 'price.created',
data: createMockStripePriceCreatedData(),
};
await client
.post('/webhooks/stripe')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('stripe-signature', 'correct-signature')
.set('Content-Type', 'application/json')
.send(JSON.stringify(productUpdatedPayload))
.expect(200)
.then((res) => {
expect(res.body.stripeProductId).toBeDefined();
});
await client
.post('/webhooks/stripe')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('stripe-signature', 'correct-signature')
.set('Content-Type', 'application/json')
.send(JSON.stringify(priceCreatedPayload))
.expect(200)
.then((res) => {
expect(res.body.stripePriceId).toBeDefined();
expect(res.body.stripeMeterId).toBeDefined();
});
});
it('should handle subscription.created webhook event', async () => {
const subscriptionCreatedPayload = {
type: 'customer.subscription.created',
data: createMockStripeSubscriptionCreatedData(),
};
const entitlementUpdatedPayload = {
type: 'entitlements.active_entitlement_summary.updated',
data: createMockStripeEntitlementUpdatedData(),
};
await client
.post('/webhooks/stripe')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('stripe-signature', 'correct-signature')
.set('Content-Type', 'application/json')
.send(JSON.stringify(subscriptionCreatedPayload))
.expect(200)
.then((res) => {
expect(res.body.stripeSubscriptionId).toBeDefined();
expect(res.body.stripeCustomerId).toBeDefined();
});
await client
.post('/webhooks/stripe')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('stripe-signature', 'correct-signature')
.set('Content-Type', 'application/json')
.send(JSON.stringify(entitlementUpdatedPayload))
.expect(200)
.then((res) => {
expect(res.body.stripeEntitlementCustomerId).toBeDefined();
});
});
it('should handle entitlements.active_entitlement_summary.updated when the subscription is not found', async () => {
const entitlementUpdatedPayload = {
type: 'entitlements.active_entitlement_summary.updated',
data: createMockStripeEntitlementUpdatedData({
customer: 'new_customer',
}),
};
await client
.post('/webhooks/stripe')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('stripe-signature', 'correct-signature')
.set('Content-Type', 'application/json')
.send(JSON.stringify(entitlementUpdatedPayload))
.expect(404);
});
it('should reject webhook with invalid signature', async () => {
const entitlementUpdatedPayload = {
type: 'customer.entitlement.created',
data: {
object: {
id: 'ent_test123',
},
},
};
await client
.post('/webhooks/stripe')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('stripe-signature', 'invalid-signature')
.set('Content-Type', 'application/json')
.send(JSON.stringify(entitlementUpdatedPayload))
.expect(500);
});
});

View File

@@ -0,0 +1,413 @@
import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
import { randomUUID } from 'node:crypto';
import { addDays, addMonths, startOfMonth } from 'date-fns';
import request from 'supertest';
import {
getBillingUsageCacheService,
getSeededBillingWorkspaceId,
listCreditGrants,
quitBillingFixtureRedis,
readAllowanceCounter,
resetBillingCreditState,
setupResourceCreditSubscription,
warmAllowanceCounter,
setSubscriptionStatus,
} from 'test/integration/billing/utils/billing-credit-fixtures.util';
import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
import { alignGrantExpiryToPeriodEnd } from 'src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util';
const client = request(`http://localhost:${APP_PORT}`);
const PERIOD_START = startOfMonth(new Date());
const PERIOD_END = addMonths(PERIOD_START, 1);
const ALLOWANCE_MICRO = 1_000_000;
const GRANT_MUTATION = `
mutation GrantWorkspaceCredits(
$workspaceId: UUID!
$amount: Float!
$type: BillingCreditGrantType!
$reason: String
$expiresInDays: Int
$clientOperationId: UUID!
) {
grantWorkspaceCredits(
workspaceId: $workspaceId
amount: $amount
type: $type
reason: $reason
expiresInDays: $expiresInDays
clientOperationId: $clientOperationId
) {
id
amount
type
reason
expiresAt
isActive
}
}
`;
const REVOKE_MUTATION = `
mutation RevokeWorkspaceCreditGrant($workspaceId: UUID!, $creditGrantId: UUID!) {
revokeWorkspaceCreditGrant(
workspaceId: $workspaceId
creditGrantId: $creditGrantId
) {
id
revokedAt
}
}
`;
const grantCredits = (variables: Record<string, unknown>) =>
callAdminGraphql(GRANT_MUTATION, {
clientOperationId: randomUUID(),
...variables,
});
const callAdminGraphql = (query: string, variables: Record<string, unknown>) =>
client
.post('/admin-panel')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.set('Content-Type', 'application/json')
.send({ query, variables });
describe('Admin credit grant and revoke (integration)', () => {
let workspaceId: string;
beforeAll(async () => {
workspaceId = await getSeededBillingWorkspaceId();
});
beforeEach(async () => {
await resetBillingCreditState(workspaceId);
await setupResourceCreditSubscription({
workspaceId,
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
creditAmountMicro: ALLOWANCE_MICRO,
});
});
afterEach(async () => {
await resetBillingCreditState(workspaceId);
});
afterAll(async () => {
await quitBillingFixtureRedis();
});
it('records a granted amount on the ledger and mirrors it', async () => {
const response = await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: 'Outage on the 3rd',
});
expect(response.body.errors).toBeUndefined();
const grants = await listCreditGrants(workspaceId);
expect(grants).toHaveLength(1);
expect(grants[0]).toMatchObject({
amountMicro: 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
type: BillingCreditGrantType.COMPENSATION,
reason: 'Outage on the 3rd',
revokedAt: null,
});
});
it('leaves a granted amount without an expiry so no missed transition can drop it', async () => {
const response = await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
});
expect(response.body.errors).toBeUndefined();
expect(response.body.data.grantWorkspaceCredits.expiresAt).toBeNull();
const grants = await listCreditGrants(workspaceId);
expect(grants[0].expiresAt).toBeNull();
});
// Rounded up to a period end rather than the exact day: credits are spent and
// settled a period at a time, so a deadline inside one would be invisible to
// both the cached counter and the carry-forward.
it('expires a time-boxed grant at the end of the period the requested day falls in', async () => {
const response = await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.SALES,
reason: 'Pilot credits',
expiresInDays: 30,
});
expect(response.body.errors).toBeUndefined();
expect(response.body.data.grantWorkspaceCredits.isActive).toBe(true);
const [storedGrant] = await listCreditGrants(workspaceId);
// Which period the thirtieth day lands in depends on when the suite runs,
// so the boundary is derived the same way the server derives it rather
// than listed.
const expectedExpiresAt = alignGrantExpiryToPeriodEnd({
requestedExpiresAt: addDays(new Date(), 30),
currentPeriodStart: PERIOD_START,
currentPeriodEnd: PERIOD_END,
interval: SubscriptionInterval.Month,
});
expect(storedGrant.expiresAt).toEqual(expectedExpiresAt);
expect(expectedExpiresAt.getTime()).toBeGreaterThanOrEqual(
addDays(new Date(), 30).getTime(),
);
});
it('refuses an expiry beyond the accepted range', async () => {
const response = await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
expiresInDays: 100_000,
});
expect(response.body.errors).toBeDefined();
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
it('adds the granted amount to a warm available-credits counter', async () => {
const cache = getBillingUsageCacheService();
await cache.warmAvailableCredits(
workspaceId,
PERIOD_START,
PERIOD_END,
500_000,
);
await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
});
expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
500_000 + 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
);
});
// The aligned deadline lands on the period end the counter already expires
// with, so the cached balance stays valid and can simply be incremented.
it('keeps a warm available-credits counter usable for a time-boxed grant', async () => {
const cache = getBillingUsageCacheService();
await cache.warmAvailableCredits(
workspaceId,
PERIOD_START,
PERIOD_END,
500_000,
);
await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.SALES,
reason: null,
expiresInDays: 1,
});
expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
500_000 + 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
);
});
it('takes a revoked grant back off the ledger and the available-credits counter', async () => {
const cache = getBillingUsageCacheService();
await cache.warmAvailableCredits(
workspaceId,
PERIOD_START,
PERIOD_END,
500_000,
);
const granted = await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
});
const creditGrantId = granted.body.data.grantWorkspaceCredits.id;
const revoked = await callAdminGraphql(REVOKE_MUTATION, {
workspaceId,
creditGrantId,
});
expect(revoked.body.errors).toBeUndefined();
expect(
revoked.body.data.revokeWorkspaceCreditGrant.revokedAt,
).not.toBeNull();
const grants = await listCreditGrants(workspaceId);
expect(grants[0].revokedAt).not.toBeNull();
expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
500_000,
);
});
it.each([
BillingCreditGrantType.ROLLOVER,
BillingCreditGrantType.ONBOARDING_REWARD,
])('refuses to grant a %s by hand', async (type) => {
const response = await grantCredits({
workspaceId,
amount: 1,
type,
reason: null,
});
expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',
);
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
it('drops the warm allowance counter when a grant lands', async () => {
await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
});
expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
it('takes a revoked grant off the ledger and drops the counter', async () => {
const granted = await grantCredits({
workspaceId,
amount: 2,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
});
const creditGrantId = granted.body.data.grantWorkspaceCredits.id;
await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
const revoked = await callAdminGraphql(REVOKE_MUTATION, {
workspaceId,
creditGrantId,
});
expect(revoked.body.errors).toBeUndefined();
expect(
revoked.body.data.revokeWorkspaceCreditGrant.revokedAt,
).not.toBeNull();
const grants = await listCreditGrants(workspaceId);
expect(grants[0].revokedAt).not.toBeNull();
expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
// The panel only offers the three operator types, but the mutation is
// reachable directly and these two are written by the period transition and
// the onboarding jobs.
it.each([
BillingCreditGrantType.ROLLOVER,
BillingCreditGrantType.ONBOARDING_REWARD,
])('refuses to grant a %s by hand', async (type) => {
const response = await grantCredits({
workspaceId,
amount: 1,
type,
reason: null,
});
expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',
);
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
it('refuses an amount above the configured ceiling', async () => {
const response = await grantCredits({
workspaceId,
amount: 1_000_000_000,
type: BillingCreditGrantType.COMPENSATION,
reason: null,
});
expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
'BILLING_CREDIT_AMOUNT_INVALID',
);
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
// The admin panel keeps one operation id per open modal, so an Apollo retry
// or a resubmit after a lost response must answer with the grant the first
// attempt wrote rather than crediting the workspace a second time.
it('answers a retried grant with the original instead of granting twice', async () => {
const clientOperationId = randomUUID();
const variables = {
workspaceId,
amount: 25,
type: BillingCreditGrantType.COMPENSATION,
reason: 'Retried by the client',
clientOperationId,
};
const first = await callAdminGraphql(GRANT_MUTATION, variables);
const second = await callAdminGraphql(GRANT_MUTATION, variables);
expect(second.body.data.grantWorkspaceCredits.id).toBe(
first.body.data.grantWorkspaceCredits.id,
);
expect(await listCreditGrants(workspaceId)).toHaveLength(1);
});
// The refusal to time-box a grant with no billing period must not reach a
// replay: the subscription that anchored the original deadline can be gone by
// the time the client retries, and the operation already succeeded.
it('answers a retried time-boxed grant after the subscription is canceled', async () => {
const clientOperationId = randomUUID();
const variables = {
workspaceId,
amount: 25,
type: BillingCreditGrantType.SALES,
reason: 'Retried after cancellation',
clientOperationId,
expiresInDays: 30,
};
const first = await callAdminGraphql(GRANT_MUTATION, variables);
expect(first.body.errors).toBeUndefined();
await setSubscriptionStatus(workspaceId, SubscriptionStatus.Canceled);
const second = await callAdminGraphql(GRANT_MUTATION, variables);
expect(second.body.errors).toBeUndefined();
expect(second.body.data.grantWorkspaceCredits.id).toBe(
first.body.data.grantWorkspaceCredits.id,
);
expect(await listCreditGrants(workspaceId)).toHaveLength(1);
});
});

View File

@@ -0,0 +1,343 @@
import { addMonths, startOfMonth, subMonths } from 'date-fns';
import request from 'supertest';
import { createMockStripeInvoiceFinalizedData } from 'test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util';
import {
getBillingUsageCacheService,
getSeededBillingWorkspaceId,
insertCreditGrant,
listCreditGrants,
quitBillingFixtureRedis,
readAllowanceCounter,
resetBillingCreditState,
setupResourceCreditSubscription,
TEST_STRIPE_CUSTOMER_ID,
warmAllowanceCounter,
} from 'test/integration/billing/utils/billing-credit-fixtures.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { type BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
const client = request(`http://localhost:${APP_PORT}`);
// Whole calendar months, anchored so the period the transition opens is the
// one running right now. The ledger filters on now(), so periods fixed in the
// past would read as expired and assert nothing.
const PERIOD_BOUNDARY = startOfMonth(new Date());
const CLOSING_PERIOD_START = subMonths(PERIOD_BOUNDARY, 1);
const CLOSING_PERIOD_END = PERIOD_BOUNDARY;
const NEXT_PERIOD_END = addMonths(PERIOD_BOUNDARY, 1);
const ALLOWANCE_MICRO = 1_000_000;
const postInvoiceFinalized = (
invoiceId = 'in_test_default',
{ periodStart = CLOSING_PERIOD_END, periodEnd = NEXT_PERIOD_END } = {},
) =>
client
.post('/webhooks/stripe')
.set('stripe-signature', 'correct-signature')
.set('Content-Type', 'application/json')
.send(
JSON.stringify({
type: 'invoice.finalized',
data: createMockStripeInvoiceFinalizedData({
periodStart,
periodEnd,
stripeCustomerId: TEST_STRIPE_CUSTOMER_ID,
invoiceId,
}),
}),
);
describe('Billing credit rollover (integration)', () => {
let workspaceId: string;
let billingUsageService: BillingUsageService;
let usageSpy: jest.SpyInstance;
beforeAll(async () => {
workspaceId = await getSeededBillingWorkspaceId();
billingUsageService = getAppProviderByClassName<BillingUsageService>(
'BillingUsageService',
);
});
beforeEach(async () => {
await resetBillingCreditState(workspaceId);
await setupResourceCreditSubscription({
workspaceId,
periodStart: CLOSING_PERIOD_START,
periodEnd: CLOSING_PERIOD_END,
creditAmountMicro: ALLOWANCE_MICRO,
});
// Usage is read from ClickHouse, whose inserts are asynchronous. Stubbing
// the read keeps every expectation exact instead of racing ingestion; the
// query itself has its own unit coverage.
usageSpy = jest.spyOn(billingUsageService, 'getCreditsUsedBetweenOrNull');
});
afterEach(async () => {
usageSpy?.mockRestore();
await resetBillingCreditState(workspaceId);
});
afterAll(async () => {
await quitBillingFixtureRedis();
});
it('carries the unspent allowance into the next period', async () => {
usageSpy.mockResolvedValue(300_000);
await postInvoiceFinalized().expect(200);
const grants = await listCreditGrants(workspaceId);
expect(grants).toHaveLength(1);
expect(grants[0]).toMatchObject({
amountMicro: 700_000,
type: BillingCreditGrantType.ROLLOVER,
revokedAt: null,
});
expect(new Date(grants[0].effectiveAt)).toEqual(CLOSING_PERIOD_END);
// Successors carry no deadline: stamping the next period end would put the
// balance back at the mercy of the transition after this one running.
expect(grants[0].expiresAt).toBeNull();
});
it('reads usage over the closing period, not the one just opened', async () => {
usageSpy.mockResolvedValue(0);
await postInvoiceFinalized().expect(200);
expect(usageSpy).toHaveBeenCalledWith({
workspaceId,
from: CLOSING_PERIOD_START,
to: CLOSING_PERIOD_END,
});
});
it('carries nothing when the whole allowance was spent', async () => {
usageSpy.mockResolvedValue(ALLOWANCE_MICRO);
await postInvoiceFinalized().expect(200);
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
it('closes the grants it carried forward so they cannot be counted twice', async () => {
usageSpy.mockResolvedValue(0);
await insertCreditGrant({
workspaceId,
amountMicro: 500_000,
type: BillingCreditGrantType.COMPENSATION,
effectiveAt: CLOSING_PERIOD_START,
expiresAt: NEXT_PERIOD_END,
});
await postInvoiceFinalized().expect(200);
const grants = await listCreditGrants(workspaceId);
const compensation = grants.find(
(grant) =>
grant.type === BillingCreditGrantType.COMPENSATION &&
grant.sourceGrantId === null,
);
expect(compensation).toBeDefined();
// Its expiry was pulled back to the boundary, so the balance counts it
// once through its carried-forward copy rather than twice.
expect(compensation?.expiresAt).toEqual(CLOSING_PERIOD_END);
expect(
grants.some(
(grant) =>
grant.type === BillingCreditGrantType.COMPENSATION &&
grant.sourceGrantId === compensation!.id,
),
).toBe(true);
});
it('caps the carried rollover at the configured multiple of the allowance', async () => {
usageSpy.mockResolvedValue(0);
await insertCreditGrant({
workspaceId,
amountMicro: ALLOWANCE_MICRO,
type: BillingCreditGrantType.ROLLOVER,
effectiveAt: CLOSING_PERIOD_START,
expiresAt: CLOSING_PERIOD_END,
});
await postInvoiceFinalized().expect(200);
const carried = (await listCreditGrants(workspaceId)).filter(
(grant) => grant.sourceGrantId !== null || grant.idempotencyKey !== null,
);
const carriedRollover = carried.filter(
(grant) => grant.type === BillingCreditGrantType.ROLLOVER,
);
// allowance + expiring rollover = 2M unspent, clamped to (2 - 1) x 1M.
expect(
carriedRollover.reduce((total, grant) => total + grant.amountMicro, 0),
).toBe(ALLOWANCE_MICRO);
});
// A redelivery must not hand out the credits a second time.
it('is idempotent when Stripe redelivers the same invoice', async () => {
usageSpy.mockResolvedValue(300_000);
await postInvoiceFinalized().expect(200);
const afterFirst = await listCreditGrants(workspaceId);
await postInvoiceFinalized().expect(200);
const afterSecond = await listCreditGrants(workspaceId);
expect(afterSecond).toHaveLength(afterFirst.length);
expect(
afterSecond.reduce((total, grant) => total + grant.amountMicro, 0),
).toBe(afterFirst.reduce((total, grant) => total + grant.amountMicro, 0));
});
// Returning normally would answer 200 and Stripe would never redeliver, so
// the transition would be lost and the balance would expire unrolled.
it('fails the webhook when usage cannot be read so Stripe redelivers', async () => {
usageSpy.mockResolvedValue(null);
await postInvoiceFinalized().expect(500);
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
it('adds the carried balance to a warm available-credits counter', async () => {
usageSpy.mockResolvedValue(300_000);
const cache = getBillingUsageCacheService();
await cache.warmAvailableCredits(
workspaceId,
CLOSING_PERIOD_START,
NEXT_PERIOD_END,
120_000,
);
await postInvoiceFinalized().expect(200);
expect(
await cache.getAvailableCredits(workspaceId, CLOSING_PERIOD_START),
).toBe(120_000 + 700_000);
});
it('leaves a warm available-credits counter alone when a successful delivery is repeated', async () => {
usageSpy.mockResolvedValue(300_000);
const cache = getBillingUsageCacheService();
await cache.warmAvailableCredits(
workspaceId,
CLOSING_PERIOD_START,
NEXT_PERIOD_END,
120_000,
);
await postInvoiceFinalized().expect(200);
const afterFirst = await cache.getAvailableCredits(
workspaceId,
CLOSING_PERIOD_START,
);
await postInvoiceFinalized().expect(200);
expect(afterFirst).toBe(120_000 + 700_000);
expect(
await cache.getAvailableCredits(workspaceId, CLOSING_PERIOD_START),
).toBe(afterFirst);
});
it('drops the allowance counter on the period transition', async () => {
usageSpy.mockResolvedValue(300_000);
// The counter is keyed by the period the subscription is currently in,
// which is the one the invoice is closing: Stripe moves the subscription
// forward in a separate event.
await warmAllowanceCounter(workspaceId, CLOSING_PERIOD_START, 120_000);
await postInvoiceFinalized().expect(200);
expect(
await readAllowanceCounter(workspaceId, CLOSING_PERIOD_START),
).toBeNull();
});
// A subscription anchored on the 31st runs January 31 to February 28. Once
// the subscription.updated webhook has moved the subscription on, calendar
// arithmetic clamps February 28 back to January 28 and the closing period
// swallows three days of the period before it.
describe('a month-end anchor whose subscription already advanced', () => {
const MONTH_END_BOUNDARY = new Date('2026-02-28T00:00:00.000Z');
const TRUE_CLOSING_PERIOD_START = new Date('2026-01-31T00:00:00.000Z');
const MONTH_END_NEXT_PERIOD_END = new Date('2026-03-31T00:00:00.000Z');
it('reads the closing period start off the ledger rather than the calendar', async () => {
usageSpy.mockResolvedValue(0);
await setupResourceCreditSubscription({
workspaceId,
periodStart: MONTH_END_BOUNDARY,
periodEnd: MONTH_END_NEXT_PERIOD_END,
creditAmountMicro: ALLOWANCE_MICRO,
});
// What the previous transition left behind: a grant closed at the instant
// the period it belonged to ended.
await insertCreditGrant({
workspaceId,
amountMicro: 100_000,
type: BillingCreditGrantType.ROLLOVER,
effectiveAt: new Date('2025-12-31T00:00:00.000Z'),
expiresAt: TRUE_CLOSING_PERIOD_START,
});
await postInvoiceFinalized('in_test_month_end', {
periodStart: MONTH_END_BOUNDARY,
periodEnd: MONTH_END_NEXT_PERIOD_END,
}).expect(200);
expect(usageSpy).toHaveBeenCalledWith({
workspaceId,
from: TRUE_CLOSING_PERIOD_START,
to: MONTH_END_BOUNDARY,
});
});
});
describe('closing a trial', () => {
it('carries credits earned during the trial into the first paid period', async () => {
usageSpy.mockResolvedValue(0);
await setupResourceCreditSubscription({
workspaceId,
periodStart: CLOSING_PERIOD_START,
periodEnd: CLOSING_PERIOD_END,
creditAmountMicro: ALLOWANCE_MICRO,
status: 'trialing',
trialStart: CLOSING_PERIOD_START,
trialEnd: CLOSING_PERIOD_END,
});
await insertCreditGrant({
workspaceId,
amountMicro: 250_000,
type: BillingCreditGrantType.ONBOARDING_REWARD,
effectiveAt: CLOSING_PERIOD_START,
expiresAt: null,
});
await postInvoiceFinalized('in_test_trial').expect(200);
const reward = (await listCreditGrants(workspaceId)).find(
(grant) =>
grant.type === BillingCreditGrantType.ONBOARDING_REWARD &&
grant.sourceGrantId !== null,
);
expect(reward).toBeDefined();
expect(reward?.amountMicro).toBe(250_000);
expect(reward?.expiresAt).toBeNull();
});
});
});

View File

@@ -0,0 +1,264 @@
import { createClient, type RedisClientType } from 'redis';
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { type SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
import { type BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
// The dev seeder gives every workspace a billingCustomer and an active
// billingSubscription, but no subscription item, and no period. Rollover needs
// the whole chain — subscription -> item -> product -> price with a
// credit_amount — so these helpers finish the fixture and put the period where
// the test wants it.
export const TEST_STRIPE_CUSTOMER_ID = 'cus_default0';
export const TEST_STRIPE_SUBSCRIPTION_ID = 'sub_default0';
const TEST_STRIPE_PRODUCT_ID = 'prod_resource_credit_test';
const TEST_STRIPE_PRICE_ID = 'price_resource_credit_test';
const TEST_STRIPE_SUBSCRIPTION_ITEM_ID = 'si_resource_credit_test';
export type CreditGrantRow = {
id: string;
amountMicro: number;
type: BillingCreditGrantType;
effectiveAt: Date;
expiresAt: Date | null;
revokedAt: Date | null;
reason: string | null;
idempotencyKey: string | null;
sourceGrantId: string | null;
};
const query = async <T>(sql: string, params: unknown[] = []): Promise<T[]> =>
global.testDataSource.query(sql, params);
// The billing seeds insert with orIgnore, so the customer and subscription
// land on exactly one workspace and which one is not worth hardcoding.
export const getSeededBillingWorkspaceId = async (): Promise<string> => {
const [row] = await query<{ workspaceId: string }>(
`SELECT "workspaceId" FROM core."billingSubscription" WHERE "stripeSubscriptionId" = $1`,
[TEST_STRIPE_SUBSCRIPTION_ID],
);
if (!row) {
throw new Error(
`No seeded billing subscription ${TEST_STRIPE_SUBSCRIPTION_ID}: the dev seeder did not run`,
);
}
return row.workspaceId;
};
export const setupResourceCreditSubscription = async ({
workspaceId,
periodStart,
periodEnd,
creditAmountMicro,
status = 'active',
trialStart = null,
trialEnd = null,
}: {
workspaceId: string;
periodStart: Date;
periodEnd: Date;
creditAmountMicro: number;
status?: string;
trialStart?: Date | null;
trialEnd?: Date | null;
}): Promise<{ subscriptionId: string }> => {
await query(
`UPDATE core."billingSubscription"
SET "currentPeriodStart" = $2, "currentPeriodEnd" = $3, status = $4,
"trialStart" = $5, "trialEnd" = $6, interval = 'month'
WHERE "workspaceId" = $1 AND "stripeSubscriptionId" = $7`,
[
workspaceId,
periodStart,
periodEnd,
status,
trialStart,
trialEnd,
TEST_STRIPE_SUBSCRIPTION_ID,
],
);
const [subscription] = await query<{ id: string }>(
`SELECT id FROM core."billingSubscription"
WHERE "workspaceId" = $1 AND "stripeSubscriptionId" = $2`,
[workspaceId, TEST_STRIPE_SUBSCRIPTION_ID],
);
await query(
`INSERT INTO core."billingProduct"
("stripeProductId", active, name, description, metadata)
VALUES ($1, true, 'Test resource credit', '', $2)
ON CONFLICT ("stripeProductId") DO UPDATE SET metadata = EXCLUDED.metadata`,
[TEST_STRIPE_PRODUCT_ID, JSON.stringify({ productKey: 'RESOURCE_CREDIT' })],
);
await query(
`INSERT INTO core."billingPrice"
("stripePriceId", "stripeProductId", active, currency, "taxBehavior",
type, "billingScheme", "usageType", interval, "unitAmount", metadata)
VALUES ($1, $2, true, 'usd', 'UNSPECIFIED', 'RECURRING', 'PER_UNIT',
'LICENSED', 'month', 1000, $3)
ON CONFLICT ("stripePriceId") DO UPDATE SET metadata = EXCLUDED.metadata`,
[
TEST_STRIPE_PRICE_ID,
TEST_STRIPE_PRODUCT_ID,
JSON.stringify({ credit_amount: String(creditAmountMicro) }),
],
);
await query(
`INSERT INTO core."billingSubscriptionItem"
("billingSubscriptionId", "stripeSubscriptionId", "stripeProductId",
"stripePriceId", "stripeSubscriptionItemId", quantity)
VALUES ($1, $2, $3, $4, $5, 1)
ON CONFLICT ("stripeSubscriptionItemId") DO UPDATE
SET "stripePriceId" = EXCLUDED."stripePriceId",
"stripeProductId" = EXCLUDED."stripeProductId"`,
[
subscription.id,
TEST_STRIPE_SUBSCRIPTION_ID,
TEST_STRIPE_PRODUCT_ID,
TEST_STRIPE_PRICE_ID,
TEST_STRIPE_SUBSCRIPTION_ITEM_ID,
],
);
return { subscriptionId: subscription.id };
};
export const insertCreditGrant = async ({
workspaceId,
amountMicro,
type,
effectiveAt,
expiresAt,
idempotencyKey = null,
}: {
workspaceId: string;
amountMicro: number;
type: BillingCreditGrantType;
effectiveAt: Date;
expiresAt: Date | null;
idempotencyKey?: string | null;
}): Promise<string> => {
const [row] = await query<{ id: string }>(
`INSERT INTO core."billingCreditGrant"
("workspaceId", "amountMicro", type, "effectiveAt", "expiresAt", "idempotencyKey")
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id`,
[workspaceId, amountMicro, type, effectiveAt, expiresAt, idempotencyKey],
);
return row.id;
};
export const listCreditGrants = async (
workspaceId: string,
): Promise<CreditGrantRow[]> =>
query<CreditGrantRow>(
`SELECT id, "amountMicro"::bigint::int AS "amountMicro", type, "effectiveAt",
"expiresAt", "revokedAt", reason, "idempotencyKey", "sourceGrantId"
FROM core."billingCreditGrant"
WHERE "workspaceId" = $1
ORDER BY "createdAt" ASC`,
[workspaceId],
);
let redisClient: RedisClientType | null = null;
const getRedisClient = async (): Promise<RedisClientType> => {
if (!isDefined(redisClient)) {
redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
}
return redisClient;
};
export const quitBillingFixtureRedis = async (): Promise<void> => {
if (isDefined(redisClient)) {
await redisClient.quit();
redisClient = null;
}
};
const buildTestAllowanceCounterKey = (
workspaceId: string,
periodStart: Date,
): string =>
`${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineUsageLimit}:${buildAllowanceCounterKey({ workspaceId, periodStart })}`;
export const warmAllowanceCounter = async (
workspaceId: string,
periodStart: Date,
valueMicro: number,
): Promise<void> => {
const redis = await getRedisClient();
await redis.set(
buildTestAllowanceCounterKey(workspaceId, periodStart),
String(valueMicro),
);
};
export const readAllowanceCounter = async (
workspaceId: string,
periodStart: Date,
): Promise<number | null> => {
const redis = await getRedisClient();
const value = await redis.get(
buildTestAllowanceCounterKey(workspaceId, periodStart),
);
return isDefined(value) ? Number(value) : null;
};
export const resetBillingCreditState = async (
workspaceId: string,
): Promise<void> => {
await query(
`DELETE FROM core."billingCreditGrant" WHERE "workspaceId" = $1`,
[workspaceId],
);
const cache = getBillingUsageCacheService();
await cache.flushAvailableCredits(workspaceId);
await cache.flushCounterAdjustmentMarkers(workspaceId);
const redis = await getRedisClient();
const staleKeys = [
...(await redis.keys(`*{${workspaceId}}:quota:allowance:*`)),
...(await redis.keys(`*currentBillingSubscription:${workspaceId}*`)),
];
if (isNonEmptyArray(staleKeys)) {
await redis.del(staleKeys);
}
};
export const getBillingUsageCacheService = (): BillingUsageCacheService =>
getAppProviderByClassName<BillingUsageCacheService>(
'BillingUsageCacheService',
);
// Cancelling is what makes getCurrentBillingSubscription stop returning it, so
// this is how a test reaches the no-subscription path without deleting rows the
// rest of the suite shares.
export const setSubscriptionStatus = async (
workspaceId: string,
status: SubscriptionStatus,
): Promise<void> => {
await query(
`UPDATE "core"."billingSubscription" SET status = $2 WHERE "workspaceId" = $1`,
[workspaceId, status],
);
};

View File

@@ -0,0 +1,25 @@
import type Stripe from 'stripe';
export const createMockStripeEntitlementUpdatedData = (
overrides = {},
): Stripe.EntitlementsActiveEntitlementSummaryUpdatedEvent.Data => ({
object: {
object: 'entitlements.active_entitlement_summary',
customer: 'cus_default1',
livemode: false,
entitlements: {
object: 'list',
data: [
{
id: 'ent_test_61',
object: 'entitlements.active_entitlement',
feature: 'feat_test_61',
livemode: false,
lookup_key: 'SSO',
},
],
has_more: false,
url: '/v1/customer/cus_Q/entitlements',
},
...overrides,
},
});

View File

@@ -0,0 +1,60 @@
// Typed to what the handler actually reads rather than to Stripe.Invoice: the
// payload crosses the wire as JSON, so the runtime shape is what matters, and
// a full Stripe.Invoice fixture would be a few hundred lines of noise.
export type MockStripeInvoiceFinalizedData = {
object: {
id: string;
object: 'invoice';
billing_reason: string;
created: number;
customer: string;
period_start: number;
period_end: number;
parent: {
subscription_details: {
subscription: string;
};
};
};
};
const toUnixSeconds = (date: Date): number => Math.floor(date.getTime() / 1000);
export const createMockStripeInvoiceFinalizedData = ({
periodStart,
periodEnd,
stripeCustomerId = 'cus_default0',
stripeSubscriptionId = 'sub_default0',
billingReason = 'subscription_cycle',
invoiceId = 'in_test_default',
// Stripe raises a cycle invoice at the handover, which for an advance-stamped
// one is the period it opens. The boundary is resolved off this rather than
// off our own clock, so a fixture that leaves it out no longer models the
// handover at all.
createdAt = periodStart,
}: {
periodStart: Date;
periodEnd: Date;
createdAt?: Date;
stripeCustomerId?: string;
stripeSubscriptionId?: string;
billingReason?: string;
invoiceId?: string;
}): MockStripeInvoiceFinalizedData => ({
object: {
id: invoiceId,
object: 'invoice',
billing_reason: billingReason,
created: toUnixSeconds(createdAt),
customer: stripeCustomerId,
// The invoice for a subscription_cycle bills the period it opens, so its
// period_start is the instant the previous period closed.
period_start: toUnixSeconds(periodStart),
period_end: toUnixSeconds(periodEnd),
parent: {
subscription_details: {
subscription: stripeSubscriptionId,
},
},
},
});

View File

@@ -0,0 +1,33 @@
import type Stripe from 'stripe';
export const createMockStripePriceCreatedData = (
overrides = {},
): Stripe.PriceCreatedEvent.Data => ({
object: {
id: 'price_1Q',
object: 'price',
active: true,
billing_scheme: 'per_unit',
created: 1733734326,
currency: 'usd',
custom_unit_amount: null,
livemode: false,
lookup_key: null,
metadata: {},
nickname: null,
product: 'prod_RLN',
recurring: {
interval: 'month',
interval_count: 1,
meter: null,
trial_period_days: null,
usage_type: 'licensed',
},
tax_behavior: 'unspecified',
tiers_mode: null,
transform_quantity: null,
type: 'recurring',
unit_amount: 0,
unit_amount_decimal: '0',
...overrides,
},
});

View File

@@ -0,0 +1,39 @@
import type Stripe from 'stripe';
import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';
import { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';
export const createMockStripeProductUpdatedData = (
overrides = {},
): Stripe.ProductUpdatedEvent.Data => ({
object: {
id: 'prod_RLN',
object: 'product',
active: true,
created: 1733410584,
default_price: null,
description: null,
images: [],
livemode: false,
marketing_features: [],
metadata: {
planKey: 'base',
priceUsageBased: BillingUsageType.LICENSED,
productKey: BillingProductKey.BASE_PRODUCT,
},
name: 'kjnnjkjknkjnjkn',
package_dimensions: null,
shippable: null,
statement_descriptor: null,
tax_code: 'txcd_10103001',
type: 'service',
unit_label: null,
updated: 1734694649,
url: null,
},
previous_attributes: {
default_price: 'price_1Q',
updated: 1733410585,
},
...overrides,
});

View File

@@ -0,0 +1,133 @@
import type Stripe from 'stripe';
export const createMockStripeSubscriptionCreatedData = (
overrides = {},
): Stripe.CustomerSubscriptionCreatedEvent.Data => ({
object: {
object: 'subscription',
id: 'sub_default',
customer: 'cus_default1',
customer_account: null,
status: 'active',
items: {
data: [
{
plan: {
id: 'plan_default',
object: 'plan',
active: true,
amount_decimal: '0',
billing_scheme: 'per_unit',
interval_count: 1,
livemode: false,
nickname: null,
tiers_mode: null,
transform_usage: null,
trial_period_days: null,
interval: 'month',
currency: 'usd',
amount: 0,
created: 1672531200,
product: 'prod_default',
usage_type: 'licensed',
metadata: {},
meter: null,
},
id: '',
object: 'subscription_item',
billing_thresholds: null,
created: 0,
current_period_end: 1672531200,
current_period_start: 1672531200,
discounts: [],
metadata: {},
price: {
id: 'price_default',
object: 'price',
active: true,
billing_scheme: 'per_unit',
created: 1672531200,
currency: 'usd',
custom_unit_amount: null,
livemode: false,
lookup_key: null,
metadata: {},
nickname: null,
product: 'prod_default',
recurring: {
interval: 'month',
interval_count: 1,
meter: null,
trial_period_days: null,
usage_type: 'licensed',
},
tax_behavior: null,
tiers_mode: null,
transform_quantity: null,
type: 'recurring',
unit_amount: 1000,
unit_amount_decimal: '1000',
},
subscription: '',
tax_rates: null,
},
],
object: 'list',
has_more: false,
url: '',
},
cancel_at_period_end: false,
currency: 'usd',
metadata: { workspaceId: '3b8e6458-5fc1-4e63-8563-008ccddaa6db' },
trial_end: null,
trial_start: null,
canceled_at: null,
...overrides,
application: null,
application_fee_percent: null,
automatic_tax: {
disabled_reason: null,
enabled: true,
liability: {
type: 'self',
},
},
billing_cycle_anchor: 0,
billing_cycle_anchor_config: null,
billing_mode: {
type: 'flexible',
flexible: {},
},
billing_thresholds: null,
cancel_at: null,
cancellation_details: null,
collection_method: 'charge_automatically',
created: 0,
days_until_due: null,
default_payment_method: null,
default_source: null,
description: null,
discounts: [],
ended_at: null,
invoice_settings: {
account_tax_ids: null,
issuer: {
type: 'self',
},
},
latest_invoice: null,
livemode: false,
next_pending_invoice_item_invoice: null,
on_behalf_of: null,
pause_collection: null,
payment_settings: null,
pending_invoice_item_interval: null,
pending_setup_intent: null,
pending_update: null,
schedule: null,
start_date: 0,
test_clock: null,
transfer_data: null,
trial_settings: null,
},
});