Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 6 additions & 7 deletions src/controller/checkout.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { signUserToken } from '../utils/signUserToken';
import { verifyRecaptcha } from '../utils/verifyRecaptcha';
import { setupAuth } from '../plugins/auth';
import { stripePaymentsAdapter } from '../infrastructure/adapters/stripe.adapter';
import { UserType } from '../core/users/User';

export function checkoutController(usersService: UsersService, paymentsService: PaymentService) {
return async function (fastify: FastifyInstance) {
Expand Down Expand Up @@ -190,9 +189,9 @@ export function checkoutController(usersService: UsersService, paymentsService:
throw new ForbiddenError();
}

const price = await paymentsService.getPriceById(priceId);
const price = await stripePaymentsAdapter.getPriceById(priceId);

if (price.type === UserType.Business) throw new BadRequestError('Business plan is no longer available');
if (price.isBusinessPlan()) throw new BadRequestError('Business plan is no longer available');

const subscriptionAttempt = await paymentsService.createSubscription({
customerId,
Expand Down Expand Up @@ -286,7 +285,7 @@ export function checkoutController(usersService: UsersService, paymentsService:
throw new ForbiddenError();
}

const price = await paymentsService.getPriceById(priceId);
const price = await stripePaymentsAdapter.getPriceById(priceId);

if (price.interval !== 'lifetime') {
throw new BadRequestError('Only lifetime plans are supported');
Expand Down Expand Up @@ -362,12 +361,12 @@ export function checkoutController(usersService: UsersService, paymentsService:
const userUuid = req.user?.payload?.uuid;
const user = await usersService.findUserByUuid(userUuid).catch(() => null);

const price = await paymentsService.getPriceById(priceId, currency);
const price = await stripePaymentsAdapter.getPriceById(priceId, currency);

let amount = price.amount;

if (promoCodeName) {
const couponCode = await paymentsService.getPromoCodeByName(price.product, promoCodeName);
const couponCode = await paymentsService.getPromoCodeByName(price.productId, promoCodeName);
if (couponCode.amountOff) {
amount = Math.max(0, price.amount - couponCode.amountOff);
} else if (couponCode.percentOff) {
Expand All @@ -393,7 +392,7 @@ export function checkoutController(usersService: UsersService, paymentsService:
const amountTotal = taxForPrice?.amount_total ?? price.amount;

return res.status(200).send({
price,
price: price.toJSON(),
taxes: {
tax: taxAmount,
decimalTax: taxAmount / 100,
Expand Down
14 changes: 12 additions & 2 deletions src/controller/payments.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,15 +425,25 @@ export function paymentsController(
},
async (req, rep) => {
const { currency } = req.query;
const userType = (req.query.userType as UserType) || UserType.Individual;

const { currencyValue, isError, errorMessage } = checkCurrency(currency);

if (isError) {
return rep.status(400).send({ message: errorMessage });
}

return paymentService.getPrices(currencyValue, userType);
const prices = await stripePaymentsAdapter.getPrices(currencyValue);

const mappedPrices = prices.map((price) => ({
id: price.id,
productId: price.productId,
currency: price.currency,
amount: price.amount,
bytes: price.bytes,
interval: price?.interval,
}));

return mappedPrices;
},
);

Expand Down
41 changes: 22 additions & 19 deletions src/infrastructure/adapters/stripe.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,28 +56,31 @@ export class StripePaymentsAdapter implements PaymentsAdapter {

async getPrices(currency: string = 'eur'): Promise<Price[]> {
const prices = await this.provider.prices.search({
query: `metadata["show"]:"1" active:"true" currency:"${currency}"`,
query: `metadata["show"]:"1" active:"true" currency:"eur"`,
expand: ['data.currency_options', 'data.product'],
limit: 100,
});

return prices.data.map((price) => {
const businessSeats = this.getBusinessSeats(price);

return Price.toDomain({
id: price.id,
productId: (price.product as Stripe.Product).id,
bytes: Number.parseInt(price.metadata.bytes),
interval: this.getInterval(price.recurring!.interval),
commitmentPlan: this.hasAnnualCommitment(price),
recurring: price.type === 'recurring',
amount: price.currency_options![currency].unit_amount as number,
currency: price.currency,
decimalAmount: (price.currency_options![currency].unit_amount as number) / 100,
type: price.metadata.type === 'business' ? UserType.Business : UserType.Individual,
...businessSeats,
return prices.data
.filter((price) => price.metadata.maxSpaceBytes && price.currency_options)
.map((price) => {
const businessSeats = this.getBusinessSeats(price);
const currencyOptions = price.currency_options![currency] ?? price.currency_options!['eur'];

return Price.toDomain({
id: price.id,
productId: (price.product as Stripe.Product).id,
bytes: Number.parseInt(price.metadata.maxSpaceBytes),
interval: this.getInterval(price.recurring?.interval),
commitmentPlan: this.hasAnnualCommitment(price),
recurring: price.type === 'recurring',
amount: currencyOptions.unit_amount as number,
currency,
decimalAmount: (currencyOptions.unit_amount as number) / 100,
type: price.metadata.type === 'business' ? UserType.Business : UserType.Individual,
...businessSeats,
});
});
});
}

async getPriceById(priceId: Price['id'], currency: string = 'eur'): Promise<Price> {
Expand All @@ -92,12 +95,12 @@ export class StripePaymentsAdapter implements PaymentsAdapter {
return Price.toDomain({
id: price.id,
productId: (price.product as Stripe.Product).id,
bytes: Number.parseInt(price.metadata.bytes),
bytes: Number.parseInt(price.metadata.maxSpaceBytes),
interval: this.getInterval(price.recurring?.interval),
commitmentPlan: this.hasAnnualCommitment(price),
recurring: price.type === 'recurring',
amount: price.currency_options![currency].unit_amount as number,
currency: price.currency,
currency,
decimalAmount: (price.currency_options![currency].unit_amount as number) / 100,
type: isBusinessPlan ? UserType.Business : UserType.Individual,
...businessSeats,
Expand Down
25 changes: 23 additions & 2 deletions src/infrastructure/domain/entities/price.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ export class Price implements PriceAttributes {
this.decimalAmount = attributes.decimalAmount;
this.recurring = attributes.recurring;
this.type = attributes.type;
this.minimumSeats = attributes.minimumSeats;
this.maximumSeats = attributes.maximumSeats;
this.buildBusinessSeats(attributes.minimumSeats, attributes.maximumSeats);
}

static toDomain(attributes: PriceAttributes): Price {
Expand All @@ -61,4 +60,26 @@ export class Price implements PriceAttributes {
public isRecurring(): boolean {
return this.recurring;
}

public toJSON(): PriceAttributes {
return {
id: this.id,
productId: this.productId,
bytes: this.bytes,
interval: this.interval,
commitmentPlan: this.commitmentPlan,
recurring: this.recurring,
amount: this.amount,
currency: this.currency,
decimalAmount: this.decimalAmount,
type: this.type,
...(this.minimumSeats !== undefined && { minimumSeats: this.minimumSeats }),
...(this.maximumSeats !== undefined && { maximumSeats: this.maximumSeats }),
};
}

private buildBusinessSeats(minimumSeats?: number, maximumSeats?: number) {
if (minimumSeats !== undefined) this.minimumSeats = minimumSeats;
if (maximumSeats !== undefined) this.maximumSeats = maximumSeats;
}
}
106 changes: 3 additions & 103 deletions src/services/payment.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import Stripe from 'stripe';
import dayjs from 'dayjs';

import { DisplayPrice } from '../core/users/DisplayPrice';
import { ProductsRepository } from '../core/users/ProductsRepository';
import { UserSubscription, UserType } from '../core/users/User';
import { Bit2MeService } from './bit2me.service';
Expand Down Expand Up @@ -35,7 +34,7 @@ import {
CustomerSource,
Customer as StripeCustomer,
} from '../types/stripe';
import { PaymentIntent, PromotionCode, PriceByIdResponse } from '../types/payment';
import { PaymentIntent, PromotionCode } from '../types/payment';
import { RenewalPeriod, PlanSubscription, SubscriptionCreated } from '../types/subscription';
import { stripePaymentsAdapter } from '../infrastructure/adapters/stripe.adapter';

Expand Down Expand Up @@ -190,10 +189,6 @@ export class PaymentService {
}
}

async getPrice(priceId: string): Promise<Stripe.Price> {
return this.provider.prices.retrieve(priceId);
}

/**
* Creates an invoice to purchase a one time plan.
*
Expand Down Expand Up @@ -261,8 +256,8 @@ export class PaymentService {
throw new BadRequestError('Invoice item does not have a price.');
}

const price = await this.getPrice(invoiceItem.pricing?.price_details?.price);
const isLifetime = price.type === 'one_time';
const price = await stripePaymentsAdapter.getPriceById(invoiceItem.pricing?.price_details?.price);
const isLifetime = price.interval === 'lifetime';

if (isLifetime && isCryptoCurrency(currency)) {
const normalizedCurrencyForBit2Me = normalizeForBit2Me(currency);
Expand Down Expand Up @@ -903,101 +898,6 @@ export class PaymentService {
};
}

async getPrices(currency?: string, userType: UserType = UserType.Individual): Promise<DisplayPrice[]> {
const currencyValue = currency ?? 'eur';

const res = await this.provider.prices.search({
query: `metadata["show"]:"1" active:"true" currency:"${currencyValue}"`,
expand: ['data.currency_options', 'data.product'],
limit: 100,
});

return res.data
.filter((price) => {
const priceProductType = ((price.product as Stripe.Product).metadata.type as UserType) || UserType.Individual;
return (
price.metadata.maxSpaceBytes &&
price.currency_options &&
price.currency_options[currencyValue].unit_amount &&
priceProductType === userType
);
})
.map((price) => {
const hasAnnualCommitment = this.hasAnnualCommitment(price);
const recurringInterval = hasAnnualCommitment ? 'year' : (price.recurring?.interval as 'year' | 'month');

return {
id: price.id,
productId: (price.product as Stripe.Product).id,
currency: currencyValue,
amount: price.currency_options![currencyValue].unit_amount as number,
bytes: parseInt(price.metadata.maxSpaceBytes),
interval: price.type === 'one_time' ? 'lifetime' : recurringInterval,
};
});
}

async getPricesRaw(currency?: string, expandProduct = false): Promise<Stripe.Price[]> {
const currencyValue = currency ?? 'eur';

const expandOptions = ['data.currency_options'];

if (expandProduct) {
expandOptions.push('data.product');
}

//!TODO: add metadata["show"]:"1" in query param
const res = await this.provider.prices.search({
query: `active:"true" currency:"${currencyValue}"`,
expand: expandOptions,
limit: 100,
});

return res.data.filter(
(price) =>
price.metadata.maxSpaceBytes && price.currency_options && price.currency_options[currencyValue].unit_amount,
);
}

/**
* Returns the requested price if exists
* @param priceId - The id of the requested price
* @param currency - The currency of the requested price
* @returns - The selected price if it exists and it is active
*/
async getPriceById(priceId: string, currency = 'eur'): Promise<PriceByIdResponse> {
const availablePrices = await this.getPricesRaw(currency);

const selectedPrice = availablePrices.find((price) => price.id === priceId && price.active);

if (!selectedPrice) {
throw new NotFoundError('The requested price does not exist');
}

let businessSeats;
const { currency_options, recurring, metadata, type, product } = selectedPrice;
const isBusinessPrice = metadata?.type === 'business';

if (isBusinessPrice) {
businessSeats = {
minimumSeats: Number(metadata.minimumSeats),
maximumSeats: Number(metadata.maximumSeats),
};
}

return {
id: priceId,
currency,
amount: currency_options![currency].unit_amount as number,
bytes: Number.parseInt(metadata?.maxSpaceBytes),
interval: type === 'one_time' ? 'lifetime' : recurring?.interval,
decimalAmount: (currency_options![currency].unit_amount as number) / 100,
type: isBusinessPrice ? UserType.Business : UserType.Individual,
product: product as string,
...businessSeats,
};
}

/**
* Returns the tax for a given price
* @param priceId - The Id of the price that we want to calculate the tax for
Expand Down
Loading
Loading