208 lines
11 KiB
JavaScript
208 lines
11 KiB
JavaScript
"use strict";
|
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
};
|
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
};
|
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
};
|
|
var MapRefinementService_1;
|
|
var _a, _b, _c, _d, _e;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.MapRefinementService = void 0;
|
|
const common_1 = require("@nestjs/common");
|
|
const typeorm_1 = require("@nestjs/typeorm");
|
|
const typeorm_2 = require("typeorm");
|
|
const map_candidate_entity_1 = require("./entities/map-candidate.entity");
|
|
const place_jordan_entity_1 = require("./entities/place-jordan.entity");
|
|
const place_syria_entity_1 = require("./entities/place-syria.entity");
|
|
const place_egypt_entity_1 = require("./entities/place-egypt.entity");
|
|
let MapRefinementService = MapRefinementService_1 = class MapRefinementService {
|
|
dataSource;
|
|
candidateRepository;
|
|
jordanRepository;
|
|
syriaRepository;
|
|
egyptRepository;
|
|
logger = new common_1.Logger(MapRefinementService_1.name);
|
|
constructor(dataSource, candidateRepository, jordanRepository, syriaRepository, egyptRepository) {
|
|
this.dataSource = dataSource;
|
|
this.candidateRepository = candidateRepository;
|
|
this.jordanRepository = jordanRepository;
|
|
this.syriaRepository = syriaRepository;
|
|
this.egyptRepository = egyptRepository;
|
|
}
|
|
async suggestPlace(dto, submittedBy) {
|
|
const lat = parseFloat(dto.lat || dto.latitude);
|
|
const lng = parseFloat(dto.lng || dto.longitude);
|
|
const country = (dto.country || 'JORDAN').toUpperCase();
|
|
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...`);
|
|
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] || {};
|
|
const isArabic = (text) => /[\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: map_candidate_entity_1.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:${spatialData.neigh_id}`);
|
|
this.runExternalVerification(saved.id).catch(err => this.logger.error(`❌ Verification failed for ${saved.id}: ${err.message}`));
|
|
return {
|
|
...saved,
|
|
governorate_name: spatialData.gov_name,
|
|
district_name: spatialData.dist_name,
|
|
neighborhood_name: spatialData.neigh_name,
|
|
location_wkt: `POINT(${lng} ${lat})`
|
|
};
|
|
}
|
|
async runExternalVerification(candidateId) {
|
|
const candidate = await this.candidateRepository.findOne({ where: { id: candidateId } });
|
|
if (!candidate)
|
|
return;
|
|
this.logger.log(`🔍 Starting automated verification for candidate ${candidate.id}...`);
|
|
try {
|
|
const axios = require('axios');
|
|
const searchUrl = `https://duckduckgo.com/html/?q=${candidate.latitude},${candidate.longitude}`;
|
|
const response = await axios.get(searchUrl, {
|
|
headers: {
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
|
|
},
|
|
timeout: 10000
|
|
});
|
|
const html = response.data;
|
|
const titleMatch = html.match(/<title>([^<]+)<\/title>/);
|
|
if (titleMatch) {
|
|
let officialName = titleMatch[1].replace(' at DuckDuckGo', '').replace(' - DuckDuckGo', '').trim();
|
|
const isCoordinates = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(officialName);
|
|
if (!isCoordinates && officialName.length > 5) {
|
|
candidate.verified_name = officialName;
|
|
const cleanUser = candidate.name.toLowerCase().trim();
|
|
const cleanOfficial = officialName.toLowerCase();
|
|
if (cleanOfficial.includes(cleanUser) || cleanUser.includes(cleanOfficial)) {
|
|
candidate.confidence_score = 90;
|
|
}
|
|
else {
|
|
candidate.confidence_score = 60;
|
|
}
|
|
this.logger.log(`🎯 Verified: Found "${officialName}" near suggestion. Trust: ${candidate.confidence_score}%`);
|
|
}
|
|
else {
|
|
candidate.confidence_score = 10;
|
|
this.logger.log(`⚠️ No specific POI name found for coordinates ${candidate.latitude},${candidate.longitude}`);
|
|
}
|
|
}
|
|
candidate.verification_metadata = {
|
|
last_check: new Date().toISOString(),
|
|
source: 'DDG_SCRAPE'
|
|
};
|
|
await this.candidateRepository.save(candidate);
|
|
}
|
|
catch (error) {
|
|
this.logger.error(`Automated verification error: ${error.message}`);
|
|
}
|
|
}
|
|
async getCandidates(status) {
|
|
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) {
|
|
const candidate = await this.candidateRepository.findOne({ where: { id } });
|
|
if (!candidate)
|
|
throw new common_1.NotFoundException('Candidate not found');
|
|
const placeData = {
|
|
latitude: candidate.latitude,
|
|
longitude: candidate.longitude,
|
|
name: candidate.name,
|
|
name_ar: candidate.name_ar,
|
|
name_en: candidate.name_en,
|
|
category: candidate.category,
|
|
address: candidate.address,
|
|
description: candidate.description,
|
|
location: candidate.location,
|
|
source: `suggested_by_${candidate.submittedBy}`,
|
|
};
|
|
let repo;
|
|
switch (candidate.country) {
|
|
case map_candidate_entity_1.CountryCode.SYRIA:
|
|
repo = this.syriaRepository;
|
|
break;
|
|
case map_candidate_entity_1.CountryCode.EGYPT:
|
|
repo = this.egyptRepository;
|
|
break;
|
|
default: repo = this.jordanRepository;
|
|
}
|
|
const approvedPlace = repo.create(placeData);
|
|
await repo.save(approvedPlace);
|
|
candidate.status = map_candidate_entity_1.CandidateStatus.APPROVED;
|
|
await this.candidateRepository.save(candidate);
|
|
this.logger.log(`✅ Approved candidate ${id}: ${candidate.name} moved to production.`);
|
|
return { success: true, place: approvedPlace };
|
|
}
|
|
async rejectCandidate(id, reason) {
|
|
const candidate = await this.candidateRepository.findOne({ where: { id } });
|
|
if (!candidate)
|
|
throw new common_1.NotFoundException('Candidate not found');
|
|
candidate.status = map_candidate_entity_1.CandidateStatus.REJECTED;
|
|
candidate.rejectionReason = reason;
|
|
return this.candidateRepository.save(candidate);
|
|
}
|
|
};
|
|
exports.MapRefinementService = MapRefinementService;
|
|
exports.MapRefinementService = MapRefinementService = MapRefinementService_1 = __decorate([
|
|
(0, common_1.Injectable)(),
|
|
__param(1, (0, typeorm_1.InjectRepository)(map_candidate_entity_1.MapCandidate)),
|
|
__param(2, (0, typeorm_1.InjectRepository)(place_jordan_entity_1.PlaceJordan)),
|
|
__param(3, (0, typeorm_1.InjectRepository)(place_syria_entity_1.PlaceSyria)),
|
|
__param(4, (0, typeorm_1.InjectRepository)(place_egypt_entity_1.PlaceEgypt)),
|
|
__metadata("design:paramtypes", [typeof (_a = typeof typeorm_2.DataSource !== "undefined" && typeorm_2.DataSource) === "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 typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _d : Object, typeof (_e = typeof typeorm_2.Repository !== "undefined" && typeorm_2.Repository) === "function" ? _e : Object])
|
|
], MapRefinementService);
|
|
//# sourceMappingURL=map-refinement.service.js.map
|