feat: implement billing, usage tracking, and administrative geocoding features in API with infrastructure updates
This commit is contained in:
+36
@@ -0,0 +1,36 @@
|
||||
import { BillingService } from './billing.service';
|
||||
import { PayMobProvider } from './providers/paymob.provider';
|
||||
import { BinanceProvider } from './providers/binance.provider';
|
||||
import { PaymentProvider } from './entities/transaction.entity';
|
||||
export declare class BillingController {
|
||||
private billingService;
|
||||
private paymobProvider;
|
||||
private binanceProvider;
|
||||
private readonly logger;
|
||||
constructor(billingService: BillingService, paymobProvider: PayMobProvider, binanceProvider: BinanceProvider);
|
||||
getSubscription(req: any): Promise<import("./entities/subscription.entity").Subscription>;
|
||||
checkout(req: any, body: {
|
||||
plan: string;
|
||||
provider: PaymentProvider;
|
||||
}): Promise<{
|
||||
checkoutUrl: any;
|
||||
orderId: string;
|
||||
prepayId: any;
|
||||
} | {
|
||||
checkoutUrl: string;
|
||||
orderId: string;
|
||||
}>;
|
||||
handlePaymobCallback(query: any, req: any): Promise<string>;
|
||||
handlePaymobWebhook(body: any, hmac: string): Promise<{
|
||||
status: string;
|
||||
message: string;
|
||||
} | {
|
||||
status: string;
|
||||
message?: undefined;
|
||||
}>;
|
||||
handleBinanceWebhook(body: any, req: any): Promise<{
|
||||
returnCode: string;
|
||||
returnMessage: any;
|
||||
}>;
|
||||
getInvoices(req: any): Promise<import("./entities/transaction.entity").Transaction[]>;
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
"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 BillingController_1;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BillingController = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const billing_service_1 = require("./billing.service");
|
||||
const paymob_provider_1 = require("./providers/paymob.provider");
|
||||
const binance_provider_1 = require("./providers/binance.provider");
|
||||
const firebase_auth_guard_1 = require("../auth/guards/firebase-auth.guard");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const transaction_entity_1 = require("./entities/transaction.entity");
|
||||
let BillingController = BillingController_1 = class BillingController {
|
||||
billingService;
|
||||
paymobProvider;
|
||||
binanceProvider;
|
||||
logger = new common_1.Logger(BillingController_1.name);
|
||||
constructor(billingService, paymobProvider, binanceProvider) {
|
||||
this.billingService = billingService;
|
||||
this.paymobProvider = paymobProvider;
|
||||
this.binanceProvider = binanceProvider;
|
||||
}
|
||||
async getSubscription(req) {
|
||||
return this.billingService.getSubscription(req.tenant.id);
|
||||
}
|
||||
async checkout(req, body) {
|
||||
const tenantId = req.tenant.id;
|
||||
const plan = body.plan;
|
||||
const pricing = {
|
||||
'STARTER': 29,
|
||||
'PRO': 89,
|
||||
};
|
||||
const amount = pricing[plan] || 0;
|
||||
if (amount === 0 && plan !== 'FREE') {
|
||||
throw new common_1.BadRequestException('Invalid plan or price not configured');
|
||||
}
|
||||
if (body.provider === transaction_entity_1.PaymentProvider.PAYMOB) {
|
||||
const { paymentKey, orderId } = await this.paymobProvider.createPaymentKey(tenantId, amount, plan);
|
||||
const iframeId = this.billingService.getIframeId();
|
||||
const checkoutUrl = `https://accept.paymob.com/api/acceptance/iframes/${iframeId}?payment_token=${paymentKey}`;
|
||||
return { checkoutUrl, orderId };
|
||||
}
|
||||
if (body.provider === transaction_entity_1.PaymentProvider.BINANCE) {
|
||||
return this.binanceProvider.createOrder(tenantId, amount, plan);
|
||||
}
|
||||
throw new common_1.BadRequestException('Invalid payment provider');
|
||||
}
|
||||
async handlePaymobCallback(query, req) {
|
||||
this.logger.log(`🔄 PayMob Redirect Callback: ID ${query.id}, Success: ${query.success}`);
|
||||
if (query.success === 'true' && query.id) {
|
||||
try {
|
||||
const txDetails = await this.paymobProvider.getTransactionDetails(query.id);
|
||||
if (txDetails && txDetails.success === true) {
|
||||
const extraDesc = txDetails.order?.shipping_data?.extra_description || "";
|
||||
const [tenantId, plan] = extraDesc.split('|');
|
||||
if (tenantId) {
|
||||
await this.billingService.processSuccessfulPayment(query.id.toString(), transaction_entity_1.PaymentProvider.PAYMOB, txDetails.amount_cents / 100, { tenantId, plan: plan || 'PRO' });
|
||||
this.logger.log(`🚀 Immediate Activation triggered via Callback for Tenant ${tenantId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
this.logger.error(`Failed during immediate activation fallback: ${e.message}`);
|
||||
}
|
||||
}
|
||||
const targetUrl = `https://map-dashboard.intaleqapp.com/dashboard.html#billing?payment_status=${query.success === 'true' ? 'success' : 'failed'}&id=${query.id}`;
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html lang="ar" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Intaleq Maps | تمت العملية بنجاح</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;900&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body { font-family: 'Cairo', sans-serif; background: #050505; color: white; overflow: hidden; }
|
||||
.pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .7; transform: scale(0.95); } }
|
||||
</style>
|
||||
</head>
|
||||
<body class="flex items-center justify-center h-screen">
|
||||
<div class="text-center space-y-8 max-w-md p-10 bg-white shadow-2xl rounded-[3rem] border border-white/10 relative overflow-hidden">
|
||||
<!-- Animated Background Glow -->
|
||||
<div class="absolute -top-20 -left-20 w-40 h-40 bg-blue-600/20 blur-[80px] rounded-full"></div>
|
||||
<div class="absolute -bottom-20 -right-20 w-40 h-40 bg-emerald-600/20 blur-[80px] rounded-full"></div>
|
||||
|
||||
<div class="relative z-10">
|
||||
<div class="w-24 h-24 bg-emerald-500 rounded-full mx-auto flex items-center justify-center shadow-[0_0_50px_rgba(16,185,129,0.4)] pulse mb-8">
|
||||
<svg class="w-12 h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<h1 class="text-3xl font-black text-slate-900 mb-4">شكراً لك، حمزة!</h1>
|
||||
<p class="text-slate-500 font-bold mb-8">تم تفعيل خطة <span class="text-blue-600">PRO</span> بنجاح. يتم الآن توجيهك إلى لوحة التحكم...</p>
|
||||
|
||||
<div class="flex items-center justify-center gap-2">
|
||||
<div class="w-2 h-2 bg-blue-600 rounded-full animate-bounce"></div>
|
||||
<div class="w-2 h-2 bg-blue-600 rounded-full animate-bounce [animation-delay:-0.15s]"></div>
|
||||
<div class="w-2 h-2 bg-blue-600 rounded-full animate-bounce [animation-delay:-0.3s]"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
setTimeout(() => {
|
||||
window.location.href = "${targetUrl}";
|
||||
}, 2500);
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
async handlePaymobWebhook(body, hmac) {
|
||||
this.logger.log(`📥 PayMob Webhook Received: Transaction ID ${body.obj?.id}`);
|
||||
if (!this.paymobProvider.verifyHmac(body.obj, hmac)) {
|
||||
this.logger.error('❌ PayMob HMAC Verification Failed');
|
||||
throw new common_1.BadRequestException('Invalid signature');
|
||||
}
|
||||
if (body.obj.success === true) {
|
||||
const extraDesc = body.obj.order?.shipping_data?.extra_description || "";
|
||||
const [tenantId, plan] = extraDesc.split('|');
|
||||
if (!tenantId) {
|
||||
this.logger.error(`❌ PayMob Webhook failed: No tenantId in metadata. Raw: ${extraDesc}`);
|
||||
return { status: 'error', message: 'No tenantId found' };
|
||||
}
|
||||
await this.billingService.processSuccessfulPayment(body.obj.id.toString(), transaction_entity_1.PaymentProvider.PAYMOB, body.obj.amount_cents / 100, {
|
||||
tenantId,
|
||||
plan: plan || 'PRO'
|
||||
});
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
async handleBinanceWebhook(body, req) {
|
||||
const timestamp = req.headers['binancepay-timestamp'];
|
||||
const nonce = req.headers['binancepay-nonce'];
|
||||
const signature = req.headers['binancepay-signature'];
|
||||
this.logger.log(`📥 Binance Webhook Received: Transaction ID ${body.bizId || 'UNKNOWN'}`);
|
||||
if (!timestamp || !nonce || !signature) {
|
||||
this.logger.error('❌ Binance Webhook: Missing required headers');
|
||||
throw new common_1.BadRequestException('Missing headers');
|
||||
}
|
||||
if (!this.binanceProvider.verifySignature(timestamp, nonce, signature, body)) {
|
||||
this.logger.error('❌ Binance Signature Verification Failed');
|
||||
throw new common_1.BadRequestException('Invalid signature');
|
||||
}
|
||||
if (body.bizStatus === 'PAY_SUCCESS') {
|
||||
try {
|
||||
let dataObj = {};
|
||||
if (body.data) {
|
||||
dataObj = JSON.parse(body.data);
|
||||
}
|
||||
let tenantId = '';
|
||||
let plan = 'PRO';
|
||||
if (dataObj.passThroughInfo) {
|
||||
const passThrough = JSON.parse(dataObj.passThroughInfo);
|
||||
tenantId = passThrough.tenantId;
|
||||
plan = passThrough.plan;
|
||||
}
|
||||
if (!tenantId) {
|
||||
this.logger.error(`❌ Binance Webhook failed: No tenantId found. Body: ${JSON.stringify(body)}`);
|
||||
return { returnCode: 'FAIL', returnMessage: 'No tenantId found' };
|
||||
}
|
||||
const externalTxId = dataObj.merchantTradeNo || body.bizId?.toString();
|
||||
await this.billingService.processSuccessfulPayment(externalTxId, transaction_entity_1.PaymentProvider.BINANCE, 0, { tenantId, plan });
|
||||
this.logger.log(`✅ Binance Payment Processed Successfully for Tenant ${tenantId}`);
|
||||
}
|
||||
catch (err) {
|
||||
this.logger.error(`❌ Failed to process Binance payment: ${err.message}`);
|
||||
return { returnCode: 'FAIL', returnMessage: err.message };
|
||||
}
|
||||
}
|
||||
return {
|
||||
returnCode: 'SUCCESS',
|
||||
returnMessage: null,
|
||||
};
|
||||
}
|
||||
async getInvoices(req) {
|
||||
return this.billingService.getTransactionHistory(req.tenant.id);
|
||||
}
|
||||
};
|
||||
exports.BillingController = BillingController;
|
||||
__decorate([
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
(0, common_1.UseGuards)(firebase_auth_guard_1.FirebaseAuthGuard),
|
||||
(0, common_1.Get)('subscription'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'Get current subscription details' }),
|
||||
__param(0, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], BillingController.prototype, "getSubscription", null);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
(0, common_1.UseGuards)(firebase_auth_guard_1.FirebaseAuthGuard),
|
||||
(0, common_1.Post)('checkout'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'Initialize a checkout session' }),
|
||||
__param(0, (0, common_1.Req)()),
|
||||
__param(1, (0, common_1.Body)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], BillingController.prototype, "checkout", null);
|
||||
__decorate([
|
||||
(0, common_1.Get)('callback/paymob'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'PayMob Redirection Handler' }),
|
||||
__param(0, (0, common_1.Query)()),
|
||||
__param(1, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], BillingController.prototype, "handlePaymobCallback", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('webhooks/paymob'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'PayMob Payment Webhook' }),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__param(1, (0, common_1.Query)('hmac')),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object, String]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], BillingController.prototype, "handlePaymobWebhook", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('webhooks/binance'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'Binance Payment Webhook' }),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__param(1, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], BillingController.prototype, "handleBinanceWebhook", null);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
(0, common_1.UseGuards)(firebase_auth_guard_1.FirebaseAuthGuard),
|
||||
(0, common_1.Get)('invoices'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'Get payment history' }),
|
||||
__param(0, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], BillingController.prototype, "getInvoices", null);
|
||||
exports.BillingController = BillingController = BillingController_1 = __decorate([
|
||||
(0, swagger_1.ApiTags)('billing'),
|
||||
(0, common_1.Controller)('billing'),
|
||||
__metadata("design:paramtypes", [billing_service_1.BillingService,
|
||||
paymob_provider_1.PayMobProvider,
|
||||
binance_provider_1.BinanceProvider])
|
||||
], BillingController);
|
||||
//# sourceMappingURL=billing.controller.js.map
|
||||
File diff suppressed because one or more lines are too long
+2
@@ -0,0 +1,2 @@
|
||||
export declare class BillingModule {
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
"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;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BillingModule = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const subscription_entity_1 = require("./entities/subscription.entity");
|
||||
const transaction_entity_1 = require("./entities/transaction.entity");
|
||||
const billing_service_1 = require("./billing.service");
|
||||
const billing_controller_1 = require("./billing.controller");
|
||||
const paymob_provider_1 = require("./providers/paymob.provider");
|
||||
const binance_provider_1 = require("./providers/binance.provider");
|
||||
const tenant_entity_1 = require("../auth/entities/tenant.entity");
|
||||
let BillingModule = class BillingModule {
|
||||
};
|
||||
exports.BillingModule = BillingModule;
|
||||
exports.BillingModule = BillingModule = __decorate([
|
||||
(0, common_1.Module)({
|
||||
imports: [
|
||||
typeorm_1.TypeOrmModule.forFeature([subscription_entity_1.Subscription, transaction_entity_1.Transaction, tenant_entity_1.Tenant]),
|
||||
],
|
||||
providers: [billing_service_1.BillingService, paymob_provider_1.PayMobProvider, binance_provider_1.BinanceProvider],
|
||||
controllers: [billing_controller_1.BillingController],
|
||||
exports: [billing_service_1.BillingService],
|
||||
})
|
||||
], BillingModule);
|
||||
//# sourceMappingURL=billing.module.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"billing.module.js","sourceRoot":"","sources":["../../src/billing/billing.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAwC;AACxC,6CAAgD;AAChD,wEAA8D;AAC9D,sEAA4D;AAC5D,uDAAmD;AACnD,6DAAyD;AACzD,iEAA6D;AAC7D,mEAA+D;AAC/D,kEAAwD;AAUjD,IAAM,aAAa,GAAnB,MAAM,aAAa;CAAG,CAAA;AAAhB,sCAAa;wBAAb,aAAa;IARzB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE;YACP,uBAAa,CAAC,UAAU,CAAC,CAAC,kCAAY,EAAE,gCAAW,EAAE,sBAAM,CAAC,CAAC;SAC9D;QACD,SAAS,EAAE,CAAC,gCAAc,EAAE,gCAAc,EAAE,kCAAe,CAAC;QAC5D,WAAW,EAAE,CAAC,sCAAiB,CAAC;QAChC,OAAO,EAAE,CAAC,gCAAc,CAAC;KAC1B,CAAC;GACW,aAAa,CAAG"}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Subscription } from './entities/subscription.entity';
|
||||
import { Transaction, PaymentProvider } from './entities/transaction.entity';
|
||||
import { Tenant } from '../auth/entities/tenant.entity';
|
||||
import { MailService } from '../common/mail.service';
|
||||
export declare class BillingService {
|
||||
private subscriptionRepository;
|
||||
private transactionRepository;
|
||||
private tenantRepository;
|
||||
private configService;
|
||||
private mailService;
|
||||
private readonly logger;
|
||||
constructor(subscriptionRepository: Repository<Subscription>, transactionRepository: Repository<Transaction>, tenantRepository: Repository<Tenant>, configService: ConfigService, mailService: MailService);
|
||||
getIframeId(): string;
|
||||
getSubscription(tenantId: string): Promise<Subscription>;
|
||||
processSuccessfulPayment(externalTxId: string, provider: PaymentProvider, amount: number, metadata: any): Promise<void>;
|
||||
private upgradeTenantPlan;
|
||||
getTransactionHistory(tenantId: string): Promise<Transaction[]>;
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
"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
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"billing.service.js","sourceRoot":"","sources":["../../src/billing/billing.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,2CAA4F;AAC5F,2CAA+C;AAC/C,6CAAmD;AACnD,qCAAqC;AACrC,wEAAkF;AAClF,sEAA4F;AAC5F,kEAAoE;AACpE,yDAAqD;AAG9C,IAAM,cAAc,sBAApB,MAAM,cAAc;IAKf;IAEA;IAEA;IACA;IACA;IAVO,MAAM,GAAG,IAAI,eAAM,CAAC,gBAAc,CAAC,IAAI,CAAC,CAAC;IAE1D,YAEU,sBAAgD,EAEhD,qBAA8C,EAE9C,gBAAoC,EACpC,aAA4B,EAC5B,WAAwB;QANxB,2BAAsB,GAAtB,sBAAsB,CAA0B;QAEhD,0BAAqB,GAArB,qBAAqB,CAAyB;QAE9C,qBAAgB,GAAhB,gBAAgB,CAAoB;QACpC,kBAAa,GAAb,aAAa,CAAe;QAC5B,gBAAW,GAAX,WAAW,CAAa;IAC/B,CAAC;IAKJ,WAAW;QACT,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;IAC9D,CAAC;IAKD,KAAK,CAAC,eAAe,CAAC,QAAgB;QACpC,IAAI,GAAG,GAAG,MAAM,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QAG7E,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,GAAG,GAAG,MAAM,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC;gBAC3C,QAAQ;gBACR,IAAI,EAAE,MAAM;gBACZ,mBAAmB,EAAE,IAAI;gBACzB,MAAM,EAAE,wCAAkB,CAAC,MAAM;aAClC,CAAC,CAAC;QACL,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC;IAKD,KAAK,CAAC,wBAAwB,CAC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AAC,MAAM,GAAG,wCAAkB,CAAC,MAAM,CAAC;QACvC,GAAG,CAAC,kBAAkB,GAAG,IAAI,IAAI,EAAE,CAAC;QAEpC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC;QAC7B,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;QAC7C,GAAG,CAAC,gBAAgB,GAAG,SAAS,CAAC;QAEjC,MAAM,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,qBAAqB,CAAC,QAAgB;QAC1C,OAAO,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC;YACrC,KAAK,EAAE,EAAE,QAAQ,EAAE;YACnB,KAAK,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE;SAC7B,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AApIY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,0BAAgB,EAAC,kCAAY,CAAC,CAAA;IAE9B,WAAA,IAAA,0BAAgB,EAAC,gCAAW,CAAC,CAAA;IAE7B,WAAA,IAAA,0BAAgB,EAAC,sBAAM,CAAC,CAAA;yDAHO,oBAAU,oBAAV,oBAAU,oDAEX,oBAAU,oBAAV,oBAAU,oDAEf,oBAAU,oBAAV,oBAAU,oDACb,sBAAa,oBAAb,sBAAa,gCACf,0BAAW;GAXvB,cAAc,CAoI1B"}
|
||||
@@ -0,0 +1,18 @@
|
||||
export declare enum SubscriptionStatus {
|
||||
ACTIVE = "ACTIVE",
|
||||
PAST_DUE = "PAST_DUE",
|
||||
CANCELED = "CANCELED",
|
||||
TRIALING = "TRIALING"
|
||||
}
|
||||
export declare class Subscription {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
plan: string;
|
||||
status: SubscriptionStatus;
|
||||
monthlyRequestLimit: number;
|
||||
currentPeriodStart: Date;
|
||||
currentPeriodEnd: Date;
|
||||
canceledAt: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"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);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Subscription = exports.SubscriptionStatus = void 0;
|
||||
const typeorm_1 = require("typeorm");
|
||||
var SubscriptionStatus;
|
||||
(function (SubscriptionStatus) {
|
||||
SubscriptionStatus["ACTIVE"] = "ACTIVE";
|
||||
SubscriptionStatus["PAST_DUE"] = "PAST_DUE";
|
||||
SubscriptionStatus["CANCELED"] = "CANCELED";
|
||||
SubscriptionStatus["TRIALING"] = "TRIALING";
|
||||
})(SubscriptionStatus || (exports.SubscriptionStatus = SubscriptionStatus = {}));
|
||||
let Subscription = class Subscription {
|
||||
id;
|
||||
tenantId;
|
||||
plan;
|
||||
status;
|
||||
monthlyRequestLimit;
|
||||
currentPeriodStart;
|
||||
currentPeriodEnd;
|
||||
canceledAt;
|
||||
createdAt;
|
||||
updatedAt;
|
||||
};
|
||||
exports.Subscription = Subscription;
|
||||
__decorate([
|
||||
(0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
|
||||
__metadata("design:type", String)
|
||||
], Subscription.prototype, "id", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Index)(),
|
||||
(0, typeorm_1.Column)(),
|
||||
__metadata("design:type", String)
|
||||
], Subscription.prototype, "tenantId", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ default: 'FREE' }),
|
||||
__metadata("design:type", String)
|
||||
], Subscription.prototype, "plan", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({
|
||||
type: 'enum',
|
||||
enum: SubscriptionStatus,
|
||||
default: SubscriptionStatus.ACTIVE,
|
||||
}),
|
||||
__metadata("design:type", String)
|
||||
], Subscription.prototype, "status", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ type: 'int', default: 8000 }),
|
||||
__metadata("design:type", Number)
|
||||
], Subscription.prototype, "monthlyRequestLimit", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ type: 'timestamp', nullable: true }),
|
||||
__metadata("design:type", Date)
|
||||
], Subscription.prototype, "currentPeriodStart", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ type: 'timestamp', nullable: true }),
|
||||
__metadata("design:type", Date)
|
||||
], Subscription.prototype, "currentPeriodEnd", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ type: 'timestamp', nullable: true }),
|
||||
__metadata("design:type", Date)
|
||||
], Subscription.prototype, "canceledAt", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.CreateDateColumn)(),
|
||||
__metadata("design:type", Date)
|
||||
], Subscription.prototype, "createdAt", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.UpdateDateColumn)(),
|
||||
__metadata("design:type", Date)
|
||||
], Subscription.prototype, "updatedAt", void 0);
|
||||
exports.Subscription = Subscription = __decorate([
|
||||
(0, typeorm_1.Entity)('subscriptions')
|
||||
], Subscription);
|
||||
//# sourceMappingURL=subscription.entity.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"subscription.entity.js","sourceRoot":"","sources":["../../../src/billing/entities/subscription.entity.ts"],"names":[],"mappings":";;;;;;;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IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;+CAAC;AAGhB;IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;+CAAC;uBAlCL,YAAY;IADxB,IAAA,gBAAM,EAAC,eAAe,CAAC;GACX,YAAY,CAmCxB"}
|
||||
@@ -0,0 +1,23 @@
|
||||
export declare enum PaymentStatus {
|
||||
PENDING = "PENDING",
|
||||
SUCCESS = "SUCCESS",
|
||||
FAILED = "FAILED",
|
||||
REFUNDED = "REFUNDED"
|
||||
}
|
||||
export declare enum PaymentProvider {
|
||||
PAYMOB = "PAYMOB",
|
||||
BINANCE = "BINANCE",
|
||||
MANUAL = "MANUAL"
|
||||
}
|
||||
export declare class Transaction {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
subscriptionId: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
provider: PaymentProvider;
|
||||
externalTransactionId: string;
|
||||
status: PaymentStatus;
|
||||
metadata: Record<string, any>;
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"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);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Transaction = exports.PaymentProvider = exports.PaymentStatus = void 0;
|
||||
const typeorm_1 = require("typeorm");
|
||||
var PaymentStatus;
|
||||
(function (PaymentStatus) {
|
||||
PaymentStatus["PENDING"] = "PENDING";
|
||||
PaymentStatus["SUCCESS"] = "SUCCESS";
|
||||
PaymentStatus["FAILED"] = "FAILED";
|
||||
PaymentStatus["REFUNDED"] = "REFUNDED";
|
||||
})(PaymentStatus || (exports.PaymentStatus = PaymentStatus = {}));
|
||||
var PaymentProvider;
|
||||
(function (PaymentProvider) {
|
||||
PaymentProvider["PAYMOB"] = "PAYMOB";
|
||||
PaymentProvider["BINANCE"] = "BINANCE";
|
||||
PaymentProvider["MANUAL"] = "MANUAL";
|
||||
})(PaymentProvider || (exports.PaymentProvider = PaymentProvider = {}));
|
||||
let Transaction = class Transaction {
|
||||
id;
|
||||
tenantId;
|
||||
subscriptionId;
|
||||
amount;
|
||||
currency;
|
||||
provider;
|
||||
externalTransactionId;
|
||||
status;
|
||||
metadata;
|
||||
createdAt;
|
||||
};
|
||||
exports.Transaction = Transaction;
|
||||
__decorate([
|
||||
(0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "id", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Index)(),
|
||||
(0, typeorm_1.Column)(),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "tenantId", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ nullable: true }),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "subscriptionId", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ type: 'decimal', precision: 10, scale: 2 }),
|
||||
__metadata("design:type", Number)
|
||||
], Transaction.prototype, "amount", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ default: 'USD' }),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "currency", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({
|
||||
type: 'enum',
|
||||
enum: PaymentProvider,
|
||||
}),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "provider", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Index)(),
|
||||
(0, typeorm_1.Column)({ nullable: true }),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "externalTransactionId", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({
|
||||
type: 'enum',
|
||||
enum: PaymentStatus,
|
||||
default: PaymentStatus.PENDING,
|
||||
}),
|
||||
__metadata("design:type", String)
|
||||
], Transaction.prototype, "status", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ type: 'jsonb', nullable: true }),
|
||||
__metadata("design:type", Object)
|
||||
], Transaction.prototype, "metadata", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.CreateDateColumn)(),
|
||||
__metadata("design:type", Date)
|
||||
], Transaction.prototype, "createdAt", void 0);
|
||||
exports.Transaction = Transaction = __decorate([
|
||||
(0, typeorm_1.Entity)('transactions')
|
||||
], Transaction);
|
||||
//# sourceMappingURL=transaction.entity.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"transaction.entity.js","sourceRoot":"","sources":["../../../src/billing/entities/transaction.entity.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAMiB;AAEjB,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,oCAAmB,CAAA;IACnB,oCAAmB,CAAA;IACnB,kCAAiB,CAAA;IACjB,sCAAqB,CAAA;AACvB,CAAC,EALW,aAAa,6BAAb,aAAa,QAKxB;AAED,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,sCAAmB,CAAA;IACnB,oCAAiB,CAAA;AACnB,CAAC,EAJW,eAAe,+BAAf,eAAe,QAI1B;AAGM,IAAM,WAAW,GAAjB,MAAM,WAAW;IAEtB,EAAE,CAAS;IAIX,QAAQ,CAAS;IAGjB,cAAc,CAAS;IAGvB,MAAM,CAAS;IAGf,QAAQ,CAAS;IAMjB,QAAQ,CAAkB;IAI1B,qBAAqB,CAAS;IAO9B,MAAM,CAAgB;IAGtB,QAAQ,CAAsB;IAG9B,SAAS,CAAO;CACjB,CAAA;AAvCY,kCAAW;AAEtB;IADC,IAAA,gCAAsB,EAAC,MAAM,CAAC;;uCACpB;AAIX;IAFC,IAAA,eAAK,GAAE;IACP,IAAA,gBAAM,GAAE;;6CACQ;AAGjB;IADC,IAAA,gBAAM,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;;mDACJ;AAGvB;IADC,IAAA,gBAAM,EAAC,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;;2CACtC;AAGf;IADC,IAAA,gBAAM,EAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;;6CACV;AAMjB;IAJC,IAAA,gBAAM,EAAC;QACN,IAAI,EAAE,MAAM;QACZ,IAAI,EAAE,eAAe;KACtB,CAAC;;6CACwB;AAI1B;IAFC,IAAA,eAAK,GAAE;IACP,IAAA,gBAAM,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;;0DACG;AAO9B;IALC,IAAA,gBAAM,EAAC;QACN,IAAI,EAAE,MAAM;QACZ,IAAI,EAAE,aAAa;QACnB,OAAO,EAAE,aAAa,CAAC,OAAO;KAC/B,CAAC;;2CACoB;AAGtB;IADC,IAAA,gBAAM,EAAC,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;;6CACZ;AAG9B;IADC,IAAA,0BAAgB,GAAE;8BACR,IAAI;8CAAC;sBAtCL,WAAW;IADvB,IAAA,gBAAM,EAAC,cAAc,CAAC;GACV,WAAW,CAuCvB"}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
export declare class BinanceProvider {
|
||||
private configService;
|
||||
private readonly logger;
|
||||
private readonly apiUrl;
|
||||
constructor(configService: ConfigService);
|
||||
private get apiKey();
|
||||
private get secretKey();
|
||||
private generateSignature;
|
||||
createOrder(tenantId: string, amount: number, plan: string): Promise<{
|
||||
checkoutUrl: any;
|
||||
orderId: string;
|
||||
prepayId: any;
|
||||
}>;
|
||||
verifySignature(timestamp: string, nonce: string, signature: string, payloadBody: any): boolean;
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
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 __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
var BinanceProvider_1;
|
||||
var _a;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BinanceProvider = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const config_1 = require("@nestjs/config");
|
||||
const axios_1 = __importDefault(require("axios"));
|
||||
const crypto = __importStar(require("crypto"));
|
||||
let BinanceProvider = BinanceProvider_1 = class BinanceProvider {
|
||||
configService;
|
||||
logger = new common_1.Logger(BinanceProvider_1.name);
|
||||
apiUrl = 'https://bpay.binanceapi.com/binancepay/openapi/v2/order';
|
||||
constructor(configService) {
|
||||
this.configService = configService;
|
||||
}
|
||||
get apiKey() {
|
||||
return this.configService.get('BINANCE_PAY_API_KEY') || '';
|
||||
}
|
||||
get secretKey() {
|
||||
return this.configService.get('BINANCE_PAY_SECRET_KEY') || '';
|
||||
}
|
||||
generateSignature(timestamp, nonce, body) {
|
||||
const payload = timestamp + '\n' + nonce + '\n' + JSON.stringify(body) + '\n';
|
||||
return crypto
|
||||
.createHmac('sha512', this.secretKey)
|
||||
.update(payload)
|
||||
.digest('hex')
|
||||
.toUpperCase();
|
||||
}
|
||||
async createOrder(tenantId, amount, plan) {
|
||||
this.logger.log(`Creating Binance Pay order for ${tenantId} - ${plan}`);
|
||||
if (!this.apiKey || !this.secretKey) {
|
||||
this.logger.error('Binance Pay API keys are not configured');
|
||||
throw new common_1.InternalServerErrorException('Payment provider is not configured properly');
|
||||
}
|
||||
const nonce = crypto.randomBytes(16).toString('hex');
|
||||
const timestamp = Date.now().toString();
|
||||
const merchantTradeNo = `txn_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
|
||||
const body = {
|
||||
env: {
|
||||
terminalType: 'WEB',
|
||||
},
|
||||
merchantTradeNo: merchantTradeNo,
|
||||
orderAmount: amount,
|
||||
currency: 'USDT',
|
||||
goods: {
|
||||
goodsType: '01',
|
||||
goodsCategory: 'Z000',
|
||||
referenceGoodsId: plan,
|
||||
goodsName: `${plan} Plan Subscription`,
|
||||
goodsDetail: `Subscription to ${plan} plan for Maps SaaS`,
|
||||
},
|
||||
passThroughInfo: JSON.stringify({ tenantId, plan }),
|
||||
returnUrl: `https://map-dashboard.intaleqapp.com/dashboard.html#billing`,
|
||||
};
|
||||
const signature = this.generateSignature(timestamp, nonce, body);
|
||||
try {
|
||||
const response = await axios_1.default.post(this.apiUrl, body, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'BinancePay-Timestamp': timestamp,
|
||||
'BinancePay-Nonce': nonce,
|
||||
'BinancePay-Certificate-SN': this.apiKey,
|
||||
'BinancePay-Signature': signature,
|
||||
},
|
||||
});
|
||||
if (response.data && response.data.status === 'SUCCESS') {
|
||||
return {
|
||||
checkoutUrl: response.data.data.checkoutUrl,
|
||||
orderId: merchantTradeNo,
|
||||
prepayId: response.data.data.prepayId,
|
||||
};
|
||||
}
|
||||
else {
|
||||
this.logger.error(`Binance API Error: ${JSON.stringify(response.data)}`);
|
||||
throw new common_1.InternalServerErrorException('Failed to create Binance order');
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
this.logger.error(`Error communicating with Binance API: ${error.message}`);
|
||||
throw new common_1.InternalServerErrorException('Failed to communicate with payment provider');
|
||||
}
|
||||
}
|
||||
verifySignature(timestamp, nonce, signature, payloadBody) {
|
||||
const payload = timestamp + '\n' + nonce + '\n' + JSON.stringify(payloadBody) + '\n';
|
||||
const expectedSignature = crypto
|
||||
.createHmac('sha512', this.secretKey)
|
||||
.update(payload)
|
||||
.digest('hex')
|
||||
.toUpperCase();
|
||||
try {
|
||||
return crypto.timingSafeEqual(Buffer.from(signature || ''), Buffer.from(expectedSignature));
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
exports.BinanceProvider = BinanceProvider;
|
||||
exports.BinanceProvider = BinanceProvider = BinanceProvider_1 = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__metadata("design:paramtypes", [typeof (_a = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _a : Object])
|
||||
], BinanceProvider);
|
||||
//# sourceMappingURL=binance.provider.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"binance.provider.js","sourceRoot":"","sources":["../../../src/billing/providers/binance.provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAkF;AAClF,2CAA+C;AAC/C,kDAA0B;AAC1B,+CAAiC;AAG1B,IAAM,eAAe,uBAArB,MAAM,eAAe;IAIN;IAHH,MAAM,GAAG,IAAI,eAAM,CAAC,iBAAe,CAAC,IAAI,CAAC,CAAC;IAC1C,MAAM,GAAG,yDAAyD,CAAC;IAEpF,YAAoB,aAA4B;QAA5B,kBAAa,GAAb,aAAa,CAAe;IAAG,CAAC;IAEpD,IAAY,MAAM;QAChB,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,CAAS,qBAAqB,CAAC,IAAI,EAAE,CAAC;IACrE,CAAC;IAED,IAAY,SAAS;QACnB,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,CAAS,wBAAwB,CAAC,IAAI,EAAE,CAAC;IACxE,CAAC;IAKO,iBAAiB,CAAC,SAAiB,EAAE,KAAa,EAAE,IAAS;QACnE,MAAM,OAAO,GAAG,SAAS,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,IAA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G,IAAI,GAAG,KAAK,GAAG,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC;QACrF,MAAM,iBAAiB,GAAG,MAAM;aAC7B,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC;aACpC,MAAM,CAAC,OAAO,CAAC;aACf,MAAM,CAAC,KAAK,CAAC;aACb,WAAW,EAAE,CAAC;QAEjB,IAAI,CAAC;YACD,OAAO,MAAM,CAAC,eAAe,CACzB,MAAM,CAAC,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC,EAC5B,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CACjC,CAAC;QACN,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,OAAO,KAAK,CAAC;QACjB,CAAC;IACH,CAAC;CACF,CAAA;AA5GY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,mBAAU,GAAE;yDAKwB,sBAAa,oBAAb,sBAAa;GAJrC,eAAe,CA4G3B"}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
export declare class PayMobProvider {
|
||||
private configService;
|
||||
private readonly logger;
|
||||
private readonly baseUrl;
|
||||
constructor(configService: ConfigService);
|
||||
createPaymentKey(tenantId: string, amount: number, plan: string): Promise<{
|
||||
paymentKey: string;
|
||||
orderId: string;
|
||||
}>;
|
||||
getTransactionDetails(transactionId: string): Promise<any>;
|
||||
private getAuthToken;
|
||||
verifyHmac(payload: any, hmac: string): boolean;
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
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 __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
var PayMobProvider_1;
|
||||
var _a;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PayMobProvider = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const config_1 = require("@nestjs/config");
|
||||
const axios_1 = __importDefault(require("axios"));
|
||||
const crypto = __importStar(require("crypto"));
|
||||
let PayMobProvider = PayMobProvider_1 = class PayMobProvider {
|
||||
configService;
|
||||
logger = new common_1.Logger(PayMobProvider_1.name);
|
||||
baseUrl = 'https://accept.paymob.com/api';
|
||||
constructor(configService) {
|
||||
this.configService = configService;
|
||||
}
|
||||
async createPaymentKey(tenantId, amount, plan) {
|
||||
try {
|
||||
const authToken = await this.getAuthToken();
|
||||
const orderRes = await axios_1.default.post(`${this.baseUrl}/ecommerce/orders`, {
|
||||
auth_token: authToken,
|
||||
delivery_needed: "false",
|
||||
amount_cents: amount * 50 * 100,
|
||||
currency: "EGP",
|
||||
items: [{
|
||||
name: `${plan} Subscription`,
|
||||
amount_cents: amount * 50 * 100,
|
||||
description: `Intaleq Maps ${plan} Plan`
|
||||
}],
|
||||
shipping_data: {
|
||||
first_name: "Intaleq",
|
||||
last_name: "User",
|
||||
email: "user@intaleq.com",
|
||||
phone_number: "+201000000000",
|
||||
extra_description: `${tenantId}|${plan}`
|
||||
}
|
||||
});
|
||||
const orderId = orderRes.data.id;
|
||||
const keyRes = await axios_1.default.post(`${this.baseUrl}/acceptance/payment_keys`, {
|
||||
auth_token: authToken,
|
||||
amount_cents: amount * 50 * 100,
|
||||
expiration: 3600,
|
||||
order_id: orderId,
|
||||
billing_data: {
|
||||
apartment: "NA",
|
||||
email: "user@intaleq.com",
|
||||
floor: "NA",
|
||||
first_name: "Intaleq",
|
||||
street: "NA",
|
||||
building: "NA",
|
||||
phone_number: "+201000000000",
|
||||
shipping_method: "NA",
|
||||
postal_code: "NA",
|
||||
city: "NA",
|
||||
country: "NA",
|
||||
last_name: "User",
|
||||
state: "NA"
|
||||
},
|
||||
currency: "EGP",
|
||||
integration_id: this.configService.get('PAYMOB_INTEGRATION_ID') || 4556055,
|
||||
lock_order_when_paid: "false"
|
||||
});
|
||||
return {
|
||||
paymentKey: keyRes.data.token,
|
||||
orderId: orderId.toString()
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
this.logger.error(`PayMob Payment Key failed: ${error.response?.data ? JSON.stringify(error.response.data) : error.message}`);
|
||||
throw new common_1.BadRequestException('Failed to initialize PayMob payment');
|
||||
}
|
||||
}
|
||||
async getTransactionDetails(transactionId) {
|
||||
try {
|
||||
const authToken = await this.getAuthToken();
|
||||
const res = await axios_1.default.get(`${this.baseUrl}/acceptance/transactions/${transactionId}`, {
|
||||
headers: { Authorization: `Bearer ${authToken}` }
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
catch (error) {
|
||||
this.logger.error(`Failed to fetch PayMob transaction ${transactionId}: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async getAuthToken() {
|
||||
const authRes = await axios_1.default.post(`${this.baseUrl}/auth/tokens`, {
|
||||
api_key: this.configService.get('PAYMOB_API_KEY'),
|
||||
});
|
||||
return authRes.data.token;
|
||||
}
|
||||
verifyHmac(payload, hmac) {
|
||||
const secret = this.configService.get('PAYMOB_HMAC_SECRET');
|
||||
if (!secret)
|
||||
return false;
|
||||
const { amount_cents, created_at, currency, error_occured, has_parent_transaction, id, integration_id, is_3d_secure, is_auth, is_capture, is_refunded, is_standalone_payment, is_voided, order, owner, pending, success } = payload;
|
||||
const source_pan = payload.source_data?.pan || "";
|
||||
const source_sub_type = payload.source_data?.sub_type || "";
|
||||
const source_type = payload.source_data?.type || "";
|
||||
const data = [
|
||||
amount_cents,
|
||||
created_at,
|
||||
currency,
|
||||
error_occured,
|
||||
has_parent_transaction,
|
||||
id,
|
||||
integration_id,
|
||||
is_3d_secure,
|
||||
is_auth,
|
||||
is_capture,
|
||||
is_refunded,
|
||||
is_standalone_payment,
|
||||
is_voided,
|
||||
order.id || order,
|
||||
owner,
|
||||
pending,
|
||||
source_pan,
|
||||
source_sub_type,
|
||||
source_type,
|
||||
success
|
||||
].join("");
|
||||
const hash = crypto
|
||||
.createHmac('sha512', secret)
|
||||
.update(data)
|
||||
.digest('hex');
|
||||
return hash === hmac;
|
||||
}
|
||||
};
|
||||
exports.PayMobProvider = PayMobProvider;
|
||||
exports.PayMobProvider = PayMobProvider = PayMobProvider_1 = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__metadata("design:paramtypes", [typeof (_a = typeof config_1.ConfigService !== "undefined" && config_1.ConfigService) === "function" ? _a : Object])
|
||||
], PayMobProvider);
|
||||
//# sourceMappingURL=paymob.provider.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"paymob.provider.js","sourceRoot":"","sources":["../../../src/billing/providers/paymob.provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAyE;AACzE,2CAA+C;AAC/C,kDAA0B;AAC1B,+CAAiC;AAG1B,IAAM,cAAc,sBAApB,MAAM,cAAc;IAIL;IAHH,MAAM,GAAG,IAAI,eAAM,CAAC,gBAAc,CAAC,IAAI,CAAC,CAAC;IACzC,OAAO,GAAG,+BAA+B,CAAC;IAE3D,YAAoB,aAA4B;QAA5B,kBAAa,GAAb,aAAa,CAAe;IAAG,CAAC;IAKpD,KAAK,CAAC,gBAAgB,CAAC,QAAgB,EAAE,MAAc,EAAE,IAAY;QACnE,IAAI,CAAC;YAEH,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAG5C,MAAM,QAAQ,GAAG,MAAM,eAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,mBAAmB,EAAE;gBACpE,UAAU,EAAE,SAAS;gBACrB,eAAe,EAAE,OAAO;gBACxB,YAAY,EAAE,MAAM,GAAG,EAAE,GAAG,GAAG;gBAC/B,QAAQ,EAAE,KAAK;gBACf,KAAK,EAAE,CAAC;wBACN,IAAI,EAAE,GAAG,IAAI,eAAe;wBAC5B,YAAY,EAAE,MAAM,GAAG,EAAE,GAAG,GAA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