2026-04-16-1

This commit is contained in:
Hamza-Ayed
2026-04-16 03:39:49 +03:00
parent 3d61362602
commit 58f06eeba3
15 changed files with 579 additions and 106 deletions
@@ -51,6 +51,89 @@ export class BillingController {
throw new BadRequestException('Invalid payment provider');
}
/**
* PayMob Redirection Callback (Success/Fail)
* This handles the GET request when PayMob redirects the user back to our site
*/
@Get('callback/paymob')
@ApiOperation({ summary: 'PayMob Redirection Handler' })
async handlePaymobCallback(@Query() query: any, @Req() req: any) {
this.logger.log(`🔄 PayMob Redirect Callback: ID ${query.id}, Success: ${query.success}`);
// Fallback: If success=true, proactively fetch transaction details and upgrade
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(),
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}`);
}
}
// Redirect back to dashboard with status
const targetUrl = `https://map-dashbord.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>
`;
}
/**
* PayMob Transaction Processed Webhook
* This is called by PayMob when a transaction is attempted
@@ -16,20 +16,17 @@ export class PayMobProvider {
async createPaymentKey(tenantId: string, amount: number, plan: string): Promise<{ paymentKey: string; orderId: string }> {
try {
// 1. Authentication Request
const authRes = await axios.post(`${this.baseUrl}/auth/tokens`, {
api_key: this.configService.get('PAYMOB_API_KEY'),
});
const authToken = authRes.data.token;
const authToken = await this.getAuthToken();
// 2. Order Registration
const orderRes = await axios.post(`${this.baseUrl}/ecommerce/orders`, {
auth_token: authToken,
delivery_needed: "false",
amount_cents: amount * 100, // PayMob uses cents
currency: "EGP", // Or USD based on integration
amount_cents: amount * 50 * 100, // Convert USD to EGP (1:50) and then to Cents
currency: "EGP",
items: [{
name: `${plan} Subscription`,
amount_cents: amount * 100,
amount_cents: amount * 50 * 100,
description: `Intaleq Maps ${plan} Plan`
}],
shipping_data: {
@@ -46,7 +43,7 @@ export class PayMobProvider {
// 3. Payment Key Generation
const keyRes = await axios.post(`${this.baseUrl}/acceptance/payment_keys`, {
auth_token: authToken,
amount_cents: amount * 100,
amount_cents: amount * 50 * 100, // FIXED: Now using the x50 multiplier here too
expiration: 3600,
order_id: orderId,
billing_data: {
@@ -79,6 +76,33 @@ export class PayMobProvider {
}
}
/**
* Fetch transaction details from PayMob by ID
*/
async getTransactionDetails(transactionId: string): Promise<any> {
try {
const authToken = await this.getAuthToken();
const res = await axios.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;
}
}
/**
* Get Authentication Token
*/
private async getAuthToken(): Promise<string> {
const authRes = await axios.post(`${this.baseUrl}/auth/tokens`, {
api_key: this.configService.get('PAYMOB_API_KEY'),
});
return authRes.data.token;
}
/**
* Verify HMAC signature from PayMob Webhook
*/
@@ -104,15 +128,12 @@ export class PayMobProvider {
order,
owner,
pending,
source_data_pan,
source_data_sub_type,
source_data_type,
success
} = payload;
const source_pan = source_data_pan || "";
const source_sub_type = source_data_sub_type || "";
const source_type = source_data_type || "";
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,
@@ -128,7 +149,7 @@ export class PayMobProvider {
is_refunded,
is_standalone_payment,
is_voided,
order.id, // PayMob sends order as object
order.id || order, // Can be object or ID depending on version
owner,
pending,
source_pan,
@@ -1,9 +1,10 @@
import { Controller, Get, Post, Delete, Body, Query, UseGuards, HttpException, HttpStatus } from '@nestjs/common';
import { Controller, Get, Post, Delete, Body, Query, UseGuards, Req, HttpException, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery, ApiHeader } from '@nestjs/swagger';
import { GeocodingService } from './geocoding.service';
import { AdminBoundariesService } from './admin-boundaries.service';
import { JordanResearchService } from './jordan-research.service';
import { AdministrativeLinkingService } from './administrative-linking.service';
import { MapRefinementService } from './map-refinement.service';
import { ApiKeyGuard } from '../common/guards/api-key.guard';
import { TenantThrottlerGuard } from '../common/guards/rate-limiter.guard';
import { SearchQueryDto } from './dto/search-query.dto';
@@ -19,6 +20,7 @@ export class GeocodingController {
private readonly adminBoundariesService: AdminBoundariesService,
private readonly jordanResearchService: JordanResearchService,
private readonly adminLinkingService: AdministrativeLinkingService,
private readonly refinementService: MapRefinementService,
) {}
@Get('search')
@@ -38,9 +40,10 @@ export class GeocodingController {
}
@Post('places')
@ApiOperation({ summary: 'Add a new location (User Submitted)' })
async addPlace(@Body() placeData: any) {
return this.geocodingService.addPlace(placeData);
@ApiOperation({ summary: 'Add a new location (User Submitted - Goes to Audit)' })
async addPlace(@Req() req: any, @Body() placeData: any) {
const userId = req.user?.uid || req.tenant?.id || 'api_key_user';
return this.refinementService.suggestPlace(placeData, userId);
}
@Delete('places')
@@ -4,8 +4,8 @@ import { FirebaseAuthGuard } from '../auth/guards/firebase-auth.guard';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiHeader } from '@nestjs/swagger';
import { CandidateStatus } from './entities/map-candidate.entity';
@ApiTags('map-refinement')
@Controller('map-refinement')
@ApiTags('map-refinement-places')
@Controller('map-refinement/places')
export class MapRefinementController {
constructor(private readonly refinementService: MapRefinementService) {}
@@ -1,6 +1,6 @@
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Repository, DataSource } from 'typeorm';
import { MapCandidate, CandidateStatus, CountryCode } from './entities/map-candidate.entity';
import { PlaceJordan } from './entities/place-jordan.entity';
import { PlaceSyria } from './entities/place-syria.entity';
@@ -11,6 +11,7 @@ export class MapRefinementService {
private readonly logger = new Logger(MapRefinementService.name);
constructor(
private dataSource: DataSource,
@InjectRepository(MapCandidate)
private candidateRepository: Repository<MapCandidate>,
@InjectRepository(PlaceJordan)
@@ -22,23 +23,87 @@ export class MapRefinementService {
) {}
async suggestPlace(dto: any, submittedBy: string): Promise<MapCandidate> {
const lat = parseFloat(dto.lat || dto.latitude);
const lng = parseFloat(dto.lng || dto.longitude);
const country = (dto.country || 'JORDAN').toUpperCase() as CountryCode;
if (isNaN(lat) || isNaN(lng)) {
throw new Error('Invalid coordinates: Latitude and Longitude must be numbers');
}
this.logger.log(`📍 Suggesting place: ${dto.name} at [${lat}, ${lng}]. Performing spatial enrichment...`);
// Spatial Enrichment: Finding hierarchy IDs and Names for feedback
const enrichment = await this.dataSource.query(`
SELECT
g.id as gov_id, g.name_ar as gov_name,
d.id as dist_id, d.name_ar as dist_name,
s.id as sub_id, s.name_ar as sub_name,
n.id as neigh_id, n.name_ar as neigh_name
FROM (SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326) as p) p
LEFT JOIN admin_boundaries g ON g.admin_level = 4 AND ST_Within(p.p::geometry, g.geom::geometry)
LEFT JOIN admin_boundaries d ON d.admin_level = 6 AND ST_Within(p.p::geometry, d.geom::geometry)
LEFT JOIN admin_boundaries s ON s.admin_level = 8 AND ST_Within(p.p::geometry, s.geom::geometry)
LEFT JOIN neighborhood_polygons n ON ST_Within(p.p::geometry, n.geometry::geometry)
LIMIT 1
`, [lng, lat]);
const spatialData = enrichment[0] || {};
// Smart name mapping (Arabic detection)
const isArabic = (text: string) => /[\u0600-\u06FF]/.test(text);
const nameAr = dto.name_ar || (isArabic(dto.name) ? dto.name : null);
const nameEn = dto.name_en || (!isArabic(dto.name) ? dto.name : null);
const candidate = this.candidateRepository.create({
...dto,
name: dto.name,
name_ar: nameAr,
name_en: nameEn,
category: dto.category,
address: dto.address,
latitude: lat,
longitude: lng,
submittedBy,
status: CandidateStatus.PENDING,
country: country,
location: {
type: 'Point',
coordinates: [parseFloat(dto.longitude), parseFloat(dto.latitude)],
coordinates: [lng, lat],
},
governorate_id: spatialData.gov_id,
district_id: spatialData.dist_id,
sub_district_id: spatialData.sub_id,
neighborhood_id: spatialData.neigh_id
});
return this.candidateRepository.save(candidate) as unknown as Promise<MapCandidate>;
const saved = await this.candidateRepository.save(candidate);
this.logger.log(`✅ Success: Candidate ${saved.id} enriched with Gov:${saved.governorate_id}, Neigh:${saved.neighborhood_id}`);
// Return with enriched names for immediate feedback
return {
...saved,
governorate_name: spatialData.gov_name,
district_name: spatialData.dist_name,
neighborhood_name: spatialData.neigh_name,
location_wkt: `POINT(${lng} ${lat})`
} as any;
}
async getCandidates(status?: CandidateStatus): Promise<MapCandidate[]> {
return this.candidateRepository.find({
where: status ? { status } : {},
order: { created_at: 'DESC' },
});
async getCandidates(status?: CandidateStatus): Promise<any[]> {
const query = `
SELECT
c.*,
g.name_ar as governorate_name,
d.name_ar as district_name,
n.name_ar as neighborhood_name
FROM map_candidates c
LEFT JOIN admin_boundaries g ON c.governorate_id = g.id
LEFT JOIN admin_boundaries d ON c.district_id = d.id
LEFT JOIN neighborhood_polygons n ON c.neighborhood_id = n.id
${status ? 'WHERE c.status = $1' : ''}
ORDER BY c.created_at DESC
`;
return this.candidateRepository.query(query, status ? [status] : []);
}
async approveCandidate(id: number): Promise<any> {
+2 -1
View File
@@ -107,8 +107,9 @@ export class MapsController {
const profile = query.profile || 'car';
const steps = query.steps === 'true';
const locale = query.locale || 'en';
const alternatives = query.alternatives === 'true';
return this.mapsService.getRoute(waypoints, profile, steps, locale);
return this.mapsService.getRoute(waypoints, profile, steps, locale, alternatives);
}
@Get('config')
+4 -4
View File
@@ -22,7 +22,7 @@ export class MapsService {
this.graphHopperUrl = this.configService.get('GRAPH_HOPPER_URL', 'http://routing:8080');
}
async getRoute(waypoints: [number, number][], profile: string = 'car', steps: boolean = false, locale: string = 'en') {
async getRoute(waypoints: [number, number][], profile: string = 'car', steps: boolean = false, locale: string = 'en', alternatives: boolean = false) {
if (waypoints.length < 2) {
throw new HttpException('At least two waypoints are required', HttpStatus.BAD_REQUEST);
}
@@ -64,7 +64,7 @@ export class MapsService {
};
// GraphHopper ONLY supports alternative routes if there are exactly 2 points (Start and End)
if (waypoints.length === 2) {
if (alternatives && waypoints.length === 2) {
payload.algorithm = 'alternative_route';
payload['ch.disable'] = true; // Required for alternative routes
payload['alternative_route.max_paths'] = 2; // Return main route + 1 alternative
@@ -93,7 +93,7 @@ export class MapsService {
const trafficAwareDuration = baseDuration * trafficFactor;
// Process alternative routes if any without breaking existing frontend variables
const alternatives = paths.slice(1).map(alt => ({
const altRoutes = paths.slice(1).map(alt => ({
distance: alt.distance,
duration: Math.round(alt.time / 1000),
points: alt.points,
@@ -111,7 +111,7 @@ export class MapsService {
points: route.points,
bbox: route.bbox,
instructions: route.instructions, // Added: turn-by-turn maneuvers
alternatives: alternatives
alternatives: altRoutes
};
} catch (error) {
const msg = error.response ? `GH Error: ${JSON.stringify(error.response.data)}` : `DNS/Connection Error: ${error.message}`;
+25 -4
View File
@@ -18,6 +18,12 @@ const QUOTA_LIMITS: Record<TenantPlan, number> = {
[TenantPlan.ENTERPRISE]: 1000000,
};
const RATE_LIMITS: Record<TenantPlan, number> = {
[TenantPlan.FREE]: 10,
[TenantPlan.PRO]: 500,
[TenantPlan.ENTERPRISE]: 5000,
};
@Injectable()
export class UsageInterceptor implements NestInterceptor {
private readonly logger = new Logger(UsageInterceptor.name);
@@ -34,17 +40,32 @@ export class UsageInterceptor implements NestInterceptor {
const plan = tenant.plan || TenantPlan.FREE;
const limit = QUOTA_LIMITS[plan];
const { allowed, used } = await this.usageService.checkQuota(tenant.id, limit);
if (!allowed) {
// 1. Quota Enforcement
const { allowed: quotaAllowed, used: monthlyUsed } = await this.usageService.checkQuota(tenant.id, limit);
if (!quotaAllowed) {
throw new HttpException({
statusCode: HttpStatus.TOO_MANY_REQUESTS,
error: 'Quota Exceeded',
message: 'Monthly API usage quota exceeded',
used,
used: monthlyUsed,
limit,
upgrade_url: 'https://map-dashbord.intaleqapp.com/#billing'
}, HttpStatus.TOO_MANY_REQUESTS);
}
// 2. Rate Limit Enforcement
const rpmLimit = RATE_LIMITS[plan];
const { allowed: rateAllowed, used: currentRpm } = await this.usageService.checkRateLimit(tenant.id, rpmLimit);
if (!rateAllowed) {
throw new HttpException({
statusCode: HttpStatus.TOO_MANY_REQUESTS,
error: 'Rate Limit Exceeded',
message: `Request rate limit exceeded (${rpmLimit} req/min for ${plan} plan)`,
current_rate: currentRpm,
limit: rpmLimit,
retry_after: '60s'
}, HttpStatus.TOO_MANY_REQUESTS);
}
}
const startTime = Date.now();
+46 -2
View File
@@ -61,6 +61,35 @@ export class UsageService {
};
}
/**
* Check if a tenant has exceeded their per-minute rate limit
*/
async checkRateLimit(tenantId: string, limit: number): Promise<{ allowed: boolean; used: number }> {
const key = this.getRateLimitKey(tenantId);
try {
const client = this.redisService.getClient();
const usedRaw = await client.get(key);
const used = usedRaw ? parseInt(usedRaw, 10) : 0;
if (used >= limit) {
return { allowed: false, used };
}
// Increment and set expiry if new
const multi = client.multi();
multi.incr(key);
if (!usedRaw) {
multi.expire(key, 60); // 1 minute window
}
await multi.exec();
return { allowed: true, used: used + 1 };
} catch (err) {
this.logger.error(`Rate limit check failed for ${tenantId}: ${err.message}`);
return { allowed: true, used: 0 }; // Fail open for reliability
}
}
/**
* Get usage history for charts
*/
@@ -77,11 +106,19 @@ export class UsageService {
}
/**
* Get real-time summary for the dashboard
* Get real-time summary for the dashboard including limits
*/
async getUsageSummary(tenantId: string) {
async getUsageSummary(tenantId: string, plan: string = 'FREE') {
const monthlyUsage = await this.getMonthlyUsage(tenantId);
// Map of plans to limits (synced with interceptor)
const QUOTA_LIMITS = {
'FREE': 8000,
'PRO': 50000,
'ENTERPRISE': 1000000
};
const monthlyLimit = QUOTA_LIMITS[plan] || 8000;
// Get daily stats and performance metrics
const stats = await this.usageRepository
.createQueryBuilder('usage')
@@ -100,6 +137,7 @@ export class UsageService {
return {
monthlyUsage,
monthlyLimit,
totalToday,
avgLatency,
successRate,
@@ -112,4 +150,10 @@ export class UsageService {
const yearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
return `usage:${tenantId}:${yearMonth}`;
}
private getRateLimitKey(tenantId: string): string {
const now = new Date();
const window = `${now.getFullYear()}${now.getMonth()}${now.getDate()}${now.getHours()}${now.getMinutes()}`;
return `ratelimit:${tenantId}:${window}`;
}
}