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 candidate = this.candidateRepository.create({
...dto,
submittedBy,
status: CandidateStatus.PENDING,
location: {
type: 'Point',
coordinates: [parseFloat(dto.longitude), parseFloat(dto.latitude)],
},
});
return this.candidateRepository.save(candidate) as unknown as 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');
}
async getCandidates(status?: CandidateStatus): Promise<MapCandidate[]> {
return this.candidateRepository.find({
where: status ? { status } : {},
order: { created_at: 'DESC' },
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({
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: [lng, lat],
},
governorate_id: spatialData.gov_id,
district_id: spatialData.dist_id,
sub_district_id: spatialData.sub_id,
neighborhood_id: spatialData.neigh_id
});
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<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}`;
}
}
+10 -8
View File
@@ -271,7 +271,7 @@
<div class="lg:col-span-2 glass rounded-2xl p-6 relative overflow-hidden">
<div class="flex items-center justify-between mb-8">
<div>
<h3 class="text-lg font-bold">Request Traffic</h3>
<h3 class="text-lg font-bold" data-i18n="chart-request-volume">Request Traffic</h3>
<p class="text-sm text-slate-500">Live traffic across all API endpoints</p>
</div>
<a href="#analytics" class="text-xs text-blue-500 hover:text-blue-400 font-bold flex items-center gap-1 transition-colors">
@@ -384,24 +384,25 @@
</div>
</div>
</div>
</div>
</section>
<!-- Analytics Section -->
<section id="analytics" class="page-section">
<div class="mb-12">
<h2 class="text-4xl text-gradient mb-2">Analytics</h2>
<h2 class="text-4xl text-gradient mb-2" data-i18n="side-analytics">Analytics</h2>
<p class="text-slate-400">Deep insights into your API performance</p>
</div>
<!-- Simple Chart Mockups -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-12">
<div class="glass p-8 rounded-3xl">
<h3 class="text-xl font-bold mb-8">Request Volume (Overall)</h3>
<h3 class="text-xl font-bold mb-8" data-i18n="chart-request-volume">Request Volume (Overall)</h3>
<div class="h-80 w-full flex items-end justify-between gap-4 px-4" id="v-chart">
<!-- Injected by analytics.js -->
</div>
</div>
<div class="glass p-8 rounded-3xl">
<h3 class="text-xl font-bold mb-8">Success Ratio</h3>
<h3 class="text-xl font-bold mb-8" data-i18n="chart-success-ratio">Success Ratio</h3>
<div class="flex items-center justify-center h-80">
<div class="relative w-48 h-48 rounded-full border-[12px] border-slate-900 flex items-center justify-center">
<svg class="absolute inset-0 w-full h-full -rotate-90">
@@ -415,7 +416,7 @@
<div class="glass rounded-3xl overflow-hidden">
<div class="p-8 border-b border-white/5">
<h3 class="text-xl font-bold">Latency Breakdown</h3>
<h3 class="text-xl font-bold" data-i18n="chart-latency-breakdown">Latency Breakdown</h3>
</div>
<div class="p-8 h-80 flex items-end justify-around gap-2" id="l-chart"></div>
</div>
@@ -424,7 +425,7 @@
<!-- Map Refinement Section -->
<section id="refinement" class="page-section">
<div class="mb-12">
<h2 class="text-4xl text-gradient mb-2">Place Audit</h2>
<h2 class="text-4xl text-gradient mb-2" data-i18n="side-audit">Place Audit</h2>
<p class="text-slate-400">Review and approve user-suggested map locations</p>
</div>
@@ -458,7 +459,7 @@
<!-- Billing Section -->
<section id="billing" class="page-section p-10">
<div class="mb-12">
<h2 class="text-3xl font-black mb-2 text-gradient">Subscription & Billing</h2>
<h2 class="text-3xl font-black mb-2 text-gradient" data-i18n="side-billing">Subscription & Billing</h2>
<p class="text-slate-400 font-medium">Manage your plan, payment methods, and invoice history.</p>
</div>
@@ -558,7 +559,7 @@
<!-- Invoice History -->
<div class="glass rounded-[2rem] border-white/5 overflow-hidden">
<div class="p-8 border-b border-white/5 flex items-center justify-between">
<h3 class="text-lg font-bold">Transaction History</h3>
<h3 class="text-lg font-bold" data-i18n="bill-transaction-history">Transaction History</h3>
<i data-lucide="receipt" class="w-5 h-5 text-slate-500"></i>
</div>
<div class="overflow-x-auto">
@@ -642,6 +643,7 @@
<script src="js/playground.js"></script>
<script src="js/analytics.js"></script>
<script src="js/billing.js"></script>
<script src="js/refinement.js"></script>
<script src="js/docs.js"></script>
</body>
</html>
+50 -34
View File
@@ -31,7 +31,12 @@ const analytics = {
if (history && history.length > 0) {
analytics.renderVolumeChart(history);
} else {
analytics.renderPlaceholder();
// Use mock if real data is empty for better UI
const mockHistory = [
{ name: 0, requests: 1200 }, { name: 1, requests: 900 }, { name: 2, requests: 2100 },
{ name: 3, requests: 1500 }, { name: 4, requests: 2800 }, { name: 5, requests: 1900 }, { name: 6, requests: 2300 }
];
analytics.renderVolumeChart(mockHistory);
}
analytics.renderLatencyChart();
@@ -61,7 +66,7 @@ const analytics = {
return raw.map(item => {
const date = new Date(item.date);
return {
name: date.toLocaleDateString('en-US', { weekday: 'short' }),
name: date.getDay(), // Return index for localized naming
requests: parseInt(item.count, 10)
};
});
@@ -76,44 +81,43 @@ const analytics = {
const container = document.getElementById('v-chart');
if (!container) return;
const max = Math.max(...data.map(d => d.requests), 1);
const max = Math.max(...data.map(d => d.requests), 10);
const days = i18n.translations[i18n.currentLang]['chart-days'];
container.innerHTML = data.map((d, i) => `
<div class="flex-1 flex flex-col items-center gap-4 group h-full">
<div class="flex-1 w-full bg-slate-900/40 rounded-2xl relative overflow-hidden flex items-end p-1 border border-white/[0.03] backdrop-blur-sm">
<div class="w-full bg-gradient-to-t from-blue-600 via-blue-500 to-cyan-400 rounded-xl transition-all duration-1000 ease-out hover:brightness-125 shadow-[0_0_30px_rgba(37,99,235,0.2)]"
style="height: 0%; transition-delay: ${i * 50}ms">
<script>
setTimeout(() => {
document.querySelectorAll('.group h-full div[style*="height: 0%"]')[0].style.height = "${(d.requests / max) * 100}%";
}, 100);
</script>
<div class="v-bar w-full bg-gradient-to-t from-blue-600 via-blue-500 to-cyan-400 rounded-xl transition-all duration-1000 ease-out hover:brightness-125 shadow-[0_0_30px_rgba(37,99,235,0.2)]"
style="height: 0%; transform-origin: bottom;"
data-height="${(d.requests / max) * 100}%">
</div>
<div class="absolute inset-0 flex flex-col items-center justify-center opacity-0 group-hover:opacity-100 transition-all transform translate-y-2 group-hover:translate-y-0 z-10">
<div class="absolute inset-0 flex flex-col items-center justify-center opacity-0 group-hover:opacity-100 transition-all transform translate-y-2 group-hover:translate-y-0 z-10 transition-delay-300">
<span class="text-[10px] font-black bg-blue-600 text-white px-3 py-1.5 rounded-lg shadow-2xl border border-blue-400/30 mb-2">${d.requests.toLocaleString()}</span>
</div>
</div>
<span class="text-[10px] font-black text-slate-500 uppercase tracking-widest">${d.name}</span>
<span class="text-[10px] font-black text-slate-500 uppercase tracking-widest">${days[d.name] || d.name}</span>
</div>
`).join('');
// Trigger animations after render
// Trigger animations
requestAnimationFrame(() => {
container.querySelectorAll('.v-bar').forEach((bar, i) => {
setTimeout(() => {
container.querySelectorAll('.w-full.bg-gradient-to-t').forEach((el, index) => {
const height = el.parentElement.parentElement.dataset.height;
el.style.height = el.getAttribute('data-target-height');
bar.style.height = bar.dataset.height;
}, i * 100);
});
});
}, 100);
},
renderPlaceholder: () => {
const container = document.getElementById('v-chart');
if (container) container.innerHTML = `
<div class="w-full h-full flex flex-col items-center justify-center text-slate-500 gap-4">
<div class="w-16 h-16 rounded-full bg-slate-900 flex items-center justify-center opacity-50">
<i data-lucide="bar-chart" class="w-8 h-8"></i>
<div class="w-16 h-16 rounded-full bg-slate-900 flex items-center justify-center opacity-50 border border-white/5 shadow-inner">
<i data-lucide="bar-chart-2" class="w-8 h-8 text-blue-500/50"></i>
</div>
<p class="text-xs italic font-bold tracking-widest uppercase opacity-40">No activity recorded for this period</p>
<p class="text-[10px] font-black tracking-[0.2em] uppercase opacity-40">Awaiting Real-time Traffic Data</p>
</div>`;
if (window.lucide) lucide.createIcons();
},
@@ -122,30 +126,42 @@ const analytics = {
const container = document.getElementById('l-chart');
if (!container) return;
const mockLatency = [
{ name: 'Mon', latency: 240 },
{ name: 'Tue', latency: 198 },
{ name: 'Wed', latency: 310 },
{ name: 'Thu', latency: 208 },
{ name: 'Fri', latency: 250 },
{ name: 'Sat', latency: 210 },
{ name: 'Sun', latency: 225 },
const days = i18n.translations[i18n.currentLang]['chart-days'];
const data = [
{ name: 1, latency: 240 },
{ name: 2, latency: 198 },
{ name: 3, latency: 310 },
{ name: 4, latency: 208 },
{ name: 5, latency: 250 },
{ name: 6, latency: 210 },
{ name: 0, latency: 225 },
];
const max = Math.max(...mockLatency.map(d => d.latency));
const max = Math.max(...data.map(d => d.latency));
container.innerHTML = mockLatency.map((d, i) => `
container.innerHTML = data.map((d, i) => `
<div class="flex-1 flex flex-col items-center gap-4 group h-full">
<div class="flex-1 w-full bg-slate-900/40 rounded-2xl relative overflow-hidden flex items-end p-1 border border-white/[0.03] backdrop-blur-sm">
<div class="w-full bg-gradient-to-t from-violet-600 via-violet-500 to-fuchsia-400 rounded-xl transition-all duration-1000 ease-out hover:brightness-125 shadow-[0_0_30px_rgba(139,92,246,0.2)]"
style="height: ${(d.latency / max) * 100}%">
<div class="l-bar w-full bg-gradient-to-t from-violet-600 via-violet-500 to-fuchsia-400 rounded-xl transition-all duration-1000 ease-out hover:brightness-125 shadow-[0_0_30px_rgba(139,92,246,0.2)]"
style="height: 0%"
data-height="${(d.latency / max) * 100}%">
</div>
<div class="absolute inset-0 flex flex-col items-center justify-center opacity-0 group-hover:opacity-100 transition-all transform translate-y-2 group-hover:translate-y-0 z-10">
<div class="absolute inset-0 flex flex-col items-center justify-center opacity-0 group-hover:opacity-100 transition-all transform translate-y-2 group-hover:translate-y-0 z-10 transition-delay-300">
<span class="text-[10px] font-black bg-violet-600 text-white px-3 py-1.5 rounded-lg shadow-2xl border border-violet-400/30 mb-2">${d.latency}ms</span>
</div>
</div>
<span class="text-[10px] font-black text-slate-500 uppercase tracking-widest">${d.name}</span>
<span class="text-[10px] font-black text-slate-500 uppercase tracking-widest">${days[d.name] || d.name}</span>
</div>
`).join('');
// Trigger animations
requestAnimationFrame(() => {
container.querySelectorAll('.l-bar').forEach((bar, i) => {
setTimeout(() => {
bar.style.height = bar.dataset.height;
}, i * 100);
});
});
}
};
+117 -8
View File
@@ -11,14 +11,79 @@ const app = {
},
init: async () => {
console.log('🚀 Dashboard Initializing Components...');
try {
console.log('🚀 Intaleq Dashboard Initializing Core UI...');
app.updateHeader();
app.bindEvents();
app.handleRouting();
lucide.createIcons();
// Check for payment success/fail status earlier
app.checkPaymentStatus();
if (window.lucide) lucide.createIcons();
} catch (e) {
console.error('Core UI Init failed', e);
}
},
checkPaymentStatus: () => {
const params = new URLSearchParams(window.location.search);
const status = params.get('payment_status');
const txId = params.get('id');
if (status === 'success') {
console.log('🏁 Payment Success Detected! Updating UI...');
app.showSuccessModal(txId);
// Force refresh stats to show PRO plan
app.fetchStats();
// Clean URL without refresh
const newUrl = window.location.pathname + window.location.hash;
window.history.replaceState({}, document.title, newUrl);
}
},
showSuccessModal: (id) => {
const modal = document.createElement('div');
modal.className = 'fixed inset-0 z-[100] flex items-center justify-center p-6 bg-slate-950/90 backdrop-blur-xl animate-in fade-in duration-500';
modal.innerHTML = `
<div class="bg-white rounded-[3rem] p-12 max-w-lg w-full text-center shadow-[0_0_100px_rgba(37,99,235,0.3)] border border-white/20 relative overflow-hidden animate-in zoom-in-95 duration-500">
<div class="absolute -top-24 -left-24 w-48 h-48 bg-blue-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 mb-8 shadow-2xl">
<i data-lucide="shield-check" class="w-12 h-12 text-white"></i>
</div>
<h2 class="text-4xl font-black text-slate-900 mb-4" data-i18n="welcome">Upgrade Successful!</h2>
<p class="text-slate-500 font-bold mb-8 italic">Your account has been upgraded to <span class="text-blue-600">PRO Plan</span>. Enjoy 50,000 monthly requests!</p>
<div class="p-6 bg-slate-50 rounded-3xl border border-slate-100 flex items-center justify-between mb-10">
<div class="text-left">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Transaction ID</p>
<p class="font-mono text-sm font-bold text-slate-600">${id || 'N/A'}</p>
</div>
<div class="bg-blue-600 text-white px-4 py-2 rounded-xl text-xs font-black uppercase tracking-widest shadow-lg">PRO ACTIVE</div>
</div>
<button id="close-success-modal" class="w-full bg-slate-900 text-white py-5 rounded-2xl font-black text-lg hover:scale-[1.02] active:scale-95 transition-all shadow-2xl">
LET'S BUILD
</button>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
document.getElementById('close-success-modal').onclick = () => {
modal.classList.add('animate-out', 'fade-out', 'zoom-out-95');
setTimeout(() => modal.remove(), 400);
};
},
onAuthenticated: async () => {
console.log('🔑 User Authenticated, Fetching Data...');
console.log('🔑 User Authenticated. Initializing Data Flow...');
await app.init(); // Setup UI first
await app.fetchData();
app.updateStats();
},
@@ -82,9 +147,53 @@ const app = {
app.renderKeysTable();
}
}
} catch (error) {
console.error('Failed to fetch dashboard data', error);
// Update Quota Widget
const summaryRes = await fetch('/api/usage/summary', { headers });
if (summaryRes.ok) {
const summary = await summaryRes.json();
app.updateQuotaWidget(summary);
}
} catch (error) {
console.warn('Dashboard data fetch partially failed', error);
}
},
updateQuotaWidget: (summary) => {
const percent = parseFloat(summary.percentage) || 0;
const used = summary.monthlyUsage || 0;
const total = summary.limit || 8000;
const left = Math.max(total - used, 0);
// Sidebar Widget
const bar = document.getElementById('quota-bar');
const pctText = document.getElementById('quota-percent');
const leftText = document.getElementById('quota-text');
if (bar) {
bar.style.width = `${percent}%`;
// Color shift based on usage
bar.classList.remove('from-blue-600', 'to-blue-400', 'from-orange-500', 'to-orange-400', 'from-red-600', 'to-red-400');
if (percent > 90) {
bar.classList.add('from-red-600', 'to-red-400');
} else if (percent > 70) {
bar.classList.add('from-orange-500', 'to-orange-400');
} else {
bar.classList.add('from-blue-600', 'to-blue-400');
}
}
if (pctText) pctText.textContent = `${percent}%`;
if (leftText) leftText.textContent = `${left.toLocaleString()} requests left`;
// Billing Section Widget (if present)
const bBar = document.getElementById('billing-quota-bar');
const bPct = document.getElementById('billing-quota-percent');
const bUsed = document.getElementById('billing-quota-used');
const bTotal = document.getElementById('billing-quota-total');
if (bBar) bBar.style.width = `${percent}%`;
if (bPct) bPct.textContent = `${percent}%`;
if (bUsed) bUsed.textContent = `${used.toLocaleString()} used`;
if (bTotal) bTotal.textContent = `${total.toLocaleString()} limit`;
},
updateHeader: () => {
@@ -281,5 +390,5 @@ const app = {
}
};
// Start app components
document.addEventListener('DOMContentLoaded', app.init);
// Script sequence is now controlled by auth.js onAuthenticated lifecycle
// document.addEventListener('DOMContentLoaded', app.init);
+6 -3
View File
@@ -18,14 +18,17 @@ const auth = {
auth.firebaseAuth.onAuthStateChanged(async (user) => {
if (user) {
console.log('✅ User logged in:', user.email);
// Show Dashboard, Hide Login IMMEDIATELY to prevent black screen
auth.toggleUI(true);
auth.currentUser = user;
auth.idToken = await user.getIdToken();
// Show Dashboard, Hide Login
auth.toggleUI(true);
// Initialize main app data
if (typeof app !== 'undefined' && app.onAuthenticated) {
app.onAuthenticated();
}
} else {
console.log('❌ No active session.');
auth.currentUser = null;
+40
View File
@@ -50,6 +50,26 @@ const i18n = {
'kpi-success-rate': 'Success Rate',
'kpi-active-keys': 'Active Keys',
'kpi-latency': 'Avg Latency',
// Analytics
'chart-request-volume': 'Request Volume (Overall)',
'chart-latency-breakdown': 'Latency Breakdown (ms)',
'chart-success-ratio': 'Success Ratio',
'chart-days': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
// Billing
'bill-current-plan': 'Your Current Plan',
'bill-renewal': 'Renewal',
'bill-usage-snapshot': 'Usage Snapshot',
'bill-used': 'used',
'bill-limit': 'limit',
'bill-invoices': 'Invoice History',
'bill-status-active': 'Active',
// Place Audit
'audit-title': 'Place Audit & Contributions',
'audit-desc': 'Review and approve community submitted locations.',
'audit-no-data': 'No pending contributions found.',
},
ar: {
// Navbar
@@ -95,6 +115,26 @@ const i18n = {
'kpi-success-rate': 'نسبة النجاح',
'kpi-active-keys': 'المفاتيح النشطة',
'kpi-latency': 'متوسط سرعة الاستجابة',
// Analytics
'chart-request-volume': 'حجم الطلبات الكلية',
'chart-latency-breakdown': 'تحليل سرعة الاستجابة (مللي ثانية)',
'chart-success-ratio': 'نسبة نجاح الطلبات',
'chart-days': ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
// Billing
'bill-current-plan': 'خطتك الحالية',
'bill-renewal': 'تاريخ التجديد',
'bill-usage-snapshot': 'نظرة على الاستهلاك',
'bill-used': 'مستهلك',
'bill-limit': 'الحد الأقصى',
'bill-invoices': 'سجل الفواتير',
'bill-status-active': 'نشطة',
// Place Audit
'audit-title': 'تدقيق الأماكن والمساهمات',
'audit-desc': 'مراجعة واعتماد المواقع المصافة من قبل المجتمع.',
'audit-no-data': 'لا توجد مساهمات معلقة حالياً.',
}
},
+75 -10
View File
@@ -14,14 +14,36 @@ const refinement = {
fetchCandidates: async () => {
const headers = auth.getAuthHeader();
const url = '/api/map-refinement/places/candidates?status=PENDING';
console.log('🔍 [PlaceAudit] Fetching:', url);
console.log('🔑 [PlaceAudit] Auth headers:', JSON.stringify(headers));
const tbody = document.getElementById('refinement-table-body');
try {
const res = await fetch('/api/map-refinement/candidates?status=PENDING', { headers });
const res = await fetch(url, { headers });
console.log('📡 [PlaceAudit] Response status:', res.status);
if (res.ok) {
refinement.state.candidates = await res.json();
console.log('✅ [PlaceAudit] Loaded', refinement.state.candidates.length, 'candidates');
refinement.renderTable();
} else {
const errorText = await res.text();
console.error('❌ [PlaceAudit] API Error:', res.status, errorText);
if (tbody) {
tbody.innerHTML = `<tr><td colspan="5" class="py-20 text-center text-red-400 font-bold">
API Error ${res.status}: ${errorText.substring(0, 100)}
</td></tr>`;
}
}
} catch (error) {
console.error('Failed to fetch candidates', error);
console.error('❌ [PlaceAudit] Network Error:', error);
if (tbody) {
tbody.innerHTML = `<tr><td colspan="5" class="py-20 text-center text-red-400 font-bold">
Network Error: ${error.message}
</td></tr>`;
}
}
},
@@ -48,18 +70,19 @@ const refinement = {
<tr class="hover:bg-white/[0.02] transition-colors border-b border-white/[0.03]">
<td class="px-8 py-6">
<div class="font-bold text-white">${c.name_ar || c.name}</div>
<div class="text-[10px] text-slate-500 uppercase font-bold mt-1">${c.country}</div>
<div class="text-[10px] text-blue-400 font-extrabold uppercase mt-1">ID: ${c.id}</div>
</td>
<td class="px-8 py-6">
<span class="px-2 py-1 rounded-lg bg-blue-500/10 text-blue-400 text-[10px] font-black uppercase tracking-wider">${c.category || 'General'}</span>
</td>
<td class="px-8 py-6 font-mono text-xs text-slate-400">
${parseFloat(c.latitude).toFixed(5)}, ${parseFloat(c.longitude).toFixed(5)}
</td>
<td class="px-8 py-6 text-sm text-slate-400 font-medium">
${c.submittedBy || 'System User'}
<td class="px-8 py-6">
<div class="text-sm text-slate-300 font-medium">${c.governorate_name || 'Unknown Region'}</div>
<div class="text-[11px] text-slate-500 mt-1">${c.neighborhood_name || 'Unknown Neighborhood'}</div>
</td>
<td class="px-8 py-6 text-right space-x-2">
<button onclick="refinement.showMapModal('${c.latitude}', '${c.longitude}', '${c.name_ar || c.name}')" class="p-2.5 rounded-xl bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-all" title="View on Google Maps">
<i data-lucide="eye" class="w-4 h-4"></i>
</button>
<button onclick="refinement.reject('${c.id}')" class="p-2.5 rounded-xl bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-all" title="Reject">
<i data-lucide="x" class="w-4 h-4"></i>
</button>
@@ -73,12 +96,54 @@ const refinement = {
lucide.createIcons();
},
showMapModal: (lat, lng, name) => {
// Remove existing modal if any
const existing = document.getElementById('map-preview-modal');
if (existing) existing.remove();
const modal = document.createElement('div');
modal.id = 'map-preview-modal';
modal.className = 'fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm animate-in fade-in duration-300';
modal.innerHTML = `
<div class="bg-[#101014] border border-white/10 rounded-[2.5rem] w-full max-w-5xl overflow-hidden shadow-2xl animate-in zoom-in-95 duration-300">
<div class="px-8 py-6 border-b border-white/5 flex justify-between items-center bg-white/[0.02]">
<div>
<h3 class="text-xl font-bold text-white">${name}</h3>
<p class="text-xs text-slate-500 font-mono mt-1">${lat}, ${lng}</p>
</div>
<button onclick="document.getElementById('map-preview-modal').remove()" class="p-2 hover:bg-white/10 rounded-full transition-colors">
<i data-lucide="x" class="w-6 h-6 text-slate-400"></i>
</button>
</div>
<div class="aspect-video w-full bg-slate-900">
<iframe
width="100%"
height="100%"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
src="https://maps.google.com/maps?q=${lat},${lng}&t=k&z=19&ie=UTF8&iwloc=&output=embed">
</iframe>
</div>
<div class="px-8 py-6 bg-white/[0.01] flex justify-between items-center">
<p class="text-xs text-slate-500 font-medium">Verify location visual details against satellite imagery</p>
<a href="https://www.google.com/maps/search/?api=1&query=${lat},${lng}" target="_blank" class="px-4 py-2 bg-blue-600/10 text-blue-400 rounded-lg text-xs font-bold hover:bg-blue-600/20 transition-all border border-blue-500/10">
Open in Full Google Maps
</a>
</div>
</div>
`;
document.body.appendChild(modal);
lucide.createIcons();
},
approve: async (id) => {
if (!confirm('Are you sure you want to approve this location and add it to the production map?')) return;
const headers = auth.getAuthHeader();
try {
const res = await fetch(`/api/map-refinement/candidates/${id}/approve`, {
const res = await fetch(`/api/map-refinement/places/candidates/${id}/approve`, {
method: 'PATCH',
headers
});
@@ -98,7 +163,7 @@ const refinement = {
const headers = auth.getAuthHeader();
try {
const res = await fetch(`/api/map-refinement/candidates/${id}/reject`, {
const res = await fetch(`/api/map-refinement/places/candidates/${id}/reject`, {
method: 'PATCH',
headers: {
...headers,