Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

6.9 KB
Raw Blame
import type { VisitedCountries } from '../entities/VisitedCountries.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';

/** `visited_countries` — every scalar column, `AT10`'s own read shape. */
export interface VisitedCountryRow {
  country_code: string;
  created_at: string | null;
  source: string;
}

/**
 * The generated `visited_countries` table, under one alias for the reads
 * ({@link listForUser} SELECTs `created_at`) and one for the writes
 * ({@link markVisited}/{@link markFromRegion} never bind it: the legacy
 * statements' own column lists omit it, leaving the schema's `DEFAULT
 * CURRENT_TIMESTAMP` to fill it in, and the generated type marks it
 * `InsertOptional`).
 */
type VisitedCountriesReadKyselyDB = Pick<DB, 'visited_countries'>;
type VisitedCountriesWriteKyselyDB = Pick<DB, 'visited_countries'>;

/**
 * The source as callers see it. 'region' marks a country that only came onto
 * the map through one of its regions and goes again with the last of them
 * (#2597); to everyone else it reads as a mark made by hand, as it always did.
 */
function publicSource(source: string): string {
  return source === 'region' ? 'manual' : source;
}

/**
 * `visited_countries` — the user's own explicit "I've been here" marks
 * (Plan 3f Task 1, atlas). `markVisited` (AT12) needs the `changes > 0`
 * signal the legacy `.run(...).changes` gave (whether this call actually
 * ADDED the mark, not just re-confirmed one already there, so a caller
 * reporting "N countries added" doesn't double-count) — Kysely's
 * `InsertResult.numInsertedOrUpdatedRows` is the SQLite `changes` count
 * verbatim (`BudgetCategoryOrderRepository`'s own `insertIgnore`-vs-this
 * distinction: that one doesn't need the signal, this one does), so this one
 * write goes through Kysely rather than `em.upsert` (which has no comparable
 * "was this actually new" return).
 */
export class VisitedCountriesRepository extends TrekRepository<VisitedCountries> {
  private readDb() {
    return this.kysely<VisitedCountriesReadKyselyDB>();
  }

  private writeDb() {
    return this.kysely<VisitedCountriesWriteKyselyDB>();
  }

  /** AT10 (`listVisitedCountries`) — `SELECT country_code, created_at, source FROM visited_countries WHERE user_id = ? ORDER BY created_at DESC`. */
  async listForUser(userId: number): Promise<VisitedCountryRow[]> {
    const rows = await this.readDb()
      .selectFrom('visited_countries')
      .select(['country_code', 'created_at', 'source'])
      .where('user_id', '=', userId)
      .orderBy('created_at', 'desc')
      .execute();
    return rows.map((row) => ({ ...row, source: publicSource(row.source) }));
  }

  /**
   * AT5/AT7/AT43 (`stats`'s no-trip early return, `stats`'s manual-country
   * merge, `getTravelStats`'s manual-country merge — three identical-text
   * call sites) — `SELECT country_code FROM visited_countries WHERE user_id
   * = ?`. Returns the bare code list; every one of the three callers only
   * ever reads `.country_code` off the legacy row shape.
   */
  async listCodesForUser(userId: number): Promise<string[]> {
    const rows = await this.writeDb()
      .selectFrom('visited_countries')
      .select('country_code')
      .where('user_id', '=', userId)
      .execute();
    return rows.map((r) => r.country_code);
  }

  /** AT8/AT9 (`countryPlaces`'s no-trip early return, `countryPlaces`'s mark lookup — identical text) — `SELECT source FROM visited_countries WHERE user_id = ? AND country_code = ?`. */
  async findSource(userId: number, countryCode: string): Promise<{ source: string } | undefined> {
    const row = await this.writeDb()
      .selectFrom('visited_countries')
      .select('source')
      .where('user_id', '=', userId)
      .where('country_code', '=', countryCode)
      .executeTakeFirst();
    return row && { source: publicSource(row.source) };
  }

  /**
   * `unmarkRegion`'s cascade check: whether the user marked the country visited
   * themselves (by hand or from Dawarich), rather than it only coming in
   * through one of its regions (#2597).
   */
  async hasOwnMark(userId: number, countryCode: string): Promise<boolean> {
    const row = await this.writeDb()
      .selectFrom('visited_countries')
      .select('country_code')
      .where('user_id', '=', userId)
      .where('country_code', '=', countryCode)
      .where('source', '!=', 'region')
      .executeTakeFirst();
    return !!row;
  }

  /**
   * AT12 (`markCountry`, inside its transaction) — `INSERT OR IGNORE INTO
   * visited_countries (user_id, country_code, source) VALUES (?, ?, ?)`.
   * Returns whether this call actually inserted a new row (see class
   * docstring) — the legacy `.changes > 0` this repository preserves.
   */
  async markVisited(userId: number, countryCode: string, source: 'manual' | 'dawarich'): Promise<boolean> {
    const result = await this.writeDb()
      .insertInto('visited_countries')
      .values({ user_id: userId, country_code: countryCode, source })
      .onConflict((oc) => oc.doNothing())
      .executeTakeFirst();
    return (result.numInsertedOrUpdatedRows ?? 0n) > 0n;
  }

  /** AT14 (`unmarkCountry`, inside its transaction) — `DELETE FROM visited_countries WHERE user_id = ? AND country_code = ?`. */
  async unmark(userId: number, countryCode: string): Promise<void> {
    await this.writeDb()
      .deleteFrom('visited_countries')
      .where('user_id', '=', userId)
      .where('country_code', '=', countryCode)
      .execute();
  }

  /**
   * AT19 (`markRegion`, inside its transaction) — `INSERT OR IGNORE INTO
   * visited_countries (user_id, country_code, source) VALUES (?, ?, 'region')`.
   * A country that only came onto the map through one of its regions is
   * written as 'region', not 'manual', so removing its last region can tell
   * it apart from a country the user ticked off itself (#2597). The conflict
   * is ignored, so a country already marked keeps its own source. Rows written
   * before this change carry 'manual' and are left as they are. No `changes`
   * signal here; the legacy statement never checked it either.
   */
  async markFromRegion(userId: number, countryCode: string): Promise<void> {
    await this.writeDb()
      .insertInto('visited_countries')
      .values({ user_id: userId, country_code: countryCode, source: 'region' })
      .onConflict((oc) => oc.doNothing())
      .execute();
  }

  /**
   * `markCountry`, inside its transaction, right after {@link markVisited}: a
   * country that only came in through a region becomes the user's own mark
   * once they mark it visited themselves. Any other row is left alone.
   */
  async promoteFromRegion(userId: number, countryCode: string, source: 'manual' | 'dawarich'): Promise<void> {
    await this.writeDb()
      .updateTable('visited_countries')
      .set({ source })
      .where('user_id', '=', userId)
      .where('country_code', '=', countryCode)
      .where('source', '=', 'region')
      .execute();
  }
}