SPB Git

Repository Public

sync.ts 6.7 KB 165 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : apps/api/src/sync.ts9 * Module           : api10 * Repository       : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website  : https://jeux.uqo-eval.app12 * Created          : 2026-11-2513 * Last Modified    : 2026-11-2514 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Synchronisation : lit la source (lecture seule), normalise, déduplique et45 * met à jour le bassin de propriétés du jeu. Les compétitions publiées ne sont46 * jamais touchées : elles vivent sur leurs instantanés.47 */48import { DEFAULT_NORMALIZE_OPTIONS, dedupeProperties, isEligible, normalizeListing, type NormalizedProperty } from "@jeux/engine";49import { config } from "./config.ts";50import { sql } from "./db.ts";51import { SqliteListingProvider, type ListingDataProvider } from "./source.ts";5253export interface SyncStats {54  scanned: number;55  normalized: number;56  deduplicated: number;57  eligible: number;58  deactivated: number;59  rejections: Record<string, number>;60  byCategory: Record<string, number>;61  durationMs: number;62}6364let running = false;6566export function isSyncRunning(): boolean {67  return running;68}6970export async function runSync(provider?: ListingDataProvider): Promise<SyncStats> {71  if (running) throw new Error("Une synchronisation est déjà en cours.");72  running = true;73  const started = Date.now();74  let jobId: number | null = null;75  let source: ListingDataProvider | null = null;76  try {77    const [job] = await sql<{ id: number }[]>`insert into data_sync_jobs default values returning id`;78    jobId = job!.id;79    source = provider ?? new SqliteListingProvider(config.listingsDbPath);80    const rejections: Record<string, number> = {};81    const normalized: NormalizedProperty[] = [];82    let scanned = 0;83    const now = new Date();84    for (const { listing, priceLog } of source.iterate()) {85      scanned += 1;86      const result = normalizeListing(listing, priceLog, { ...DEFAULT_NORMALIZE_OPTIONS, now });87      if (result.ok) normalized.push(result.property);88      else rejections[result.reason] = (rejections[result.reason] ?? 0) + 1;89      if (scanned % 2000 === 0) await new Promise((resolve) => setImmediate(resolve));90    }91    const unique = dedupeProperties(normalized);92    const byCategory: Record<string, number> = {};93    let eligibleCount = 0;94    const rows = unique.map((p) => {95      const eligible = isEligible(p);96      if (eligible) {97        eligibleCount += 1;98        byCategory[p.category] = (byCategory[p.category] ?? 0) + 1;99      }100      return {101        source_ref: p.sourceUid,102        category: p.category,103        region_code: p.regionCode,104        municipality: p.municipality,105        price: p.price,106        living_area: p.livingAreaSqft,107        data: p as unknown as postgres.JSONValue,108        eligible,109      };110    });111112    const stamp = new Date();113    let deactivated = 0;114    await sql.begin(async (tx) => {115      for (let i = 0; i < rows.length; i += 400) {116        const chunk = rows.slice(i, i + 400).map((r) => ({ ...r, data: tx.json(r.data), last_synced_at: stamp, active: true }));117        await tx`118          insert into properties ${tx(chunk, "source_ref", "category", "region_code", "municipality", "price", "living_area", "data", "eligible", "last_synced_at", "active")}119          on conflict (source_ref) do update set120            category = excluded.category, region_code = excluded.region_code, municipality = excluded.municipality,121            price = excluded.price, living_area = excluded.living_area, data = excluded.data,122            eligible = excluded.eligible, last_synced_at = excluded.last_synced_at, active = true`;123      }124      const gone = await tx`update properties set active = false where last_synced_at < ${stamp} and active`;125      deactivated = gone.count;126      await tx`delete from market_stats`;127      await tx`128        insert into market_stats (scope, category, key, prices, per_sqft)129        select 'municipalite', category, municipality,130               array_agg(price order by price),131               coalesce(array_agg(round(price::numeric / living_area)::int order by price) filter (where living_area > 0), '{}')132        from properties where eligible and active group by category, municipality`;133      await tx`134        insert into market_stats (scope, category, key, prices, per_sqft)135        select 'region', category, region_code,136               array_agg(price order by price),137               coalesce(array_agg(round(price::numeric / living_area)::int order by price) filter (where living_area > 0), '{}')138        from properties where eligible and active and region_code is not null group by category, region_code`;139    });140141    const stats: SyncStats = {142      scanned,143      normalized: normalized.length,144      deduplicated: normalized.length - unique.length,145      eligible: eligibleCount,146      deactivated,147      rejections,148      byCategory,149      durationMs: Date.now() - started,150    };151    await sql`update data_sync_jobs set status = 'success', finished_at = now(), stats = ${sql.json(stats as never)} where id = ${jobId}`;152    return stats;153  } catch (error) {154    if (jobId !== null) {155      await sql`update data_sync_jobs set status = 'failed', finished_at = now(), error = ${String(error)} where id = ${jobId}`.catch(() => {});156    }157    throw error;158  } finally {159    if (!provider && source) source.close();160    running = false;161  }162}163164import type postgres from "postgres";165
Files main
Menu

Theme