Files
cal.diy/packages/features/ee/teams/lib/payments.ts
T
+12 a4a3eb5ea9 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]>
2024-10-04 13:44:50 -07:00

305 lines
10 KiB
TypeScript

import type Stripe from "stripe";
import { z } from "zod";
import { getStripeCustomerIdFromUserId } from "@calcom/app-store/stripepayment/lib/customer";
import stripe from "@calcom/app-store/stripepayment/lib/server";
import {
IS_PRODUCTION,
MINIMUM_NUMBER_OF_ORG_SEATS,
ORGANIZATION_SELF_SERVE_MIN_SEATS,
ORGANIZATION_SELF_SERVE_PRICE,
WEBAPP_URL,
} from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import { BillingPeriod } from "@calcom/prisma/zod-utils";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
const log = logger.getSubLogger({ prefix: ["teams/lib/payments"] });
const teamPaymentMetadataSchema = z.object({
// Redefine paymentId, subscriptionId and subscriptionItemId to ensure that they are present and nonNullable
paymentId: z.string(),
subscriptionId: z.string(),
subscriptionItemId: z.string(),
orgSeats: teamMetadataSchema.unwrap().shape.orgSeats,
});
/** Used to prevent double charges for the same team */
export const checkIfTeamPaymentRequired = async ({ teamId = -1 }) => {
const team = await prisma.team.findUniqueOrThrow({
where: { id: teamId },
select: { metadata: true },
});
const metadata = teamMetadataSchema.parse(team.metadata);
/** If there's no paymentId, we need to pay this team */
if (!metadata?.paymentId) return { url: null };
const checkoutSession = await stripe.checkout.sessions.retrieve(metadata.paymentId);
/** If there's a pending session but it isn't paid, we need to pay this team */
if (checkoutSession.payment_status !== "paid") return { url: null };
/** If the session is already paid we return the upgrade URL so team is updated. */
return { url: `${WEBAPP_URL}/api/teams/${teamId}/upgrade?session_id=${metadata.paymentId}` };
};
/**
* Used to generate a checkout session when trying to create a team
*/
export const generateTeamCheckoutSession = async ({
teamName,
teamSlug,
userId,
}: {
teamName: string;
teamSlug: string;
userId: number;
}) => {
const customer = await getStripeCustomerIdFromUserId(userId);
const session = await stripe.checkout.sessions.create({
customer,
mode: "subscription",
allow_promotion_codes: true,
success_url: `${WEBAPP_URL}/api/teams/create?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${WEBAPP_URL}/settings/my-account/profile`,
line_items: [
{
/** We only need to set the base price and we can upsell it directly on Stripe's checkout */
price: process.env.STRIPE_TEAM_MONTHLY_PRICE_ID,
/**Initially it will be just the team owner */
quantity: 1,
},
],
customer_update: {
address: "auto",
},
// Disabled when testing locally as usually developer doesn't setup Tax in Stripe Test mode
automatic_tax: {
enabled: IS_PRODUCTION,
},
subscription_data: {
trial_period_days: 14, // Add a 14-day trial
},
metadata: {
teamName,
teamSlug,
userId,
dubCustomerId: userId, // pass the userId during checkout creation for sales conversion tracking: https://d.to/conversions/stripe
},
});
return session;
};
/**
* @deprecated Move over to internal-team-billing
* Used to generate a checkout session when creating a new org (parent team) or backwards compatibility for old teams
*/
export const purchaseTeamOrOrgSubscription = async (input: {
teamId: number;
/**
* The actual number of seats in the team.
* The seats that we would charge for could be more than this depending on the MINIMUM_NUMBER_OF_ORG_SEATS in case of an organization
* For a team it would be the same as this value
*/
seatsUsed: number;
/**
* If provided, this is the exact number we would charge for.
*/
seatsToChargeFor?: number | null;
userId: number;
isOrg?: boolean;
pricePerSeat: number | null;
billingPeriod?: BillingPeriod;
}) => {
const {
teamId,
seatsToChargeFor,
seatsUsed,
userId,
isOrg,
pricePerSeat,
billingPeriod = BillingPeriod.MONTHLY,
} = input;
const { url } = await checkIfTeamPaymentRequired({ teamId });
if (url) return { url };
// For orgs, enforce minimum of MINIMUM_NUMBER_OF_ORG_SEATS seats if `seatsToChargeFor` not set
const seats = isOrg ? Math.max(seatsUsed, MINIMUM_NUMBER_OF_ORG_SEATS) : seatsUsed;
const quantity = seatsToChargeFor ? seatsToChargeFor : seats;
const customer = await getStripeCustomerIdFromUserId(userId);
const fixedPrice = await getFixedPrice();
let priceId: string | undefined;
if (pricePerSeat) {
if (
isOrg &&
pricePerSeat === ORGANIZATION_SELF_SERVE_PRICE &&
seats === ORGANIZATION_SELF_SERVE_MIN_SEATS
) {
priceId = fixedPrice as string;
} else {
const customPriceObj = await getPriceObject(fixedPrice);
priceId = await createPrice({
isOrg: !!isOrg,
teamId,
pricePerSeat,
billingPeriod,
product: customPriceObj.product as string, // We don't expand the object from stripe so just use the product as ID
currency: customPriceObj.currency,
});
}
} else {
priceId = fixedPrice as string;
}
const session = await stripe.checkout.sessions.create({
customer,
mode: "subscription",
allow_promotion_codes: true,
success_url: `${WEBAPP_URL}/api/teams/${teamId}/upgrade?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${WEBAPP_URL}/settings/my-account/profile`,
line_items: [
{
price: priceId,
quantity: quantity,
},
],
customer_update: {
address: "auto",
},
// Disabled when testing locally as usually developer doesn't setup Tax in Stripe Test mode
automatic_tax: {
enabled: IS_PRODUCTION,
},
metadata: {
teamId,
},
subscription_data: {
metadata: {
teamId,
dubCustomerId: userId,
},
},
});
return { url: session.url };
async function createPrice({
isOrg,
teamId,
pricePerSeat,
billingPeriod,
product,
currency,
}: {
isOrg: boolean;
teamId: number;
pricePerSeat: number;
billingPeriod: BillingPeriod;
product: Stripe.Product | string;
currency: string;
}) {
try {
const pricePerSeatInCents = pricePerSeat * 100;
// Price comes in monthly so we need to convert it to a monthly/yearly price
const occurrence = billingPeriod === "MONTHLY" ? 1 : 12;
const yearlyPrice = pricePerSeatInCents * occurrence;
const customPriceObj = await stripe.prices.create({
nickname: `Custom price for ${isOrg ? "Organization" : "Team"} ID: ${teamId}`,
unit_amount: yearlyPrice, // Stripe expects the amount in cents
// Use the same currency as in the fixed price to avoid hardcoding it.
currency: currency,
recurring: { interval: billingPeriod === "MONTHLY" ? "month" : "year" }, // Define your subscription interval
product: typeof product === "string" ? product : product.id,
tax_behavior: "exclusive",
});
return customPriceObj.id;
} catch (e) {
log.error(
`Error creating custom price for ${isOrg ? "Organization" : "Team"} ID: ${teamId}`,
safeStringify(e)
);
throw new Error("Error in creation of custom price");
}
}
/**
* Determines the priceId depending on if a custom price is required or not.
* If the organization has a custom price per seat, it will create a new price in stripe and return its ID.
*/
async function getFixedPrice() {
const fixedPriceId = isOrg
? process.env.STRIPE_ORG_MONTHLY_PRICE_ID
: process.env.STRIPE_TEAM_MONTHLY_PRICE_ID;
if (!fixedPriceId) {
throw new Error(
"You need to have STRIPE_ORG_MONTHLY_PRICE_ID and STRIPE_TEAM_MONTHLY_PRICE_ID env variables set"
);
}
log.debug("Getting price ID", safeStringify({ fixedPriceId, isOrg, teamId, pricePerSeat }));
return fixedPriceId;
}
};
async function getPriceObject(priceId: string) {
const priceObj = await stripe.prices.retrieve(priceId);
if (!priceObj) throw new Error(`No price found for ID ${priceId}`);
return priceObj;
}
export const getTeamWithPaymentMetadata = async (teamId: number) => {
const team = await prisma.team.findUniqueOrThrow({
where: { id: teamId },
select: { metadata: true, members: true, isOrganization: true },
});
const metadata = teamPaymentMetadataSchema.parse(team.metadata);
return { ...team, metadata };
};
export const updateQuantitySubscriptionFromStripe = async (teamId: number) => {
try {
const { url } = await checkIfTeamPaymentRequired({ teamId });
/**
* If there's no pending checkout URL it means that this team has not been paid.
* We cannot update the subscription yet, this will be handled on publish/checkout.
**/
if (!url) return;
const team = await getTeamWithPaymentMetadata(teamId);
const { subscriptionId, subscriptionItemId, orgSeats } = team.metadata;
// Either it would be custom pricing where minimum number of seats are changed(available in orgSeats) or it would be default MINIMUM_NUMBER_OF_ORG_SEATS
// We can't go below this quantity for subscription
const orgMinimumSubscriptionQuantity = orgSeats || MINIMUM_NUMBER_OF_ORG_SEATS;
const membershipCount = team.members.length;
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
const subscriptionQuantity = subscription.items.data.find(
(sub) => sub.id === subscriptionItemId
)?.quantity;
if (!subscriptionQuantity) throw new Error("Subscription not found");
if (team.isOrganization && membershipCount < orgMinimumSubscriptionQuantity) {
console.info(
`Org ${teamId} has less members than the min required ${orgMinimumSubscriptionQuantity}, skipping updating subscription.`
);
return;
}
await stripe.subscriptions.update(subscriptionId, {
items: [{ quantity: membershipCount, id: subscriptionItemId }],
});
console.info(
`Updated subscription ${subscriptionId} for team ${teamId} to ${team.members.length} seats.`
);
} catch (error) {
let message = "Unknown error on updateQuantitySubscriptionFromStripe";
if (error instanceof Error) message = error.message;
console.error(message);
}
};