lecoffre-back/src/app/api/admin/StripeController.ts
2024-04-19 15:11:21 +02:00

98 lines
2.9 KiB
TypeScript

import authHandler from "@App/middlewares/AuthHandler";
import ruleHandler from "@App/middlewares/RulesHandler";
// import roleHandler from "@App/middlewares/RolesHandler";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Controller, Get, Post} from "@ControllerPattern/index";
import StripeService from "@Services/common/StripeService/StripeService";
import { validateOrReject } from "class-validator";
import { Request, Response } from "express";
import { Subscription } from "le-coffre-resources/dist/Admin";
import { Service } from "typedi";
@Controller()
@Service()
export default class StripeController extends ApiController {
constructor(private stripeService: StripeService) {
super();
}
/**
* @description Create a new checkout session
*/
@Post("/api/v1/admin/stripe", [authHandler, ruleHandler])
protected async createStripeSubscriptionCheckout(req: Request, response: Response) {
try {
const officeId: string = req.body.user.office_Id;
//add office id to request body
req.body.office = { uid: officeId };
//init Subscription resource with request body values
const subscriptionEntity = Subscription.hydrate<Subscription>(req.body, { strategy: "excludeAll" });
await validateOrReject(subscriptionEntity, { groups: ["createSubscription"], forbidUnknownValues: false });
const stripeSession = await this.stripeService.createCheckoutSession(subscriptionEntity);
this.httpCreated(response, stripeSession);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
@Get("/api/v1/admin/stripe/:uid")
protected async getStripeSubscriptionByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "No uid provided");
return;
}
const stripe_subscription = await this.stripeService.getStripeSubscriptionByUid(uid);
this.httpSuccess(response, stripe_subscription);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
@Get("/api/v1/admin/stripe/:uid/client-portal", [authHandler, ruleHandler])
protected async getClientPortalSession(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "No uid provided");
return;
}
const client_portal = await this.stripeService.createClientPortalSession(uid);
this.httpSuccess(response, client_portal);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
@Get("/api/v1/admin/stripe/:uid/customer")
protected async getCustomerBySubscription(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "No uid provided");
return;
}
const customer = await this.stripeService.getCustomerBySubscription(uid);
this.httpSuccess(response, customer);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
}