feat: Clean up payment links endpoints

This commit is contained in:
Ahmed Bouhuolia
2024-09-25 19:37:09 +02:00
parent 323b95de7b
commit 1cc71eb368
14 changed files with 183 additions and 132 deletions

View File

@@ -1,13 +1,13 @@
import { Inject, Service } from 'typedi'; import { Inject, Service } from 'typedi';
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { body, param } from 'express-validator'; import { param } from 'express-validator';
import BaseController from '@/api/controllers/BaseController'; import BaseController from '@/api/controllers/BaseController';
import { GetInvoicePaymentLinkMetadata } from '@/services/Sales/Invoices/GetInvoicePaymentLinkMetadata'; import { PaymentLinksApplication } from '@/services/PaymentLinks/PaymentLinksApplication';
@Service() @Service()
export class PublicSharableLinkController extends BaseController { export class PublicSharableLinkController extends BaseController {
@Inject() @Inject()
private getSharableLinkMetaService: GetInvoicePaymentLinkMetadata; private paymentLinkApp: PaymentLinksApplication;
/** /**
* Router constructor. * Router constructor.
@@ -16,12 +16,18 @@ export class PublicSharableLinkController extends BaseController {
const router = Router(); const router = Router();
router.get( router.get(
'/sharable-links/meta/invoice/:linkId', '/:paymentLinkId/invoice',
[param('linkId').exists()], [param('paymentLinkId').exists()],
this.validationResult, this.validationResult,
this.getPaymentLinkPublicMeta.bind(this), this.getPaymentLinkPublicMeta.bind(this),
this.validationResult this.validationResult
); );
router.post(
'/:paymentLinkId/stripe_checkout_session',
[param('paymentLinkId').exists()],
this.validationResult,
this.createInvoicePaymentLinkCheckoutSession.bind(this)
);
return router; return router;
} }
@@ -33,19 +39,45 @@ export class PublicSharableLinkController extends BaseController {
* @returns * @returns
*/ */
public async getPaymentLinkPublicMeta( public async getPaymentLinkPublicMeta(
req: Request, req: Request<{ paymentLinkId: string }>,
res: Response, res: Response,
next: NextFunction next: NextFunction
) { ) {
const { linkId } = req.params; const { paymentLinkId } = req.params;
try { try {
const data = const data = await this.paymentLinkApp.getInvoicePaymentLink(
await this.getSharableLinkMetaService.getInvoicePaymentLinkMeta(linkId); paymentLinkId
);
return res.status(200).send({ data }); return res.status(200).send({ data });
} catch (error) { } catch (error) {
next(error); next(error);
} }
} }
/**
* Creates a Stripe checkout session for the given payment link id.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
public async createInvoicePaymentLinkCheckoutSession(
req: Request<{ paymentLinkId: string }>,
res: Response,
next: NextFunction
) {
const { paymentLinkId } = req.params;
try {
const session =
await this.paymentLinkApp.createInvoicePaymentCheckoutSession(
paymentLinkId
);
return res.status(200).send(session);
} catch (error) {
next(error);
}
}
} }

View File

@@ -27,10 +27,6 @@ export class StripeIntegrationController extends BaseController {
this.validationResult, this.validationResult,
asyncMiddleware(this.createAccountLink.bind(this)) asyncMiddleware(this.createAccountLink.bind(this))
); );
router.post(
'/:linkId/create_checkout_session',
this.createCheckoutSession.bind(this)
);
return router; return router;
} }
@@ -75,33 +71,6 @@ export class StripeIntegrationController extends BaseController {
} }
} }
/**
* Creates a Stripe checkout session for the given payment link id.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
public async createCheckoutSession(
req: Request<{ linkId: number }>,
res: Response,
next: NextFunction
) {
const { linkId } = req.params;
const { tenantId } = req;
try {
const session =
await this.stripePaymentApp.createSaleInvoiceCheckoutSession(
tenantId,
linkId
);
return res.status(200).send(session);
} catch (error) {
next(error);
}
}
/** /**
* Creates a new Stripe account. * Creates a new Stripe account.
* @param {Request} req - The Express request object. * @param {Request} req - The Express request object.

View File

@@ -87,7 +87,10 @@ export default () => {
app.use('/account', Container.get(Account).router()); app.use('/account', Container.get(Account).router());
app.use('/webhooks', Container.get(Webhooks).router()); app.use('/webhooks', Container.get(Webhooks).router());
app.use('/demo', Container.get(OneClickDemoController).router()); app.use('/demo', Container.get(OneClickDemoController).router());
app.use(Container.get(PublicSharableLinkController).router()); app.use(
'/payment-links',
Container.get(PublicSharableLinkController).router()
);
// - Dashboard routes. // - Dashboard routes.
// --------------------------- // ---------------------------

View File

@@ -50,7 +50,8 @@ export const injectI18nUtils = (req) => {
export const initalizeTenantServices = async (tenantId: number) => { export const initalizeTenantServices = async (tenantId: number) => {
const tenant = await Tenant.query() const tenant = await Tenant.query()
.findById(tenantId) .findById(tenantId)
.withGraphFetched('metadata'); .withGraphFetched('metadata')
.throwIfNotFound();
const tenantServices = Container.get(TenancyService); const tenantServices = Container.get(TenancyService);
const tenantsManager = Container.get(TenantsManagerService); const tenantsManager = Container.get(TenantsManagerService);

View File

@@ -34,9 +34,9 @@ export const PrepardExpenses = {
export const StripeClearingAccount = { export const StripeClearingAccount = {
name: 'Stripe Clearing', name: 'Stripe Clearing',
slug: 'stripe-clearing', slug: 'stripe-clearing',
account_type: 'other-current-liability', account_type: 'other-current-asset',
parent_account_id: null, parent_account_id: null,
code: '50006', code: '100020',
active: true, active: true,
index: 1, index: 1,
predefined: true, predefined: true,

View File

@@ -1,20 +1,21 @@
import config from '@/config'; import { Inject, Service } from 'typedi';
import { StripePaymentService } from './StripePaymentService'; import { StripePaymentService } from '../StripePayment/StripePaymentService';
import HasTenancyService from '../Tenancy/TenancyService'; import HasTenancyService from '../Tenancy/TenancyService';
import { ISaleInvoice } from '@/interfaces'; import { ISaleInvoice } from '@/interfaces';
import { Inject, Service } from 'typedi';
import { StripeInvoiceCheckoutSessionPOJO } from '@/interfaces/StripePayment'; import { StripeInvoiceCheckoutSessionPOJO } from '@/interfaces/StripePayment';
import { PaymentLink } from '@/system/models'; import { PaymentLink } from '@/system/models';
import { initializeTenantSettings } from '@/api/middleware/SettingsMiddleware';
import config from '@/config';
const origin = 'http://localhost'; const origin = 'http://localhost';
@Service() @Service()
export class CreateInvoiceCheckoutSession { export class CreateInvoiceCheckoutSession {
@Inject() @Inject()
private stripePaymentService: StripePaymentService; private tenancy: HasTenancyService;
@Inject() @Inject()
private tenancy: HasTenancyService; private stripePaymentService: StripePaymentService;
/** /**
* Creates a new Stripe checkout session from the given sale invoice. * Creates a new Stripe checkout session from the given sale invoice.
@@ -23,17 +24,18 @@ export class CreateInvoiceCheckoutSession {
* @returns {Promise<StripeInvoiceCheckoutSessionPOJO>} * @returns {Promise<StripeInvoiceCheckoutSessionPOJO>}
*/ */
async createInvoiceCheckoutSession( async createInvoiceCheckoutSession(
tenantId: number, publicPaymentLinkId: string
publicPaymentLinkId: number
): Promise<StripeInvoiceCheckoutSessionPOJO> { ): Promise<StripeInvoiceCheckoutSessionPOJO> {
const { SaleInvoice } = this.tenancy.models(tenantId);
// Retrieves the payment link from the given id. // Retrieves the payment link from the given id.
const paymentLink = await PaymentLink.query() const paymentLink = await PaymentLink.query()
.findOne('linkId', publicPaymentLinkId) .findOne('linkId', publicPaymentLinkId)
.where('resourceType', 'SaleInvoice') .where('resourceType', 'SaleInvoice')
.throwIfNotFound(); .throwIfNotFound();
const tenantId = paymentLink.tenantId;
await initializeTenantSettings(tenantId);
const { SaleInvoice } = this.tenancy.models(tenantId);
// Retrieves the invoice from associated payment link. // Retrieves the invoice from associated payment link.
const invoice = await SaleInvoice.query() const invoice = await SaleInvoice.query()
.findById(paymentLink.resourceId) .findById(paymentLink.resourceId)

View File

@@ -4,7 +4,7 @@ import { ServiceError } from '@/exceptions';
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable'; import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
import HasTenancyService from '@/services/Tenancy/TenancyService'; import HasTenancyService from '@/services/Tenancy/TenancyService';
import { PaymentLink } from '@/system/models'; import { PaymentLink } from '@/system/models';
import { GetInvoicePaymentLinkMetaTransformer } from './GetInvoicePaymentLinkTransformer'; import { GetInvoicePaymentLinkMetaTransformer } from '../Sales/Invoices/GetInvoicePaymentLinkTransformer';
import { initalizeTenantServices } from '@/api/middleware/TenantDependencyInjection'; import { initalizeTenantServices } from '@/api/middleware/TenantDependencyInjection';
@Service() @Service()

View File

@@ -0,0 +1,37 @@
import { Inject, Service } from 'typedi';
import { GetInvoicePaymentLinkMetadata } from './GetInvoicePaymentLinkMetadata';
import { CreateInvoiceCheckoutSession } from './CreateInvoiceCheckoutSession';
import { StripeInvoiceCheckoutSessionPOJO } from '@/interfaces/StripePayment';
@Service()
export class PaymentLinksApplication {
@Inject()
private getInvoicePaymentLinkMetadataService: GetInvoicePaymentLinkMetadata;
@Inject()
private createInvoiceCheckoutSessionService: CreateInvoiceCheckoutSession;
/**
* Retrieves the invoice payment link.
* @param {string} paymentLinkId
* @returns {}
*/
public getInvoicePaymentLink(paymentLinkId: string) {
return this.getInvoicePaymentLinkMetadataService.getInvoicePaymentLinkMeta(
paymentLinkId
);
}
/**
* Create the invoice payment checkout session from the given payment link id.
* @param {string} paymentLinkId - Payment link id.
* @returns {Promise<StripeInvoiceCheckoutSessionPOJO>}
*/
public createInvoicePaymentCheckoutSession(
paymentLinkId: string
): Promise<StripeInvoiceCheckoutSessionPOJO> {
return this.createInvoiceCheckoutSessionService.createInvoiceCheckoutSession(
paymentLinkId
);
}
}

View File

@@ -1,6 +1,9 @@
import { Inject, Service } from 'typedi'; import { Inject, Service } from 'typedi';
import { Knex } from 'knex';
import { GetSaleInvoice } from '../Sales/Invoices/GetSaleInvoice'; import { GetSaleInvoice } from '../Sales/Invoices/GetSaleInvoice';
import { CreatePaymentReceived } from '../Sales/PaymentReceived/CreatePaymentReceived'; import { CreatePaymentReceived } from '../Sales/PaymentReceived/CreatePaymentReceived';
import HasTenancyService from '../Tenancy/TenancyService';
import UnitOfWork from '../UnitOfWork';
@Service() @Service()
export class CreatePaymentReceiveStripePayment { export class CreatePaymentReceiveStripePayment {
@@ -10,6 +13,12 @@ export class CreatePaymentReceiveStripePayment {
@Inject() @Inject()
private createPaymentReceivedService: CreatePaymentReceived; private createPaymentReceivedService: CreatePaymentReceived;
@Inject()
private tenancy: HasTenancyService;
@Inject()
private uow: UnitOfWork;
/** /**
* *
* @param {number} tenantId * @param {number} tenantId
@@ -21,17 +30,35 @@ export class CreatePaymentReceiveStripePayment {
saleInvoiceId: number, saleInvoiceId: number,
paidAmount: number paidAmount: number
) { ) {
const invoice = await this.getSaleInvoiceService.getSaleInvoice( const { accountRepository } = this.tenancy.repositories(tenantId);
tenantId,
saleInvoiceId // Create a payment received transaction under UOW envirement.
); return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
await this.createPaymentReceivedService.createPaymentReceived(tenantId, { // Finds or creates a new stripe payment clearing account (current asset).
customerId: invoice.customerId, const stripeClearingAccount =
paymentDate: new Date(), accountRepository.findOrCreateStripeClearing({}, trx);
amount: paidAmount,
depositAccountId: 1002, // Retrieves the given invoice to create payment transaction associated to it.
statement: '', const invoice = await this.getSaleInvoiceService.getSaleInvoice(
entries: [{ invoiceId: saleInvoiceId, paymentAmount: paidAmount }], tenantId,
saleInvoiceId
);
// Create a payment received transaction associated to the given invoice.
await this.createPaymentReceivedService.createPaymentReceived(
tenantId,
{
customerId: invoice.customerId,
paymentDate: new Date(),
amount: paidAmount,
exchangeRate: 1,
referenceNo: '',
statement: '',
depositAccountId: stripeClearingAccount.id,
entries: [{ invoiceId: saleInvoiceId, paymentAmount: paidAmount }],
},
{},
trx
);
}); });
} }
} }

View File

@@ -1,6 +1,4 @@
import { Inject } from 'typedi'; import { Inject } from 'typedi';
import { CreateInvoiceCheckoutSession } from './CreateInvoiceCheckoutSession';
import { StripeInvoiceCheckoutSessionPOJO } from '@/interfaces/StripePayment';
import { CreateStripeAccountService } from './CreateStripeAccountService'; import { CreateStripeAccountService } from './CreateStripeAccountService';
import { CreateStripeAccountLinkService } from './CreateStripeAccountLink'; import { CreateStripeAccountLinkService } from './CreateStripeAccountLink';
import { CreateStripeAccountDTO } from './types'; import { CreateStripeAccountDTO } from './types';
@@ -14,9 +12,6 @@ export class StripePaymentApplication {
@Inject() @Inject()
private createStripeAccountLinkService: CreateStripeAccountLinkService; private createStripeAccountLinkService: CreateStripeAccountLinkService;
@Inject()
private createInvoiceCheckoutSessionService: CreateInvoiceCheckoutSession;
@Inject() @Inject()
private exchangeStripeOAuthTokenService: ExchangeStripeOAuthTokenService; private exchangeStripeOAuthTokenService: ExchangeStripeOAuthTokenService;
@@ -51,22 +46,6 @@ export class StripePaymentApplication {
); );
} }
/**
* Creates the Stripe checkout session from the given sale invoice.
* @param {number} tenantId
* @param {string} paymentLinkId
* @returns {Promise<StripeInvoiceCheckoutSessionPOJO>}
*/
public createSaleInvoiceCheckoutSession(
tenantId: number,
paymentLinkId: number
): Promise<StripeInvoiceCheckoutSessionPOJO> {
return this.createInvoiceCheckoutSessionService.createInvoiceCheckoutSession(
tenantId,
paymentLinkId
);
}
/** /**
* Retrieves Stripe OAuth2 connect link. * Retrieves Stripe OAuth2 connect link.
* @returns {string} * @returns {string}

View File

@@ -7,6 +7,7 @@ import {
} from '@/interfaces/StripePayment'; } from '@/interfaces/StripePayment';
import HasTenancyService from '@/services/Tenancy/TenancyService'; import HasTenancyService from '@/services/Tenancy/TenancyService';
import { Tenant } from '@/system/models'; import { Tenant } from '@/system/models';
import { initalizeTenantServices } from '@/api/middleware/TenantDependencyInjection';
@Service() @Service()
export class StripeWebhooksSubscriber { export class StripeWebhooksSubscriber {
@@ -41,6 +42,8 @@ export class StripeWebhooksSubscriber {
const tenantId = parseInt(metadata.tenantId, 10); const tenantId = parseInt(metadata.tenantId, 10);
const saleInvoiceId = parseInt(metadata.saleInvoiceId, 10); const saleInvoiceId = parseInt(metadata.saleInvoiceId, 10);
await initalizeTenantServices(tenantId);
// Get the amount from the event // Get the amount from the event
const amount = event.data.object.amount_total; const amount = event.data.object.amount_total;

View File

@@ -3,7 +3,7 @@ import clsx from 'classnames';
import { AppToaster, Box, Group, Stack } from '@/components'; import { AppToaster, Box, Group, Stack } from '@/components';
import { usePaymentPortalBoot } from './PaymentPortalBoot'; import { usePaymentPortalBoot } from './PaymentPortalBoot';
import { useDrawerActions } from '@/hooks/state'; import { useDrawerActions } from '@/hooks/state';
import { useCreateStripeCheckoutSession } from '@/hooks/query/stripe-integration'; import { useCreateStripeCheckoutSession } from '@/hooks/query/payment-link';
import { DRAWERS } from '@/constants/drawers'; import { DRAWERS } from '@/constants/drawers';
import styles from './PaymentPortal.module.scss'; import styles from './PaymentPortal.module.scss';

View File

@@ -10,6 +10,8 @@ import {
import useApiRequest from '../useRequest'; import useApiRequest from '../useRequest';
import { transformToCamelCase, transfromToSnakeCase } from '@/utils'; import { transformToCamelCase, transfromToSnakeCase } from '@/utils';
const GetPaymentLinkInvoice = 'GetPaymentLinkInvoice';
// Create Payment Link // Create Payment Link
// ------------------------------------ // ------------------------------------
interface CreatePaymentLinkValues { interface CreatePaymentLinkValues {
@@ -101,13 +103,49 @@ export function useGetInvoicePaymentLink(
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useQuery<GetInvoicePaymentLinkResponse, Error>( return useQuery<GetInvoicePaymentLinkResponse, Error>(
['sharable-link-meta', linkId], [GetPaymentLinkInvoice, linkId],
() => () =>
apiRequest apiRequest
.get(`/sharable-links/meta/invoice/${linkId}`) .get(`/payment-links/${linkId}/invoice`)
.then((res) => transformToCamelCase(res.data?.data)), .then((res) => transformToCamelCase(res.data?.data)),
{ {
...options, ...options,
}, },
); );
} }
// Create Stripe Checkout Session.
// ------------------------------------
interface CreateCheckoutSessionValues {
linkId: string;
}
interface CreateCheckoutSessionResponse {
sessionId: string;
publishableKey: string;
redirectTo: string;
}
export const useCreateStripeCheckoutSession = (
options?: UseMutationOptions<
CreateCheckoutSessionResponse,
Error,
CreateCheckoutSessionValues
>,
): UseMutationResult<
CreateCheckoutSessionResponse,
Error,
CreateCheckoutSessionValues
> => {
const apiRequest = useApiRequest();
return useMutation(
(values: CreateCheckoutSessionValues) => {
return apiRequest
.post(`/payment-links/${values.linkId}/stripe_checkout_session`, values)
.then(
(res) =>
transformToCamelCase(res.data) as CreateCheckoutSessionResponse,
);
},
{ ...options },
);
};

View File

@@ -107,46 +107,6 @@ export const useCreateStripeAccount = (
); );
}; };
// Create Stripe Checkout Session.
// ------------------------------------
interface CreateCheckoutSessionValues {
linkId: string;
}
interface CreateCheckoutSessionResponse {
sessionId: string;
publishableKey: string;
redirectTo: string;
}
export const useCreateStripeCheckoutSession = (
options?: UseMutationOptions<
CreateCheckoutSessionResponse,
Error,
CreateCheckoutSessionValues
>,
): UseMutationResult<
CreateCheckoutSessionResponse,
Error,
CreateCheckoutSessionValues
> => {
const apiRequest = useApiRequest();
return useMutation(
(values: CreateCheckoutSessionValues) => {
return apiRequest
.post(
`/stripe_integration/${values.linkId}/create_checkout_session`,
values,
)
.then(
(res) =>
transformToCamelCase(res.data) as CreateCheckoutSessionResponse,
);
},
{ ...options },
);
};
// Create Stripe Account OAuth Link. // Create Stripe Account OAuth Link.
// ------------------------------------ // ------------------------------------