Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(settings): timezone picker searches by CST/EST/IST; list cached in memory

Sidwebworksd941275b6999
diff --git a/apps/erp/app/components/Form/Timezone.tsx b/apps/erp/app/components/Form/Timezone.tsx
index 84d5e21da5..a3a86e3ac5 100644
--- a/apps/erp/app/components/Form/Timezone.tsx
+++ b/apps/erp/app/components/Form/Timezone.tsx
@@ -29,10 +29,11 @@ const Timezone = (props: ComponentProps<typeof TimezoneBase>) => {
const [region = "Other", ...rest] = name.split("/");
const city = rest.join("/").replace(/_/g, " ");
const group = rest.length === 0 ? "Other" : region;
- // pg interval text: "05:30:00" / "-06:00:00" / "00:00:00"
+ // pg interval text: "05:30:00" / "-06:00:00" / "00:00:00" → "±HH:MM"
+ // (relative-to-UTC is implied; no "UTC" prefix noise in the label)
const offset = utcOffset.startsWith("-")
- ? `UTC-${utcOffset.slice(1, 6)}`
- : `UTC+${utcOffset.slice(0, 5)}`;
+ ? `-${utcOffset.slice(1, 6)}`
+ : `+${utcOffset.slice(0, 5)}`;
const label = `${city || name} (${offset})`;
const list = groups.get(group) ?? [];
list.push({ label, value: name });
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index 2c001bf6f4..226cb84191 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -98,39 +98,33 @@ export async function getCustomFieldsSchemas(
return result;
}
-const TIMEZONES_CACHE_KEY = "timezones:v1";
// tzdata only changes when the Postgres image is upgraded — a day-long TTL
// keeps the pg_timezone_names scan (~1ms but per-request) off the hot path
// while still picking up a DB upgrade within 24h.
-const TIMEZONES_CACHE_TTL_SECONDS = 60 * 60 * 24;
+const TIMEZONES_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
+let cachedTimezoneNames: {
+ data: { name: string; utcOffset: string }[];
+ fetchedAt: number;
+} | null = null;
/**
- * Redis-cached wrapper around the get_timezone_names RPC (pg_timezone_names).
- * The list is global (not company-scoped). Follows the getCustomFieldsSchemas
- * pattern: a miss, unreachable Redis (the @carbon/kv resilience wrapper fails
- * soft), or a corrupt entry all fall through to the database.
+ * In-memory memo of the get_timezone_names RPC (pg_timezone_names). The list
+ * is global (not company-scoped), identical for every tenant, and never
+ * invalidated by user action — so a per-process memo beats Redis: no network
+ * round-trip, nothing to invalidate, and a cold start simply refetches
+ * (~1ms scan). A failed fetch is returned as-is and not cached.
*/
export async function getCachedTimezoneNames(client: SupabaseClient<Database>) {
- const cached = await redis.get(TIMEZONES_CACHE_KEY);
- if (cached) {
- try {
- return {
- data: JSON.parse(cached) as { name: string; utcOffset: string }[],
- error: null
- };
- } catch {
- // Corrupt cache entry — fall through to the source of truth.
- }
+ if (
+ cachedTimezoneNames &&
+ Date.now() - cachedTimezoneNames.fetchedAt < TIMEZONES_CACHE_TTL_MS
+ ) {
+ return { data: cachedTimezoneNames.data, error: null };
}
const result = await getTimezoneNames(client);
if (result.data?.length) {
- await redis.set(
- TIMEZONES_CACHE_KEY,
- JSON.stringify(result.data),
- "EX",
- TIMEZONES_CACHE_TTL_SECONDS
- );
+ cachedTimezoneNames = { data: result.data, fetchedAt: Date.now() };
}
return result;
diff --git a/packages/form/src/components/Timezone.tsx b/packages/form/src/components/Timezone.tsx
index 537d80f5d1..631dfe3a2b 100644
--- a/packages/form/src/components/Timezone.tsx
+++ b/packages/form/src/components/Timezone.tsx
@@ -1,4 +1,8 @@
-import { getTimezones, type TimezoneGroup } from "@carbon/utils";
+import {
+ getTimezoneAbbreviations,
+ getTimezones,
+ type TimezoneGroup
+} from "@carbon/utils";
import { useMemo } from "react";
import type { ComboboxProps } from "./Combobox";
import Combobox from "./Combobox";
@@ -14,19 +18,25 @@ type TimezoneProps = Omit<ComboboxProps, "options"> & {
/**
* Searchable timezone picker. Options are flattened to full IANA names with
- * the current offset ("America/Chicago (UTC-06:00)") so search matches by
- * city, region, or offset.
+ * their colloquial abbreviations and current offset —
+ * "America/Chicago (CST/CDT, -06:00)" — so search matches by city, region,
+ * offset, or the abbreviation people actually type (CST, EST, IST, …). The
+ * offset is relative to UTC by definition, so no "UTC" prefix.
*/
const Timezone = ({ options, ...props }: TimezoneProps) => {
const flatOptions = useMemo(() => {
const groups = options?.length ? options : getTimezones();
return groups.flatMap((group) =>
group.options.map((option) => {
- const offset = /\(UTC[^)]*\)/.exec(option.label)?.[0];
+ const offset = /[+-]\d{2}:\d{2}/.exec(option.label)?.[0];
+ const abbreviations = getTimezoneAbbreviations(option.value)
+ .filter((a) => a !== option.value)
+ .join("/");
+ const detail = [abbreviations, offset].filter(Boolean).join(", ");
return {
value: option.value,
label: `${option.value.replace(/_/g, " ")}${
- offset ? ` ${offset}` : ""
+ detail ? ` (${detail})` : ""
}`
};
})
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 7d7690c724..10f87c0371 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -221,16 +221,26 @@ function VirtualizedCommand({
const parentRef = useRef<HTMLDivElement>(null);
const filteredOptions = useMemo(() => {
- return search
- ? options.filter((option) => {
- const value =
- typeof option.label === "string"
- ? `${option.label} ${option.helper}`
- : reactNodeToString(option.label);
-
- return value.toLowerCase().includes(search.toLowerCase());
- })
- : options;
+ if (!search) return options;
+ const query = search.toLowerCase();
+ // Rank word-boundary hits above mid-word substrings, then earlier hits
+ // first — searching "EST" should surface "(EST/EDT, …)" timezones before
+ // cities that merely contain "est" (Creston, Bucharest…). Stable sort, so
+ // equally-ranked options keep their original order.
+ const scored: { option: (typeof options)[number]; score: number }[] = [];
+ for (const option of options) {
+ const text = (
+ typeof option.label === "string"
+ ? `${option.label} ${option.helper}`
+ : reactNodeToString(option.label)
+ ).toLowerCase();
+ const index = text.indexOf(query);
+ if (index === -1) continue;
+ const atWordStart =
+ index === 0 || !/[a-z0-9]/.test(text.charAt(index - 1));
+ scored.push({ option, score: (atWordStart ? 0 : 100000) + index });
+ }
+ return scored.sort((a, b) => a.score - b.score).map((s) => s.option);
}, [options, search]);
const virtualizer = useVirtualizer({
diff --git a/packages/utils/src/geo.test.ts b/packages/utils/src/geo.test.ts
new file mode 100644
index 0000000000..49a759d44f
--- /dev/null
+++ b/packages/utils/src/geo.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+import { getTimezoneAbbreviations, getTimezones, isValidTimeZone } from "./geo";
+
+describe("getTimezoneAbbreviations", () => {
+ it("returns the colloquial abbreviations people search by", () => {
+ // US zones: both standard and daylight from Intl's short names.
+ expect(getTimezoneAbbreviations("America/Chicago")).toEqual(["CST", "CDT"]);
+ expect(getTimezoneAbbreviations("America/New_York")).toEqual([
+ "EST",
+ "EDT"
+ ]);
+ // Zones where en-US short is a GMT offset: derived from the long name's
+ // initials — the user-facing point of the feature.
+ expect(getTimezoneAbbreviations("Asia/Calcutta")).toEqual(["IST"]);
+ expect(getTimezoneAbbreviations("Asia/Tokyo")).toEqual(["JST"]);
+ // The generic (qualifier-stripped) form is included so "CET" finds
+ // Berlin/Paris even though the long names give CEST.
+ expect(getTimezoneAbbreviations("Europe/Berlin")).toContain("CET");
+ expect(getTimezoneAbbreviations("Australia/Sydney")).toContain("AEST");
+ expect(getTimezoneAbbreviations("Europe/London")).toEqual(["GMT", "BST"]);
+ expect(getTimezoneAbbreviations("UTC")).toEqual(["UTC"]);
+ });
+
+ it("returns [] for unresolvable zones instead of throwing", () => {
+ expect(getTimezoneAbbreviations("Fake/Zone")).toEqual([]);
+ });
+});
+
+describe("getTimezones", () => {
+ it("labels read '(abbreviations, ±HH:MM)' — no redundant UTC prefix", () => {
+ const all = getTimezones().flatMap((g) => g.options);
+ const chicago = all.find((o) => o.value === "America/Chicago");
+ expect(chicago?.label).toMatch(/\(CST\/CDT, [+-]\d{2}:\d{2}\)$/);
+ expect(chicago?.label).not.toContain("UTC");
+ const kolkata = all.find(
+ (o) => o.value === "Asia/Calcutta" || o.value === "Asia/Kolkata"
+ );
+ expect(kolkata?.label).toContain("IST");
+ });
+
+ it("drops an abbreviation identical to the zone name (UTC, GMT)", () => {
+ const all = getTimezones().flatMap((g) => g.options);
+ const utc = all.find((o) => o.value === "UTC");
+ // "UTC (+00:00)", not "UTC (UTC, +00:00)"
+ expect(utc?.label).toBe("UTC (+00:00)");
+ });
+});
+
+describe("isValidTimeZone", () => {
+ it("accepts IANA names and rejects garbage", () => {
+ expect(isValidTimeZone("America/Chicago")).toBe(true);
+ expect(isValidTimeZone("Fake/Zone")).toBe(false);
+ });
+});
diff --git a/packages/utils/src/geo.ts b/packages/utils/src/geo.ts
index 3ad4373f9f..4cdb6a92ef 100644
--- a/packages/utils/src/geo.ts
+++ b/packages/utils/src/geo.ts
@@ -18,13 +18,75 @@ function offsetLabel(zone: string): string {
timeZoneName: "longOffset"
}).formatToParts(new Date());
const name = parts.find((p) => p.type === "timeZoneName")?.value ?? "";
- // "GMT" (UTC itself) and "GMT-06:00" → "UTC±HH:MM"
- return name === "GMT" ? "UTC+00:00" : name.replace("GMT", "UTC");
+ // "GMT" (UTC itself) and "GMT-06:00" → "±HH:MM" (relative-to-UTC implied)
+ return name === "GMT" ? "+00:00" : name.replace("GMT", "");
} catch {
return "";
}
}
+const timeZoneNameOf = (
+ zone: string,
+ style: "short" | "long",
+ month: number
+): string => {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: zone,
+ timeZoneName: style
+ }).formatToParts(new Date(Date.UTC(new Date().getUTCFullYear(), month, 15)));
+ return parts.find((p) => p.type === "timeZoneName")?.value ?? "";
+};
+
+const ABBREVIATION = /^[A-Za-z]{2,6}$/;
+const abbreviationCache = new Map<string, string[]>();
+
+/**
+ * Colloquial abbreviations for a zone — what people actually type into the
+ * picker: CST/CDT, EST, PST, IST, JST, AEST… Sampled in January AND July so
+ * both the standard and daylight names appear. US-style zones get them from
+ * Intl's `short` name directly; zones where en-US `short` is a "GMT+5:30"
+ * offset (India, Japan, Australia…) derive them from the `long` name's
+ * initials ("India Standard Time" → IST). Memoized — abbreviations don't
+ * change within a session.
+ */
+export function getTimezoneAbbreviations(zone: string): string[] {
+ const cached = abbreviationCache.get(zone);
+ if (cached) return cached;
+
+ const abbreviations: string[] = [];
+ const add = (abbreviation: string) => {
+ if (
+ ABBREVIATION.test(abbreviation) &&
+ !abbreviations.includes(abbreviation)
+ ) {
+ abbreviations.push(abbreviation);
+ }
+ };
+ try {
+ for (const month of [0, 6]) {
+ const short = timeZoneNameOf(zone, "short", month);
+ if (ABBREVIATION.test(short)) {
+ add(short);
+ continue;
+ }
+ const words = timeZoneNameOf(zone, "long", month).split(/\s+/);
+ add(words.map((word) => word[0]).join(""));
+ // The generic form too — "Central European Standard Time" gives CEST,
+ // but people search CET. Skip when it collapses below 3 letters (CT,
+ // IT…) — too short to be a useful search token.
+ const generic = words
+ .filter((word) => !/^(Standard|Summer|Daylight)$/i.test(word))
+ .map((word) => word[0])
+ .join("");
+ if (generic.length >= 3) add(generic);
+ }
+ } catch {
+ // Unresolvable zone — no abbreviations.
+ }
+ abbreviationCache.set(zone, abbreviations);
+ return abbreviations;
+}
+
let cachedTimezones: TimezoneGroup[] | null = null;
let cachedAt = 0;
// Offset labels show the CURRENT UTC offset, which changes at DST transitions —
@@ -58,9 +120,15 @@ export function getTimezones(): TimezoneGroup[] {
const city = rest.join("/").replace(/_/g, " ");
const group = rest.length === 0 ? "Other" : region;
const offset = offsetLabel(zone);
- const label = city
- ? `${city}${offset ? ` (${offset})` : ""}`
- : `${zone}${offset ? ` (${offset})` : ""}`;
+ // "CST/CDT, -06:00" — abbreviations first so typing "CST" finds the zone
+ // instead of matching stray letters in other city names; the offset is
+ // relative to UTC by definition, so no prefix. An abbreviation identical
+ // to the zone name (UTC, GMT) adds nothing and is dropped.
+ const abbreviations = getTimezoneAbbreviations(zone)
+ .filter((a) => a !== zone)
+ .join("/");
+ const detail = [abbreviations, offset].filter(Boolean).join(", ");
+ const label = `${city || zone}${detail ? ` (${detail})` : ""}`;
const options = groups.get(group) ?? [];
options.push({ label, value: zone });
groups.set(group, options);