Files
maps-saas/apps/api/dist/billing/billing.service.js
T

131 lines
6.4 KiB
JavaScript

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var BillingService_1;
var _a, _b, _c, _d;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BillingService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const subscription_entity_1 = require("./entities/subscription.entity");
const transaction_entity_1 = require("./entities/transaction.entity");
const tenant_entity_1 = require("../auth/entities/tenant.entity");
const mail_service_1 = require("../common/mail.service");
let BillingService = BillingService_1 = class BillingService {
subscriptionRepository;
transactionRepository;
tenantRepository;
configService;
mailService;
logger = new common_1.Logger(BillingService_1.name);
constructor(subscriptionRepository, transactionRepository, tenantRepository, configService, mailService) {
this.subscriptionRepository = subscriptionRepository;
this.transactionRepository = transactionRepository;
this.tenantRepository = tenantRepository;
this.configService = configService;
this.mailService = mailService;
}
getIframeId() {
return this.configService.get('PAYMOB_IFRAME_ID', '837992');
}
async getSubscription(tenantId) {
let sub = await this.subscriptionRepository.findOne({ where: { tenantId } });
if (!sub) {
sub = await this.subscriptionRepository.save({
tenantId,
plan: 'FREE',
monthlyRequestLimit: 5000,
status: subscription_entity_1.SubscriptionStatus.ACTIVE,
});
}
return sub;
}
async processSuccessfulPayment(externalTxId, provider, amount, metadata) {
let txn = await this.transactionRepository.findOne({ where: { externalTransactionId: externalTxId } });
if (txn && txn.status === transaction_entity_1.PaymentStatus.SUCCESS) {
this.logger.warn(`Transaction ${externalTxId} already processed.`);
return;
}
if (!txn) {
const tenantId = metadata.tenantId;
if (!tenantId)
throw new common_1.BadRequestException('No tenantId found in payment metadata');
txn = await this.transactionRepository.save({
tenantId,
externalTransactionId: externalTxId,
amount,
provider,
status: transaction_entity_1.PaymentStatus.SUCCESS,
metadata,
});
}
else {
txn.status = transaction_entity_1.PaymentStatus.SUCCESS;
txn.metadata = { ...txn.metadata, ...metadata };
await this.transactionRepository.save(txn);
}
const tenantId = txn.tenantId;
const plan = metadata.plan || 'PRO';
await this.upgradeTenantPlan(tenantId, plan);
try {
const tenant = await this.tenantRepository.findOne({ where: { id: tenantId } });
if (tenant && tenant.email) {
await this.mailService.sendInvoiceEmail(tenant.email, {
tenantName: tenant.name,
plan: plan,
amount: `${amount} EGP`,
transactionId: externalTxId,
});
}
}
catch (err) {
this.logger.error(`Failed to send invoice email for tx ${externalTxId}: ${err.message}`);
}
this.logger.log(`✅ Tenant ${tenantId} upgraded to ${plan} after payment ${externalTxId}`);
}
async upgradeTenantPlan(tenantId, plan) {
await this.tenantRepository.update(tenantId, { plan });
const limits = {
[tenant_entity_1.TenantPlan.FREE]: 5000,
[tenant_entity_1.TenantPlan.STARTER]: 25000,
[tenant_entity_1.TenantPlan.PRO]: 100000,
[tenant_entity_1.TenantPlan.ENTERPRISE]: 500000,
};
const sub = await this.getSubscription(tenantId);
sub.plan = plan;
sub.monthlyRequestLimit = limits[plan] || 8000;
sub.status = subscription_entity_1.SubscriptionStatus.ACTIVE;
sub.currentPeriodStart = new Date();
const nextMonth = new Date();
nextMonth.setMonth(nextMonth.getMonth() + 1);
sub.currentPeriodEnd = nextMonth;
await this.subscriptionRepository.save(sub);
}
async getTransactionHistory(tenantId) {
return this.transactionRepository.find({
where: { tenantId },
order: { createdAt: 'DESC' },
});
}
};
exports.BillingService = BillingService;
exports.BillingService = BillingService = BillingService_1 = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, typeorm_1.InjectRepository)(subscription_entity_1.Subscription)),
__param(1, (0, typeorm_1.InjectRepository)(transaction_entity_1.Transaction)),
__param(2, (0, typeorm_1.InjectRepository)(tenant_entity_1.Tenant)),
__metadata("design:paramtypes", [typeof (_a = typeof typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _a : Object, typeof (_b = typeof typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _b : Object, typeof (_c = typeof typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _c : Object, typeof (_d = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _d : Object, mail_service_1.MailService])
], BillingService);
//# sourceMappingURL=billing.service.js.map