forked from Yara724/api
lookup vehicle-kinds added
This commit is contained in:
@@ -3,6 +3,8 @@ import {
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from "@nestjs/common";
|
||||
import {
|
||||
resolveFanavaranClientKey,
|
||||
@@ -20,6 +22,7 @@ import {
|
||||
selectFanavaranDriverId,
|
||||
} from "src/claim-request-management/fanavaran-driver-inquiry";
|
||||
import { LookupDbService } from "./entities/db-service/lookup.db.service";
|
||||
import { VehicleKindDbService } from "./entities/db-service/vehicle-kind.db.service";
|
||||
import {
|
||||
asObjectRecord,
|
||||
filterPoliciesByLine,
|
||||
@@ -36,6 +39,11 @@ import {
|
||||
type FanavaranCarPolicyProduct,
|
||||
type HydratedFanavaranCarPolicy,
|
||||
} from "./fanavaran-last-car-policy";
|
||||
import {
|
||||
asVehicleKindRows,
|
||||
isVehicleKindsSyncStale,
|
||||
VEHICLE_KINDS_REFRESH_MS,
|
||||
} from "./vehicle-kind-search";
|
||||
import { gregorianDateInIran } from "src/helpers/iran-datetime";
|
||||
|
||||
type TejaratAccidentReasonRow = {
|
||||
@@ -50,14 +58,41 @@ type TejaratAccidentLabelRow = {
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class LookupsService {
|
||||
export class LookupsService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(LookupsService.name);
|
||||
private vehicleKindsSyncPromise: Promise<void> | null = null;
|
||||
private vehicleKindsRefreshTimer: ReturnType<typeof setInterval> | null =
|
||||
null;
|
||||
|
||||
constructor(
|
||||
private readonly lookupDbService: LookupDbService,
|
||||
private readonly fanavaranLookupService: FanavaranLookupService,
|
||||
private readonly vehicleKindDbService: VehicleKindDbService,
|
||||
) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.vehicleKindsRefreshTimer = setInterval(() => {
|
||||
void this.ensureVehicleKindsSynced(true).catch((error) => {
|
||||
this.logger.warn(
|
||||
`Weekly vehicle-kinds refresh failed: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
}, VEHICLE_KINDS_REFRESH_MS);
|
||||
// Best-effort warm sync shortly after boot (non-blocking).
|
||||
setTimeout(() => {
|
||||
void this.ensureVehicleKindsSynced(false).catch(() => undefined);
|
||||
}, 15_000);
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
if (this.vehicleKindsRefreshTimer) {
|
||||
clearInterval(this.vehicleKindsRefreshTimer);
|
||||
this.vehicleKindsRefreshTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private activeClientKey() {
|
||||
return resolveFanavaranClientKey();
|
||||
}
|
||||
@@ -182,9 +217,122 @@ export class LookupsService {
|
||||
}
|
||||
|
||||
async getVehicleKinds(): Promise<any> {
|
||||
await this.ensureVehicleKindsSynced(false);
|
||||
const fromDb = await this.vehicleKindDbService.findAllPublic();
|
||||
if (fromDb.length > 0) return fromDb;
|
||||
// Fallback if sync somehow left the collection empty.
|
||||
return await this.getClientRemoteLookup("vehicle-kinds");
|
||||
}
|
||||
|
||||
/**
|
||||
* Typeahead for frontend dropdowns.
|
||||
* Always echoes `q` so the client can ignore stale responses (race when
|
||||
* keystrokes outrun in-flight requests).
|
||||
*/
|
||||
async searchVehicleKindsList(input: {
|
||||
q?: string | null;
|
||||
limit?: number | null;
|
||||
}): Promise<{
|
||||
q: string;
|
||||
count: number;
|
||||
items: Array<Record<string, unknown>>;
|
||||
}> {
|
||||
const q = String(input.q ?? "").trim();
|
||||
const limitRaw = Number(input.limit ?? 50);
|
||||
const limit = Number.isFinite(limitRaw)
|
||||
? Math.min(Math.max(Math.trunc(limitRaw), 1), 100)
|
||||
: 50;
|
||||
|
||||
await this.ensureVehicleKindsSynced(false);
|
||||
|
||||
if (!q) {
|
||||
return { q: "", count: 0, items: [] };
|
||||
}
|
||||
|
||||
const items = await this.vehicleKindDbService.searchActiveByCaption(
|
||||
q,
|
||||
limit,
|
||||
);
|
||||
return {
|
||||
q,
|
||||
count: items.length,
|
||||
items: items as unknown as Array<Record<string, unknown>>,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure `vehicle-kinds` Mongo collection is populated and not older than 1 week.
|
||||
* Concurrent callers share one in-flight sync.
|
||||
*/
|
||||
async ensureVehicleKindsSynced(force: boolean): Promise<void> {
|
||||
if (this.vehicleKindsSyncPromise) {
|
||||
return this.vehicleKindsSyncPromise;
|
||||
}
|
||||
|
||||
const count = await this.vehicleKindDbService.countDocuments();
|
||||
const latest = await this.vehicleKindDbService.getLatestSyncedAt();
|
||||
const stale = isVehicleKindsSyncStale(latest);
|
||||
if (!force && count > 0 && !stale) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.vehicleKindsSyncPromise = this.syncVehicleKindsCollection()
|
||||
.catch((error) => {
|
||||
this.logger.warn(
|
||||
`vehicle-kinds sync failed: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
// If we already have rows, keep serving them.
|
||||
if (count === 0) throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
this.vehicleKindsSyncPromise = null;
|
||||
});
|
||||
|
||||
return this.vehicleKindsSyncPromise;
|
||||
}
|
||||
|
||||
private async syncVehicleKindsCollection(): Promise<void> {
|
||||
const clientKey = this.activeClientKey();
|
||||
const definition = this.findRemoteLookup("vehicle-kinds");
|
||||
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = await this.fanavaranLookupService.fetchFromFanavaran(
|
||||
clientKey,
|
||||
definition.url,
|
||||
);
|
||||
await this.fanavaranLookupService.writeCacheFile(
|
||||
clientKey,
|
||||
definition.cacheFile,
|
||||
raw,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Live Fanavaran vehicle-kinds fetch failed; falling back to cache/file: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
raw = await this.fanavaranLookupService.getRemoteLookup(
|
||||
clientKey,
|
||||
definition.url,
|
||||
definition.cacheFile,
|
||||
);
|
||||
}
|
||||
|
||||
const rows = asVehicleKindRows(raw);
|
||||
if (!rows.length) {
|
||||
throw new NotFoundException("Fanavaran vehicle-kinds returned no rows");
|
||||
}
|
||||
|
||||
const written =
|
||||
await this.vehicleKindDbService.replaceAllFromFanavaran(rows);
|
||||
this.logger.log(
|
||||
`Synced vehicle-kinds collection: ${written} documents (client=${clientKey})`,
|
||||
);
|
||||
}
|
||||
|
||||
async getPersonRole(): Promise<any> {
|
||||
return await this.getClientRemoteLookup("person-role");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user