Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 04b235c861 | |||
| 21fb1b30d2 | |||
| 2fa6e3d87b | |||
| 6be78cae35 | |||
| 40bd6dcfea | |||
| 4884961c8e |
@@ -259,6 +259,10 @@ This means:
|
|||||||
| TC-API-8.9 | SSO bridge — no Better Auth session | POST /api/portal/session-from-auth without Better Auth session cookie | 401 Unauthorized |
|
| TC-API-8.9 | SSO bridge — no Better Auth session | POST /api/portal/session-from-auth without Better Auth session cookie | 401 Unauthorized |
|
||||||
| TC-API-8.10 | SSO bridge — no matching client | POST /api/portal/session-from-auth with valid Better Auth session for a user with no client record | 404 Not Found, error "No client record found for this user" |
|
| TC-API-8.10 | SSO bridge — no matching client | POST /api/portal/session-from-auth with valid Better Auth session for a user with no client record | 404 Not Found, error "No client record found for this user" |
|
||||||
| TC-API-8.11 | SSO bridge — returned session works on portal routes | After TC-API-8.8, use returned sessionId as `X-Impersonation-Session-Id` header on GET /api/portal/me | 200 OK, client profile returned |
|
| TC-API-8.11 | SSO bridge — returned session works on portal routes | After TC-API-8.8, use returned sessionId as `X-Impersonation-Session-Id` header on GET /api/portal/me | 200 OK, client profile returned |
|
||||||
|
| TC-API-8.12 | Portal GET pets returns extended fields (GRO-2187) | Establish a portal session (TC-API-8.8), then `GET /api/portal/pets` with `X-Impersonation-Session-Id` | 200 OK; each pet includes `coatType`, `petSizeCategory`, `healthAlerts`, `preferredCuts`, `medicalAlerts` (in addition to id/name/breed/weight/birthDate/photoUrl/notes) |
|
||||||
|
| TC-API-8.13 | Portal pet update — owner success + persistence (GRO-2187, fixes [GRO-1480](/GRO/issues/GRO-1480) §5.23) | With a portal session for the pet's owner, `PATCH /api/portal/pets/{petId}` with body `{ "name": "...", "breed": "...", "weightKg": 18.25, "healthAlerts": "...", "coatType": "double", "petSizeCategory": "xlarge", "preferredCuts": ["teddy bear"], "medicalAlerts": [{"type":"allergy","description":"oatmeal","severity":"medium"}] }` | 200 OK; response reflects the update with `petSizeCategory: "extra_large"` (web `xlarge` → DB `extra_large`). A follow-up `GET /api/portal/pets` shows the persisted values |
|
||||||
|
| TC-API-8.14 | Portal pet update — non-owner blocked (GRO-2187) | `PATCH /api/portal/pets/{petId}` for a pet owned by a different client, using another client's portal session | 403 Forbidden (or 404 if pet id is unknown); no mutation persisted |
|
||||||
|
| TC-API-8.15 | Portal pet update — invalid enum rejected (GRO-2187) | `PATCH /api/portal/pets/{petId}` with `coatType: "fluffy"` or `petSizeCategory: "gigantic"` | 422 Unprocessable Entity; pet unchanged |
|
||||||
|
|
||||||
### 4.9 Waitlist
|
### 4.9 Waitlist
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- Migration: 0041_route_optimization.sql
|
||||||
|
-- Route optimization schema: geocoding columns on clients, groomerRoutes +
|
||||||
|
-- routeStops tables, and route settings on business_settings.
|
||||||
|
-- Written idempotently so it is safe to re-run.
|
||||||
|
|
||||||
|
-- ─── Enums ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE "route_status" AS ENUM ('draft', 'optimized', 'in_progress', 'completed');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- ─── Clients: geocoding columns ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "latitude" double precision;
|
||||||
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "longitude" double precision;
|
||||||
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "geocoded_at" timestamp;
|
||||||
|
|
||||||
|
-- ─── Business settings: route optimization config ─────────────────────────────
|
||||||
|
|
||||||
|
ALTER TABLE "business_settings"
|
||||||
|
ADD COLUMN IF NOT EXISTS "default_travel_buffer_mins" integer NOT NULL DEFAULT 15;
|
||||||
|
ALTER TABLE "business_settings"
|
||||||
|
ADD COLUMN IF NOT EXISTS "route_optimization_provider" text DEFAULT 'nominatim';
|
||||||
|
-- Encrypted at rest at the application layer (AES-256-GCM).
|
||||||
|
ALTER TABLE "business_settings"
|
||||||
|
ADD COLUMN IF NOT EXISTS "google_maps_api_key" text;
|
||||||
|
|
||||||
|
-- ─── Groomer routes table ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS "groomer_routes" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"staff_id" uuid NOT NULL REFERENCES "staff"("id") ON DELETE CASCADE,
|
||||||
|
"route_date" date NOT NULL,
|
||||||
|
"status" "route_status" NOT NULL DEFAULT 'draft',
|
||||||
|
"total_travel_mins" integer,
|
||||||
|
"total_distance_km" numeric(8, 2),
|
||||||
|
"optimized_at" timestamp,
|
||||||
|
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT "uq_groomer_routes_staff_date" UNIQUE ("staff_id", "route_date")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "idx_groomer_routes_staff_id"
|
||||||
|
ON "groomer_routes"("staff_id");
|
||||||
|
|
||||||
|
-- ─── Route stops table ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS "route_stops" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"route_id" uuid NOT NULL REFERENCES "groomer_routes"("id") ON DELETE CASCADE,
|
||||||
|
"appointment_id" uuid NOT NULL REFERENCES "appointments"("id") ON DELETE CASCADE,
|
||||||
|
"stop_order" integer NOT NULL,
|
||||||
|
"latitude" double precision NOT NULL,
|
||||||
|
"longitude" double precision NOT NULL,
|
||||||
|
"travel_mins_from_prev" integer,
|
||||||
|
"travel_distance_km_from_prev" numeric(8, 2),
|
||||||
|
"buffer_mins" integer NOT NULL DEFAULT 15,
|
||||||
|
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT "uq_route_stops_route_appointment" UNIQUE ("route_id", "appointment_id"),
|
||||||
|
CONSTRAINT "uq_route_stops_route_order" UNIQUE ("route_id", "stop_order")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "idx_route_stops_route_id"
|
||||||
|
ON "route_stops"("route_id");
|
||||||
@@ -281,6 +281,13 @@
|
|||||||
"when": 1780000000002,
|
"when": 1780000000002,
|
||||||
"tag": "0040_register_missing_coat_type_values",
|
"tag": "0040_register_missing_coat_type_values",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 41,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1780000000003,
|
||||||
|
"tag": "0041_route_optimization",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -78,6 +78,9 @@ export function buildClient(overrides: Partial<ClientRow> = {}): ClientRow {
|
|||||||
stripeCustomerId: null,
|
stripeCustomerId: null,
|
||||||
status: "active",
|
status: "active",
|
||||||
disabledAt: null,
|
disabledAt: null,
|
||||||
|
latitude: null,
|
||||||
|
longitude: null,
|
||||||
|
geocodedAt: null,
|
||||||
createdAt: new Date("2025-01-01T00:00:00Z"),
|
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
...overrides,
|
...overrides,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
boolean,
|
boolean,
|
||||||
|
date,
|
||||||
|
doublePrecision,
|
||||||
index,
|
index,
|
||||||
integer,
|
integer,
|
||||||
jsonb,
|
jsonb,
|
||||||
@@ -140,6 +142,10 @@ export const clients = pgTable(
|
|||||||
stripeCustomerId: text("stripe_customer_id"),
|
stripeCustomerId: text("stripe_customer_id"),
|
||||||
status: clientStatusEnum("status").notNull().default("active"),
|
status: clientStatusEnum("status").notNull().default("active"),
|
||||||
disabledAt: timestamp("disabled_at"),
|
disabledAt: timestamp("disabled_at"),
|
||||||
|
// Geocoded coordinates for route optimization; null until geocoded.
|
||||||
|
latitude: doublePrecision("latitude"),
|
||||||
|
longitude: doublePrecision("longitude"),
|
||||||
|
geocodedAt: timestamp("geocoded_at"),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
},
|
},
|
||||||
@@ -555,6 +561,16 @@ export const businessSettings = pgTable("business_settings", {
|
|||||||
accentColor: text("accent_color").notNull().default("#8b7355"),
|
accentColor: text("accent_color").notNull().default("#8b7355"),
|
||||||
messagingPhoneNumber: text("messaging_phone_number"),
|
messagingPhoneNumber: text("messaging_phone_number"),
|
||||||
telnyxMessagingProfileId: text("telnyx_messaging_profile_id"),
|
telnyxMessagingProfileId: text("telnyx_messaging_profile_id"),
|
||||||
|
// Route optimization settings.
|
||||||
|
defaultTravelBufferMins: integer("default_travel_buffer_mins")
|
||||||
|
.notNull()
|
||||||
|
.default(15),
|
||||||
|
routeOptimizationProvider: text("route_optimization_provider").default(
|
||||||
|
"nominatim"
|
||||||
|
),
|
||||||
|
// Encrypted at rest at the application layer (AES-256-GCM), mirroring
|
||||||
|
// the handling of authProviderConfigs.clientSecret.
|
||||||
|
googleMapsApiKey: text("google_maps_api_key"),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
});
|
});
|
||||||
@@ -658,3 +674,69 @@ export const bufferRules = pgTable(
|
|||||||
index("idx_buffer_rules_service_id").on(t.serviceId),
|
index("idx_buffer_rules_service_id").on(t.serviceId),
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ─── Route Optimization ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const routeStatusEnum = pgEnum("route_status", [
|
||||||
|
"draft",
|
||||||
|
"optimized",
|
||||||
|
"in_progress",
|
||||||
|
"completed",
|
||||||
|
]);
|
||||||
|
|
||||||
|
// A groomer's optimized route for a single day. One row per (staff, date).
|
||||||
|
export const groomerRoutes = pgTable(
|
||||||
|
"groomer_routes",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
staffId: uuid("staff_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => staff.id, { onDelete: "cascade" }),
|
||||||
|
routeDate: date("route_date", { mode: "string" }).notNull(),
|
||||||
|
status: routeStatusEnum("status").notNull().default("draft"),
|
||||||
|
// Populated once the route is optimized.
|
||||||
|
totalTravelMins: integer("total_travel_mins"),
|
||||||
|
totalDistanceKm: numeric("total_distance_km", { precision: 8, scale: 2 }),
|
||||||
|
optimizedAt: timestamp("optimized_at"),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(t) => [
|
||||||
|
// One route per groomer per day.
|
||||||
|
unique("uq_groomer_routes_staff_date").on(t.staffId, t.routeDate),
|
||||||
|
index("idx_groomer_routes_staff_id").on(t.staffId),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// An ordered stop within a groomer's route, tied to an appointment.
|
||||||
|
export const routeStops = pgTable(
|
||||||
|
"route_stops",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
routeId: uuid("route_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => groomerRoutes.id, { onDelete: "cascade" }),
|
||||||
|
appointmentId: uuid("appointment_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => appointments.id, { onDelete: "cascade" }),
|
||||||
|
stopOrder: integer("stop_order").notNull(),
|
||||||
|
latitude: doublePrecision("latitude").notNull(),
|
||||||
|
longitude: doublePrecision("longitude").notNull(),
|
||||||
|
// Null for the first stop in the route.
|
||||||
|
travelMinsFromPrev: integer("travel_mins_from_prev"),
|
||||||
|
travelDistanceKmFromPrev: numeric("travel_distance_km_from_prev", {
|
||||||
|
precision: 8,
|
||||||
|
scale: 2,
|
||||||
|
}),
|
||||||
|
bufferMins: integer("buffer_mins").notNull().default(15),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(t) => [
|
||||||
|
// An appointment appears at most once per route.
|
||||||
|
unique("uq_route_stops_route_appointment").on(t.routeId, t.appointmentId),
|
||||||
|
// Stop order is unique within a route.
|
||||||
|
unique("uq_route_stops_route_order").on(t.routeId, t.stopOrder),
|
||||||
|
index("idx_route_stops_route_id").on(t.routeId),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|||||||
@@ -0,0 +1,313 @@
|
|||||||
|
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||||
|
import {
|
||||||
|
NominatimGeocodingProvider,
|
||||||
|
GoogleGeocodingProvider,
|
||||||
|
resolveGeocodingProvider,
|
||||||
|
geocodeBatch,
|
||||||
|
type FetchLike,
|
||||||
|
} from "../services/geocoding.js";
|
||||||
|
|
||||||
|
/** Builds a fake fetch returning a single JSON body, recording the called URLs. */
|
||||||
|
function fakeFetch(
|
||||||
|
body: unknown,
|
||||||
|
init: { ok?: boolean; status?: number; statusText?: string } = {}
|
||||||
|
): { fetchImpl: FetchLike; calls: string[] } {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const fetchImpl: FetchLike = async (url) => {
|
||||||
|
calls.push(url);
|
||||||
|
return {
|
||||||
|
ok: init.ok ?? true,
|
||||||
|
status: init.status ?? 200,
|
||||||
|
statusText: init.statusText ?? "OK",
|
||||||
|
json: async () => body,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
return { fetchImpl, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Virtual clock whose `sleep` advances `now`, so throttle timing is deterministic. */
|
||||||
|
function fakeClock() {
|
||||||
|
const state = { t: 0 };
|
||||||
|
const sleeps: number[] = [];
|
||||||
|
return {
|
||||||
|
now: () => state.t,
|
||||||
|
sleep: async (ms: number) => {
|
||||||
|
sleeps.push(ms);
|
||||||
|
state.t += ms;
|
||||||
|
},
|
||||||
|
sleeps,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const NOMINATIM_ROW = {
|
||||||
|
lat: "40.7128",
|
||||||
|
lon: "-74.0060",
|
||||||
|
display_name: "New York, NY, USA",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("NominatimGeocodingProvider", () => {
|
||||||
|
it("parses the top match into a GeocodeResult", async () => {
|
||||||
|
const { fetchImpl, calls } = fakeFetch([NOMINATIM_ROW]);
|
||||||
|
const provider = new NominatimGeocodingProvider({ fetchImpl });
|
||||||
|
|
||||||
|
const result = await provider.geocode("123 Main St");
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
latitude: 40.7128,
|
||||||
|
longitude: -74.006,
|
||||||
|
formattedAddress: "New York, NY, USA",
|
||||||
|
provider: "nominatim",
|
||||||
|
});
|
||||||
|
expect(calls).toHaveLength(1);
|
||||||
|
expect(calls[0]).toContain("/search");
|
||||||
|
expect(calls[0]).toContain("q=123+Main+St");
|
||||||
|
expect(calls[0]).toContain("format=jsonv2");
|
||||||
|
expect(calls[0]).toContain("limit=1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for an empty result set", async () => {
|
||||||
|
const { fetchImpl } = fakeFetch([]);
|
||||||
|
const provider = new NominatimGeocodingProvider({ fetchImpl });
|
||||||
|
expect(await provider.geocode("nowhere at all")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a blank address without calling fetch", async () => {
|
||||||
|
const { fetchImpl, calls } = fakeFetch([NOMINATIM_ROW]);
|
||||||
|
const provider = new NominatimGeocodingProvider({ fetchImpl });
|
||||||
|
expect(await provider.geocode(" ")).toBeNull();
|
||||||
|
expect(calls).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws on a non-OK HTTP response", async () => {
|
||||||
|
const { fetchImpl } = fakeFetch("rate limited", {
|
||||||
|
ok: false,
|
||||||
|
status: 429,
|
||||||
|
statusText: "Too Many Requests",
|
||||||
|
});
|
||||||
|
const provider = new NominatimGeocodingProvider({ fetchImpl });
|
||||||
|
await expect(provider.geocode("123 Main St")).rejects.toThrow(
|
||||||
|
/Nominatim geocoding failed: 429/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends the configured User-Agent and honors a custom base URL", async () => {
|
||||||
|
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
|
||||||
|
const fetchImpl: FetchLike = async (url, opts) => {
|
||||||
|
calls.push({ url, headers: opts?.headers });
|
||||||
|
return { ok: true, status: 200, statusText: "OK", json: async () => [NOMINATIM_ROW] };
|
||||||
|
};
|
||||||
|
const provider = new NominatimGeocodingProvider({
|
||||||
|
fetchImpl,
|
||||||
|
baseUrl: "https://nominatim.example.com/",
|
||||||
|
userAgent: "TestAgent/9.9",
|
||||||
|
});
|
||||||
|
|
||||||
|
await provider.geocode("123 Main St");
|
||||||
|
|
||||||
|
expect(calls[0]!.url).toContain("https://nominatim.example.com/search");
|
||||||
|
expect(calls[0]!.headers?.["User-Agent"]).toBe("TestAgent/9.9");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throttles to ~1 req/sec across consecutive calls (first call not delayed)", async () => {
|
||||||
|
const clock = fakeClock();
|
||||||
|
const { fetchImpl } = fakeFetch([NOMINATIM_ROW]);
|
||||||
|
const provider = new NominatimGeocodingProvider({
|
||||||
|
fetchImpl,
|
||||||
|
minRequestIntervalMs: 1000,
|
||||||
|
now: clock.now,
|
||||||
|
sleep: clock.sleep,
|
||||||
|
});
|
||||||
|
|
||||||
|
await provider.geocode("a");
|
||||||
|
await provider.geocode("b");
|
||||||
|
await provider.geocode("c");
|
||||||
|
|
||||||
|
// First request immediate; each subsequent waits the full interval.
|
||||||
|
expect(clock.sleeps).toEqual([1000, 1000]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GoogleGeocodingProvider", () => {
|
||||||
|
const GOOGLE_OK = {
|
||||||
|
status: "OK",
|
||||||
|
results: [
|
||||||
|
{
|
||||||
|
formatted_address: "1600 Amphitheatre Pkwy, Mountain View, CA",
|
||||||
|
geometry: { location: { lat: 37.4224, lng: -122.0842 } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
it("parses the first result into a GeocodeResult", async () => {
|
||||||
|
const { fetchImpl, calls } = fakeFetch(GOOGLE_OK);
|
||||||
|
const provider = new GoogleGeocodingProvider("test-key", { fetchImpl });
|
||||||
|
|
||||||
|
const result = await provider.geocode("1600 Amphitheatre Pkwy");
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
latitude: 37.4224,
|
||||||
|
longitude: -122.0842,
|
||||||
|
formattedAddress: "1600 Amphitheatre Pkwy, Mountain View, CA",
|
||||||
|
provider: "google",
|
||||||
|
});
|
||||||
|
expect(calls[0]).toContain("key=test-key");
|
||||||
|
expect(calls[0]).toContain("address=1600+Amphitheatre+Pkwy");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null on ZERO_RESULTS", async () => {
|
||||||
|
const { fetchImpl } = fakeFetch({ status: "ZERO_RESULTS", results: [] });
|
||||||
|
const provider = new GoogleGeocodingProvider("test-key", { fetchImpl });
|
||||||
|
expect(await provider.geocode("nowhere")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws on an API error status with the error message", async () => {
|
||||||
|
const { fetchImpl } = fakeFetch({
|
||||||
|
status: "REQUEST_DENIED",
|
||||||
|
error_message: "The provided API key is invalid.",
|
||||||
|
});
|
||||||
|
const provider = new GoogleGeocodingProvider("bad-key", { fetchImpl });
|
||||||
|
await expect(provider.geocode("123 Main St")).rejects.toThrow(
|
||||||
|
/Google geocoding error: REQUEST_DENIED: The provided API key is invalid\./
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a blank address without calling fetch", async () => {
|
||||||
|
const { fetchImpl, calls } = fakeFetch(GOOGLE_OK);
|
||||||
|
const provider = new GoogleGeocodingProvider("test-key", { fetchImpl });
|
||||||
|
expect(await provider.geocode("")).toBeNull();
|
||||||
|
expect(calls).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects construction with an empty API key", () => {
|
||||||
|
expect(() => new GoogleGeocodingProvider("")).toThrow(/non-empty API key/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveGeocodingProvider", () => {
|
||||||
|
const originalEnv = process.env.GOOGLE_MAPS_API_KEY;
|
||||||
|
afterEach(() => {
|
||||||
|
if (originalEnv === undefined) delete process.env.GOOGLE_MAPS_API_KEY;
|
||||||
|
else process.env.GOOGLE_MAPS_API_KEY = originalEnv;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults to Nominatim when provider is unset", () => {
|
||||||
|
const provider = resolveGeocodingProvider(null);
|
||||||
|
expect(provider.name).toBe("nominatim");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns Nominatim for an explicit nominatim setting", () => {
|
||||||
|
const provider = resolveGeocodingProvider({
|
||||||
|
routeOptimizationProvider: "nominatim",
|
||||||
|
});
|
||||||
|
expect(provider.name).toBe("nominatim");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns Google and decrypts the stored key when provider is google", () => {
|
||||||
|
const decrypt = vi.fn().mockReturnValue("decrypted-google-key");
|
||||||
|
const provider = resolveGeocodingProvider(
|
||||||
|
{ routeOptimizationProvider: "google", googleMapsApiKey: "enc:abc" },
|
||||||
|
{ decrypt }
|
||||||
|
);
|
||||||
|
expect(provider.name).toBe("google");
|
||||||
|
expect(decrypt).toHaveBeenCalledWith("enc:abc");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to Nominatim (with a warning) when google has no usable key", () => {
|
||||||
|
delete process.env.GOOGLE_MAPS_API_KEY;
|
||||||
|
const warn = vi.fn();
|
||||||
|
const provider = resolveGeocodingProvider(
|
||||||
|
{ routeOptimizationProvider: "google", googleMapsApiKey: null },
|
||||||
|
{ warn }
|
||||||
|
);
|
||||||
|
expect(provider.name).toBe("nominatim");
|
||||||
|
expect(warn).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to Nominatim (with a warning) when decryption fails", () => {
|
||||||
|
const decrypt = vi.fn().mockImplementation(() => {
|
||||||
|
throw new Error("bad ciphertext");
|
||||||
|
});
|
||||||
|
const warn = vi.fn();
|
||||||
|
delete process.env.GOOGLE_MAPS_API_KEY;
|
||||||
|
const provider = resolveGeocodingProvider(
|
||||||
|
{ routeOptimizationProvider: "google", googleMapsApiKey: "enc:corrupt" },
|
||||||
|
{ decrypt, warn }
|
||||||
|
);
|
||||||
|
expect(provider.name).toBe("nominatim");
|
||||||
|
expect(warn).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses GOOGLE_MAPS_API_KEY env var as a fallback key source", () => {
|
||||||
|
process.env.GOOGLE_MAPS_API_KEY = "env-key";
|
||||||
|
const provider = resolveGeocodingProvider({
|
||||||
|
routeOptimizationProvider: "google",
|
||||||
|
});
|
||||||
|
expect(provider.name).toBe("google");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("geocodeBatch", () => {
|
||||||
|
it("geocodes items in order and preserves keys", async () => {
|
||||||
|
const { fetchImpl } = fakeFetch([NOMINATIM_ROW]);
|
||||||
|
const provider = new NominatimGeocodingProvider({
|
||||||
|
fetchImpl,
|
||||||
|
minRequestIntervalMs: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const outcomes = await geocodeBatch(
|
||||||
|
[
|
||||||
|
{ key: "c1", address: "123 Main St" },
|
||||||
|
{ key: "c2", address: "456 Oak Ave" },
|
||||||
|
],
|
||||||
|
provider
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(outcomes.map((o) => o.key)).toEqual(["c1", "c2"]);
|
||||||
|
expect(outcomes[0]!.result?.latitude).toBe(40.7128);
|
||||||
|
expect(outcomes[1]!.error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("captures per-item errors and continues the batch", async () => {
|
||||||
|
let call = 0;
|
||||||
|
const fetchImpl: FetchLike = async () => {
|
||||||
|
call += 1;
|
||||||
|
if (call === 1) {
|
||||||
|
return { ok: false, status: 500, statusText: "Server Error", json: async () => "" };
|
||||||
|
}
|
||||||
|
return { ok: true, status: 200, statusText: "OK", json: async () => [NOMINATIM_ROW] };
|
||||||
|
};
|
||||||
|
const provider = new NominatimGeocodingProvider({ fetchImpl, minRequestIntervalMs: 0 });
|
||||||
|
|
||||||
|
const outcomes = await geocodeBatch(
|
||||||
|
[
|
||||||
|
{ key: 1, address: "bad" },
|
||||||
|
{ key: 2, address: "good" },
|
||||||
|
],
|
||||||
|
provider
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(outcomes[0]!.result).toBeNull();
|
||||||
|
expect(outcomes[0]!.error).toMatch(/500/);
|
||||||
|
expect(outcomes[1]!.result?.latitude).toBe(40.7128);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports progress for each completed item", async () => {
|
||||||
|
const { fetchImpl } = fakeFetch([NOMINATIM_ROW]);
|
||||||
|
const provider = new NominatimGeocodingProvider({ fetchImpl, minRequestIntervalMs: 0 });
|
||||||
|
const progress: Array<[number, number]> = [];
|
||||||
|
|
||||||
|
await geocodeBatch(
|
||||||
|
[
|
||||||
|
{ key: "a", address: "1 St" },
|
||||||
|
{ key: "b", address: "2 St" },
|
||||||
|
],
|
||||||
|
provider,
|
||||||
|
{ onProgress: (completed, total) => progress.push([completed, total]) }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(progress).toEqual([
|
||||||
|
[1, 2],
|
||||||
|
[2, 2],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { Hono } from "hono";
|
||||||
|
|
||||||
|
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||||
|
const OTHER_CLIENT_ID = "550e8400-e29b-41d4-a716-446655440099";
|
||||||
|
const PET_ID = "880e8400-e29b-41d4-a716-446655440004";
|
||||||
|
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
|
||||||
|
|
||||||
|
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
|
||||||
|
|
||||||
|
const ACTIVE_SESSION = {
|
||||||
|
id: SESSION_ID,
|
||||||
|
clientId: CLIENT_ID,
|
||||||
|
status: "active" as const,
|
||||||
|
expiresAt: futureDate(),
|
||||||
|
createdAt: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// A persisted pet owned by CLIENT_ID. weightKg is a string because the column is
|
||||||
|
// numeric (Drizzle serialises numeric to string).
|
||||||
|
const PET = {
|
||||||
|
id: PET_ID,
|
||||||
|
clientId: CLIENT_ID,
|
||||||
|
name: "Rex",
|
||||||
|
species: "dog",
|
||||||
|
breed: "Labrador",
|
||||||
|
weightKg: "12.50",
|
||||||
|
dateOfBirth: null,
|
||||||
|
healthAlerts: null,
|
||||||
|
groomingNotes: null,
|
||||||
|
coatType: null,
|
||||||
|
petSizeCategory: null,
|
||||||
|
preferredCuts: [],
|
||||||
|
medicalAlerts: [],
|
||||||
|
photoKey: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
let selectSessionRow: Record<string, unknown> | null = null;
|
||||||
|
let selectPetRow: Record<string, unknown> | null = null;
|
||||||
|
let updatedValues: Record<string, unknown>[] = [];
|
||||||
|
|
||||||
|
function resetMock() {
|
||||||
|
selectSessionRow = null;
|
||||||
|
selectPetRow = null;
|
||||||
|
updatedValues = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock("@groombook/db", () => {
|
||||||
|
function makeChainable(data: unknown[]): unknown {
|
||||||
|
const arr = [...data];
|
||||||
|
const chain = new Proxy(arr, {
|
||||||
|
get(target, prop) {
|
||||||
|
if (prop === "where" || prop === "orderBy" || prop === "limit") {
|
||||||
|
return () => chain;
|
||||||
|
}
|
||||||
|
// @ts-expect-error proxy
|
||||||
|
return target[prop];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return chain;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tableProxy(name: string) {
|
||||||
|
return new Proxy(
|
||||||
|
{ _name: name },
|
||||||
|
{ get: (t, p) => (p === "_name" ? name : { table: name, column: p }) }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const impersonationSessions = tableProxy("impersonationSessions");
|
||||||
|
const pets = tableProxy("pets");
|
||||||
|
|
||||||
|
return {
|
||||||
|
getDb: () => ({
|
||||||
|
select: () => ({
|
||||||
|
from: (table: { _name: string }) => {
|
||||||
|
if (table._name === "impersonationSessions") {
|
||||||
|
return makeChainable(selectSessionRow ? [selectSessionRow] : []);
|
||||||
|
}
|
||||||
|
if (table._name === "pets") {
|
||||||
|
return makeChainable(selectPetRow ? [selectPetRow] : []);
|
||||||
|
}
|
||||||
|
return makeChainable([]);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
update: () => ({
|
||||||
|
set: (vals: Record<string, unknown>) => ({
|
||||||
|
where: () => ({
|
||||||
|
returning: () => {
|
||||||
|
if (selectPetRow) {
|
||||||
|
updatedValues.push(vals);
|
||||||
|
return [{ ...selectPetRow, ...vals }];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
// portalAudit inserts an audit row after the handler; make it a no-op so
|
||||||
|
// the middleware does not log a swallowed error during tests.
|
||||||
|
insert: () => ({ values: () => ({ returning: () => [] }) }),
|
||||||
|
}),
|
||||||
|
impersonationSessions,
|
||||||
|
pets,
|
||||||
|
// Other tables imported by the portal router but unused in these tests.
|
||||||
|
appointments: tableProxy("appointments"),
|
||||||
|
waitlistEntries: tableProxy("waitlistEntries"),
|
||||||
|
clients: tableProxy("clients"),
|
||||||
|
services: tableProxy("services"),
|
||||||
|
staff: tableProxy("staff"),
|
||||||
|
invoices: tableProxy("invoices"),
|
||||||
|
invoiceLineItems: tableProxy("invoiceLineItems"),
|
||||||
|
impersonationAuditLogs: tableProxy("impersonationAuditLogs"),
|
||||||
|
eq: vi.fn(),
|
||||||
|
and: vi.fn(),
|
||||||
|
inArray: vi.fn(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const { portalRouter } = await import("../routes/portal.js");
|
||||||
|
|
||||||
|
const app = new Hono();
|
||||||
|
app.route("/portal", portalRouter);
|
||||||
|
|
||||||
|
function jsonPatch(path: string, body: unknown, headers?: Record<string, string>) {
|
||||||
|
return app.request(path, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...headers,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => resetMock());
|
||||||
|
|
||||||
|
describe("PATCH /portal/pets/:petId", () => {
|
||||||
|
it("updates an owned pet and persists the mapped columns (200)", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = PET;
|
||||||
|
|
||||||
|
// Mirrors the groombook/web PetForm payload: it spreads the GET-shaped pet
|
||||||
|
// (weight, notes, birthDate, photoUrl) and adds the form's edited keys
|
||||||
|
// (weightKg, healthAlerts, coatType, …). "xlarge" must map to "extra_large".
|
||||||
|
const res = await jsonPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{
|
||||||
|
id: PET_ID,
|
||||||
|
name: "Rex Updated",
|
||||||
|
breed: "Golden Retriever",
|
||||||
|
weight: "12.50",
|
||||||
|
weightKg: 18.25,
|
||||||
|
notes: "old grooming notes",
|
||||||
|
healthAlerts: "Allergic to oatmeal shampoo",
|
||||||
|
photoUrl: "pets/rex.jpg",
|
||||||
|
coatType: "double",
|
||||||
|
petSizeCategory: "xlarge",
|
||||||
|
preferredCuts: ["teddy bear", "puppy cut"],
|
||||||
|
medicalAlerts: [
|
||||||
|
{ id: "a1", type: "allergy", description: "oatmeal", severity: "medium" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.name).toBe("Rex Updated");
|
||||||
|
expect(body.petSizeCategory).toBe("extra_large");
|
||||||
|
expect(body.coatType).toBe("double");
|
||||||
|
|
||||||
|
const persisted = updatedValues[0]!;
|
||||||
|
expect(persisted.name).toBe("Rex Updated");
|
||||||
|
expect(persisted.breed).toBe("Golden Retriever");
|
||||||
|
// weightKg (form key) wins over weight (GET key) and is stored as a string.
|
||||||
|
expect(persisted.weightKg).toBe("18.25");
|
||||||
|
expect(persisted.groomingNotes).toBe("old grooming notes");
|
||||||
|
expect(persisted.healthAlerts).toBe("Allergic to oatmeal shampoo");
|
||||||
|
expect(persisted.photoKey).toBe("pets/rex.jpg");
|
||||||
|
expect(persisted.coatType).toBe("double");
|
||||||
|
expect(persisted.petSizeCategory).toBe("extra_large");
|
||||||
|
expect(persisted.preferredCuts).toEqual(["teddy bear", "puppy cut"]);
|
||||||
|
expect(persisted.medicalAlerts).toEqual([
|
||||||
|
{ id: "a1", type: "allergy", description: "oatmeal", severity: "medium" },
|
||||||
|
]);
|
||||||
|
expect(persisted.updatedAt).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the weight key when weightKg is absent", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = PET;
|
||||||
|
|
||||||
|
const res = await jsonPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ weight: "9.75" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(updatedValues[0]!.weightKg).toBe("9.75");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 403 when the pet belongs to a different client", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = { ...PET, clientId: OTHER_CLIENT_ID };
|
||||||
|
|
||||||
|
const res = await jsonPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ name: "Hacker" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(updatedValues).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 404 when the pet does not exist", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = null;
|
||||||
|
|
||||||
|
const res = await jsonPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ name: "Ghost" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 422 for an invalid coatType", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = PET;
|
||||||
|
|
||||||
|
const res = await jsonPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ coatType: "fluffy" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(422);
|
||||||
|
expect(updatedValues).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 422 for an invalid petSizeCategory", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = PET;
|
||||||
|
|
||||||
|
const res = await jsonPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ petSizeCategory: "gigantic" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(422);
|
||||||
|
expect(updatedValues).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 without an impersonation session header", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = PET;
|
||||||
|
|
||||||
|
const res = await jsonPatch(`/portal/pets/${PET_ID}`, { name: "NoAuth" });
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
+145
-1
@@ -225,9 +225,153 @@ portalRouter.get("/pets", async (c) => {
|
|||||||
const clientId = c.get("portalClientId");
|
const clientId = c.get("portalClientId");
|
||||||
|
|
||||||
const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId));
|
const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId));
|
||||||
return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weight: p.weightKg, birthDate: p.dateOfBirth, photoUrl: p.photoKey, notes: p.groomingNotes })));
|
return c.json(clientPets.map(p => ({
|
||||||
|
id: p.id,
|
||||||
|
name: p.name,
|
||||||
|
breed: p.breed,
|
||||||
|
weight: p.weightKg,
|
||||||
|
birthDate: p.dateOfBirth,
|
||||||
|
photoUrl: p.photoKey,
|
||||||
|
notes: p.groomingNotes,
|
||||||
|
coatType: p.coatType,
|
||||||
|
petSizeCategory: p.petSizeCategory,
|
||||||
|
healthAlerts: p.healthAlerts,
|
||||||
|
preferredCuts: p.preferredCuts,
|
||||||
|
medicalAlerts: p.medicalAlerts,
|
||||||
|
})));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── Customer-facing pet update ───────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// The customer portal pet-profile form (groombook/web) saves edits via
|
||||||
|
// PATCH /api/portal/pets/:petId. The web payload mixes the keys returned by
|
||||||
|
// GET /portal/pets (weight, birthDate, photoUrl, notes) with the form's own
|
||||||
|
// edited keys (weightKg, healthAlerts, coatType, …), so we accept both spellings
|
||||||
|
// and map each to its `pets` column. Ownership is enforced exactly like the
|
||||||
|
// appointment-notes handler: 404 if the pet does not exist, 403 if it belongs to
|
||||||
|
// another client.
|
||||||
|
|
||||||
|
// Allowed enum values mirror packages/db/src/schema.ts coatTypeEnum /
|
||||||
|
// petSizeCategoryEnum. Kept as plain string lists so an invalid value can be
|
||||||
|
// rejected with 422 in-handler (zValidator failures would surface as 400).
|
||||||
|
const PORTAL_COAT_TYPES: readonly string[] = ["short", "medium", "long", "double", "wire", "silky", "curly", "hairless"];
|
||||||
|
const PORTAL_PET_SIZES: readonly string[] = ["small", "medium", "large", "extra_large"];
|
||||||
|
// The web size dropdown emits "xlarge"; the DB enum value is "extra_large".
|
||||||
|
const PORTAL_PET_SIZE_ALIASES: Record<string, string> = { xlarge: "extra_large" };
|
||||||
|
|
||||||
|
const portalMedicalAlertSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
type: z.string(),
|
||||||
|
description: z.string(),
|
||||||
|
severity: z.enum(["low", "medium", "high"]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const portalPetUpdateSchema = z.object({
|
||||||
|
name: z.string().min(1).max(200).optional(),
|
||||||
|
breed: z.string().max(200).nullable().optional(),
|
||||||
|
// weightKg is the form's edited key; weight is the GET-shaped key. Accept both.
|
||||||
|
weightKg: z.union([z.number(), z.string()]).nullable().optional(),
|
||||||
|
weight: z.union([z.number(), z.string()]).nullable().optional(),
|
||||||
|
birthDate: z.string().nullable().optional(),
|
||||||
|
notes: z.string().max(2000).nullable().optional(),
|
||||||
|
healthAlerts: z.string().max(2000).nullable().optional(),
|
||||||
|
photoUrl: z.string().nullable().optional(),
|
||||||
|
// coatType / petSizeCategory validated in-handler so bad values return 422.
|
||||||
|
coatType: z.string().nullable().optional(),
|
||||||
|
petSizeCategory: z.string().nullable().optional(),
|
||||||
|
preferredCuts: z.array(z.string()).nullable().optional(),
|
||||||
|
medicalAlerts: z.array(portalMedicalAlertSchema).nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
portalRouter.patch(
|
||||||
|
"/pets/:petId",
|
||||||
|
zValidator("json", portalPetUpdateSchema),
|
||||||
|
async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const petId = c.req.param("petId");
|
||||||
|
const body = c.req.valid("json");
|
||||||
|
const clientId = c.get("portalClientId");
|
||||||
|
|
||||||
|
const [pet] = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.id, petId))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!pet) {
|
||||||
|
return c.json({ error: "Not found" }, 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pet.clientId !== clientId) {
|
||||||
|
return c.json({ error: "Forbidden" }, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateData: Record<string, unknown> = { updatedAt: new Date() };
|
||||||
|
|
||||||
|
if (body.name !== undefined) updateData.name = body.name;
|
||||||
|
if (body.breed !== undefined) updateData.breed = body.breed;
|
||||||
|
|
||||||
|
if (body.weightKg !== undefined || body.weight !== undefined) {
|
||||||
|
const w = body.weightKg ?? body.weight;
|
||||||
|
updateData.weightKg = w === null || w === undefined ? null : String(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.birthDate !== undefined) {
|
||||||
|
updateData.dateOfBirth = body.birthDate ? new Date(body.birthDate) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.notes !== undefined) updateData.groomingNotes = body.notes;
|
||||||
|
if (body.healthAlerts !== undefined) updateData.healthAlerts = body.healthAlerts;
|
||||||
|
if (body.photoUrl !== undefined) updateData.photoKey = body.photoUrl;
|
||||||
|
|
||||||
|
if (body.coatType !== undefined) {
|
||||||
|
if (body.coatType !== null && !PORTAL_COAT_TYPES.includes(body.coatType)) {
|
||||||
|
return c.json({ error: "Invalid coatType" }, 422);
|
||||||
|
}
|
||||||
|
updateData.coatType = body.coatType;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.petSizeCategory !== undefined) {
|
||||||
|
let size: string | null = body.petSizeCategory;
|
||||||
|
if (size !== null) {
|
||||||
|
size = PORTAL_PET_SIZE_ALIASES[size] ?? size;
|
||||||
|
if (!PORTAL_PET_SIZES.includes(size)) {
|
||||||
|
return c.json({ error: "Invalid petSizeCategory" }, 422);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updateData.petSizeCategory = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.preferredCuts !== undefined) updateData.preferredCuts = body.preferredCuts ?? [];
|
||||||
|
if (body.medicalAlerts !== undefined) updateData.medicalAlerts = body.medicalAlerts ?? [];
|
||||||
|
|
||||||
|
const [updated] = await db
|
||||||
|
.update(pets)
|
||||||
|
.set(updateData)
|
||||||
|
.where(eq(pets.id, petId))
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (!updated) {
|
||||||
|
return c.json({ error: "Not found" }, 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
id: updated.id,
|
||||||
|
name: updated.name,
|
||||||
|
breed: updated.breed,
|
||||||
|
weight: updated.weightKg,
|
||||||
|
birthDate: updated.dateOfBirth,
|
||||||
|
photoUrl: updated.photoKey,
|
||||||
|
notes: updated.groomingNotes,
|
||||||
|
coatType: updated.coatType,
|
||||||
|
petSizeCategory: updated.petSizeCategory,
|
||||||
|
healthAlerts: updated.healthAlerts,
|
||||||
|
preferredCuts: updated.preferredCuts,
|
||||||
|
medicalAlerts: updated.medicalAlerts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
portalRouter.get("/invoices", async (c) => {
|
portalRouter.get("/invoices", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const clientId = c.get("portalClientId");
|
||||||
|
|||||||
@@ -0,0 +1,419 @@
|
|||||||
|
import { decryptSecret } from "@groombook/db";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abstracted geocoding service layer (GRO-2153, Phase 1.2 of Route Optimization).
|
||||||
|
*
|
||||||
|
* Provides a provider-agnostic interface for turning a street address into
|
||||||
|
* latitude/longitude coordinates, with two concrete implementations:
|
||||||
|
*
|
||||||
|
* - {@link NominatimGeocodingProvider} — OpenStreetMap Nominatim (default, free,
|
||||||
|
* self-hostable). Enforces the public Nominatim usage policy of at most one
|
||||||
|
* request per second.
|
||||||
|
* - {@link GoogleGeocodingProvider} — Google Geocoding API (optional fallback,
|
||||||
|
* requires an API key stored encrypted at rest in `businessSettings`).
|
||||||
|
*
|
||||||
|
* Provider selection is driven by `businessSettings.routeOptimizationProvider`
|
||||||
|
* via {@link resolveGeocodingProvider}. A {@link geocodeBatch} helper geocodes a
|
||||||
|
* list of addresses while respecting the active provider's rate limit.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Identifier for a supported geocoding backend. Mirrors `route_optimization_provider`. */
|
||||||
|
export type GeocodingProviderName = "nominatim" | "google";
|
||||||
|
|
||||||
|
/** Successful geocoding result in WGS84 decimal degrees. */
|
||||||
|
export interface GeocodeResult {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
/** Provider-normalized display address, when available. */
|
||||||
|
formattedAddress: string | null;
|
||||||
|
/** Which provider produced this result. */
|
||||||
|
provider: GeocodingProviderName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Abstract geocoding provider contract. */
|
||||||
|
export interface GeocodingProvider {
|
||||||
|
/** Stable provider identifier. */
|
||||||
|
readonly name: GeocodingProviderName;
|
||||||
|
/**
|
||||||
|
* Minimum milliseconds to leave between consecutive requests. Used both by the
|
||||||
|
* provider's internal rate limiter and by {@link geocodeBatch} so callers do
|
||||||
|
* not need to know provider-specific limits.
|
||||||
|
*/
|
||||||
|
readonly minRequestIntervalMs: number;
|
||||||
|
/**
|
||||||
|
* Geocode a single address.
|
||||||
|
* @returns the top match, or `null` when the address is blank or unresolvable.
|
||||||
|
* @throws on transport failures or provider-level errors (e.g. quota, bad key).
|
||||||
|
*/
|
||||||
|
geocode(address: string): Promise<GeocodeResult | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Constants -------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Nominatim usage policy: at most 1 request per second. */
|
||||||
|
const NOMINATIM_RATE_LIMIT_MS = 1000;
|
||||||
|
const DEFAULT_NOMINATIM_BASE_URL = "https://nominatim.openstreetmap.org";
|
||||||
|
/** Nominatim requires a descriptive User-Agent identifying the application. */
|
||||||
|
const DEFAULT_NOMINATIM_USER_AGENT = "GroomBook/1.0 (+https://groombook.app route-optimization)";
|
||||||
|
|
||||||
|
const GOOGLE_GEOCODE_BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json";
|
||||||
|
/**
|
||||||
|
* Google permits a high request rate; a small floor keeps batch traffic polite
|
||||||
|
* without throttling interactive single calls.
|
||||||
|
*/
|
||||||
|
const GOOGLE_RATE_LIMIT_MS = 20;
|
||||||
|
|
||||||
|
// --- Injectable primitives (for testability) -------------------------------
|
||||||
|
|
||||||
|
/** Minimal `fetch` shape this module depends on. Defaults to the global `fetch`. */
|
||||||
|
export type FetchLike = (
|
||||||
|
input: string,
|
||||||
|
init?: { headers?: Record<string, string> }
|
||||||
|
) => Promise<{
|
||||||
|
ok: boolean;
|
||||||
|
status: number;
|
||||||
|
statusText: string;
|
||||||
|
json(): Promise<unknown>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
type NowFn = () => number;
|
||||||
|
type SleepFn = (ms: number) => Promise<void>;
|
||||||
|
|
||||||
|
const defaultSleep: SleepFn = (ms) =>
|
||||||
|
new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
const defaultFetch: FetchLike = (input, init) =>
|
||||||
|
(globalThis.fetch as unknown as FetchLike)(input, init);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serializes async tasks and guarantees at least `intervalMs` between the start
|
||||||
|
* of consecutive tasks. A failing task never wedges the queue.
|
||||||
|
*/
|
||||||
|
class RateLimiter {
|
||||||
|
// Negative infinity so the very first task never waits.
|
||||||
|
private last = Number.NEGATIVE_INFINITY;
|
||||||
|
private chain: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly intervalMs: number,
|
||||||
|
private readonly now: NowFn = Date.now,
|
||||||
|
private readonly sleep: SleepFn = defaultSleep
|
||||||
|
) {}
|
||||||
|
|
||||||
|
run<T>(task: () => Promise<T>): Promise<T> {
|
||||||
|
const result = this.chain.then(async () => {
|
||||||
|
if (this.intervalMs > 0) {
|
||||||
|
const elapsed = this.now() - this.last;
|
||||||
|
const wait = this.intervalMs - elapsed;
|
||||||
|
if (wait > 0) await this.sleep(wait);
|
||||||
|
}
|
||||||
|
this.last = this.now();
|
||||||
|
return task();
|
||||||
|
});
|
||||||
|
// Keep the queue alive regardless of whether this task resolves or rejects.
|
||||||
|
this.chain = result.then(
|
||||||
|
() => undefined,
|
||||||
|
() => undefined
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeAddress(address: string): string {
|
||||||
|
return address.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Nominatim provider ----------------------------------------------------
|
||||||
|
|
||||||
|
interface NominatimSearchRow {
|
||||||
|
lat?: string;
|
||||||
|
lon?: string;
|
||||||
|
display_name?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NominatimProviderOptions {
|
||||||
|
/** Override the Nominatim instance base URL (e.g. a self-hosted mirror). */
|
||||||
|
baseUrl?: string;
|
||||||
|
/** User-Agent header identifying this application, per Nominatim policy. */
|
||||||
|
userAgent?: string;
|
||||||
|
/** Minimum spacing between requests; defaults to the 1 req/sec policy. */
|
||||||
|
minRequestIntervalMs?: number;
|
||||||
|
fetchImpl?: FetchLike;
|
||||||
|
now?: NowFn;
|
||||||
|
sleep?: SleepFn;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NominatimGeocodingProvider implements GeocodingProvider {
|
||||||
|
readonly name = "nominatim" as const;
|
||||||
|
readonly minRequestIntervalMs: number;
|
||||||
|
|
||||||
|
private readonly baseUrl: string;
|
||||||
|
private readonly userAgent: string;
|
||||||
|
private readonly fetchImpl: FetchLike;
|
||||||
|
private readonly limiter: RateLimiter;
|
||||||
|
|
||||||
|
constructor(options: NominatimProviderOptions = {}) {
|
||||||
|
this.baseUrl = (options.baseUrl ?? DEFAULT_NOMINATIM_BASE_URL).replace(/\/+$/, "");
|
||||||
|
this.userAgent = options.userAgent ?? DEFAULT_NOMINATIM_USER_AGENT;
|
||||||
|
this.minRequestIntervalMs = options.minRequestIntervalMs ?? NOMINATIM_RATE_LIMIT_MS;
|
||||||
|
this.fetchImpl = options.fetchImpl ?? defaultFetch;
|
||||||
|
this.limiter = new RateLimiter(this.minRequestIntervalMs, options.now, options.sleep);
|
||||||
|
}
|
||||||
|
|
||||||
|
async geocode(address: string): Promise<GeocodeResult | null> {
|
||||||
|
const query = normalizeAddress(address);
|
||||||
|
if (!query) return null;
|
||||||
|
|
||||||
|
return this.limiter.run(async () => {
|
||||||
|
const url = new URL(`${this.baseUrl}/search`);
|
||||||
|
url.searchParams.set("q", query);
|
||||||
|
url.searchParams.set("format", "jsonv2");
|
||||||
|
url.searchParams.set("limit", "1");
|
||||||
|
|
||||||
|
const res = await this.fetchImpl(url.toString(), {
|
||||||
|
headers: { "User-Agent": this.userAgent },
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(
|
||||||
|
`Nominatim geocoding failed: ${res.status} ${res.statusText}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = (await res.json()) as NominatimSearchRow[];
|
||||||
|
if (!Array.isArray(body) || body.length === 0) return null;
|
||||||
|
|
||||||
|
const top = body[0]!;
|
||||||
|
const latitude = Number(top.lat);
|
||||||
|
const longitude = Number(top.lon);
|
||||||
|
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
latitude,
|
||||||
|
longitude,
|
||||||
|
formattedAddress: top.display_name ?? null,
|
||||||
|
provider: this.name,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Google provider -------------------------------------------------------
|
||||||
|
|
||||||
|
interface GoogleGeocodeResponse {
|
||||||
|
status: string;
|
||||||
|
error_message?: string;
|
||||||
|
results?: Array<{
|
||||||
|
formatted_address?: string;
|
||||||
|
geometry?: { location?: { lat?: number; lng?: number } };
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleProviderOptions {
|
||||||
|
baseUrl?: string;
|
||||||
|
minRequestIntervalMs?: number;
|
||||||
|
fetchImpl?: FetchLike;
|
||||||
|
now?: NowFn;
|
||||||
|
sleep?: SleepFn;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GoogleGeocodingProvider implements GeocodingProvider {
|
||||||
|
readonly name = "google" as const;
|
||||||
|
readonly minRequestIntervalMs: number;
|
||||||
|
|
||||||
|
private readonly apiKey: string;
|
||||||
|
private readonly baseUrl: string;
|
||||||
|
private readonly fetchImpl: FetchLike;
|
||||||
|
private readonly limiter: RateLimiter;
|
||||||
|
|
||||||
|
constructor(apiKey: string, options: GoogleProviderOptions = {}) {
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new Error("GoogleGeocodingProvider requires a non-empty API key");
|
||||||
|
}
|
||||||
|
this.apiKey = apiKey;
|
||||||
|
this.baseUrl = options.baseUrl ?? GOOGLE_GEOCODE_BASE_URL;
|
||||||
|
this.minRequestIntervalMs = options.minRequestIntervalMs ?? GOOGLE_RATE_LIMIT_MS;
|
||||||
|
this.fetchImpl = options.fetchImpl ?? defaultFetch;
|
||||||
|
this.limiter = new RateLimiter(this.minRequestIntervalMs, options.now, options.sleep);
|
||||||
|
}
|
||||||
|
|
||||||
|
async geocode(address: string): Promise<GeocodeResult | null> {
|
||||||
|
const query = normalizeAddress(address);
|
||||||
|
if (!query) return null;
|
||||||
|
|
||||||
|
return this.limiter.run(async () => {
|
||||||
|
const url = new URL(this.baseUrl);
|
||||||
|
url.searchParams.set("address", query);
|
||||||
|
url.searchParams.set("key", this.apiKey);
|
||||||
|
|
||||||
|
const res = await this.fetchImpl(url.toString());
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(
|
||||||
|
`Google geocoding failed: ${res.status} ${res.statusText}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = (await res.json()) as GoogleGeocodeResponse;
|
||||||
|
if (body.status === "ZERO_RESULTS") return null;
|
||||||
|
if (body.status !== "OK") {
|
||||||
|
const detail = body.error_message ? `: ${body.error_message}` : "";
|
||||||
|
throw new Error(`Google geocoding error: ${body.status}${detail}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const top = body.results?.[0];
|
||||||
|
const location = top?.geometry?.location;
|
||||||
|
const latitude = location?.lat;
|
||||||
|
const longitude = location?.lng;
|
||||||
|
if (
|
||||||
|
typeof latitude !== "number" ||
|
||||||
|
typeof longitude !== "number" ||
|
||||||
|
!Number.isFinite(latitude) ||
|
||||||
|
!Number.isFinite(longitude)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
latitude,
|
||||||
|
longitude,
|
||||||
|
formattedAddress: top?.formatted_address ?? null,
|
||||||
|
provider: this.name,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Provider selection ----------------------------------------------------
|
||||||
|
|
||||||
|
/** Subset of `businessSettings` relevant to geocoding provider selection. */
|
||||||
|
export interface GeocodingSettings {
|
||||||
|
routeOptimizationProvider?: string | null;
|
||||||
|
/** Google API key, encrypted at rest (AES-256-GCM via `encryptSecret`). */
|
||||||
|
googleMapsApiKey?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolveProviderOptions {
|
||||||
|
/** Decryption function for the stored Google key. Defaults to `decryptSecret`. */
|
||||||
|
decrypt?: (ciphertext: string) => string;
|
||||||
|
/** Options forwarded to the constructed provider (base URL, fetch, timing). */
|
||||||
|
nominatim?: NominatimProviderOptions;
|
||||||
|
google?: GoogleProviderOptions;
|
||||||
|
/** Sink for non-fatal selection warnings. Defaults to `console.warn`. */
|
||||||
|
warn?: (message: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the Google API key from settings (decrypting the at-rest value) or,
|
||||||
|
* as a development convenience, from the `GOOGLE_MAPS_API_KEY` env var.
|
||||||
|
* Returns `null` when no usable key is available.
|
||||||
|
*/
|
||||||
|
function resolveGoogleApiKey(
|
||||||
|
settings: GeocodingSettings,
|
||||||
|
decrypt: (ciphertext: string) => string,
|
||||||
|
warn: (message: string) => void
|
||||||
|
): string | null {
|
||||||
|
const stored = settings.googleMapsApiKey?.trim();
|
||||||
|
if (stored) {
|
||||||
|
try {
|
||||||
|
const decrypted = decrypt(stored).trim();
|
||||||
|
if (decrypted) return decrypted;
|
||||||
|
} catch (err) {
|
||||||
|
warn(
|
||||||
|
`Failed to decrypt googleMapsApiKey; falling back to Nominatim: ${
|
||||||
|
err instanceof Error ? err.message : String(err)
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fromEnv = process.env.GOOGLE_MAPS_API_KEY?.trim();
|
||||||
|
return fromEnv ? fromEnv : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Selects a geocoding provider based on `businessSettings.routeOptimizationProvider`.
|
||||||
|
*
|
||||||
|
* - `"google"` returns a {@link GoogleGeocodingProvider} when a usable key exists,
|
||||||
|
* otherwise warns and falls back to Nominatim.
|
||||||
|
* - Any other value (including `null`/`undefined`) returns a
|
||||||
|
* {@link NominatimGeocodingProvider}.
|
||||||
|
*/
|
||||||
|
export function resolveGeocodingProvider(
|
||||||
|
settings: GeocodingSettings | null | undefined,
|
||||||
|
options: ResolveProviderOptions = {}
|
||||||
|
): GeocodingProvider {
|
||||||
|
const warn = options.warn ?? ((message: string) => console.warn(message));
|
||||||
|
const decrypt = options.decrypt ?? decryptSecret;
|
||||||
|
const requested = settings?.routeOptimizationProvider ?? "nominatim";
|
||||||
|
|
||||||
|
if (requested === "google") {
|
||||||
|
const apiKey = resolveGoogleApiKey(settings ?? {}, decrypt, warn);
|
||||||
|
if (apiKey) {
|
||||||
|
return new GoogleGeocodingProvider(apiKey, options.google);
|
||||||
|
}
|
||||||
|
warn(
|
||||||
|
"routeOptimizationProvider is 'google' but no usable API key was found; falling back to Nominatim"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new NominatimGeocodingProvider(options.nominatim);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Batch geocoding -------------------------------------------------------
|
||||||
|
|
||||||
|
/** Input item for {@link geocodeBatch}: a caller-defined key and its address. */
|
||||||
|
export interface BatchGeocodeItem<K> {
|
||||||
|
key: K;
|
||||||
|
address: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-item outcome from {@link geocodeBatch}. */
|
||||||
|
export interface BatchGeocodeOutcome<K> {
|
||||||
|
key: K;
|
||||||
|
address: string;
|
||||||
|
/** Resolved coordinates, or `null` when unresolvable. */
|
||||||
|
result: GeocodeResult | null;
|
||||||
|
/** Present when the geocode call threw; the batch continues past errors. */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GeocodeBatchOptions<K> {
|
||||||
|
/** Invoked after each item completes; useful for progress reporting. */
|
||||||
|
onProgress?: (
|
||||||
|
completed: number,
|
||||||
|
total: number,
|
||||||
|
outcome: BatchGeocodeOutcome<K>
|
||||||
|
) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Geocodes a list of addresses sequentially through the given provider. The
|
||||||
|
* provider's internal rate limiter enforces throttling (e.g. Nominatim's
|
||||||
|
* 1 req/sec), so addresses are processed one at a time and individual failures
|
||||||
|
* are captured per item rather than aborting the whole batch.
|
||||||
|
*/
|
||||||
|
export async function geocodeBatch<K>(
|
||||||
|
items: ReadonlyArray<BatchGeocodeItem<K>>,
|
||||||
|
provider: GeocodingProvider,
|
||||||
|
options: GeocodeBatchOptions<K> = {}
|
||||||
|
): Promise<Array<BatchGeocodeOutcome<K>>> {
|
||||||
|
const outcomes: Array<BatchGeocodeOutcome<K>> = [];
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
let outcome: BatchGeocodeOutcome<K>;
|
||||||
|
try {
|
||||||
|
const result = await provider.geocode(item.address);
|
||||||
|
outcome = { key: item.key, address: item.address, result };
|
||||||
|
} catch (err) {
|
||||||
|
outcome = {
|
||||||
|
key: item.key,
|
||||||
|
address: item.address,
|
||||||
|
result: null,
|
||||||
|
error: err instanceof Error ? err.message : String(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outcomes.push(outcome);
|
||||||
|
options.onProgress?.(outcomes.length, items.length, outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user