69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
import { Body, Controller, Logger, Post, Req } from '@nestjs/common';
|
|
import { PurchaseService } from '../service/purchase.service';
|
|
import { UserService } from '../service/user.service';
|
|
import { PurchaseItem } from '../dto/purchase-item';
|
|
import { StripeService } from '../service/stripe.service';
|
|
import { PurchaseStatus } from 'src/dto/purchase-status';
|
|
import { TokenService } from 'src/service/token.service';
|
|
|
|
@Controller('/buy')
|
|
export class BuyController {
|
|
private static PURCHASE_STATUS_TO_REEVALUATE = [
|
|
PurchaseStatus.CREATED,
|
|
PurchaseStatus.IN_PROGRESS,
|
|
];
|
|
private readonly logger = new Logger(BuyController.name);
|
|
|
|
constructor(
|
|
private readonly purchaseService: PurchaseService,
|
|
private readonly userService: UserService,
|
|
private readonly tokenService: TokenService,
|
|
private readonly stripeService: StripeService,
|
|
) {}
|
|
|
|
@Post('/start')
|
|
public async startPurchaseFlow(
|
|
@Req() request,
|
|
@Body('quantity') quantity: number,
|
|
) {
|
|
const userId = request.userId;
|
|
const user = await this.userService.getUserById(userId);
|
|
const purchase = await this.purchaseService.createPurchase(
|
|
user,
|
|
PurchaseItem.PAELLA,
|
|
quantity,
|
|
);
|
|
const { sessionId, sessionUrl } =
|
|
await this.stripeService.createStripeSession(purchase);
|
|
purchase.stripeSessionId = sessionId;
|
|
this.purchaseService.recordPurchase(purchase);
|
|
this.logger.debug(`Redirecting to ${sessionUrl}`);
|
|
return { url: sessionUrl };
|
|
}
|
|
|
|
@Post('/complete')
|
|
public async complete(@Req() request) {
|
|
const userId = request.userId;
|
|
const user = await this.userService.getUserById(userId);
|
|
const purchases = await this.purchaseService.getPurchasesForUser(user);
|
|
purchases
|
|
.filter((purchase) =>
|
|
BuyController.PURCHASE_STATUS_TO_REEVALUATE.includes(purchase.status),
|
|
)
|
|
.forEach(async (purchase) => {
|
|
const { isPaid } = await this.stripeService.getStripeSessionFromId(
|
|
purchase.stripeSessionId!,
|
|
);
|
|
purchase.status = isPaid
|
|
? PurchaseStatus.COMPLETED
|
|
: PurchaseStatus.IN_PROGRESS;
|
|
this.purchaseService.recordPurchase(purchase);
|
|
if (purchase.status === PurchaseStatus.COMPLETED) {
|
|
this.tokenService.addTokens(user, purchase);
|
|
}
|
|
});
|
|
|
|
return { url: '/signup' };
|
|
}
|
|
}
|