refactor: Billing service (#15366)
* WIP: Billing service * WIP * Update __handler.ts * Update index.ts * WIP * WIP Signed-off-by: zomars <[email protected]> * WIP Signed-off-by: zomars <[email protected]> * Update delete.handler.ts * Update delete.handler.ts * Update internal-team-billing.ts * WIP * Type fixes Signed-off-by: zomars <[email protected]> * WIP Signed-off-by: zomars <[email protected]> * Discard changes to apps/api/v2/src/ee/event-types/event-types_2024_04_15/controllers/event-types.controller.ts * Discard changes to packages/app-store/skype/config.json * style: update text area (#15934) * chore: update text-editor input * chore: update text-editor input * final update * Update Editor.tsx --------- Co-authored-by: unknown <[email protected]> Co-authored-by: Anik Dhabal Babu <[email protected]> * fix: #15697 Assignment warning modal poping up ,even when hosts are added . (#15699) * removed reduntand check on assignedusers * update for managed eventtype * formatted * comments * Updated comments * extracted checkForEmptyAssignment and added tests * updated comments * updated to show dialog also when not yet saved * update translations * updated comments * updated translation * updated types * chore: update naming and comments * Delete apps/web/lib/checkForEmptyAssignment.ts deleted since file was renamed * Delete apps/web/test/lib/checkForEmptyAssignment.test.ts deleted as the file is renamed to be more descriptive * update to do teamcheck before * chore: revert name to CheckForEmptyAssignment * updated check conditions * updated useEffect dependencies --------- Co-authored-by: Anik Dhabal Babu <[email protected]> * fix: getting an error when a team member tries to leave (#15925) a team Co-authored-by: Somay Chauhan <[email protected]> Co-authored-by: Amit Sharma <[email protected]> * feat: add transitions to more components (#15916) * add transitions to more components * chore: Remove duplicate class * fix: Change minimum number of teams required for org self-serve (#15955) * fix: Change minimum number of teams required for org self-serve Signed-off-by: Souptik Datta <[email protected]> * refactor: Use a new constant for displaying org helper text dialogue Signed-off-by: Souptik Datta <[email protected]> * Update packages/lib/constants.ts * Update turbo.json --------- Signed-off-by: Souptik Datta <[email protected]> Co-authored-by: Keith Williams <[email protected]> * feat: pwa ready and add shortcut for quick access (#15957) * chore: Update site.webmanifest with additional display properties * chore: Update site.webmanifest with additional display properties * Update apps/web/public/site.webmanifest --------- Co-authored-by: Keith Williams <[email protected]> * i18n: update translations for "by proceeding, ..." (#15921) * feat: Add title attribute to iframe in embed.ts (#15944) * feat: Add title attribute to iframe in embed.ts * Update packages/embeds/embed-core/src/embed.ts --------- Co-authored-by: Hariom Balhara <[email protected]> * fix: Assignment reminder modal appears when deleting a team event type (#15544) * fix: Assignment reminder modal appears when deleting a team event type * update * Update EventTypeSingleLayout.tsx * Update event-types-single-view.tsx * update * Early return https://handbook.cal.com/engineering/best-practices/prefer-early-returns --------- Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Hariom <[email protected]> * fix: Add CORP and COEP headers to embedded pages (#15275) * Add CORP headers * Improve test * Add unit tests as well --------- Co-authored-by: Keith Williams <[email protected]> * feat: No-show bookings - do not count towards a member's round robin assignment (#15323) * feat: No-show bookings - do not count towards a member's round robin assignment * filter no show organizer * remove logs * fix: filter bookings where host attendee is no show * fix: use not condition for noShow * chore: test * add default false for noShowHost * Revert "chore: test" This reverts commit c914a8fc4a14ca9c7d8c4a08ff8b0f463789171c. * chore: integration test * fix: noShowHost not working for null * Update packages/lib/server/getLuckyUser.ts * chore: update test description --------- Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: gh0st91848 <[email protected]> Co-authored-by: Hariom Balhara <[email protected]> * refactor: v1 orgs unlimited teams (#15908) * refactor: v1 orgs unlimited teams * fix: response message ownerId --------- Co-authored-by: Keith Williams <[email protected]> * fix: refresh connect atoms on token change (#15933) * added dropdown * change comment * fix: added types --------- Co-authored-by: Morgan <[email protected]> Co-authored-by: Keith Williams <[email protected]> * fix: Next.js bundle analysis (#15903) * fix: Next.js bundle analysis * Added the main checkout back * fix: type in webhook payload (#15912) Co-authored-by: CarinaWolli <[email protected]> * fix: auto accept (#15975) * fix: auto accept * Update packages/lib/server/repository/organization.ts Co-authored-by: Hariom Balhara <[email protected]> --------- Co-authored-by: Hariom Balhara <[email protected]> * fix: Broken GitHub workflows (#15979) * test: Delete credential endpoint (#15322) * Init * Add mock trpc context * Intro mockDatabaseClient * Introduce mockDatabaseClient class * Add delete video app test * Add calendar test * Remove unused func from bookingScenario * Remove console.log * Add app repository * Add createMany method to event type repository * Remove instance of MockDatabaseClient from video test * Add destination calendar repository * Remove instances of MockDatabaseClient * abstract logic to own handler * Remove dev dependency * Clean up * Type fix * Pull yarn.lock from main --------- Co-authored-by: Anik Dhabal Babu <[email protected]> * fix: #15967 Show better error when wrong variable is used in custom event name (#15974) * update to show exact err msg with custom event name * updated tests for validateCustomEventName --------- Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Anik Dhabal Babu <[email protected]> * WIP Signed-off-by: zomars <[email protected]> * Update yarn.lock * Update publish.handler.ts * Update internal-team-billing.test.ts * rename create to init * remove sync services * wip tests for delete team * wip tets * wip tests * tests/internal-test * remove return that is inaccessable * remove team calls to use repository * remove redudant file * update team repo * add stripe mocks and test * fix constants * tests to main stripe handler * remove logs * fix constants * Update packages/features/ee/billing/api/webhook/_customer.subscription.deleted.team-plan.ts Co-authored-by: Omar López <[email protected]> * move workflow logic to a service * use static method > creating new class * fix: remove http code deep in repo + tests * Feedback * Update index.ts * Type fix * Lazy load fixes --------- Signed-off-by: zomars <[email protected]> Signed-off-by: Souptik Datta <[email protected]> Co-authored-by: Rohan Advani <[email protected]> Co-authored-by: unknown <[email protected]> Co-authored-by: Anik Dhabal Babu <[email protected]> Co-authored-by: Vijay <[email protected]> Co-authored-by: Somay Chauhan <[email protected]> Co-authored-by: Amit Sharma <[email protected]> Co-authored-by: Hichem Fantar <[email protected]> Co-authored-by: Souptik Datta <[email protected]> Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Johannes Maendle <[email protected]> Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: gh0st91848 <[email protected]> Co-authored-by: Lauris Skraucis <[email protected]> Co-authored-by: Morgan <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: sean <[email protected]>
This commit is contained in:
46 files changed
+1848
-337
No files matched your search
@@ -0,0 +1,92 @@
|
||||
import { buffer } from "micro";
|
||||
import type { NextApiRequest } from "next";
|
||||
import { createMocks } from "node-mocks-http";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
|
||||
import { stripeWebhookHandler, HttpCode } from "./__handler";
|
||||
|
||||
vi.mock("micro", () => ({
|
||||
buffer: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/app-store/stripepayment/lib/server", () => ({
|
||||
default: {
|
||||
webhooks: {
|
||||
constructEvent: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const STRIPE_WEBHOOK_SECRET = "whsec_test_secret";
|
||||
|
||||
describe("stripeWebhookHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("STRIPE_WEBHOOK_SECRET", STRIPE_WEBHOOK_SECRET);
|
||||
});
|
||||
|
||||
const mockRequest = (headers: Record<string, string>, body: string): NextApiRequest =>
|
||||
({
|
||||
headers,
|
||||
body,
|
||||
} as unknown as NextApiRequest);
|
||||
|
||||
it("should throw an error if stripe-signature header is missing", async () => {
|
||||
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const handler = stripeWebhookHandler({});
|
||||
await expect(handler(req)).rejects.toThrow(new HttpCode(400, "Missing stripe-signature"));
|
||||
});
|
||||
|
||||
it("should throw an error if STRIPE_WEBHOOK_SECRET is missing", async () => {
|
||||
vi.stubEnv("STRIPE_WEBHOOK_SECRET", "");
|
||||
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"stripe-signature": "test_signature",
|
||||
},
|
||||
});
|
||||
const handler = stripeWebhookHandler({});
|
||||
await expect(handler(req)).rejects.toThrow(new HttpCode(500, "Missing STRIPE_WEBHOOK_SECRET"));
|
||||
});
|
||||
|
||||
it("should throw an error if event type is unhandled", async () => {
|
||||
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"stripe-signature": "test_signature",
|
||||
},
|
||||
});
|
||||
// const req = mockRequest({ "stripe-signature": "test_signature" }, "test_payload");
|
||||
(buffer as any).mockResolvedValueOnce(Buffer.from("test_payload"));
|
||||
(stripe.webhooks.constructEvent as any).mockReturnValueOnce({ type: "unhandled_event" });
|
||||
|
||||
const handler = stripeWebhookHandler({});
|
||||
await expect(handler(req)).rejects.toThrow(
|
||||
new HttpCode(202, "Unhandled Stripe Webhook event type unhandled_event")
|
||||
);
|
||||
});
|
||||
|
||||
it("should call the appropriate handler for a valid event", async () => {
|
||||
const req = mockRequest({ "stripe-signature": "test_signature" }, "test_payload");
|
||||
(buffer as any).mockResolvedValueOnce(Buffer.from("test_payload"));
|
||||
(stripe.webhooks.constructEvent as any).mockReturnValueOnce({
|
||||
type: "payment_intent.succeeded",
|
||||
data: "test_data",
|
||||
});
|
||||
|
||||
const mockHandler = vi.fn().mockResolvedValueOnce("handler_response");
|
||||
const handlers = {
|
||||
"payment_intent.succeeded": () => Promise.resolve({ default: mockHandler }),
|
||||
};
|
||||
|
||||
const handler = stripeWebhookHandler(handlers);
|
||||
const response = await handler(req);
|
||||
|
||||
expect(mockHandler).toHaveBeenCalledWith("test_data");
|
||||
expect(response).toBe("handler_response");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
/// <reference types="stripe-event-types" />
|
||||
import { buffer } from "micro";
|
||||
import type { NextApiRequest } from "next";
|
||||
import type Stripe from "stripe";
|
||||
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
/** Stripe Webhook Handler Mappings */
|
||||
export type SWHMap = {
|
||||
[T in Stripe.DiscriminatedEvent as T["type"]]: {
|
||||
[K in keyof T as Exclude<K, "type">]: T[K];
|
||||
};
|
||||
};
|
||||
|
||||
export type LazyModule<D> = Promise<{
|
||||
default: (data: D) => unknown | Promise<unknown>;
|
||||
}>;
|
||||
|
||||
type SWHandlers = {
|
||||
[K in keyof SWHMap]?: () => LazyModule<SWHMap[K]["data"]>;
|
||||
};
|
||||
|
||||
/** Just a shorthand for HttpError */
|
||||
export class HttpCode extends HttpError {
|
||||
constructor(statusCode: number, message: string) {
|
||||
super({ statusCode, message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows us to split big API handlers by webhook event, and lazy load them.
|
||||
* It already handles the Stripe signature verification and event construction.
|
||||
* @param handlers - A mapping of Stripe webhook event types to lazy loaded handlers.
|
||||
* @returns A function that can be used as a Next.js API handler.
|
||||
* @example
|
||||
* ```ts
|
||||
* stripeWebhookHandler({
|
||||
* "payment_intent.succeeded": () => import("./_lazyLoadedSuccessHandler"),
|
||||
* "customer.subscription.deleted": () => import("./_customer.subscription.deleted"),
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export const stripeWebhookHandler = (handlers: SWHandlers) => async (req: NextApiRequest) => {
|
||||
const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
const sig = req.headers["stripe-signature"];
|
||||
if (!sig) throw new HttpCode(400, "Missing stripe-signature");
|
||||
if (!STRIPE_WEBHOOK_SECRET) throw new HttpCode(500, "Missing STRIPE_WEBHOOK_SECRET");
|
||||
const requestBuffer = await buffer(req);
|
||||
const payload = requestBuffer.toString();
|
||||
const event = stripe.webhooks.constructEvent(
|
||||
payload,
|
||||
sig,
|
||||
STRIPE_WEBHOOK_SECRET
|
||||
) as Stripe.DiscriminatedEvent;
|
||||
const handlerGetter = handlers[event.type];
|
||||
if (!handlerGetter) throw new HttpCode(202, `Unhandled Stripe Webhook event type ${event.type}`);
|
||||
const handler = (await handlerGetter())?.default;
|
||||
// auto catch unsupported Stripe events.
|
||||
if (!handler) throw new HttpCode(202, `Unhandled Stripe Webhook event type ${event.type}`);
|
||||
// @ts-expect-error - we know the handler is defined and accpets the data type
|
||||
return await handler(event.data);
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { TeamBilling } from "../../teams";
|
||||
import type { SWHMap } from "./__handler";
|
||||
|
||||
const metadataSchema = z.object({
|
||||
teamId: z.coerce.number(),
|
||||
});
|
||||
|
||||
const handler = async (data: SWHMap["customer.subscription.deleted"]["data"]) => {
|
||||
const subscription = data.object;
|
||||
try {
|
||||
const { teamId } = metadataSchema.parse(subscription.metadata);
|
||||
const teamBilling = await TeamBilling.findAndInit(teamId);
|
||||
await teamBilling.downgrade();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
// If stripe metadata is missing teamId, we attempt to find by sub ID.
|
||||
const team = await TeamBilling.repo.findBySubscriptionId(subscription.id);
|
||||
const teamBilling = TeamBilling.init(team);
|
||||
await teamBilling.downgrade();
|
||||
return { success: true };
|
||||
}
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { HttpCode } from "./__handler";
|
||||
import type { LazyModule, SWHMap } from "./__handler";
|
||||
|
||||
type Data = SWHMap["customer.subscription.deleted"]["data"];
|
||||
|
||||
type Handlers = Record<`prod_${string}`, () => LazyModule<Data>>;
|
||||
|
||||
const STRIPE_TEAM_PRODUCT_ID = process.env.STRIPE_TEAM_PRODUCT_ID || "";
|
||||
|
||||
const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) => {
|
||||
const subscription = data.object;
|
||||
// @ts-expect-error - we know subscription.plan.product is defined when unsubscribing
|
||||
const productId = subscription.plan.product; // prod_xxxxx
|
||||
|
||||
const handlerGetter = handlers[productId];
|
||||
if (!handlerGetter) throw new HttpCode(202, `No product handler found for product: ${productId}`);
|
||||
const handler = (await handlerGetter())?.default;
|
||||
// auto catch unsupported Stripe products.
|
||||
if (!handler) throw new HttpCode(202, `No product handler found for product: ${productId}`);
|
||||
return await handler(data);
|
||||
};
|
||||
|
||||
export default stripeWebhookProductHandler({
|
||||
[STRIPE_TEAM_PRODUCT_ID]: () => import("./_customer.subscription.deleted.team-plan"),
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { SWHMap } from "./__handler";
|
||||
|
||||
// This is a placeholder to showcase adding new event handlers
|
||||
const handler = async (data: SWHMap["payment_intent.succeeded"]["data"]) => {
|
||||
const paymentIntent = data.object;
|
||||
// TODO: Implement payment intent succeeded webhook handler
|
||||
return { success: true };
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { stripeWebhookHandler } from "./__handler";
|
||||
|
||||
export default defaultHandler({
|
||||
// We only need to handle POST requests
|
||||
POST: Promise.resolve({
|
||||
default: defaultResponder(
|
||||
// We handle each Stripe webhook event type with it's own lazy loaded handler
|
||||
stripeWebhookHandler({
|
||||
"payment_intent.succeeded": () => import("./_payment_intent.succeeded"),
|
||||
// "customer.subscription.updated": () => import("./_customer.subscription.deleted"),
|
||||
"customer.subscription.deleted": () => import("./_customer.subscription.deleted"),
|
||||
})
|
||||
),
|
||||
}),
|
||||
});
|
||||
Reference in new issue
Block a user