import { Request, Response, NextFunction } from 'express'; import dokuService from '../services/dokuService'; import subscriptionRepository from '../repositories/subscriptionRepository'; import paymentRepository from '../repositories/paymentRepository'; import userRepository from '../repositories/userRepository'; import { PLANS, PAGINATION } from '../utils/constants'; import { LicensePlan } from '@prisma/client'; export class SubscriptionController { async getPlans(_req: Request, res: Response, next: NextFunction) { try { res.json({ success: true, data: Object.entries(PLANS).map(([key, value]) => ({ id: key, ...value, })), }); } catch (error) { next(error); } } async subscribe(req: Request, res: Response, next: NextFunction) { try { const { plan } = req.body; const user = await userRepository.findById(req.user!.userId); if (!user) { return res.status(404).json({ success: false, message: 'User not found' }); } const result = await dokuService.createCheckout( user.id, plan as LicensePlan, user.email, user.name ); res.json({ success: true, data: result }); } catch (error) { next(error); } } async webhook(req: Request, res: Response, next: NextFunction) { try { const result = await dokuService.handleNotification(req.body); res.json({ success: true, data: result }); } catch (error) { next(error); } } async checkStatus(req: Request, res: Response, next: NextFunction) { try { const { invoiceNumber } = req.params; const result = await dokuService.checkPaymentStatus(invoiceNumber); res.json({ success: true, data: result }); } catch (error) { next(error); } } async getMySubscriptions(req: Request, res: Response, next: NextFunction) { try { const subscriptions = await subscriptionRepository.findByUserId(req.user!.userId); res.json({ success: true, data: subscriptions }); } catch (error) { next(error); } } async getMyPayments(req: Request, res: Response, next: NextFunction) { try { const page = parseInt(req.query.page as string) || PAGINATION.defaultPage; const limit = Math.min( parseInt(req.query.limit as string) || PAGINATION.defaultLimit, PAGINATION.maxLimit ); const result = await paymentRepository.findByUserId(req.user!.userId, page, limit); res.json({ success: true, data: result }); } catch (error) { next(error); } } } export default new SubscriptionController();