@eintrek/erp-shell 0.1.62 → 0.1.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,19 +1,20 @@
1
1
  'use client';
2
2
  import * as React from 'react';
3
- import React__default, { useRef, useEffect, useMemo, useState, useCallback, createContext, useContext, Fragment, useSyncExternalStore, useTransition, Suspense } from 'react';
3
+ import React__default, { useRef, useEffect, useMemo, useState, useCallback, createContext, useContext, Fragment, useSyncExternalStore, useTransition, useLayoutEffect, Suspense } from 'react';
4
4
  import { useSession, signOut } from 'next-auth/react';
5
- import { useQueryClient, useQuery, QueryClientContext, QueryClient, hashKey, MutationCache, QueryCache, QueryClientProvider } from '@tanstack/react-query';
5
+ import { useQueryClient, useQuery, QueryClientContext, QueryClient, useIsFetching, hashKey, MutationCache, QueryCache, QueryClientProvider } from '@tanstack/react-query';
6
6
  import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
7
7
  import { cn, Button, Tooltip, TooltipTrigger, TooltipContent, Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbSeparator, BreadcrumbPage, Avatar, AvatarImage, AvatarFallback, Collapsible, CollapsibleTrigger, CollapsibleContent, Badge, DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuLabel, DropdownMenuItem, DropdownMenuSeparator, Skeleton, Dialog, DialogContent, DialogHeader, DialogTitle, Label, Textarea, DialogFooter, Card, CardHeader, CardContent } from '@eintrek/erp-theme';
8
- import { PanelLeftClose, Menu, ChevronRight, Building2, Palette, ChevronUp, Sun, Moon, Monitor, Globe, UserCog, LayoutGrid, ExternalLink, CircleHelp, Loader2, LogOut, Calculator, Warehouse, FolderKanban, Users, Store, Headset, ChevronDown, Plus, ChevronsUpDown, ImagePlus, X, CircleCheck, ArrowLeft, Ban, Home, ArrowRight, Compass, ArrowUpRight, ContactRound, UserPlus } from 'lucide-react';
8
+ import { PanelLeftClose, Menu, ChevronRight, Building2, Palette, ChevronUp, Sun, Moon, Monitor, Globe, UserCog, LayoutGrid, ExternalLink, CircleHelp, Loader2, LogOut, Calculator, Warehouse, FolderKanban, Users, Store, Headset, ChevronDown, Plus, ChevronsUpDown, Flag, MessageCircle, ImagePlus, X, CircleCheck, ArrowLeft, Ban, Home, ContactRound, UserPlus, ArrowRight, Compass, ArrowUpRight } from 'lucide-react';
9
9
  import { create } from 'zustand';
10
10
  import { persist, createJSONStorage } from 'zustand/middleware';
11
- import { useRouter, usePathname, useParams } from 'next/navigation';
11
+ import { useRouter, usePathname, useParams, useSearchParams } from 'next/navigation';
12
12
  import Link from 'next/link';
13
13
  import { createPortal } from 'react-dom';
14
14
  import { useTheme, ThemeProvider as ThemeProvider$1 } from 'next-themes';
15
15
  import axios, { isAxiosError, AxiosHeaders } from 'axios';
16
16
  export { isAxiosError } from 'axios';
17
+ import { computePosition, offset, shift, arrow } from '@floating-ui/dom';
17
18
  import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
18
19
 
19
20
  /**
@@ -733,7 +734,7 @@ function SidebarFooter({ children, className }) {
733
734
  */
734
735
  function SidebarTrigger({ className }) {
735
736
  const { open, toggle } = useSidebar();
736
- return (jsx("button", { onClick: toggle, className: cn("inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground h-8 w-8 md:h-9 md:w-9 -ml-1", className), "aria-label": open ? "ปิดเมนู" : "เปิดเมนู", children: open ? (jsx(PanelLeftClose, { className: "h-4 w-4 text-primary-foreground" })) : (jsx(Menu, { className: "h-4 w-4 text-primary-foreground" })) }));
737
+ return (jsx("button", { onClick: toggle, className: cn("inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground h-8 w-8 md:h-9 md:w-9 -ml-1", className), "aria-label": open ? "ปิดเมนู" : "เปิดเมนู", "data-guide": "shell.menu-toggle", children: open ? (jsx(PanelLeftClose, { className: "h-4 w-4 text-primary-foreground" })) : (jsx(Menu, { className: "h-4 w-4 text-primary-foreground" })) }));
737
738
  }
738
739
 
739
740
  /**
@@ -1258,35 +1259,35 @@ let declaredApp = null;
1258
1259
  // The message the dialog should open on (the ตอบกลับ link's ?help=H1004),
1259
1260
  // until it is closed or left.
1260
1261
  let pendingRef = null;
1261
- const listeners = new Set();
1262
- function emit() {
1263
- listeners.forEach(l => l());
1262
+ const listeners$1 = new Set();
1263
+ function emit$1() {
1264
+ listeners$1.forEach(l => l());
1264
1265
  }
1265
- function subscribe(l) {
1266
- listeners.add(l);
1266
+ function subscribe$1(l) {
1267
+ listeners$1.add(l);
1267
1268
  return () => {
1268
- listeners.delete(l);
1269
+ listeners$1.delete(l);
1269
1270
  };
1270
1271
  }
1271
1272
  /** Opens the dialog — a no-op when no layout has mounted one. */
1272
1273
  function openHelp() {
1273
1274
  if (!open) {
1274
1275
  open = true;
1275
- emit();
1276
+ emit$1();
1276
1277
  }
1277
1278
  }
1278
1279
  function closeHelp() {
1279
1280
  pendingRef = null;
1280
1281
  if (open) {
1281
1282
  open = false;
1282
- emit();
1283
+ emit$1();
1283
1284
  }
1284
1285
  }
1285
1286
  /** Opens the dialog on one of the person's messages, by id or "H1004". */
1286
1287
  function openHelpOn(ref) {
1287
1288
  pendingRef = ref;
1288
1289
  open = true;
1289
- emit();
1290
+ emit$1();
1290
1291
  }
1291
1292
  /** The message the dialog was asked to open on, if it has not been left. */
1292
1293
  function pendingHelpRef() {
@@ -1305,22 +1306,22 @@ function registerHelpHost() {
1305
1306
  hosts += 1;
1306
1307
  if (pendingRef)
1307
1308
  open = true;
1308
- emit();
1309
+ emit$1();
1309
1310
  return () => {
1310
1311
  hosts -= 1;
1311
1312
  if (hosts <= 0) {
1312
1313
  hosts = 0;
1313
1314
  open = false;
1314
1315
  }
1315
- emit();
1316
+ emit$1();
1316
1317
  };
1317
1318
  }
1318
1319
  function useHelpOpen() {
1319
- return useSyncExternalStore(subscribe, () => open, () => false);
1320
+ return useSyncExternalStore(subscribe$1, () => open, () => false);
1320
1321
  }
1321
1322
  /** True while a dialog host is mounted, i.e. the ช่วยเหลือ entry works. */
1322
1323
  function useHelpAvailable() {
1323
- return useSyncExternalStore(subscribe, () => hosts > 0, () => false);
1324
+ return useSyncExternalStore(subscribe$1, () => hosts > 0, () => false);
1324
1325
  }
1325
1326
  /**
1326
1327
  * Every app names itself when it builds its app-switcher links
@@ -1344,17 +1345,17 @@ function declaredHelpApp() {
1344
1345
  const OWNER_CHIP = "เจ้าของ";
1345
1346
  /** How many role names the card spells out before counting the rest. */
1346
1347
  const CARD_ROLE_LIMIT = 2;
1347
- const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1348
+ const isRecord$2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1348
1349
  /**
1349
1350
  * The answer, checked. Anything that is not the shape the card needs — an
1350
1351
  * older API, a proxy's error page, another organisation's answer — is null,
1351
1352
  * and the card shows no role line.
1352
1353
  */
1353
1354
  function parseMyRoles(payload, organizationId) {
1354
- if (!isRecord(payload))
1355
+ if (!isRecord$2(payload))
1355
1356
  return null;
1356
1357
  // Envelope { success, data } or the bare data.
1357
- const data = isRecord(payload.data) ? payload.data : payload;
1358
+ const data = isRecord$2(payload.data) ? payload.data : payload;
1358
1359
  if (!Array.isArray(data.roles))
1359
1360
  return null;
1360
1361
  if (typeof data.organization_id === "string" && data.organization_id !== organizationId) {
@@ -1363,7 +1364,7 @@ function parseMyRoles(payload, organizationId) {
1363
1364
  const roles = [];
1364
1365
  const seen = new Set();
1365
1366
  for (const r of data.roles) {
1366
- if (!isRecord(r))
1367
+ if (!isRecord$2(r))
1367
1368
  continue;
1368
1369
  const name = typeof r.name_th === "string" ? r.name_th.trim() : "";
1369
1370
  const key = typeof r.key === "string" ? r.key : "";
@@ -1584,6 +1585,242 @@ async function retryWithStoredOrganizations(config, status, send) {
1584
1585
  return undefined;
1585
1586
  }
1586
1587
 
1588
+ /**
1589
+ * Route and API-path patterns for tour steps.
1590
+ *
1591
+ * No runtime imports: the tests run this file in Node as it is.
1592
+ */
1593
+ const trimSlash = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p);
1594
+ function splitPattern(pattern) {
1595
+ const q = pattern.indexOf("?");
1596
+ if (q < 0)
1597
+ return { path: pattern, query: new URLSearchParams() };
1598
+ return { path: pattern.slice(0, q), query: new URLSearchParams(pattern.slice(q + 1)) };
1599
+ }
1600
+ function paramName(segment) {
1601
+ const bracket = /^\[([A-Za-z0-9_]+)\]$/.exec(segment);
1602
+ if (bracket)
1603
+ return bracket[1];
1604
+ const colon = /^:([A-Za-z0-9_]+)$/.exec(segment);
1605
+ return colon ? colon[1] : null;
1606
+ }
1607
+ function safeDecode(s) {
1608
+ try {
1609
+ return decodeURIComponent(s);
1610
+ }
1611
+ catch {
1612
+ return s;
1613
+ }
1614
+ }
1615
+ /**
1616
+ * Matches a Next-style page pattern ("/[code]/employee/[id]", optionally
1617
+ * "?tab=job") against a path and query. `[code]`, when given, must be the
1618
+ * organisation code. Returns the params, or null.
1619
+ */
1620
+ function matchRoute(pattern, pathname, search, code) {
1621
+ const { path, query } = splitPattern(pattern);
1622
+ const want = trimSlash(path).split("/");
1623
+ const have = trimSlash(pathname || "/").split("/");
1624
+ if (want.length !== have.length)
1625
+ return null;
1626
+ const params = {};
1627
+ for (let i = 0; i < want.length; i++) {
1628
+ const name = paramName(want[i]);
1629
+ if (name) {
1630
+ if (!have[i])
1631
+ return null;
1632
+ params[name] = safeDecode(have[i]);
1633
+ continue;
1634
+ }
1635
+ if (want[i] !== have[i])
1636
+ return null;
1637
+ }
1638
+ if (code !== undefined && params.code !== undefined && params.code !== code) {
1639
+ return null;
1640
+ }
1641
+ if ([...query.keys()].length > 0) {
1642
+ const s = search instanceof URLSearchParams ? search : new URLSearchParams(search ?? "");
1643
+ for (const [k, v] of query.entries()) {
1644
+ if (s.get(k) !== v)
1645
+ return null;
1646
+ }
1647
+ }
1648
+ return params;
1649
+ }
1650
+ /** Fills a page pattern's params ("/[code]/x/[id]" → "/O1/x/42"); null if one is missing. */
1651
+ function fillRoute(pattern, params) {
1652
+ const { path, query } = splitPattern(pattern);
1653
+ const out = [];
1654
+ for (const seg of path.split("/")) {
1655
+ const name = paramName(seg);
1656
+ if (!name) {
1657
+ out.push(seg);
1658
+ continue;
1659
+ }
1660
+ const v = params[name];
1661
+ if (!v)
1662
+ return null;
1663
+ out.push(encodeURIComponent(v));
1664
+ }
1665
+ const qs = query.toString();
1666
+ return out.join("/") + (qs ? `?${qs}` : "");
1667
+ }
1668
+ /**
1669
+ * The path of a request, without origin, base URL query or hash:
1670
+ * ("/shifts/4", "https://hr-api/api/v1") → "/api/v1/shifts/4".
1671
+ */
1672
+ function requestPath(url, baseURL) {
1673
+ const raw = url ?? "";
1674
+ let full = raw;
1675
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) && baseURL) {
1676
+ full = baseURL.replace(/\/+$/, "") + "/" + raw.replace(/^\/+/, "");
1677
+ }
1678
+ try {
1679
+ return trimSlash(new URL(full, "http://local.invalid").pathname);
1680
+ }
1681
+ catch {
1682
+ return trimSlash(full.split(/[?#]/)[0] || "/");
1683
+ }
1684
+ }
1685
+ /**
1686
+ * Whether a request path matches a step's API path: the pattern's segments
1687
+ * must be the END of the path ("/shifts/[id]" matches "/api/v1/shifts/42");
1688
+ * `[x]`/`:x` is one segment, `*` any number (including none). A RegExp is
1689
+ * tested against the whole path.
1690
+ */
1691
+ function matchApiPath(pattern, path) {
1692
+ if (pattern instanceof RegExp)
1693
+ return pattern.test(path);
1694
+ const want = trimSlash(pattern).split("/").filter(Boolean);
1695
+ const have = trimSlash(path).split("/").filter(Boolean);
1696
+ // Try every suffix of the path as the place the pattern starts.
1697
+ for (let start = 0; start <= have.length; start++) {
1698
+ if (matchSegments(want, 0, have, start))
1699
+ return true;
1700
+ }
1701
+ return false;
1702
+ }
1703
+ function matchSegments(want, wi, have, hi) {
1704
+ if (wi === want.length)
1705
+ return hi === have.length;
1706
+ const seg = want[wi];
1707
+ if (seg === "*") {
1708
+ for (let k = hi; k <= have.length; k++) {
1709
+ if (matchSegments(want, wi + 1, have, k))
1710
+ return true;
1711
+ }
1712
+ return false;
1713
+ }
1714
+ if (hi >= have.length)
1715
+ return false;
1716
+ if (paramName(seg) || seg === have[hi])
1717
+ return matchSegments(want, wi + 1, have, hi + 1);
1718
+ return false;
1719
+ }
1720
+ /** "2xx" or an exact status. */
1721
+ function matchStatus(want, status) {
1722
+ if (want === undefined || want === "2xx")
1723
+ return status >= 200 && status < 300;
1724
+ return status === want;
1725
+ }
1726
+
1727
+ /**
1728
+ * The tour's event bus and anchor helper — the parts an app calls.
1729
+ *
1730
+ * - `guideAnchor(key, id?)` → `{ "data-guide": key, "data-guide-id"?: id }`
1731
+ * - `emitGuideEvent(name, detail?)` → window CustomEvent `erp:guide:<name>`
1732
+ * - `reportApiEvent(responseOrError)` → window CustomEvent `erp:api`, which
1733
+ * the shell's own axios instance already sends for every answer. An app
1734
+ * with a second axios instance calls it from that instance's interceptor.
1735
+ *
1736
+ * Only method, path, status, the saved record's id and (on a refusal) the
1737
+ * server's message go on the bus — never a request or response body.
1738
+ *
1739
+ * No runtime imports beyond sibling pure modules.
1740
+ */
1741
+ const GUIDE_ATTRIBUTE = "data-guide";
1742
+ const GUIDE_ID_ATTRIBUTE = "data-guide-id";
1743
+ const GUIDE_LAYER_ATTRIBUTE = "data-erp-guide-layer";
1744
+ const API_EVENT = "erp:api";
1745
+ const GUIDE_EVENT_PREFIX = "erp:guide:";
1746
+ /** Spread onto the element a tour step points at. */
1747
+ function guideAnchor(key, id) {
1748
+ return id === undefined || id === null || id === ""
1749
+ ? { [GUIDE_ATTRIBUTE]: key }
1750
+ : { [GUIDE_ATTRIBUTE]: key, [GUIDE_ID_ATTRIBUTE]: String(id) };
1751
+ }
1752
+ /** Announces an app event a step can wait for (`advanceOn: { event: name }`). */
1753
+ function emitGuideEvent(name, detail) {
1754
+ if (typeof window === "undefined" || !name)
1755
+ return;
1756
+ const clean = {};
1757
+ for (const [k, v] of Object.entries(detail ?? {})) {
1758
+ if (typeof v === "string" || typeof v === "number")
1759
+ clean[k] = String(v);
1760
+ }
1761
+ try {
1762
+ window.dispatchEvent(new CustomEvent(GUIDE_EVENT_PREFIX + name, { detail: clean }));
1763
+ }
1764
+ catch {
1765
+ /* never let the tour break the app */
1766
+ }
1767
+ }
1768
+ const isRecord$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1769
+ function idOf(data) {
1770
+ const pick = (v) => typeof v === "string" && v ? v : typeof v === "number" ? String(v) : undefined;
1771
+ if (!isRecord$1(data))
1772
+ return undefined;
1773
+ return pick(data.id) ?? (isRecord$1(data.data) ? pick(data.data.id) : undefined);
1774
+ }
1775
+ function messageOf(data) {
1776
+ if (!isRecord$1(data))
1777
+ return undefined;
1778
+ const m = data.message ?? (isRecord$1(data.error) ? data.error.message : data.error);
1779
+ return typeof m === "string" && m.trim() ? m.trim().slice(0, 200) : undefined;
1780
+ }
1781
+ /** The bus detail for an axios answer or error; null when it is neither. */
1782
+ function apiEventDetail(responseOrError) {
1783
+ if (!isRecord$1(responseOrError))
1784
+ return null;
1785
+ const err = responseOrError;
1786
+ // An AxiosError has .response (or none: network failure) and .config.
1787
+ const isError = "isAxiosError" in responseOrError || ("response" in responseOrError && !("data" in responseOrError));
1788
+ const res = isError ? err.response : responseOrError;
1789
+ const config = (res?.config ?? err.config);
1790
+ if (!config)
1791
+ return null;
1792
+ const status = typeof res?.status === "number" ? res.status : 0;
1793
+ const detail = {
1794
+ method: (config.method ?? "get").toUpperCase(),
1795
+ path: requestPath(config.url, config.baseURL),
1796
+ status,
1797
+ };
1798
+ if (status >= 200 && status < 300) {
1799
+ const id = idOf(res?.data);
1800
+ if (id)
1801
+ detail.id = id;
1802
+ }
1803
+ else {
1804
+ const msg = messageOf(res?.data);
1805
+ if (msg)
1806
+ detail.message = msg;
1807
+ }
1808
+ return detail;
1809
+ }
1810
+ /** Puts an axios answer (or error) on the bus. Safe to call with anything. */
1811
+ function reportApiEvent(responseOrError) {
1812
+ if (typeof window === "undefined")
1813
+ return;
1814
+ try {
1815
+ const detail = apiEventDetail(responseOrError);
1816
+ if (detail)
1817
+ window.dispatchEvent(new CustomEvent(API_EVENT, { detail }));
1818
+ }
1819
+ catch {
1820
+ /* never let the tour break the app */
1821
+ }
1822
+ }
1823
+
1587
1824
  const isBrowser = () => typeof window !== "undefined";
1588
1825
  const isAuthEndpoint = (url) => !!url && url.includes("/api/auth/");
1589
1826
  const isAuthPage = () => isBrowser() && window.location.pathname.startsWith("/auth/");
@@ -1657,6 +1894,9 @@ instance.interceptors.response.use(response => {
1657
1894
  if (typeof window !== "undefined") {
1658
1895
  window.dispatchEvent(new CustomEvent("erp:employee-record-ok"));
1659
1896
  }
1897
+ // The guided tour advances on saves that succeeded (method, path, status
1898
+ // and the record's id only; never the body).
1899
+ reportApiEvent(response);
1660
1900
  return response;
1661
1901
  }, async (error) => {
1662
1902
  const originalRequest = error.config;
@@ -1673,6 +1913,7 @@ instance.interceptors.response.use(response => {
1673
1913
  return instance(originalRequest);
1674
1914
  }
1675
1915
  await redirectToLogout();
1916
+ reportApiEvent(error);
1676
1917
  return Promise.reject(toApiError(error));
1677
1918
  }
1678
1919
  // The server refuses every organisation-scoped call when the account has
@@ -1687,6 +1928,8 @@ instance.interceptors.response.use(response => {
1687
1928
  const listed = await retryWithStoredOrganizations(originalRequest, error.response?.status, config => instance(config));
1688
1929
  if (listed !== undefined)
1689
1930
  return listed;
1931
+ // A refused save keeps the tour's step and shows the server's message.
1932
+ reportApiEvent(error);
1690
1933
  return Promise.reject(toApiError(error));
1691
1934
  });
1692
1935
 
@@ -1713,7 +1956,7 @@ function platformApiBase(app) {
1713
1956
  * This package's version, attached to help messages so the back office can
1714
1957
  * tell which shell a report came from. Keep in step with package.json.
1715
1958
  */
1716
- const SHELL_VERSION = "0.1.62";
1959
+ const SHELL_VERSION = "0.1.64";
1717
1960
 
1718
1961
  const HELP_APP_LABEL = {
1719
1962
  platform: "แพลตฟอร์ม",
@@ -1906,13 +2149,13 @@ function describeAttached(app, ctx, email) {
1906
2149
  const myRolesQueryKey = (organizationId) => ["erp-shell", "my-roles", organizationId];
1907
2150
  // Only for a host that renders NavUser outside a QueryClientProvider: the
1908
2151
  // card still works there instead of throwing.
1909
- let fallbackClient = null;
1910
- function useShellQueryClient() {
2152
+ let fallbackClient$1 = null;
2153
+ function useShellQueryClient$1() {
1911
2154
  const provided = useContext(QueryClientContext);
1912
2155
  if (provided)
1913
2156
  return provided;
1914
- fallbackClient ?? (fallbackClient = new QueryClient());
1915
- return fallbackClient;
2157
+ fallbackClient$1 ?? (fallbackClient$1 = new QueryClient());
2158
+ return fallbackClient$1;
1916
2159
  }
1917
2160
  function subscribeStorage(onChange) {
1918
2161
  window.addEventListener("storage", onChange);
@@ -1938,7 +2181,7 @@ function useMyRoles(organizationId, enabled = true) {
1938
2181
  String(organizationId).trim() !== ""
1939
2182
  ? String(organizationId).trim()
1940
2183
  : null;
1941
- const client = useShellQueryClient();
2184
+ const client = useShellQueryClient$1();
1942
2185
  return useQuery({
1943
2186
  queryKey: myRolesQueryKey(orgId),
1944
2187
  queryFn: async ({ signal }) => {
@@ -2385,11 +2628,11 @@ function NavMain({ items, orgCode, closeOnNavigation = false, approvalCounts, ch
2385
2628
  // A one-line row: a link, lit on its own page only. No open
2386
2629
  // state, no title tooltip.
2387
2630
  return (jsxs(React.Fragment, { children: [groupHeading, jsx(SidebarMenuItem, { children: jsx(SidebarMenuButton, { asChild: true, isActive: isItemActive, className: workspaceButton, children: jsxs(Link, { href: itemUrl, prefetch: false, className: "flex items-center w-full min-w-0 flex-1 " +
2388
- (workspace ? "gap-3" : "gap-2"), onClick: handleNavLinkClick, "aria-current": isItemActive ? "page" : undefined, children: [icon, jsx("span", { id: item.id, className: "flex-1 truncate", children: item.titleTh }), badge] }) }) })] }, item.id));
2631
+ (workspace ? "gap-3" : "gap-2"), onClick: handleNavLinkClick, "aria-current": isItemActive ? "page" : undefined, ...guideAnchor(`nav.${item.id}`), children: [icon, jsx("span", { id: item.id, className: "flex-1 truncate", children: item.titleTh }), badge] }) }) })] }, item.id));
2389
2632
  }
2390
2633
  // A group: its header opens and shuts it (the chevron says which).
2391
2634
  // An open group is not the current page — only a row in it is.
2392
- return (jsxs(React.Fragment, { children: [groupHeading, jsx(Collapsible, { asChild: true, open: openIds.has(item.id), onOpenChange: isOpen => setItemOpen(item.id, isOpen), className: "group/collapsible", children: jsxs(SidebarMenuItem, { children: [jsx(CollapsibleTrigger, { asChild: true, children: jsxs(SidebarMenuButton, { isActive: isItemActive, className: workspaceButton, children: [icon, jsx("span", { id: item.id, className: "flex-1 truncate text-left", children: item.titleTh }), jsx(ChevronRight, { className: "ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" })] }) }), item.subModules && (jsx(CollapsibleContent, { children: jsx(SidebarMenuSub, { className: workspace
2635
+ return (jsxs(React.Fragment, { children: [groupHeading, jsx(Collapsible, { asChild: true, open: openIds.has(item.id), onOpenChange: isOpen => setItemOpen(item.id, isOpen), className: "group/collapsible", children: jsxs(SidebarMenuItem, { children: [jsx(CollapsibleTrigger, { asChild: true, children: jsxs(SidebarMenuButton, { isActive: isItemActive, className: workspaceButton, ...guideAnchor(`nav.${item.id}`), children: [icon, jsx("span", { id: item.id, className: "flex-1 truncate text-left", children: item.titleTh }), jsx(ChevronRight, { className: "ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" })] }) }), item.subModules && (jsx(CollapsibleContent, { children: jsx(SidebarMenuSub, { className: workspace
2393
2636
  ? "mx-0 mt-1 mb-3 ml-[21px] gap-0.5 border-l border-sidebar-border pl-2.5 [&_a]:h-auto [&_a]:gap-[11px] [&_a]:px-3 [&_a]:py-2 [&_a]:text-xs [&_svg]:!size-[17px]"
2394
2637
  : undefined, children: item.subModules.map((subItem, subIndex) => {
2395
2638
  const subItemUrl = buildUrlWithCode(code, subItem.url);
@@ -2402,7 +2645,7 @@ function NavMain({ items, orgCode, closeOnNavigation = false, approvalCounts, ch
2402
2645
  subItem.subPages &&
2403
2646
  subItem.subPages.length > 0) {
2404
2647
  return (jsx(Collapsible, { asChild: true, defaultOpen: isSubItemActive || openSub === subIndex, className: "group/sub-collapsible", children: jsxs(SidebarMenuSubItem, { children: [jsx(CollapsibleTrigger, { asChild: true, children: jsxs(SidebarMenuSubButton, { className: "w-full", isActive: isSubItemActive &&
2405
- activeSubPage === null, children: [SubIcon && (jsx(SubIcon, { className: "sidebar-submodule-icon flex-shrink-0" })), jsx("span", { className: "flex-1 truncate", children: subItem.titleTh }), jsx(ChevronDown, { className: "ml-auto size-4 transition-transform duration-200 group-data-[state=open]/sub-collapsible:rotate-180" })] }) }), jsx(CollapsibleContent, { children: jsx(SidebarMenuSub, { className: "ml-4", children: subItem.subPages.map((subPage, subPageIndex) => {
2648
+ activeSubPage === null, ...guideAnchor(`nav.${subItem.id}`), children: [SubIcon && (jsx(SubIcon, { className: "sidebar-submodule-icon flex-shrink-0" })), jsx("span", { className: "flex-1 truncate", children: subItem.titleTh }), jsx(ChevronDown, { className: "ml-auto size-4 transition-transform duration-200 group-data-[state=open]/sub-collapsible:rotate-180" })] }) }), jsx(CollapsibleContent, { children: jsx(SidebarMenuSub, { className: "ml-4", children: subItem.subPages.map((subPage, subPageIndex) => {
2406
2649
  const subPageUrl = buildUrlWithCode(code, subPage.url);
2407
2650
  const isSubPageActive = isSubItemActive &&
2408
2651
  activeSubPage === subPageIndex;
@@ -2410,7 +2653,7 @@ function NavMain({ items, orgCode, closeOnNavigation = false, approvalCounts, ch
2410
2653
  return (jsx(SidebarMenuSubItem, { children: jsx(SidebarMenuSubButton, { asChild: true, className: "font-thai w-full text-sm" +
2411
2654
  (isSubPageActive
2412
2655
  ? " font-medium"
2413
- : ""), isActive: isSubPageActive, children: jsxs(Link, { href: subPageUrl, prefetch: false, className: "w-full flex items-center", onClick: handleNavLinkClick, "aria-current": isSubPageActive
2656
+ : ""), isActive: isSubPageActive, children: jsxs(Link, { href: subPageUrl, prefetch: false, className: "w-full flex items-center", ...guideAnchor(`nav.${subPage.id}`), onClick: handleNavLinkClick, "aria-current": isSubPageActive
2414
2657
  ? "page"
2415
2658
  : undefined, children: [SubPageIcon && (jsx(SubPageIcon, { className: "sidebar-subpage-icon flex-shrink-0" })), jsx("span", { className: "flex-1 truncate", children: subPage.titleTh })] }) }) }, subPage.id));
2416
2659
  }) }) })] }) }, subItem.id));
@@ -2418,7 +2661,7 @@ function NavMain({ items, orgCode, closeOnNavigation = false, approvalCounts, ch
2418
2661
  return (jsx(SidebarMenuSubItem, { children: jsx(SidebarMenuSubButton, { asChild: true, className: "w-full" +
2419
2662
  (workspace && isSubItemActive
2420
2663
  ? " font-semibold"
2421
- : ""), isActive: isSubItemActive, children: jsxs(Link, { href: subItemUrl, prefetch: false, className: "w-full flex items-center", onClick: handleNavLinkClick, "aria-current": isSubItemActive ? "page" : undefined, children: [SubIcon && (jsx(SubIcon, { className: "sidebar-submodule-icon flex-shrink-0" })), jsx("span", { className: "flex-1 truncate", children: subItem.titleTh }), approvalCount > 0 && (jsx(Badge, { variant: "destructive", className: "ml-auto h-5 min-w-5 px-1.5 text-xs font-medium tabular-nums", children: approvalCount > 99
2664
+ : ""), isActive: isSubItemActive, children: jsxs(Link, { href: subItemUrl, prefetch: false, className: "w-full flex items-center", ...guideAnchor(`nav.${subItem.id}`), onClick: handleNavLinkClick, "aria-current": isSubItemActive ? "page" : undefined, children: [SubIcon && (jsx(SubIcon, { className: "sidebar-submodule-icon flex-shrink-0" })), jsx("span", { className: "flex-1 truncate", children: subItem.titleTh }), approvalCount > 0 && (jsx(Badge, { variant: "destructive", className: "ml-auto h-5 min-w-5 px-1.5 text-xs font-medium tabular-nums", children: approvalCount > 99
2422
2665
  ? "99+"
2423
2666
  : approvalCount }))] }) }) }, subItem.id));
2424
2667
  }) }) }))] }) })] }, item.id));
@@ -2540,13 +2783,63 @@ const WORKSPACE_LIGHT_HEADER_VARS = {
2540
2783
  "--header-title-py": "0px",
2541
2784
  };
2542
2785
 
2786
+ let entry = null;
2787
+ let openPanelImpl = null;
2788
+ const listeners = new Set();
2789
+ function emit() {
2790
+ listeners.forEach(l => l());
2791
+ }
2792
+ function subscribe(l) {
2793
+ listeners.add(l);
2794
+ return () => {
2795
+ listeners.delete(l);
2796
+ };
2797
+ }
2798
+ /** Called by the host: the entry to show (null: none), and how to open the panel. */
2799
+ function publishGuideEntry(next, openPanel) {
2800
+ const same = (next === null && entry === null) ||
2801
+ (next !== null && entry !== null && next.done === entry.done && next.total === entry.total);
2802
+ openPanelImpl = openPanel;
2803
+ if (!same) {
2804
+ entry = next;
2805
+ emit();
2806
+ }
2807
+ }
2808
+ /** Opens the tour's quest panel, when this user has a tour here. */
2809
+ function openGuidePanel() {
2810
+ openPanelImpl?.();
2811
+ }
2812
+ /** The "?" menu's entry, or null when there is no tour for this user. */
2813
+ function useGuideEntry() {
2814
+ return useSyncExternalStore(subscribe, () => entry, () => null);
2815
+ }
2816
+
2817
+ const BUTTON_CLASS = "grid size-[34px] shrink-0 place-items-center rounded-lg text-[var(--header-fg-muted,#ffffffc7)] transition-colors hover:bg-[var(--header-hover,#ffffff1f)] hover:text-[var(--header-fg,#ffffff)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--header-fg-muted,#ffffffc7)]";
2543
2818
  /**
2544
2819
  * The ช่วยเหลือ button in the top bar. Drawn in the header's ink (the
2545
2820
  * --header-* variables of the workspace chrome, white on the brand chrome).
2821
+ *
2822
+ * When this user has a guided tour in this app, it opens a small menu:
2823
+ * "ไกด์เริ่มต้น n/N" (the quest panel) and "ติดต่อทีมช่วยเหลือ" (the help
2824
+ * dialog). Otherwise one press opens the help dialog, as before.
2546
2825
  */
2547
2826
  function HelpButton({ className }) {
2548
- return (jsx("button", { type: "button", onClick: openHelp, "aria-label": "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D", title: "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D", className: "grid size-[34px] shrink-0 place-items-center rounded-lg text-[var(--header-fg-muted,#ffffffc7)] transition-colors hover:bg-[var(--header-hover,#ffffff1f)] hover:text-[var(--header-fg,#ffffff)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--header-fg-muted,#ffffffc7)]" +
2549
- (className ? ` ${className}` : ""), children: jsx(CircleHelp, { className: "size-5", strokeWidth: 1.65 }) }));
2827
+ const guide = useGuideEntry();
2828
+ const toGuide = useRef(false);
2829
+ const cls = BUTTON_CLASS + (className ? ` ${className}` : "");
2830
+ if (!guide) {
2831
+ return (jsx("button", { type: "button", onClick: openHelp, "aria-label": "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D", title: "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D", className: cls, "data-guide": "shell.help", children: jsx(CircleHelp, { className: "size-5", strokeWidth: 1.65 }) }));
2832
+ }
2833
+ return (jsxs(DropdownMenu, { children: [jsx(DropdownMenuTrigger, { asChild: true, children: jsx("button", { type: "button", "aria-label": "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D", title: "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D", className: cls, "data-guide": "shell.help", children: jsx(CircleHelp, { className: "size-5", strokeWidth: 1.65 }) }) }), jsxs(DropdownMenuContent, { align: "end", sideOffset: 8, className: "w-64", onCloseAutoFocus: e => {
2834
+ // The quest panel takes focus; the button must not take it back.
2835
+ if (toGuide.current) {
2836
+ e.preventDefault();
2837
+ toGuide.current = false;
2838
+ }
2839
+ }, children: [jsxs(DropdownMenuItem, { onSelect: () => {
2840
+ toGuide.current = true;
2841
+ setTimeout(openGuidePanel, 0);
2842
+ }, className: "gap-2.5", children: [jsx(Flag, { className: "size-4" }), jsx("span", { className: "flex-1", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsxs("span", { className: "text-xs font-semibold text-primary tabular-nums", children: [guide.done, "/", guide.total] })] }), jsxs(DropdownMenuItem, { onSelect: () => setTimeout(openHelp, 0), className: "gap-2.5", children: [jsx(MessageCircle, { className: "size-4" }), jsx("span", { className: "flex-1", children: "\u0E15\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E17\u0E35\u0E21\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D" })] })] })] }));
2550
2843
  }
2551
2844
 
2552
2845
  const hasPaginationShape = (payload) => {
@@ -3491,86 +3784,3032 @@ function resolveStaleOrganization({ code, organizations, organizationsStatus, or
3491
3784
  return { action: "forget" };
3492
3785
  }
3493
3786
 
3787
+ /* ------------------------------------------------------------------ */
3788
+ /* Copy */
3789
+ /* ------------------------------------------------------------------ */
3790
+ const COPY = {
3791
+ fieldFix: "แก้ในช่องที่ไฮไลต์ แล้วกด ถัดไป",
3792
+ saveFailed: "บันทึกไม่สำเร็จ",
3793
+ blank: "ยังไม่ได้พิมพ์",
3794
+ exitToast: "ออกจากไกด์แล้ว",
3795
+ replayDone: "ทบทวนภารกิจเสร็จแล้ว",
3796
+ replayEnded: "จบการทบทวนแล้ว",
3797
+ hiddenToast: "ซ่อนแล้ว",
3798
+ aborted: "ไกด์ไปต่อไม่ได้ ลองอีกครั้งภายหลัง",
3799
+ bridgeTitle: "กดปุ่มเมนู",
3800
+ bridgeWhy: (app) => `เมนูทั้งหมดของ ${app} อยู่ในนี้`,
3801
+ };
3802
+ /* ------------------------------------------------------------------ */
3803
+ /* Helpers */
3804
+ /* ------------------------------------------------------------------ */
3805
+ const BRIDGE_TARGET = "shell.menu-toggle";
3806
+ function initialGuideState(audience, progress) {
3807
+ return {
3808
+ audience,
3809
+ progress,
3810
+ screen: { name: "idle" },
3811
+ panelOpen: false,
3812
+ justDone: null,
3813
+ chipPulse: 0,
3814
+ nudge: 0,
3815
+ gateDismissed: false,
3816
+ };
3817
+ }
3818
+ function findMission(suite, key) {
3819
+ return key ? suite.missions.find(m => m.key === key) : undefined;
3820
+ }
3821
+ function guideContext(env, data, params = {}) {
3822
+ return {
3823
+ code: env.code,
3824
+ pathname: env.pathname,
3825
+ search: env.search,
3826
+ params: { code: env.code, ...params },
3827
+ data,
3828
+ facts: env.facts,
3829
+ can: env.can,
3830
+ visible: (anchor) => env.isVisible(anchor),
3831
+ };
3832
+ }
3833
+ function resolveText(t, ctx) {
3834
+ if (t === undefined)
3835
+ return "";
3836
+ try {
3837
+ return typeof t === "function" ? t(ctx) : t;
3838
+ }
3839
+ catch {
3840
+ return "";
3841
+ }
3842
+ }
3843
+ /** Runs an app predicate; a throw counts as `fallback`. */
3844
+ function safe(fn, fallback) {
3845
+ try {
3846
+ return fn();
3847
+ }
3848
+ catch {
3849
+ return fallback;
3850
+ }
3851
+ }
3852
+ function triggersOf(step) {
3853
+ if (!step.advanceOn)
3854
+ return [];
3855
+ return Array.isArray(step.advanceOn) ? step.advanceOn : [step.advanceOn];
3856
+ }
3857
+ function stepKind(step) {
3858
+ return step.kind ?? "click";
3859
+ }
3860
+ /** The last checkpoint at or before `index` (a mission's first step always is one). */
3861
+ function checkpointAtOrBefore(steps, index) {
3862
+ for (let i = Math.min(index, steps.length - 1); i > 0; i--) {
3863
+ if (steps[i].checkpoint)
3864
+ return i;
3865
+ }
3866
+ return 0;
3867
+ }
3868
+ function targetIdOf(step, ctx) {
3869
+ if (typeof step.targetId === "function")
3870
+ return safe(() => step.targetId(ctx), undefined);
3871
+ return step.targetId;
3872
+ }
3873
+ /** Whether the step's target (or the bridge's) is on screen. */
3874
+ function stepTargetVisible(step, env, ctx, bridge) {
3875
+ if (bridge)
3876
+ return env.isVisible(BRIDGE_TARGET);
3877
+ if (!step.target)
3878
+ return true;
3879
+ return env.isVisible(step.target, targetIdOf(step, ctx));
3880
+ }
3881
+ /** The anchor the spotlight is on for the current step. */
3882
+ function spotlightTarget(step, ctx, bridge) {
3883
+ if (bridge)
3884
+ return { anchor: BRIDGE_TARGET };
3885
+ if (!step.target)
3886
+ return null;
3887
+ return { anchor: step.target, id: targetIdOf(step, ctx) };
3888
+ }
3889
+ function needsBridge(step, env, ctx) {
3890
+ return (!!step.target &&
3891
+ step.target.startsWith("nav.") &&
3892
+ !env.sidebarOpen &&
3893
+ !env.isVisible(step.target, targetIdOf(step, ctx)));
3894
+ }
3895
+ function routeParamsFor(step, env) {
3896
+ if (!step.route)
3897
+ return {};
3898
+ return matchRoute(step.route, env.pathname, env.search, env.code) ?? {};
3899
+ }
3900
+ /** A state trigger (route, visible) that holds now; the capture event for it. */
3901
+ function stateTriggerHolds(step, env) {
3902
+ for (const t of triggersOf(step)) {
3903
+ if ("route" in t) {
3904
+ const params = matchRoute(t.route, env.pathname, env.search, env.code);
3905
+ if (params)
3906
+ return { route: { pathname: env.pathname, params } };
3907
+ }
3908
+ else if ("visible" in t) {
3909
+ if (env.isVisible(t.visible))
3910
+ return {};
3911
+ }
3912
+ }
3913
+ return null;
3914
+ }
3915
+ /** Any trigger that holds on a sync (route, visible, and — once armed — hidden). */
3916
+ function syncTriggerHolds(step, env, armed) {
3917
+ const held = stateTriggerHolds(step, env);
3918
+ if (held)
3919
+ return held;
3920
+ if (!armed)
3921
+ return null;
3922
+ for (const t of triggersOf(step)) {
3923
+ if ("hidden" in t && !env.isVisible(t.hidden))
3924
+ return {};
3925
+ }
3926
+ return null;
3927
+ }
3928
+ /** Whether any of the step's `hidden` anchors is on screen now. */
3929
+ function hiddenAnchorShown(step, env) {
3930
+ return triggersOf(step).some(t => "hidden" in t && env.isVisible(t.hidden));
3931
+ }
3932
+ function missionCount(suite) {
3933
+ return suite.missions.length;
3934
+ }
3935
+ function missionSettled(m, entry, ctx) {
3936
+ if (entry?.status === "done")
3937
+ return true;
3938
+ if (m.optional && entry?.status === "skipped")
3939
+ return true;
3940
+ return safe(() => m.alreadyDone?.(ctx) === true, false);
3941
+ }
3942
+ function settledCount(suite, progress, ctx) {
3943
+ return suite.missions.filter(m => missionSettled(m, progress.missions[m.key], ctx)).length;
3944
+ }
3945
+ function gateState(suite, ctx) {
3946
+ if (!suite.gate)
3947
+ return true;
3948
+ return safe(() => suite.gate.ready(ctx), undefined);
3949
+ }
3950
+ function missionViews(suite, progress, ctx) {
3951
+ const gate = gateState(suite, ctx);
3952
+ const settled = (key) => {
3953
+ const m = findMission(suite, key);
3954
+ return !!m && missionSettled(m, progress.missions[key], ctx);
3955
+ };
3956
+ let nextMarked = false;
3957
+ return suite.missions.map(mission => {
3958
+ const entry = progress.missions[mission.key];
3959
+ let view;
3960
+ if (entry?.status === "done")
3961
+ view = "done";
3962
+ else if (safe(() => mission.alreadyDone?.(ctx) === true, false))
3963
+ view = "already";
3964
+ else if (entry?.status === "skipped")
3965
+ view = "skipped";
3966
+ else if (entry?.status === "active")
3967
+ view = "active";
3968
+ else if (gate === false)
3969
+ view = "waiting";
3970
+ else if ((mission.after ?? []).some(k => !settled(k)))
3971
+ view = "locked";
3972
+ else
3973
+ view = "todo";
3974
+ if (!nextMarked && (view === "todo" || view === "active" || view === "skipped")) {
3975
+ nextMarked = true;
3976
+ if (view === "todo")
3977
+ view = "next";
3978
+ }
3979
+ return { mission, view, entry };
3980
+ });
3981
+ }
3982
+ /** The mission the celebration offers next: the first one not settled and not locked. */
3983
+ function nextMissionKey(suite, progress, ctx) {
3984
+ for (const v of missionViews(suite, progress, ctx)) {
3985
+ if (v.view === "next" || v.view === "todo" || v.view === "active" || v.view === "skipped") {
3986
+ return v.mission.key;
3987
+ }
3988
+ }
3989
+ return null;
3990
+ }
3991
+ /** Whether the welcome should open by itself. */
3992
+ function welcomeDue(state, suite) {
3993
+ return (state.audience === "forced" &&
3994
+ state.progress.welcome === "not_seen" &&
3995
+ state.progress.status === "in_progress" &&
3996
+ !state.progress.mission_key &&
3997
+ state.screen.name === "idle" &&
3998
+ suite.missions.length > 0);
3999
+ }
4000
+ /** Whether the floating "ภารกิจ n/N" chip shows. */
4001
+ function chipVisible(state, suite, ctx) {
4002
+ return (state.audience !== "none" &&
4003
+ state.progress.welcome !== "not_seen" &&
4004
+ state.progress.status !== "completed" &&
4005
+ !state.progress.chip_hidden &&
4006
+ state.screen.name === "idle" &&
4007
+ !state.panelOpen &&
4008
+ settledCount(suite, state.progress, ctx) < missionCount(suite));
4009
+ }
4010
+ function withProgress(d, patch) {
4011
+ d.state = { ...d.state, progress: { ...d.state.progress, ...patch } };
4012
+ }
4013
+ function setMission(d, key, entry) {
4014
+ withProgress(d, { missions: { ...d.state.progress.missions, [key]: entry } });
4015
+ }
4016
+ function setScreen(d, screen) {
4017
+ d.state = { ...d.state, screen };
4018
+ }
4019
+ function save(d, immediate = false) {
4020
+ const existing = d.effects.find(e => e.type === "save");
4021
+ if (existing)
4022
+ existing.immediate = existing.immediate || immediate;
4023
+ else
4024
+ d.effects.push({ type: "save", immediate });
4025
+ }
4026
+ function announceStep(d, suite, env) {
4027
+ const s = d.state.screen;
4028
+ if (s.name !== "step")
4029
+ return;
4030
+ const mission = findMission(suite, s.mission);
4031
+ if (!mission)
4032
+ return;
4033
+ const step = mission.steps[s.index];
4034
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4035
+ const title = s.bridge ? COPY.bridgeTitle : plainTitle(resolveText(step.title, ctx));
4036
+ const why = s.bridge ? COPY.bridgeWhy(suite.appName) : plainTitle(resolveText(step.why, ctx));
4037
+ d.effects.push({
4038
+ type: "announce",
4039
+ text: `ขั้นที่ ${s.index + 1} จาก ${mission.steps.length}. ${title}${why ? `. ${why}` : ""}`,
4040
+ });
4041
+ }
4042
+ /** "กด [บันทึก]" → "กด บันทึก" (for screen readers). */
4043
+ function plainTitle(t) {
4044
+ return t.replace(/\[([^\]]+)\]/g, "$1");
4045
+ }
3494
4046
  /**
3495
- * Top-level app chrome: sticky header, sidebar slot, content gutter and the
3496
- * session/org-context plumbing that both Accounting and HR need. Apps wrap
3497
- * it inside their `SidebarProvider` (server-rendered with the cookie-backed
3498
- * `defaultOpen`) and their `ERPProvider`, then pass app-specific bits as
3499
- * props.
3500
- *
3501
- * The padding contract is deliberately owned here so future style tweaks
3502
- * (e.g. the recent left/right/bottom gutter pass) propagate to both apps via
3503
- * an erp-shell bump — domain components must NOT add their own root padding
3504
- * or content gets indented twice.
4047
+ * Enter step `index` of the mission (or the first one after it that is not
4048
+ * skipped, forbidden or already passed). Past the end, the mission is over.
3505
4049
  */
3506
- function AppLayoutShell({ children, sidebar, loadingComponent, breadcrumb, permissionProvider, organizationId, setOrganizationId, organizations, organizationsStatus, notMemberComponent, signInUrl, selectOrganizationUrl, chrome = "brand", workspaceHeader = "brand", headerEnd, mobileBrand, showHelp = true, helpApp, }) {
3507
- const { data: session, status } = useSession();
3508
- const { open, setOpen } = useSidebar();
3509
- const router = useRouter();
3510
- const params = useParams();
3511
- const code = params?.code;
3512
- const extendedSession = session;
3513
- // Track once-authenticated so a transient accessToken drop during the
3514
- // periodic session refresh (SessionRefreshTrigger every 4 min) doesn't
3515
- // blank the whole page. The initial-load gate below still handles cold
3516
- // start; once we've seen a real token we render children optimistically
3517
- // and let the API layer surface a real 401 if the token actually died.
3518
- const hasSeenAccessTokenRef = useRef(false);
3519
- useEffect(() => {
3520
- if (extendedSession?.accessToken)
3521
- hasSeenAccessTokenRef.current = true;
3522
- }, [extendedSession?.accessToken]);
3523
- // The URL's `[code]` is authoritative: the page mounts only once the active
3524
- // organisation is the one it names (see url-org-gate.ts).
3525
- //
3526
- // The gate used to start only when the code had resolved AND an active id
3527
- // existed, which left two holes. While the organisation list loaded, the
3528
- // page mounted at once and its first requests carried the previous
3529
- // organisation — /O26000021/procurement/purchase-requisition/<id> fetched
3530
- // the document from O26000019 before the switch. And a code naming none of
3531
- // the user's organisations never resolved, so the page rendered the
3532
- // previous organisation's data under it.
3533
- const urlOrgGate = resolveUrlOrgGate({
3534
- code,
3535
- organizations,
3536
- organizationsStatus,
3537
- organizationId,
3538
- });
3539
- const switchTargetId = urlOrgGate.state === "switching" ? urlOrgGate.targetId : null;
3540
- // Switch the active organisation to the URL's. Once per target: the setter
3541
- // writes the cookie through a server action, and re-firing it on every
3542
- // render while that round trip is in flight only queues duplicates.
3543
- const requestedSwitchRef = useRef(null);
3544
- useEffect(() => {
3545
- if (!switchTargetId) {
3546
- requestedSwitchRef.current = null;
3547
- return;
4050
+ function enterStep(d, suite, env, mission, index, opts) {
4051
+ const steps = mission.steps;
4052
+ let i = Math.max(0, index);
4053
+ let firstPass = true;
4054
+ while (i < steps.length) {
4055
+ const step = steps[i];
4056
+ const params = routeParamsFor(step, env);
4057
+ const ctx = guideContext(env, d.state.progress.context, params);
4058
+ if (step.requires && !safe(() => env.can(step.requires), true)) {
4059
+ withProgress(d, { last_error: `forbidden:${step.requires}`.slice(0, 128) });
4060
+ i++;
4061
+ continue;
3548
4062
  }
3549
- if (requestedSwitchRef.current === switchTargetId)
3550
- return;
3551
- requestedSwitchRef.current = switchTargetId;
3552
- void setOrganizationId(switchTargetId);
3553
- }, [switchTargetId, setOrganizationId]);
3554
- // Once the user's organisations are known, requests prefer a stored
3555
- // organisation that is one of them (getRequestOrganizationId).
3556
- const organizationsLoaded = (organizationsStatus ??
3557
- (organizations.length > 0 ? "success" : undefined)) === "success";
3558
- useEffect(() => {
3559
- if (organizationsLoaded) {
3560
- setKnownOrganizationIds(organizations.map(org => org.id));
4063
+ if (step.skipIf && safe(() => step.skipIf(ctx), false)) {
4064
+ i++;
4065
+ continue;
3561
4066
  }
3562
- }, [organizationsLoaded, organizations]);
3563
- // An active organisation that is not one of the user's — deleted, or left —
3564
- // is replaced, so it stops being sent with every request. The URL's
3565
- // organisation, when the user is a member, is the gate's switch above;
3566
- // otherwise the user's only organisation, or none (they pick one: the
3567
- // refusal below offers it, and a path without a code goes to the picker).
3568
- // Once per stale id and target, so a setter that does not take cannot loop.
3569
- const staleRecovery = resolveStaleOrganization({
3570
- code,
3571
- organizations,
3572
- organizationsStatus,
3573
- organizationId,
4067
+ const autoPass = step.autoPass !== false && !(firstPass && opts.noAutoPass);
4068
+ firstPass = false;
4069
+ if (autoPass && stepKind(step) !== "input" && stepKind(step) !== "view") {
4070
+ const held = stateTriggerHolds(step, env);
4071
+ if (held) {
4072
+ captureInto(d, step, held, ctx);
4073
+ i++;
4074
+ continue;
4075
+ }
4076
+ }
4077
+ break;
4078
+ }
4079
+ if (i >= steps.length) {
4080
+ finishMission(d, suite, env, mission, opts.replay);
4081
+ return;
4082
+ }
4083
+ const step = steps[i];
4084
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4085
+ const away = !!step.route && !matchRoute(step.route, env.pathname, env.search, env.code);
4086
+ const bridge = !away && needsBridge(step, env, ctx);
4087
+ setScreen(d, {
4088
+ name: "step",
4089
+ mission: mission.key,
4090
+ index: i,
4091
+ replay: opts.replay,
4092
+ bridge,
4093
+ phase: away ? "away" : "waiting",
4094
+ error: opts.error ?? null,
4095
+ confirmExit: false,
4096
+ misses: 0,
4097
+ armed: hiddenAnchorShown(step, env),
4098
+ });
4099
+ if (!opts.replay) {
4100
+ const cp = checkpointAtOrBefore(steps, i);
4101
+ setMission(d, mission.key, { status: "active", step_key: step.key });
4102
+ withProgress(d, {
4103
+ mission_key: mission.key,
4104
+ step_key: step.key,
4105
+ step_index: i,
4106
+ checkpoint_key: steps[cp].key,
4107
+ });
4108
+ save(d);
4109
+ }
4110
+ if (!away) {
4111
+ // The target may already be there.
4112
+ markReadyIfVisible(d, suite, env);
4113
+ }
4114
+ }
4115
+ function markReadyIfVisible(d, suite, env) {
4116
+ const s = d.state.screen;
4117
+ if (s.name !== "step" || s.phase !== "waiting")
4118
+ return;
4119
+ const mission = findMission(suite, s.mission);
4120
+ if (!mission)
4121
+ return;
4122
+ const step = mission.steps[s.index];
4123
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4124
+ if (stepTargetVisible(step, env, ctx, s.bridge)) {
4125
+ setScreen(d, { ...s, phase: "ready" });
4126
+ announceStep(d, suite, env);
4127
+ if (s.error)
4128
+ d.effects.push({ type: "announce", text: s.error.title });
4129
+ }
4130
+ }
4131
+ function captureInto(d, step, e, ctx) {
4132
+ if (!step.capture)
4133
+ return;
4134
+ const got = safe(() => step.capture(e, ctx), undefined);
4135
+ if (!got)
4136
+ return;
4137
+ const clean = {};
4138
+ for (const [k, v] of Object.entries(got)) {
4139
+ if (typeof v === "string" && v)
4140
+ clean[k] = v;
4141
+ }
4142
+ if (Object.keys(clean).length) {
4143
+ withProgress(d, { context: { ...d.state.progress.context, ...clean } });
4144
+ }
4145
+ }
4146
+ function advance(d, suite, env, capture) {
4147
+ const s = d.state.screen;
4148
+ if (s.name !== "step")
4149
+ return;
4150
+ const mission = findMission(suite, s.mission);
4151
+ if (!mission)
4152
+ return;
4153
+ const step = mission.steps[s.index];
4154
+ if (capture) {
4155
+ captureInto(d, step, capture, guideContext(env, d.state.progress.context, routeParamsFor(step, env)));
4156
+ }
4157
+ enterStep(d, suite, env, mission, s.index + 1, { replay: s.replay });
4158
+ }
4159
+ function finishMission(d, suite, env, mission, replay) {
4160
+ if (replay) {
4161
+ setScreen(d, { name: "idle" });
4162
+ d.effects.push({ type: "toast", text: COPY.replayDone });
4163
+ return;
4164
+ }
4165
+ setMission(d, mission.key, { status: "done", step_key: null, skipped_step: null });
4166
+ withProgress(d, {
4167
+ mission_key: null,
4168
+ step_key: null,
4169
+ step_index: 0,
4170
+ checkpoint_key: null,
4171
+ context: {},
4172
+ last_error: null,
4173
+ });
4174
+ const ctx = guideContext(env, {});
4175
+ const all = settledCount(suite, d.state.progress, ctx) >= missionCount(suite);
4176
+ if (all)
4177
+ withProgress(d, { status: "completed" });
4178
+ setScreen(d, all ? { name: "complete" } : { name: "celebrate", mission: mission.key });
4179
+ d.state = { ...d.state, justDone: mission.key };
4180
+ save(d, true);
4181
+ const n = settledCount(suite, d.state.progress, ctx);
4182
+ const N = missionCount(suite);
4183
+ const title = resolveText(mission.done?.title, ctx) || `${mission.title}แล้ว`;
4184
+ d.effects.push({
4185
+ type: "announce",
4186
+ text: all
4187
+ ? `ครบ ${N} ภารกิจ ${resolveText(suite.complete.title, ctx) || "บริษัทพร้อมใช้งานแล้ว"}`
4188
+ : `ภารกิจสำเร็จ ${title} เสร็จ ${n} จาก ${N} ภารกิจ`,
4189
+ });
4190
+ }
4191
+ function startMission(d, suite, env, key, replay) {
4192
+ const mission = findMission(suite, key);
4193
+ if (!mission || mission.steps.length === 0)
4194
+ return;
4195
+ const entry = d.state.progress.missions[key];
4196
+ // A mission already done is only ever replayed; its done status stays.
4197
+ const isReplay = replay || entry?.status === "done";
4198
+ const before = d.state.progress;
4199
+ d.state = { ...d.state, panelOpen: false, justDone: null };
4200
+ if (d.state.progress.welcome === "not_seen")
4201
+ withProgress(d, { welcome: "started" });
4202
+ if (!isReplay && d.state.progress.mission_key !== key)
4203
+ withProgress(d, { context: {} });
4204
+ if (!isReplay && d.state.progress.status !== "in_progress") {
4205
+ // Picking up an optional mission after the tour completed.
4206
+ withProgress(d, { status: "in_progress" });
4207
+ }
4208
+ // Resume where it was left: back to the checkpoint at or before it.
4209
+ let index = 0;
4210
+ if (!isReplay && entry && (entry.status === "active" || entry.status === "skipped")) {
4211
+ const at = mission.steps.findIndex(s => s.key === (entry.step_key ?? entry.skipped_step));
4212
+ if (at > 0)
4213
+ index = checkpointAtOrBefore(mission.steps, at);
4214
+ }
4215
+ enterStep(d, suite, env, mission, index, { replay: isReplay });
4216
+ // A replay never writes progress; only what starting it changed (the
4217
+ // welcome, first seen through a replay) is saved.
4218
+ if (isReplay && d.state.progress !== before)
4219
+ save(d);
4220
+ }
4221
+ function exitMission(d) {
4222
+ const s = d.state.screen;
4223
+ if (s.name !== "step")
4224
+ return;
4225
+ if (!s.replay) {
4226
+ const prev = d.state.progress.missions[s.mission];
4227
+ if (prev?.status !== "done") {
4228
+ setMission(d, s.mission, {
4229
+ status: "skipped",
4230
+ step_key: d.state.progress.step_key,
4231
+ skipped_step: d.state.progress.step_key,
4232
+ });
4233
+ }
4234
+ withProgress(d, { mission_key: null });
4235
+ save(d, true);
4236
+ }
4237
+ d.state = { ...d.state, chipPulse: d.state.chipPulse + 1 };
4238
+ setScreen(d, { name: "idle" });
4239
+ }
4240
+ function triggerMatchesSignal(t, sig, env, ctx) {
4241
+ if ("api" in t && sig.kind === "api") {
4242
+ if (t.api.method && t.api.method.toUpperCase() !== sig.method.toUpperCase())
4243
+ return null;
4244
+ if (!matchApiPath(t.api.path, sig.path))
4245
+ return null;
4246
+ if (!matchStatus(t.api.status, sig.status))
4247
+ return null;
4248
+ return { api: { method: sig.method.toUpperCase(), path: sig.path, status: sig.status, id: sig.id } };
4249
+ }
4250
+ if ("event" in t && sig.kind === "event") {
4251
+ return t.event === sig.name ? { event: { name: sig.name, detail: sig.detail } } : null;
4252
+ }
4253
+ if ("activate" in t && sig.kind === "activate")
4254
+ return {};
4255
+ if ("value" in t && sig.kind === "value") {
4256
+ return safe(() => t.value(sig.value, ctx), false) ? {} : null;
4257
+ }
4258
+ return null;
4259
+ }
4260
+ /** A refused save that a commit step listens for. */
4261
+ function apiFailureFor(step, sig) {
4262
+ if (sig.kind !== "api" || sig.status < 400)
4263
+ return false;
4264
+ return triggersOf(step).some(t => "api" in t &&
4265
+ (!t.api.method || t.api.method.toUpperCase() === sig.method.toUpperCase()) &&
4266
+ matchApiPath(t.api.path, sig.path));
4267
+ }
4268
+ function reduceGuide(state, action, suite, env) {
4269
+ const d = { state, effects: [] };
4270
+ const s = state.screen;
4271
+ const ctxNow = () => guideContext(env, d.state.progress.context);
4272
+ switch (action.type) {
4273
+ case "welcome": {
4274
+ if (!welcomeDue(state, suite))
4275
+ break;
4276
+ const gate = gateState(suite, ctxNow());
4277
+ if (gate === undefined)
4278
+ break;
4279
+ if (gate === false) {
4280
+ if (!state.gateDismissed)
4281
+ setScreen(d, { name: "gate" });
4282
+ break;
4283
+ }
4284
+ setScreen(d, { name: "welcome", confirm: false });
4285
+ break;
4286
+ }
4287
+ case "welcomeSkip":
4288
+ if (s.name === "welcome")
4289
+ setScreen(d, { name: "welcome", confirm: true });
4290
+ break;
4291
+ case "welcomeStart":
4292
+ case "welcomeSkipCancel": {
4293
+ if (s.name !== "welcome")
4294
+ break;
4295
+ const first = nextMissionKey(suite, d.state.progress, ctxNow());
4296
+ if (first)
4297
+ startMission(d, suite, env, first, false);
4298
+ else
4299
+ setScreen(d, { name: "idle" });
4300
+ break;
4301
+ }
4302
+ case "welcomeSkipConfirm":
4303
+ if (s.name !== "welcome")
4304
+ break;
4305
+ withProgress(d, { welcome: "skipped" });
4306
+ d.state = { ...d.state, chipPulse: d.state.chipPulse + 1 };
4307
+ setScreen(d, { name: "idle" });
4308
+ save(d, true);
4309
+ break;
4310
+ case "gateLater":
4311
+ if (s.name === "gate") {
4312
+ d.state = { ...d.state, gateDismissed: true };
4313
+ setScreen(d, { name: "idle" });
4314
+ }
4315
+ break;
4316
+ case "start":
4317
+ if (state.audience === "none")
4318
+ break;
4319
+ if (s.name === "step" && !s.replay && s.mission !== action.mission) {
4320
+ // Leaving one mission for another: the first is set aside.
4321
+ exitMission(d);
4322
+ }
4323
+ startMission(d, suite, env, action.mission, !!action.replay);
4324
+ break;
4325
+ case "resume": {
4326
+ if (state.audience === "none" || s.name !== "idle")
4327
+ break;
4328
+ const mission = findMission(suite, d.state.progress.mission_key);
4329
+ if (!mission || d.state.progress.missions[mission.key]?.status !== "active")
4330
+ break;
4331
+ // Back to the last checkpoint at or before the step reached; the saved
4332
+ // checkpoint when the step is no longer in the tour.
4333
+ const stepAt = mission.steps.findIndex(st => st.key === d.state.progress.step_key);
4334
+ const cpAt = mission.steps.findIndex(st => st.key === d.state.progress.checkpoint_key);
4335
+ const index = stepAt >= 0 ? checkpointAtOrBefore(mission.steps, stepAt) : Math.max(cpAt, 0);
4336
+ enterStep(d, suite, env, mission, index, { replay: false });
4337
+ break;
4338
+ }
4339
+ case "sync": {
4340
+ if (s.name !== "step")
4341
+ break;
4342
+ const mission = findMission(suite, s.mission);
4343
+ if (!mission)
4344
+ break;
4345
+ const step = mission.steps[s.index];
4346
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4347
+ if (s.phase === "away") {
4348
+ if (!step.route || matchRoute(step.route, env.pathname, env.search, env.code)) {
4349
+ // Arrived: run the step again from here (it may already be passed).
4350
+ enterStep(d, suite, env, mission, s.index, { replay: s.replay, error: s.error });
4351
+ }
4352
+ break;
4353
+ }
4354
+ if (s.confirmExit)
4355
+ break;
4356
+ const kind = stepKind(step);
4357
+ const armed = s.armed || hiddenAnchorShown(step, env);
4358
+ if (kind !== "input" && kind !== "view") {
4359
+ const held = syncTriggerHolds(step, env, armed);
4360
+ if (held) {
4361
+ advance(d, suite, env, held);
4362
+ break;
4363
+ }
4364
+ }
4365
+ if (armed !== s.armed)
4366
+ setScreen(d, { ...s, armed });
4367
+ const cur = d.state.screen;
4368
+ // The menu step: done once the sidebar is open; needed again if shut.
4369
+ if (cur.bridge && (env.sidebarOpen || stepTargetVisible(step, env, ctx, false))) {
4370
+ setScreen(d, { ...cur, bridge: false, phase: "waiting" });
4371
+ }
4372
+ else if (!cur.bridge && needsBridge(step, env, ctx)) {
4373
+ setScreen(d, { ...cur, bridge: true, phase: "waiting" });
4374
+ }
4375
+ markReadyIfVisible(d, suite, env);
4376
+ break;
4377
+ }
4378
+ case "signal": {
4379
+ if (s.name !== "step" || s.phase === "away" || s.confirmExit)
4380
+ break;
4381
+ const mission = findMission(suite, s.mission);
4382
+ if (!mission)
4383
+ break;
4384
+ const step = mission.steps[s.index];
4385
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4386
+ const sig = action.signal;
4387
+ if (sig.kind === "typing") {
4388
+ if (s.error)
4389
+ setScreen(d, { ...s, error: null });
4390
+ break;
4391
+ }
4392
+ if (s.bridge)
4393
+ break;
4394
+ for (const t of triggersOf(step)) {
4395
+ const hit = triggerMatchesSignal(t, sig, env, ctx);
4396
+ if (hit) {
4397
+ advance(d, suite, env, hit);
4398
+ return { state: d.state, effects: d.effects };
4399
+ }
4400
+ }
4401
+ if (sig.kind === "api" && stepKind(step) === "commit" && apiFailureFor(step, sig)) {
4402
+ const mapped = safe(() => step.onApiError?.({ status: sig.status, message: sig.message }, ctx), undefined);
4403
+ if (mapped && mapped.step) {
4404
+ const to = mission.steps.findIndex(st => st.key === mapped.step);
4405
+ if (to >= 0) {
4406
+ enterStep(d, suite, env, mission, to, {
4407
+ replay: s.replay,
4408
+ noAutoPass: true,
4409
+ error: { title: mapped.message ?? sig.message ?? COPY.saveFailed, detail: COPY.fieldFix },
4410
+ });
4411
+ break;
4412
+ }
4413
+ }
4414
+ const error = mapped?.message
4415
+ ? { title: mapped.message, detail: undefined }
4416
+ : { title: COPY.saveFailed, detail: sig.message };
4417
+ setScreen(d, { ...s, error });
4418
+ d.effects.push({ type: "announce", text: [error.title, error.detail].filter(Boolean).join(". ") });
4419
+ withProgress(d, { last_error: `api_${sig.status}:${step.key}`.slice(0, 128) });
4420
+ }
4421
+ break;
4422
+ }
4423
+ case "next": {
4424
+ if (s.name !== "step" || s.phase !== "ready" || s.confirmExit || s.bridge)
4425
+ break;
4426
+ const mission = findMission(suite, s.mission);
4427
+ if (!mission)
4428
+ break;
4429
+ const step = mission.steps[s.index];
4430
+ const kind = stepKind(step);
4431
+ if (kind === "view") {
4432
+ advance(d, suite, env);
4433
+ break;
4434
+ }
4435
+ if (kind !== "input")
4436
+ break;
4437
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4438
+ const value = safe(() => env.targetValue(), "");
4439
+ const problem = step.validate
4440
+ ? safe(() => step.validate(value, ctx), null)
4441
+ : value.trim()
4442
+ ? null
4443
+ : COPY.blank;
4444
+ if (problem) {
4445
+ setScreen(d, { ...s, error: { title: problem, detail: COPY.fieldFix } });
4446
+ d.state = { ...d.state, nudge: d.state.nudge + 1 };
4447
+ d.effects.push({ type: "announce", text: problem });
4448
+ }
4449
+ else {
4450
+ advance(d, suite, env);
4451
+ }
4452
+ break;
4453
+ }
4454
+ case "targetLost": {
4455
+ if (s.name !== "step" || s.phase !== "ready" || s.confirmExit)
4456
+ break;
4457
+ const mission = findMission(suite, s.mission);
4458
+ if (!mission)
4459
+ break;
4460
+ const step = mission.steps[s.index];
4461
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4462
+ if (stepTargetVisible(step, env, ctx, s.bridge))
4463
+ break;
4464
+ const cp = checkpointAtOrBefore(mission.steps, s.index);
4465
+ if (cp < s.index && !s.bridge) {
4466
+ // A dialog or a menu closed under the step: back to what opens it.
4467
+ enterStep(d, suite, env, mission, cp, { replay: s.replay, noAutoPass: false });
4468
+ }
4469
+ else {
4470
+ setScreen(d, { ...s, phase: "waiting" });
4471
+ }
4472
+ break;
4473
+ }
4474
+ case "timeout": {
4475
+ if (s.name !== "step" || s.phase !== "waiting")
4476
+ break;
4477
+ const mission = findMission(suite, s.mission);
4478
+ if (!mission)
4479
+ break;
4480
+ const step = mission.steps[s.index];
4481
+ const anchor = s.bridge ? BRIDGE_TARGET : (step.target ?? step.key);
4482
+ withProgress(d, { last_error: `target_missing:${anchor}`.slice(0, 128) });
4483
+ save(d);
4484
+ const misses = s.misses + 1;
4485
+ const policy = step.onMissing ?? "retry";
4486
+ const cp = checkpointAtOrBefore(mission.steps, s.index);
4487
+ if (policy === "skip") {
4488
+ advance(d, suite, env);
4489
+ }
4490
+ else if (policy === "abort") {
4491
+ exitMission(d);
4492
+ d.effects.push({ type: "toast", text: COPY.aborted });
4493
+ }
4494
+ else if ((policy === "rewind" || (policy === "retry" && misses >= 2)) && cp < s.index) {
4495
+ enterStep(d, suite, env, mission, cp, { replay: s.replay });
4496
+ const now = d.state.screen;
4497
+ if (now.name === "step" && now.index === s.index) {
4498
+ // The checkpoint passed straight back to this step (its dialog is
4499
+ // still open): going back cannot help, so say so.
4500
+ setScreen(d, { ...now, phase: "missing", misses });
4501
+ d.effects.push({ type: "announce", text: "ไม่พบส่วนนี้บนหน้า" });
4502
+ }
4503
+ }
4504
+ else {
4505
+ setScreen(d, { ...s, phase: "missing", misses });
4506
+ d.effects.push({ type: "announce", text: "ไม่พบส่วนนี้บนหน้า" });
4507
+ }
4508
+ break;
4509
+ }
4510
+ case "retry":
4511
+ if (s.name === "step" && s.phase === "missing") {
4512
+ setScreen(d, { ...s, phase: "waiting" });
4513
+ markReadyIfVisible(d, suite, env);
4514
+ }
4515
+ break;
4516
+ case "blocked":
4517
+ if (s.name === "step")
4518
+ d.state = { ...d.state, nudge: d.state.nudge + 1 };
4519
+ break;
4520
+ case "exit":
4521
+ if (s.name !== "step")
4522
+ break;
4523
+ if (s.replay) {
4524
+ setScreen(d, { name: "idle" });
4525
+ d.effects.push({ type: "toast", text: COPY.replayEnded });
4526
+ }
4527
+ else {
4528
+ setScreen(d, { ...s, confirmExit: true });
4529
+ }
4530
+ break;
4531
+ case "exitCancel":
4532
+ if (s.name === "step" && s.confirmExit)
4533
+ setScreen(d, { ...s, confirmExit: false });
4534
+ break;
4535
+ case "exitConfirm":
4536
+ if (s.name !== "step")
4537
+ break;
4538
+ exitMission(d);
4539
+ d.effects.push({ type: "toast", text: COPY.exitToast });
4540
+ break;
4541
+ case "endWithoutSave":
4542
+ if (s.name !== "step" || !s.replay)
4543
+ break;
4544
+ setScreen(d, { name: "idle" });
4545
+ d.effects.push({ type: "closeAppDialog" }, { type: "toast", text: COPY.replayEnded });
4546
+ break;
4547
+ case "goResume": {
4548
+ if (s.name !== "step" || s.phase !== "away")
4549
+ break;
4550
+ const mission = findMission(suite, s.mission);
4551
+ if (!mission)
4552
+ break;
4553
+ const step = mission.steps[s.index];
4554
+ const ctx = guideContext(env, d.state.progress.context);
4555
+ const href = safe(() => step.resumeUrl?.(ctx), undefined) ??
4556
+ (step.route ? fillRoute(step.route, { ...d.state.progress.context, code: env.code }) : null);
4557
+ if (href)
4558
+ d.effects.push({ type: "navigate", href });
4559
+ break;
4560
+ }
4561
+ case "celebrateNext": {
4562
+ if (s.name !== "celebrate")
4563
+ break;
4564
+ const next = nextMissionKey(suite, d.state.progress, ctxNow());
4565
+ if (next)
4566
+ startMission(d, suite, env, next, false);
4567
+ else
4568
+ setScreen(d, { name: "idle" });
4569
+ break;
4570
+ }
4571
+ case "rest":
4572
+ if (s.name !== "celebrate")
4573
+ break;
4574
+ setScreen(d, { name: "idle" });
4575
+ d.state = { ...d.state, panelOpen: true, justDone: s.mission };
4576
+ break;
4577
+ case "finish": {
4578
+ if (s.name !== "complete")
4579
+ break;
4580
+ setScreen(d, { name: "idle" });
4581
+ const href = resolveText(suite.complete.action.href, ctxNow());
4582
+ const filled = href ? (fillRoute(href, { code: env.code }) ?? href) : "";
4583
+ if (filled)
4584
+ d.effects.push({ type: "navigate", href: filled });
4585
+ break;
4586
+ }
4587
+ case "openPanel":
4588
+ if (state.audience !== "none" && s.name === "idle") {
4589
+ d.state = { ...d.state, panelOpen: true };
4590
+ }
4591
+ break;
4592
+ case "closePanel":
4593
+ d.state = { ...d.state, panelOpen: false, justDone: null };
4594
+ break;
4595
+ case "hideChip":
4596
+ withProgress(d, { chip_hidden: true });
4597
+ d.state = { ...d.state, panelOpen: false };
4598
+ d.effects.push({ type: "toast", text: COPY.hiddenToast });
4599
+ save(d, true);
4600
+ break;
4601
+ case "dismissMission": {
4602
+ const m = findMission(suite, action.mission);
4603
+ if (!m?.optional)
4604
+ break;
4605
+ setMission(d, m.key, { status: "skipped", step_key: null, skipped_step: null });
4606
+ const all = settledCount(suite, d.state.progress, ctxNow()) >= missionCount(suite);
4607
+ if (all) {
4608
+ withProgress(d, { status: "completed" });
4609
+ d.state = { ...d.state, panelOpen: false };
4610
+ setScreen(d, { name: "complete" });
4611
+ }
4612
+ save(d, true);
4613
+ break;
4614
+ }
4615
+ case "serverRow": {
4616
+ // A saved row came back: its rev, the server's status, and the dates
4617
+ // the server stamps on missions ("เสร็จ 26 ต.ค. 2569 13:04").
4618
+ const missions = { ...d.state.progress.missions };
4619
+ for (const [k, m] of Object.entries(missions)) {
4620
+ const r = action.progress.missions[k];
4621
+ if (r && r.status === m.status) {
4622
+ missions[k] = { ...m, completed_at: r.completed_at ?? m.completed_at, skipped_at: r.skipped_at ?? m.skipped_at };
4623
+ }
4624
+ }
4625
+ withProgress(d, { rev: action.progress.rev, server_status: action.progress.server_status, missions });
4626
+ break;
4627
+ }
4628
+ }
4629
+ return { state: d.state, effects: d.effects };
4630
+ }
4631
+
4632
+ /**
4633
+ * A tour's progress as platform-api stores it (one row per user, org and
4634
+ * suite: GET/PUT /organizations/:id/guides/me), and the rules for reading,
4635
+ * writing and merging it. See _claude-work/peoplx-guide/API.md.
4636
+ *
4637
+ * No runtime imports: the tests run this file in Node as it is.
4638
+ */
4639
+ const KEY_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4640
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4641
+ const str = (v) => (typeof v === "string" && v !== "" ? v : null);
4642
+ function freshProgress(version, rev = 0) {
4643
+ return {
4644
+ guide_version: version,
4645
+ rev,
4646
+ status: "in_progress",
4647
+ mission_key: null,
4648
+ step_key: null,
4649
+ step_index: 0,
4650
+ checkpoint_key: null,
4651
+ missions: {},
4652
+ context: {},
4653
+ welcome: "not_seen",
4654
+ chip_hidden: false,
4655
+ last_error: null,
4656
+ skipped_step: null,
4657
+ server_status: null,
4658
+ };
4659
+ }
4660
+ const ROW_STATUSES = ["in_progress", "completed", "skipped", "aborted"];
4661
+ const MISSION_STATUSES = ["todo", "active", "done", "skipped"];
4662
+ const WELCOMES = ["not_seen", "started", "skipped"];
4663
+ /** One row (a GET `guides[]` entry, a PUT answer, a 409's `current`). Null when off-shape. */
4664
+ function parseRow(raw) {
4665
+ if (!isRecord(raw))
4666
+ return null;
4667
+ const version = Number(raw.guide_version);
4668
+ const rev = Number(raw.rev);
4669
+ if (!Number.isInteger(version) || version < 1 || !Number.isInteger(rev) || rev < 0)
4670
+ return null;
4671
+ const status = ROW_STATUSES.includes(raw.status)
4672
+ ? raw.status
4673
+ : "in_progress";
4674
+ const missions = {};
4675
+ if (isRecord(raw.missions)) {
4676
+ for (const [k, v] of Object.entries(raw.missions)) {
4677
+ if (!isRecord(v) || !MISSION_STATUSES.includes(v.status))
4678
+ continue;
4679
+ missions[k] = {
4680
+ status: v.status,
4681
+ step_key: str(v.step_key),
4682
+ skipped_step: str(v.skipped_step),
4683
+ completed_at: str(v.completed_at),
4684
+ skipped_at: str(v.skipped_at),
4685
+ };
4686
+ }
4687
+ }
4688
+ const context = {};
4689
+ if (isRecord(raw.context)) {
4690
+ for (const [k, v] of Object.entries(raw.context)) {
4691
+ if (typeof v === "string")
4692
+ context[k] = v;
4693
+ else if (typeof v === "number")
4694
+ context[k] = String(v);
4695
+ }
4696
+ }
4697
+ return {
4698
+ guide_version: version,
4699
+ rev,
4700
+ status,
4701
+ mission_key: str(raw.mission_key),
4702
+ step_key: str(raw.step_key),
4703
+ step_index: Number.isInteger(raw.step_index) ? raw.step_index : 0,
4704
+ checkpoint_key: str(raw.checkpoint_key),
4705
+ missions,
4706
+ context,
4707
+ welcome: WELCOMES.includes(raw.welcome) ? raw.welcome : "not_seen",
4708
+ chip_hidden: raw.chip_hidden === true,
4709
+ last_error: str(raw.last_error),
4710
+ skipped_step: str(raw.skipped_step),
4711
+ server_status: status,
4712
+ };
4713
+ }
4714
+ /**
4715
+ * The GET answer for one suite. Null — show nothing — for anything that is
4716
+ * not the expected shape (an older API, a proxy's page, another app's answer).
4717
+ */
4718
+ function parseGuidesAnswer(payload, suite) {
4719
+ if (!isRecord(payload))
4720
+ return null;
4721
+ const data = isRecord(payload.data) ? payload.data : payload;
4722
+ const mode = data.mode;
4723
+ const audience = data.audience;
4724
+ if (mode !== "off" && mode !== "invite" && mode !== "forced")
4725
+ return null;
4726
+ if (audience !== "forced" && audience !== "optional" && audience !== "none")
4727
+ return null;
4728
+ if (typeof data.app === "string" && data.app !== suite.app)
4729
+ return null;
4730
+ const rows = Array.isArray(data.guides) ? data.guides : [];
4731
+ let row = null;
4732
+ for (const r of rows) {
4733
+ if (isRecord(r) && r.guide_key === suite.key) {
4734
+ row = parseRow(r);
4735
+ break;
4736
+ }
4737
+ }
4738
+ let progress;
4739
+ let newerOnServer = false;
4740
+ if (!row)
4741
+ progress = freshProgress(suite.version);
4742
+ else if (row.guide_version < suite.version) {
4743
+ // A new version of the tour: start over (the server resets the row on the
4744
+ // PUT); keep the rev the server will check.
4745
+ progress = { ...freshProgress(suite.version, row.rev), server_status: row.server_status };
4746
+ }
4747
+ else {
4748
+ progress = row;
4749
+ newerOnServer = row.guide_version > suite.version;
4750
+ }
4751
+ return { mode, audience: mode === "off" ? "none" : audience, progress, newerOnServer };
4752
+ }
4753
+ const TERMINAL = ["completed", "skipped", "aborted"];
4754
+ /** The PUT body for the client's state. Drops keys the server would refuse. */
4755
+ function putBody(p, app) {
4756
+ const key = (k) => (k && KEY_RE.test(k) ? k : null);
4757
+ const missions = {};
4758
+ for (const [k, m] of Object.entries(p.missions)) {
4759
+ if (!KEY_RE.test(k))
4760
+ continue;
4761
+ missions[k] = {
4762
+ status: m.status,
4763
+ step_key: key(m.step_key ?? null),
4764
+ skipped_step: key(m.skipped_step ?? null),
4765
+ };
4766
+ }
4767
+ const context = {};
4768
+ for (const [k, v] of Object.entries(p.context)) {
4769
+ if (typeof v === "string" && v.length <= 200)
4770
+ context[k] = v;
4771
+ }
4772
+ return {
4773
+ app,
4774
+ guide_version: p.guide_version,
4775
+ rev: p.rev,
4776
+ status: p.status,
4777
+ mission_key: key(p.mission_key),
4778
+ step_key: key(p.step_key),
4779
+ step_index: Math.max(0, Math.min(1000, Math.floor(p.step_index || 0))),
4780
+ checkpoint_key: key(p.checkpoint_key),
4781
+ missions,
4782
+ context,
4783
+ welcome: p.welcome,
4784
+ chip_hidden: p.chip_hidden,
4785
+ last_error: p.last_error ? p.last_error.slice(0, 128) : null,
4786
+ skipped_step: key(p.skipped_step),
4787
+ restart: p.status === "in_progress" &&
4788
+ p.server_status !== null &&
4789
+ TERMINAL.includes(p.server_status),
4790
+ };
4791
+ }
4792
+ function stable(v) {
4793
+ if (Array.isArray(v))
4794
+ return `[${v.map(stable).join(",")}]`;
4795
+ if (isRecord(v)) {
4796
+ return `{${Object.keys(v)
4797
+ .sort()
4798
+ .map(k => `${JSON.stringify(k)}:${stable(v[k])}`)
4799
+ .join(",")}}`;
4800
+ }
4801
+ return JSON.stringify(v) ?? "null";
4802
+ }
4803
+ /**
4804
+ * What a PUT would store, without the rev it is checked against: two equal
4805
+ * keys mean the save would change nothing, and it is not sent (a replay
4806
+ * starting, a step entered again, never bump the row's rev). Key order does
4807
+ * not matter.
4808
+ */
4809
+ function payloadKey(p, app) {
4810
+ const { rev: _rev, restart: _restart, ...rest } = putBody(p, app);
4811
+ return stable(rest);
4812
+ }
4813
+ const MISSION_RANK = { todo: 0, skipped: 1, active: 1, done: 3 };
4814
+ const WELCOME_RANK = { not_seen: 0, skipped: 1, started: 1 };
4815
+ /**
4816
+ * After a 409: this tab's state laid over the server's, keeping whatever is
4817
+ * further along — a mission done anywhere stays done, the welcome once seen
4818
+ * stays seen, a hidden chip stays hidden. Otherwise this tab's own choice
4819
+ * wins. The rev is the server's.
4820
+ */
4821
+ function mergeProgress(local, remote) {
4822
+ const missions = { ...remote.missions };
4823
+ for (const [k, m] of Object.entries(local.missions)) {
4824
+ const r = remote.missions[k];
4825
+ missions[k] = !r || MISSION_RANK[m.status] >= MISSION_RANK[r.status] ? { ...r, ...m } : r;
4826
+ }
4827
+ const welcome = WELCOME_RANK[local.welcome] >= WELCOME_RANK[remote.welcome] ? local.welcome : remote.welcome;
4828
+ const completed = local.status === "completed" || remote.status === "completed";
4829
+ const mission_key = local.mission_key && missions[local.mission_key]?.status === "active"
4830
+ ? local.mission_key
4831
+ : remote.mission_key && missions[remote.mission_key]?.status === "active"
4832
+ ? remote.mission_key
4833
+ : null;
4834
+ const fromLocal = mission_key !== null && mission_key === local.mission_key;
4835
+ return {
4836
+ ...local,
4837
+ rev: remote.rev,
4838
+ server_status: remote.server_status,
4839
+ status: completed ? "completed" : local.status,
4840
+ missions,
4841
+ welcome,
4842
+ chip_hidden: local.chip_hidden || remote.chip_hidden,
4843
+ mission_key,
4844
+ step_key: fromLocal ? local.step_key : mission_key ? remote.step_key : null,
4845
+ step_index: fromLocal ? local.step_index : mission_key ? remote.step_index : 0,
4846
+ checkpoint_key: fromLocal ? local.checkpoint_key : mission_key ? remote.checkpoint_key : null,
4847
+ context: fromLocal ? local.context : mission_key ? remote.context : {},
4848
+ };
4849
+ }
4850
+ /**
4851
+ * Which of two copies (sessionStorage after F5, the server) to resume from:
4852
+ * the one further along for the same version; the server's on a tie.
4853
+ */
4854
+ function furtherProgress(a, b) {
4855
+ const score = (p) => Object.values(p.missions).reduce((s, m) => s + MISSION_RANK[m.status] * 1000, 0) +
4856
+ (p.mission_key ? 100 + p.step_index : 0) +
4857
+ WELCOME_RANK[p.welcome];
4858
+ return score(a) > score(b) ? a : b;
4859
+ }
4860
+
4861
+ /**
4862
+ * Talking to platform-api about tour progress (API.md): the GET that says
4863
+ * who sees what, and the PUT that saves, with its rev check.
4864
+ */
4865
+ function base(app) {
4866
+ return platformApiBase(app);
4867
+ }
4868
+ /** GET …/guides/me?app=…; null (show nothing) on any failure or odd answer. */
4869
+ async function fetchGuides(organizationId, suite, signal) {
4870
+ try {
4871
+ const res = await instance.get(`${base(suite.app)}/organizations/${encodeURIComponent(organizationId)}/guides/me`, { params: { app: suite.app }, signal, erpOrganizationId: organizationId });
4872
+ return parseGuidesAnswer(res.data, suite);
4873
+ }
4874
+ catch {
4875
+ return null;
4876
+ }
4877
+ }
4878
+ /**
4879
+ * PUT the whole state. On 409 the server's row comes back: merge (keeping
4880
+ * whatever is further along) and try once more with its rev. Returns the
4881
+ * stored row, or null when it could not be saved (the tour goes on; the
4882
+ * session copy keeps the place).
4883
+ */
4884
+ async function saveGuides(organizationId, suite, progress) {
4885
+ const url = `${base(suite.app)}/organizations/${encodeURIComponent(organizationId)}/guides/me/${encodeURIComponent(suite.key)}`;
4886
+ let body = progress;
4887
+ for (let attempt = 0; attempt < 2; attempt++) {
4888
+ let res;
4889
+ try {
4890
+ res = await instance.put(url, putBody(body, suite.app), {
4891
+ validateStatus: s => (s >= 200 && s < 300) || s === 409,
4892
+ erpOrganizationId: organizationId,
4893
+ });
4894
+ }
4895
+ catch {
4896
+ return null;
4897
+ }
4898
+ const payload = res.data;
4899
+ if (res.status !== 409) {
4900
+ return parseRow(payload?.data ?? payload);
4901
+ }
4902
+ const current = parseRow(payload?.current);
4903
+ if (current && current.guide_version > body.guide_version) {
4904
+ // Another app build is ahead of this one: stop writing.
4905
+ return null;
4906
+ }
4907
+ if (!current)
4908
+ body = { ...body, rev: 0, server_status: null };
4909
+ else if (current.guide_version < body.guide_version) {
4910
+ // The server's row is the previous version: this one replaces it.
4911
+ body = { ...body, rev: current.rev, server_status: current.server_status };
4912
+ }
4913
+ else
4914
+ body = mergeProgress(body, current);
4915
+ }
4916
+ return null;
4917
+ }
4918
+
4919
+ /**
4920
+ * The tour's DOM side: finding anchors, deciding whether one is really on
4921
+ * screen, and the rectangles the spotlight cuts out. Browser only; every
4922
+ * function tolerates a missing document.
4923
+ */
4924
+ const hasDocument = () => typeof document !== "undefined";
4925
+ function cssString(value) {
4926
+ return `"${value.replace(/["\\]/g, "\\$&")}"`;
4927
+ }
4928
+ function anchorSelector(anchor, id) {
4929
+ return (`[${GUIDE_ATTRIBUTE}=${cssString(anchor)}]` +
4930
+ (id ? `[${GUIDE_ID_ATTRIBUTE}=${cssString(id)}]` : ""));
4931
+ }
4932
+ /**
4933
+ * On screen: connected, with a size, not hidden by style, not inside
4934
+ * aria-hidden or inert (other than the guide's own), not a closed Radix part.
4935
+ *
4936
+ * aria-hidden that Radix put there (data-aria-hidden: everything outside an
4937
+ * open dialog, select or menu is hidden from screen readers) does not count:
4938
+ * a dialog's field is still on screen while its select's list is open.
4939
+ */
4940
+ function isPresent(el) {
4941
+ if (!el || !el.isConnected)
4942
+ return false;
4943
+ const r = el.getBoundingClientRect();
4944
+ if (r.width <= 0 || r.height <= 0)
4945
+ return false;
4946
+ // Slid off the side (a closed drawer); off the top or bottom is only
4947
+ // scrolled away, and the tour scrolls it back. So is a tab scrolled out of
4948
+ // a row of tabs that scrolls sideways, as long as the row is on screen.
4949
+ if ((r.right <= 0 || r.left >= window.innerWidth) && !inSidewaysScroller(el))
4950
+ return false;
4951
+ if (el.getAttribute("data-state") === "closed")
4952
+ return false;
4953
+ const style = getComputedStyle(el);
4954
+ if (style.visibility === "hidden" || style.display === "none")
4955
+ return false;
4956
+ for (let n = el; n; n = n.parentElement) {
4957
+ if (n.hasAttribute(GUIDE_LAYER_ATTRIBUTE))
4958
+ break;
4959
+ if (n.hasAttribute("inert"))
4960
+ return false;
4961
+ if (n.getAttribute("aria-hidden") === "true" && !n.hasAttribute("data-aria-hidden"))
4962
+ return false;
4963
+ }
4964
+ return true;
4965
+ }
4966
+ /** The first matching anchor that is on screen. */
4967
+ function findAnchor(anchor, id) {
4968
+ if (!hasDocument() || !anchor)
4969
+ return null;
4970
+ let list;
4971
+ try {
4972
+ list = document.querySelectorAll(anchorSelector(anchor, id));
4973
+ }
4974
+ catch {
4975
+ return null;
4976
+ }
4977
+ for (const el of Array.from(list)) {
4978
+ if (isPresent(el))
4979
+ return el;
4980
+ }
4981
+ return null;
4982
+ }
4983
+ function anchorVisible(anchor, id) {
4984
+ return findAnchor(anchor, id) !== null;
4985
+ }
4986
+ const FIELD = "input:not([type=hidden]),textarea,select,[contenteditable=''],[contenteditable=true]";
4987
+ /** The field to type into: the anchor itself, or the first field inside it. */
4988
+ function fieldOf(el) {
4989
+ if (!el)
4990
+ return null;
4991
+ if (el.matches(FIELD))
4992
+ return el;
4993
+ return el.querySelector(FIELD);
4994
+ }
4995
+ function fieldValue(el) {
4996
+ const f = fieldOf(el);
4997
+ if (!f)
4998
+ return "";
4999
+ if ("value" in f && typeof f.value === "string")
5000
+ return f.value;
5001
+ return f.textContent ?? "";
5002
+ }
5003
+ const FOCUSABLE = "a[href],button:not([disabled]),input:not([disabled]):not([type=hidden]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex='-1']),[contenteditable=''],[contenteditable=true]";
5004
+ function focusablesIn(root) {
5005
+ if (!root)
5006
+ return [];
5007
+ const own = root.matches(FOCUSABLE) ? [root] : [];
5008
+ return own.concat(Array.from(root.querySelectorAll(FOCUSABLE)).filter(isPresent));
5009
+ }
5010
+ function rectOf(el) {
5011
+ const r = el.getBoundingClientRect();
5012
+ return { x: r.left, y: r.top, width: r.width, height: r.height };
5013
+ }
5014
+ function padRect(r, pad) {
5015
+ return { x: r.x - pad, y: r.y - pad, width: r.width + pad * 2, height: r.height + pad * 2 };
5016
+ }
5017
+ function sameRect(a, b) {
5018
+ if (!a || !b)
5019
+ return a === b;
5020
+ return (Math.abs(a.x - b.x) < 0.5 &&
5021
+ Math.abs(a.y - b.y) < 0.5 &&
5022
+ Math.abs(a.width - b.width) < 0.5 &&
5023
+ Math.abs(a.height - b.height) < 0.5);
5024
+ }
5025
+ /** Open Radix poppers (a select's list, a menu): usable while a step runs. */
5026
+ const POPPER_SELECTOR = "[data-radix-popper-content-wrapper]";
5027
+ /** Toasts stay usable above the tour. */
5028
+ const TOASTER_SELECTOR = "[data-sonner-toaster]";
5029
+ /** Open dialogs (Radix dialog, alert dialog, sheet, popover content). */
5030
+ const OPEN_DIALOG_SELECTOR = '[role="dialog"][data-state="open"],[role="alertdialog"][data-state="open"]';
5031
+ /**
5032
+ * Whether an open dialog of the app's covers the target: the target is
5033
+ * neither in it nor around it (a confirm opened by the step's own button).
5034
+ * The ring and the hand would be drawn over the dialog, pointing at a button
5035
+ * behind it.
5036
+ */
5037
+ function coveredByDialog(el) {
5038
+ if (!hasDocument() || !el)
5039
+ return false;
5040
+ for (const d of Array.from(document.querySelectorAll(OPEN_DIALOG_SELECTOR))) {
5041
+ if (inGuideLayer(d) || !isPresent(d))
5042
+ continue;
5043
+ if (d.contains(el) || el.contains(d))
5044
+ continue;
5045
+ return true;
5046
+ }
5047
+ return false;
5048
+ }
5049
+ function openPoppers() {
5050
+ if (!hasDocument())
5051
+ return [];
5052
+ return Array.from(document.querySelectorAll(POPPER_SELECTOR)).filter(isPresent);
5053
+ }
5054
+ function inGuideLayer(node) {
5055
+ if (!node || typeof Node === "undefined" || !(node instanceof Node))
5056
+ return false;
5057
+ const el = node instanceof Element ? node : node.parentElement;
5058
+ return !!el?.closest(`[${GUIDE_LAYER_ATTRIBUTE}]`);
5059
+ }
5060
+ function prefersReducedMotion() {
5061
+ return typeof window !== "undefined" && !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
5062
+ }
5063
+ function isPhoneWidth() {
5064
+ return typeof window !== "undefined" && window.innerWidth < 768;
5065
+ }
5066
+ /* ---------------- what is really on screen ---------------- */
5067
+ const INFINITE = 1e7;
5068
+ /** The overlap of two rectangles, or null when they do not meet. */
5069
+ function intersectRect(a, b) {
5070
+ const x = Math.max(a.x, b.x);
5071
+ const y = Math.max(a.y, b.y);
5072
+ const right = Math.min(a.x + a.width, b.x + b.width);
5073
+ const bottom = Math.min(a.y + a.height, b.y + b.height);
5074
+ if (right - x <= 0 || bottom - y <= 0)
5075
+ return null;
5076
+ return { x, y, width: right - x, height: bottom - y };
5077
+ }
5078
+ /** The part of `rect` inside every clip (scroll boxes, the viewport); null when none is. */
5079
+ function visibleRect(rect, clips) {
5080
+ let r = rect;
5081
+ for (const c of clips) {
5082
+ if (!r)
5083
+ return null;
5084
+ r = intersectRect(r, c);
5085
+ }
5086
+ return r;
5087
+ }
5088
+ const clipsX = (v) => v !== "visible";
5089
+ const scrollsX = (v) => v === "auto" || v === "scroll";
5090
+ /**
5091
+ * The ancestors that cut the element off: anything with overflow other than
5092
+ * visible on an axis. The body and the root scroll the page and are covered by
5093
+ * the viewport. Read once per target; their rectangles are read every frame.
5094
+ */
5095
+ function clipAncestors(el) {
5096
+ const out = [];
5097
+ if (typeof getComputedStyle !== "function")
5098
+ return out;
5099
+ for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
5100
+ if (n.hasAttribute(GUIDE_LAYER_ATTRIBUTE))
5101
+ break;
5102
+ const s = getComputedStyle(n);
5103
+ const x = clipsX(s.overflowX);
5104
+ const y = clipsX(s.overflowY);
5105
+ if (x || y)
5106
+ out.push({ el: n, x, y });
5107
+ if (s.position === "fixed")
5108
+ break;
5109
+ }
5110
+ return out;
5111
+ }
5112
+ /** An ancestor's clip as a rectangle: unbounded on an axis it does not clip. */
5113
+ function clipRectOf(c) {
5114
+ const r = c.el.getBoundingClientRect();
5115
+ return {
5116
+ x: c.x ? r.left : -INFINITE,
5117
+ y: c.y ? r.top : -INFINITE,
5118
+ width: c.x ? r.width : INFINITE * 2,
5119
+ height: c.y ? r.height : INFINITE * 2,
5120
+ };
5121
+ }
5122
+ function viewportRect() {
5123
+ const vv = typeof window !== "undefined" ? window.visualViewport : undefined;
5124
+ return {
5125
+ x: 0,
5126
+ y: vv ? vv.offsetTop : 0,
5127
+ width: window.innerWidth,
5128
+ height: vv ? vv.height : window.innerHeight,
5129
+ };
5130
+ }
5131
+ /**
5132
+ * The part of the element a person can see: its box cut by every scroll box
5133
+ * around it and by the viewport. The spotlight, its hole, the ring and the
5134
+ * hand use this, so a tab half out of a sideways-scrolling row of tabs is not
5135
+ * spotlit where it cannot be pressed. Null when none of it is on screen.
5136
+ */
5137
+ function visibleRectOf(el, ancestors = clipAncestors(el)) {
5138
+ return visibleRect(rectOf(el), [...ancestors.map(clipRectOf), viewportRect()]);
5139
+ }
5140
+ /** Inside a box that scrolls sideways (with somewhere to scroll) that is itself on screen. */
5141
+ function inSidewaysScroller(el) {
5142
+ if (typeof getComputedStyle !== "function")
5143
+ return false;
5144
+ for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
5145
+ const s = getComputedStyle(n);
5146
+ if (scrollsX(s.overflowX) && n.scrollWidth > n.clientWidth + 1) {
5147
+ const r = n.getBoundingClientRect();
5148
+ return r.width > 0 && r.right > 0 && r.left < window.innerWidth;
5149
+ }
5150
+ }
5151
+ return false;
5152
+ }
5153
+ /**
5154
+ * How to bring a target into view, or null when it already is: to the middle
5155
+ * when it is above or below the comfortable band (under the header, at the
5156
+ * bottom edge), the nearest edge when only a side is cut off (a tab out of a
5157
+ * sideways-scrolling row, on a phone).
5158
+ */
5159
+ function revealPlan(rect, visible, viewportHeight) {
5160
+ const offVertically = rect.y < 70 || rect.y + rect.height > viewportHeight - 20;
5161
+ const cutSideways = !visible || visible.width < rect.width - 1;
5162
+ if (!offVertically && !cutSideways)
5163
+ return null;
5164
+ return { block: offVertically ? "center" : "nearest", inline: "nearest" };
5165
+ }
5166
+ /** Scrolls the target into view (instant under reduced motion). */
5167
+ function revealTarget(el) {
5168
+ const vh = window.visualViewport?.height ?? window.innerHeight;
5169
+ const plan = revealPlan(rectOf(el), visibleRectOf(el), vh);
5170
+ if (!plan)
5171
+ return;
5172
+ try {
5173
+ el.scrollIntoView({ ...plan, behavior: prefersReducedMotion() ? "auto" : "smooth" });
5174
+ }
5175
+ catch {
5176
+ el.scrollIntoView();
5177
+ }
5178
+ }
5179
+ /* ---------------- the scrim's holes, as one union ---------------- */
5180
+ /**
5181
+ * The scrim's blocking area: the screen (with a 10 px margin) minus the union
5182
+ * of the holes, as rectangles that do not overlap. Cutting each hole out with
5183
+ * an even-odd fill made the place where two holes overlap (a field and the
5184
+ * select list open over it) solid again, and the option there could not be
5185
+ * pressed.
5186
+ *
5187
+ * Every hole edge splits the screen into a grid; a cell is blocked when no
5188
+ * hole covers it. Cells in a row are joined, and identical rows stacked.
5189
+ */
5190
+ function blockedRects(holes, width, height) {
5191
+ const x0 = -10;
5192
+ const y0 = -10;
5193
+ const x1 = width + 10;
5194
+ const y1 = height + 10;
5195
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
5196
+ const hs = holes
5197
+ .filter(h => h.width > 0 && h.height > 0)
5198
+ .map(h => ({
5199
+ l: clamp(h.x, x0, x1),
5200
+ t: clamp(h.y, y0, y1),
5201
+ r: clamp(h.x + h.width, x0, x1),
5202
+ b: clamp(h.y + h.height, y0, y1),
5203
+ }))
5204
+ .filter(h => h.r > h.l && h.b > h.t);
5205
+ if (!hs.length)
5206
+ return [{ x: x0, y: y0, width: x1 - x0, height: y1 - y0 }];
5207
+ const uniq = (v) => Array.from(new Set(v)).sort((a, b) => a - b);
5208
+ const xs = uniq([x0, x1, ...hs.flatMap(h => [h.l, h.r])]);
5209
+ const ys = uniq([y0, y1, ...hs.flatMap(h => [h.t, h.b])]);
5210
+ const out = [];
5211
+ let prev = null;
5212
+ for (let j = 0; j < ys.length - 1; j++) {
5213
+ const top = ys[j];
5214
+ const bottom = ys[j + 1];
5215
+ const cy = (top + bottom) / 2;
5216
+ const row = [];
5217
+ for (let i = 0; i < xs.length - 1; i++) {
5218
+ const left = xs[i];
5219
+ const right = xs[i + 1];
5220
+ const cx = (left + right) / 2;
5221
+ const covered = hs.some(h => cx > h.l && cx < h.r && cy > h.t && cy < h.b);
5222
+ if (covered)
5223
+ continue;
5224
+ const last = row[row.length - 1];
5225
+ if (last && last.x + last.width === left)
5226
+ last.width = right - last.x;
5227
+ else
5228
+ row.push({ x: left, y: top, width: right - left, height: bottom - top });
5229
+ }
5230
+ const key = row.map(r => `${r.x},${r.width}`).join("|");
5231
+ if (prev && prev.key === key) {
5232
+ for (const r of prev.rects)
5233
+ r.height += bottom - top;
5234
+ }
5235
+ else {
5236
+ out.push(...row);
5237
+ prev = { key, rects: row };
5238
+ }
5239
+ }
5240
+ return out;
5241
+ }
5242
+
5243
+ /**
5244
+ * The tour's stylesheet. The shell has no CSS pipeline and the apps only scan
5245
+ * its dist for Tailwind classes, which cannot carry keyframes; so the layer
5246
+ * brings its own sheet, namespaced `eg-`, drawn from the theme's tokens
5247
+ * (--primary carries each app's brand accent; light and dark follow).
5248
+ */
5249
+ const GUIDE_CSS = `
5250
+ [data-erp-guide-layer]{position:fixed;inset:0;z-index:1000;pointer-events:none;font-family:inherit;color:var(--popover-foreground,#1c2634);
5251
+ --eg-scrim:rgba(12,20,34,.64);--eg-card:var(--popover,#fff);--eg-fg:var(--popover-foreground,#1c2634);
5252
+ --eg-muted:var(--muted-foreground,#6d7886);--eg-soft:var(--muted,#eef3f9);--eg-line:var(--border,#e8ecf1);
5253
+ --eg-primary:var(--primary,#3280dd);--eg-on-primary:var(--primary-foreground,#fff);
5254
+ --eg-tint:color-mix(in oklab,var(--eg-primary) 13%,var(--eg-card));--eg-strong:color-mix(in oklab,var(--eg-primary) 82%,#000);
5255
+ --eg-danger:var(--destructive,#d23b4b);--eg-ok:#1d9a5f;--eg-gold:#e6a417;
5256
+ --eg-shadow:0 18px 50px -12px rgba(16,32,64,.35),0 4px 12px rgba(16,32,64,.08);line-height:1.5;font-size:14px}
5257
+ [data-erp-guide-layer] *{box-sizing:border-box}
5258
+ [data-erp-guide-layer] button{font:inherit;color:inherit;cursor:pointer}
5259
+ .eg-i{pointer-events:auto}
5260
+ .eg-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
5261
+ .eg-scrim-svg{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}
5262
+ .eg-scrim-svg .eg-scrim-fill{fill:var(--eg-scrim);pointer-events:none}
5263
+ .eg-scrim-svg .eg-scrim-hit{fill:transparent;pointer-events:all}
5264
+ .eg-scrim{position:fixed;inset:0;background:var(--eg-scrim);pointer-events:auto}
5265
+ .eg-scrim.eg-light{background:rgba(12,20,34,.45)}
5266
+ .eg-scrim.eg-faint{background:rgba(12,20,34,.35)}
5267
+ .eg-ring{position:fixed;border-radius:12px;pointer-events:none;box-shadow:0 0 0 3px #fff,0 0 0 6px var(--eg-primary)}
5268
+ .eg-ring.eg-move{transition:left .26s ease,top .26s ease,width .26s ease,height .26s ease}
5269
+ .eg-ring::after{content:"";position:absolute;inset:-6px;border-radius:15px;border:3px solid var(--eg-primary);animation:eg-pulse 1.6s ease-out infinite}
5270
+ .eg-ring.eg-flash::after{animation:eg-flash .5s ease 1}
5271
+ @keyframes eg-pulse{0%{opacity:.9;transform:scale(1)}100%{opacity:0;transform:scale(1.12)}}
5272
+ @keyframes eg-flash{0%,100%{opacity:1;transform:none}50%{opacity:.2}}
5273
+ .eg-hand{position:fixed;width:46px;height:46px;pointer-events:none;filter:drop-shadow(0 4px 6px rgba(0,0,0,.35));animation:eg-tap 1.1s ease-in-out infinite}
5274
+ .eg-hand svg{width:46px;height:46px;fill:#fff;stroke:#1c2634;stroke-width:1.4;stroke-linejoin:round;stroke-linecap:round}
5275
+ .eg-hand.eg-flip svg{transform:scaleY(-1)}
5276
+ @keyframes eg-tap{0%,100%{transform:translate(6px,8px)}50%{transform:translate(0,0)}}
5277
+ .eg-bubble{position:fixed;left:0;top:0;width:320px;background:var(--eg-card);color:var(--eg-fg);border-radius:14px;box-shadow:var(--eg-shadow);padding:14px 16px 12px;border-top:4px solid var(--eg-primary);outline:none;pointer-events:auto}
5278
+ .eg-bubble.eg-err{border-top-color:var(--eg-danger)}
5279
+ .eg-bubble.eg-nudge{animation:eg-nudge .38s ease}
5280
+ @keyframes eg-nudge{0%,100%{translate:0}20%{translate:-7px}40%{translate:6px}60%{translate:-4px}80%{translate:2px}}
5281
+ .eg-b-top{display:flex;justify-content:space-between;align-items:center;gap:8px;font-size:12px;color:var(--eg-muted)}
5282
+ .eg-b-top .eg-mis{font-weight:600;color:var(--eg-strong);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
5283
+ .eg-b-top .eg-cnt{white-space:nowrap;font-weight:600}
5284
+ .eg-pips{display:flex;gap:4px;margin:8px 0 10px}
5285
+ .eg-pips i{flex:1;height:4px;border-radius:2px;background:var(--eg-soft)}
5286
+ .eg-pips i.eg-d{background:var(--eg-primary)}
5287
+ .eg-pips i.eg-c{background:color-mix(in oklab,var(--eg-primary) 45%,var(--eg-card))}
5288
+ .eg-b-t{margin:0;font-size:16px;font-weight:600;line-height:1.45}
5289
+ .eg-b-w{margin:2px 0 0;font-size:13.5px;color:var(--eg-muted)}
5290
+ .eg-bubble.eg-err .eg-b-t{color:var(--eg-danger)}
5291
+ .eg-k{display:inline-block;background:var(--eg-tint);color:var(--eg-strong);border-radius:7px;padding:0 7px;font-weight:600}
5292
+ .eg-b-f{display:flex;align-items:center;justify-content:space-between;margin-top:12px;gap:8px}
5293
+ .eg-b-f .eg-btn{height:34px;padding:0 14px;font-size:13.5px}
5294
+ .eg-exit{border:0;background:none;color:var(--eg-muted);font-size:12.5px;padding:4px 0;text-decoration:underline;text-underline-offset:3px}
5295
+ .eg-exit:hover{color:var(--eg-fg)}
5296
+ .eg-arrow{position:absolute;width:14px;height:14px;background:var(--eg-card);transform:rotate(45deg);border-radius:2px}
5297
+ .eg-arrow.eg-top{background:var(--eg-primary)}
5298
+ .eg-bubble.eg-err .eg-arrow.eg-top{background:var(--eg-danger)}
5299
+ .eg-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:40px;padding:0 16px;border-radius:10px;border:1px solid transparent;font-size:14px;font-weight:600;white-space:nowrap}
5300
+ .eg-btn:focus-visible,.eg-exit:focus-visible,.eg-chip:focus-visible,.eg-x:focus-visible{outline:2px solid var(--eg-primary);outline-offset:2px}
5301
+ .eg-primary{background:var(--eg-primary);color:var(--eg-on-primary)!important}
5302
+ .eg-primary:hover{background:var(--eg-strong)}
5303
+ .eg-primary[disabled]{opacity:.55;cursor:default}
5304
+ .eg-ghost{background:var(--eg-card);border-color:var(--eg-line)}
5305
+ .eg-ghost:hover{background:var(--eg-soft)}
5306
+ .eg-ghost[disabled]{opacity:.55;cursor:default}
5307
+ .eg-link{background:none;border:0;color:var(--eg-muted);font-weight:500;padding:0 6px;height:32px}
5308
+ .eg-link:hover{color:var(--eg-fg);text-decoration:underline}
5309
+ .eg-modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(440px,calc(100vw - 32px));max-height:calc(100vh - 32px);overflow:auto;background:var(--eg-card);color:var(--eg-fg);border-radius:20px;box-shadow:var(--eg-shadow);padding:28px 28px 22px;text-align:center;outline:none;pointer-events:auto}
5310
+ .eg-modal.eg-pop{animation:eg-pop .32s cubic-bezier(.2,.9,.3,1.3)}
5311
+ @keyframes eg-pop{from{opacity:0;transform:translate(-50%,-46%) scale(.94)}}
5312
+ .eg-modal h2{margin:6px 0 4px;font-size:22px;font-weight:700;letter-spacing:-.2px;line-height:1.3}
5313
+ .eg-modal .eg-sub{margin:0;color:var(--eg-muted);font-size:14.5px}
5314
+ .eg-eyebrow{margin:0;font-size:12.5px;font-weight:600;letter-spacing:.3px;color:var(--eg-strong)}
5315
+ .eg-actions{display:grid;gap:6px;margin-top:20px}
5316
+ .eg-actions .eg-btn{height:44px}
5317
+ .eg-badge{width:64px;height:64px;border-radius:18px;margin:0 auto 12px;display:grid;place-items:center;background:var(--eg-tint);color:var(--eg-strong)}
5318
+ .eg-badge svg.eg-ic{width:30px;height:30px}
5319
+ .eg-quests{list-style:none;padding:0;margin:18px 0 0;text-align:left;display:grid;gap:6px}
5320
+ .eg-quests li{display:flex;align-items:center;gap:12px;padding:9px 12px;border-radius:11px;background:var(--eg-soft);font-size:14px}
5321
+ .eg-quests li .eg-n{width:26px;height:26px;border-radius:50%;background:var(--eg-card);border:1.5px solid var(--eg-line);display:grid;place-items:center;font-size:12px;font-weight:700;color:var(--eg-muted);flex:none}
5322
+ .eg-quests li.eg-first{background:var(--eg-tint)}
5323
+ .eg-quests li.eg-first .eg-n{border-color:var(--eg-primary);color:var(--eg-strong)}
5324
+ .eg-quests li.eg-ok .eg-n{background:var(--eg-ok);border-color:var(--eg-ok);color:#fff}
5325
+ .eg-quests li .eg-n svg.eg-ic{width:15px;height:15px;stroke-width:3}
5326
+ .eg-quests li .eg-t{flex:1}
5327
+ .eg-quests li small{color:var(--eg-muted);font-size:12px;white-space:nowrap}
5328
+ .eg-modal.eg-confirm{text-align:left;width:min(380px,calc(100vw - 32px));padding:22px}
5329
+ .eg-modal.eg-confirm h2{font-size:18px;margin-top:0}
5330
+ .eg-modal.eg-confirm .eg-actions{grid-template-columns:1fr 1fr}
5331
+ .eg-medal{width:84px;height:84px;border-radius:50%;margin:4px auto 10px;display:grid;place-items:center;color:#fff;background:radial-gradient(circle at 35% 30%,#ffd666,var(--eg-gold));box-shadow:0 0 0 8px #fff4d6;animation:eg-stamp .5s cubic-bezier(.2,.9,.3,1.4) .1s both}
5332
+ .eg-medal svg.eg-ic{width:42px;height:42px;stroke-width:2.6}
5333
+ @keyframes eg-stamp{from{transform:scale(.3) rotate(-25deg);opacity:0}}
5334
+ .eg-prog{display:flex;align-items:center;gap:10px;margin-top:16px;font-size:13px;color:var(--eg-muted);font-weight:600}
5335
+ .eg-prog .eg-bar{flex:1;height:8px;border-radius:4px;background:var(--eg-soft);overflow:hidden}
5336
+ .eg-prog .eg-bar i{display:block;height:100%;background:var(--eg-primary);border-radius:4px;transition:width .9s cubic-bezier(.2,.8,.2,1) .35s}
5337
+ .eg-burst{position:absolute;left:50%;top:70px;width:0;height:0;pointer-events:none}
5338
+ .eg-burst span{position:absolute;width:8px;height:12px;border-radius:2px;opacity:0;animation:eg-conf 1.1s cubic-bezier(.15,.7,.3,1) forwards}
5339
+ @keyframes eg-conf{0%{opacity:1;transform:translate(0,0) rotate(0)}100%{opacity:0;transform:translate(var(--x),var(--y)) rotate(var(--r))}}
5340
+ .eg-card{position:fixed;left:50%;bottom:28px;transform:translateX(-50%);width:min(360px,calc(100vw - 32px));background:var(--eg-card);color:var(--eg-fg);border-radius:14px;box-shadow:var(--eg-shadow);padding:14px 16px;border-top:4px solid var(--eg-primary);pointer-events:auto;outline:none}
5341
+ .eg-card .eg-row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px}
5342
+ .eg-loading{display:flex;align-items:center;gap:10px;font-weight:600}
5343
+ .eg-spin{width:18px;height:18px;border-radius:50%;border:2.5px solid var(--eg-soft);border-top-color:var(--eg-primary);animation:eg-spin .8s linear infinite;flex:none}
5344
+ @keyframes eg-spin{to{transform:rotate(360deg)}}
5345
+ .eg-chip{position:fixed;right:22px;bottom:22px;display:flex;align-items:center;gap:10px;height:48px;padding:0 18px 0 8px;border-radius:24px;border:1px solid var(--eg-line);background:var(--eg-card);color:var(--eg-fg);box-shadow:0 8px 24px -8px rgba(16,32,64,.3);font-weight:600;font-size:14px;pointer-events:auto}
5346
+ .eg-chip svg{width:34px;height:34px}
5347
+ .eg-chip.eg-hi{animation:eg-hi 1.2s ease 2}
5348
+ @keyframes eg-hi{50%{box-shadow:0 0 0 6px color-mix(in oklab,var(--eg-primary) 35%,transparent),0 8px 24px -8px rgba(16,32,64,.3)}}
5349
+ .eg-panel{position:fixed;right:22px;bottom:82px;width:360px;max-height:calc(100vh - 110px);overflow:auto;background:var(--eg-card);color:var(--eg-fg);border:1px solid var(--eg-line);border-radius:16px;box-shadow:var(--eg-shadow);outline:none;pointer-events:auto}
5350
+ .eg-panel-bd{display:none}
5351
+ .eg-q-h{display:flex;align-items:center;gap:10px;padding:16px 12px 4px 18px}
5352
+ .eg-q-h h2{margin:0;font-size:16px;font-weight:700;flex:1}
5353
+ .eg-q-h .eg-n{font-size:13px;color:var(--eg-muted);font-weight:600}
5354
+ .eg-x{width:34px;height:34px;border-radius:10px;border:0;background:none;display:grid;place-items:center;color:var(--eg-muted)}
5355
+ .eg-x:hover{background:var(--eg-soft)}
5356
+ .eg-x svg.eg-ic{width:18px;height:18px}
5357
+ .eg-panel .eg-prog{margin:6px 18px 8px}
5358
+ .eg-q-list{list-style:none;margin:0;padding:4px 10px 6px;display:grid;gap:2px}
5359
+ .eg-q-item{display:flex;align-items:center;gap:12px;padding:10px 8px;border-radius:11px}
5360
+ .eg-q-item.eg-next{background:var(--eg-tint)}
5361
+ .eg-q-item .eg-n{width:30px;height:30px;border-radius:50%;border:1.5px solid var(--eg-line);display:grid;place-items:center;font-size:12.5px;font-weight:700;color:var(--eg-muted);flex:none;background:var(--eg-card)}
5362
+ .eg-q-item.eg-next .eg-n{border-color:var(--eg-primary);color:var(--eg-strong)}
5363
+ .eg-q-item.eg-done .eg-n{background:var(--eg-ok);border-color:var(--eg-ok);color:#fff}
5364
+ .eg-q-item.eg-done .eg-n svg.eg-ic{width:16px;height:16px;stroke-width:3}
5365
+ .eg-q-item.eg-dim .eg-n{opacity:.55}
5366
+ .eg-q-item.eg-just .eg-n{animation:eg-stamp .55s cubic-bezier(.2,.9,.3,1.4) .2s both}
5367
+ .eg-q-item .eg-t{flex:1;min-width:0}
5368
+ .eg-q-item .eg-t b{display:block;font-size:14px;font-weight:600}
5369
+ .eg-q-item.eg-done .eg-t b{color:var(--eg-muted)}
5370
+ .eg-q-item .eg-t small{display:block;font-size:12px;color:var(--eg-muted)}
5371
+ .eg-q-item .eg-t small.eg-sk{color:#b06a00}
5372
+ .eg-q-item .eg-t small.eg-lock{color:var(--eg-fg);font-weight:500}
5373
+ .eg-q-item .eg-btn{height:32px;padding:0 12px;font-size:13px}
5374
+ .eg-q-acts{display:flex;flex-direction:column;align-items:flex-end;gap:2px}
5375
+ .eg-q-acts .eg-link{height:22px;font-size:12px;padding:0 2px}
5376
+ .eg-q-f{border-top:1px solid var(--eg-line);padding:8px 12px;display:flex;justify-content:flex-end}
5377
+ .eg-toast{position:fixed;left:50%;bottom:84px;transform:translateX(-50%);background:#1c2634;color:#fff;padding:10px 16px;border-radius:10px;font-size:13.5px;box-shadow:var(--eg-shadow);max-width:calc(100vw - 32px);pointer-events:none}
5378
+ svg.eg-ic{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex:none}
5379
+ @media (max-width:767px){
5380
+ .eg-bubble{width:auto}
5381
+ .eg-arrow{display:none}
5382
+ .eg-modal{top:auto;bottom:12px;transform:translateX(-50%);width:calc(100vw - 24px);padding:24px 20px 18px}
5383
+ .eg-modal.eg-pop{animation:eg-up .3s cubic-bezier(.2,.9,.3,1.1)}
5384
+ .eg-modal .eg-actions .eg-btn{height:46px}
5385
+ .eg-chip{right:16px;bottom:calc(16px + env(safe-area-inset-bottom))}
5386
+ .eg-panel-bd{display:block;position:fixed;inset:0;background:rgba(15,23,42,.38);pointer-events:auto}
5387
+ .eg-panel{left:0;right:0;bottom:0;width:100%;max-height:85vh;border-radius:18px 18px 0 0;padding-bottom:env(safe-area-inset-bottom)}
5388
+ .eg-q-item{padding:12px 8px}
5389
+ .eg-card{bottom:calc(12px + env(safe-area-inset-bottom))}
5390
+ .eg-toast{bottom:calc(76px + env(safe-area-inset-bottom))}
5391
+ }
5392
+ @keyframes eg-up{from{opacity:0;transform:translate(-50%,30px)}}
5393
+ @media (prefers-reduced-motion:reduce){
5394
+ [data-erp-guide-layer] *,[data-erp-guide-layer] *::before,[data-erp-guide-layer] *::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important}
5395
+ .eg-ring::after{animation:none!important;opacity:1;transform:none}
5396
+ .eg-ring.eg-flash::after{animation:eg-flash .5s ease 1!important;animation-duration:.5s!important}
5397
+ .eg-hand{animation:none!important;transform:translate(4px,6px)}
5398
+ .eg-burst{display:none}
5399
+ .eg-bubble.eg-nudge{animation:none!important;border-top-color:var(--eg-danger)}
5400
+ }
5401
+ `;
5402
+
5403
+ /* ------------------------------------------------------------------ */
5404
+ /* Bits */
5405
+ /* ------------------------------------------------------------------ */
5406
+ const TH_MONTHS = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
5407
+ const pad2 = (n) => String(n).padStart(2, "0");
5408
+ /** "26 ต.ค. 2569 13:04" — day, month, Buddhist year, 24 h. */
5409
+ function formatThaiDateTime(iso) {
5410
+ if (!iso)
5411
+ return "";
5412
+ const d = new Date(iso);
5413
+ if (Number.isNaN(d.getTime()))
5414
+ return "";
5415
+ return `${d.getDate()} ${TH_MONTHS[d.getMonth()]} ${d.getFullYear() + 543} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
5416
+ }
5417
+ /** "กด [บันทึก]": the bracketed word is a chip in the brand colour. */
5418
+ function GuideTitle({ text }) {
5419
+ const parts = text.split(/(\[[^\]]+\])/g).filter(Boolean);
5420
+ return (jsx(Fragment$1, { children: parts.map((p, i) => p.startsWith("[") && p.endsWith("]") ? (jsx("span", { className: "eg-k", children: p.slice(1, -1) }, i)) : (jsx(React.Fragment, { children: p }, i))) }));
5421
+ }
5422
+ const Svg = ({ children, className = "eg-ic" }) => (jsx("svg", { className: className, viewBox: "0 0 24 24", "aria-hidden": "true", children: children }));
5423
+ const IconCheck = () => (jsx(Svg, { children: jsx("path", { d: "M20 6 9 17l-5-5" }) }));
5424
+ const IconX = () => (jsx(Svg, { children: jsx("path", { d: "M18 6 6 18M6 6l12 12" }) }));
5425
+ const IconFlag = () => (jsxs(Svg, { children: [jsx("path", { d: "M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" }), jsx("path", { d: "M4 22v-7" })] }));
5426
+ const IconTrophy = () => (jsx(Svg, { children: jsx("path", { d: "M6 9H4.5a2.5 2.5 0 0 1 0-5H6M18 9h1.5a2.5 2.5 0 0 0 0-5H18M4 22h16M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22M18 2H6v7a6 6 0 0 0 12 0V2Z" }) }));
5427
+ const HAND_PATH = "M18 11V9.5a2 2 0 0 0-4 0V9a2 2 0 0 0-4 0v.5V4a2 2 0 0 0-4 0v10l-1.6-1.6a2 2 0 0 0-2.83 2.83l3.6 3.6C6.66 20.3 8.6 22 11.5 22H14a8 8 0 0 0 8-8v-3a2 2 0 0 0-4 0z";
5428
+ /** Rounded-rectangle subpath for the scrim's holes. */
5429
+ function roundRect(r, radius) {
5430
+ const rad = Math.max(0, Math.min(radius, r.width / 2, r.height / 2));
5431
+ const { x, y, width: w, height: h } = r;
5432
+ return (`M${x + rad} ${y}H${x + w - rad}A${rad} ${rad} 0 0 1 ${x + w} ${y + rad}` +
5433
+ `V${y + h - rad}A${rad} ${rad} 0 0 1 ${x + w - rad} ${y + h}` +
5434
+ `H${x + rad}A${rad} ${rad} 0 0 1 ${x} ${y + h - rad}` +
5435
+ `V${y + rad}A${rad} ${rad} 0 0 1 ${x + rad} ${y}Z`);
5436
+ }
5437
+ const rectPath = (r) => `M${r.x} ${r.y}H${r.x + r.width}V${r.y + r.height}H${r.x}Z`;
5438
+ /**
5439
+ * The dim layer that eats every press outside the holes. The holes are a
5440
+ * union: where two overlap (a field and the select list open over it) the
5441
+ * page stays open.
5442
+ *
5443
+ * - The look: one rectangle masked by the rounded holes (a mask adds holes
5444
+ * up, so an overlap is not filled back in).
5445
+ * - The presses: a transparent path made of the screen minus the holes, as
5446
+ * rectangles that do not overlap (blockedRects). A press inside a hole
5447
+ * reaches the page underneath; any other lands on the path (marked
5448
+ * data-eg-block) and is cancelled.
5449
+ */
5450
+ function Scrim({ holes, width, height }) {
5451
+ const maskId = "eg-scrim-mask-" + React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
5452
+ const block = blockedRects(holes, width, height).map(rectPath).join("");
5453
+ return (jsxs("svg", { className: "eg-scrim-svg", width: width, height: height, "aria-hidden": "true", children: [holes.length ? (jsx("defs", { children: jsxs("mask", { id: maskId, maskUnits: "userSpaceOnUse", x: -10, y: -10, width: width + 20, height: height + 20, children: [jsx("rect", { x: -10, y: -10, width: width + 20, height: height + 20, fill: "#fff" }), holes.map((h, i) => (jsx("path", { d: roundRect(h, 12), fill: "#000" }, i)))] }) })) : null, jsx("rect", { className: "eg-scrim-fill", x: -10, y: -10, width: width + 20, height: height + 20, mask: holes.length ? `url(#${maskId})` : undefined }), jsx("path", { className: "eg-scrim-hit", d: block, "data-eg-block": "" })] }));
5454
+ }
5455
+ /** Whether two rectangles overlap. */
5456
+ const meets = (a, b) => !!intersectRect(a, b);
5457
+ /** The smallest rectangle around all of them. */
5458
+ function boundingRect(rs) {
5459
+ const x = Math.min(...rs.map(r => r.x));
5460
+ const y = Math.min(...rs.map(r => r.y));
5461
+ const right = Math.max(...rs.map(r => r.x + r.width));
5462
+ const bottom = Math.max(...rs.map(r => r.y + r.height));
5463
+ return { x, y, width: right - x, height: bottom - y };
5464
+ }
5465
+ /** Where the bubble may go, in order of preference. */
5466
+ const BUBBLE_PLACEMENTS = ["right", "bottom", "top", "left"];
5467
+ /**
5468
+ * The first placement (in BUBBLE_PLACEMENTS order) whose bubble is on screen,
5469
+ * off the target (with its open list), and off everything to keep clear;
5470
+ * failing that, the first that is only on screen and off the target; -1 when
5471
+ * none is.
5472
+ */
5473
+ function pickPlacement(results, bw, bh, anchor, clear, bounds) {
5474
+ const box = (r) => ({ x: r.x, y: r.y, width: bw, height: bh });
5475
+ const fits = (b) => b.x >= bounds.x - 1 && b.y >= bounds.y - 1 && b.x + b.width <= bounds.x + bounds.width + 1 && b.y + b.height <= bounds.y + bounds.height + 1;
5476
+ const ok = results.map(r => {
5477
+ const b = box(r);
5478
+ return fits(b) && !meets(b, anchor);
5479
+ });
5480
+ const best = results.findIndex((r, i) => ok[i] && !clear.some(c => meets(box(r), c)));
5481
+ return best >= 0 ? best : ok.indexOf(true);
5482
+ }
5483
+ const BUBBLE_TITLE_ID = "eg-bubble-title";
5484
+ const BUBBLE_WHY_ID = "eg-bubble-why";
5485
+ function useNudge(nudge, ref) {
5486
+ const first = useRef(nudge);
5487
+ useEffect(() => {
5488
+ if (nudge === first.current)
5489
+ return;
5490
+ const el = ref.current;
5491
+ if (!el)
5492
+ return;
5493
+ el.classList.remove("eg-nudge");
5494
+ void el.offsetWidth;
5495
+ el.classList.add("eg-nudge");
5496
+ }, [nudge, ref]);
5497
+ }
5498
+ function StepLayer(p) {
5499
+ const { spot, phone, viewport } = p;
5500
+ const bubbleRef = useRef(null);
5501
+ const arrowRef = useRef(null);
5502
+ const ringRef = useRef(null);
5503
+ const [pos, setPos] = useState(null);
5504
+ useNudge(p.nudge, bubbleRef);
5505
+ // Flash the ring with each nudge too (a press outside the hole).
5506
+ const firstNudge = useRef(p.nudge);
5507
+ useEffect(() => {
5508
+ if (p.nudge === firstNudge.current)
5509
+ return;
5510
+ const el = ringRef.current;
5511
+ if (!el)
5512
+ return;
5513
+ el.classList.remove("eg-flash");
5514
+ void el.offsetWidth;
5515
+ el.classList.add("eg-flash");
5516
+ }, [p.nudge]);
5517
+ const showBubble = p.phase === "ready" && (!!spot || !p.hasTarget);
5518
+ const gap = p.showHand ? 34 : 14;
5519
+ const spotKey = spot ? `${spot.x}|${spot.y}|${spot.width}|${spot.height}` : "";
5520
+ const contentKey = `${p.bubble.title}|${p.bubble.why}|${p.bubble.error?.title ?? ""}|${p.bubble.showNext}`;
5521
+ // What the bubble sits beside: the target, with an open list over it (the
5522
+ // list is what the person is choosing from now). What it must not cover:
5523
+ // open lists, and the other anchors the step allows (a map step's
5524
+ // coordinate fields).
5525
+ const popoverList = p.popovers ?? [];
5526
+ const anchor = spot ? boundingRect([spot, ...popoverList.filter(o => meets(o, spot))]) : null;
5527
+ const clear = [...popoverList, ...p.holes];
5528
+ const anchorKey = anchor ? `${anchor.x}|${anchor.y}|${anchor.width}|${anchor.height}` : "";
5529
+ const clearKey = clear.map(r => `${r.x},${r.y},${r.width},${r.height}`).join(";");
5530
+ useLayoutEffect(() => {
5531
+ const el = bubbleRef.current;
5532
+ if (!el || !showBubble)
5533
+ return;
5534
+ const m = 16;
5535
+ if (!spot || !anchor) {
5536
+ // Nothing to point at: the middle of the screen (the bottom on a phone).
5537
+ const bw = el.offsetWidth;
5538
+ const bh = el.offsetHeight;
5539
+ setPos(phone
5540
+ ? { left: m, top: viewport.offsetTop + viewport.height - bh - m, side: "dock" }
5541
+ : { left: (window.innerWidth - bw) / 2, top: viewport.offsetTop + (viewport.height - bh) / 2, side: "dock" });
5542
+ return;
5543
+ }
5544
+ if (phone) {
5545
+ // Docked to the top or the bottom of the screen, whichever covers less
5546
+ // of the target and its open list (target in the lower half: top).
5547
+ const vh = viewport.height;
5548
+ const oy = viewport.offsetTop;
5549
+ const bh = el.offsetHeight;
5550
+ const topT = oy + m + 4;
5551
+ const botT = oy + vh - bh - m;
5552
+ const { y, height: h } = anchor;
5553
+ const overlapTop = Math.max(0, topT + bh + 8 - y);
5554
+ const overlapBot = Math.max(0, y + h + gap - botT);
5555
+ const top = y + h / 2 > vh / 2
5556
+ ? overlapTop <= overlapBot
5557
+ ? topT
5558
+ : botT
5559
+ : overlapBot <= overlapTop
5560
+ ? botT
5561
+ : topT;
5562
+ setPos({ left: m, top, side: "dock" });
5563
+ return;
5564
+ }
5565
+ let cancelled = false;
5566
+ const a = anchor;
5567
+ const ref = {
5568
+ getBoundingClientRect: () => ({
5569
+ x: a.x,
5570
+ y: a.y,
5571
+ left: a.x,
5572
+ top: a.y,
5573
+ width: a.width,
5574
+ height: a.height,
5575
+ right: a.x + a.width,
5576
+ bottom: a.y + a.height,
5577
+ }),
5578
+ };
5579
+ const at = (placement) => computePosition(ref, el, {
5580
+ strategy: "fixed",
5581
+ placement,
5582
+ middleware: [
5583
+ offset(placement.startsWith("bottom") ? gap : 14),
5584
+ shift({ padding: m }),
5585
+ ...(arrowRef.current ? [arrow({ element: arrowRef.current, padding: 14 })] : []),
5586
+ ],
5587
+ });
5588
+ Promise.all(BUBBLE_PLACEMENTS.map(at))
5589
+ .then(results => {
5590
+ if (cancelled)
5591
+ return;
5592
+ const bw = el.offsetWidth;
5593
+ const bh = el.offsetHeight;
5594
+ const bounds = { x: m, y: viewport.offsetTop + m, width: window.innerWidth - 2 * m, height: viewport.height - 2 * m };
5595
+ const i = pickPlacement(results, bw, bh, a, clear, bounds);
5596
+ if (i < 0) {
5597
+ // Nowhere beside it: the bottom-right corner.
5598
+ setPos({ left: window.innerWidth - bw - m, top: viewport.height + viewport.offsetTop - bh - m, side: "dock" });
5599
+ return;
5600
+ }
5601
+ const { x, y, placement, middlewareData } = results[i];
5602
+ const side = placement.split("-")[0];
5603
+ setPos({ left: x, top: y, side, ax: middlewareData.arrow?.x, ay: middlewareData.arrow?.y });
5604
+ })
5605
+ .catch(() => {
5606
+ if (!cancelled)
5607
+ setPos({ left: m, top: m, side: "dock" });
5608
+ });
5609
+ return () => {
5610
+ cancelled = true;
5611
+ };
5612
+ // The keys stand for spot, the lists, the holes and the bubble's size.
5613
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5614
+ }, [spotKey, anchorKey, clearKey, contentKey, phone, showBubble, gap, viewport.height, viewport.offsetTop]);
5615
+ const popovers = p.popovers ?? [];
5616
+ const covered = !!p.covered;
5617
+ const holes = [...(spot && !covered ? [spot] : []), ...popovers, ...p.holes];
5618
+ const ringShown = !!spot && p.phase === "ready" && !covered && !popovers.some(o => meets(o, spot));
5619
+ const hand = spot && p.showHand && p.phase === "ready" && !covered && !popovers.length ? handPosition(spot, viewport.height) : null;
5620
+ let arrowStyle;
5621
+ if (pos && pos.side !== "dock") {
5622
+ if (pos.side === "right")
5623
+ arrowStyle = { left: -7, top: pos.ay };
5624
+ else if (pos.side === "left")
5625
+ arrowStyle = { right: -7, top: pos.ay };
5626
+ else if (pos.side === "bottom")
5627
+ arrowStyle = { top: -9, left: pos.ax };
5628
+ else
5629
+ arrowStyle = { bottom: -7, left: pos.ax };
5630
+ }
5631
+ return (jsxs(Fragment$1, { children: [jsx(Scrim, { holes: p.phase === "ready" ? holes : [], width: viewport.width, height: Math.max(viewport.height + viewport.offsetTop, 0) }), spot && ringShown ? (jsx("div", { ref: ringRef, className: "eg-ring" + (p.moving ? " eg-move" : ""), style: { left: spot.x, top: spot.y, width: spot.width, height: spot.height }, "aria-hidden": "true" })) : null, hand ? (jsx("div", { className: "eg-hand" + (hand.flip ? " eg-flip" : ""), style: { left: hand.left, top: hand.top }, "aria-hidden": "true", children: jsx("svg", { viewBox: "0 0 24 24", children: jsx("path", { d: HAND_PATH }) }) })) : null, showBubble ? (jsxs("div", { ref: bubbleRef, className: "eg-bubble" + (p.bubble.error ? " eg-err" : ""), role: "dialog", "aria-modal": "false", "aria-labelledby": BUBBLE_TITLE_ID, "aria-describedby": BUBBLE_WHY_ID, tabIndex: -1, "data-eg-bubble": "", style: {
5632
+ left: pos?.left ?? 0,
5633
+ top: pos?.top ?? 0,
5634
+ width: phone ? viewport.width - 32 : undefined,
5635
+ visibility: pos ? "visible" : "hidden",
5636
+ }, children: [jsx(BubbleBody, { ...p }), jsx("span", { ref: arrowRef, className: "eg-arrow" + (pos?.side === "bottom" ? " eg-top" : ""), style: arrowStyle ?? { display: "none" }, "aria-hidden": "true" })] })) : null, p.phase === "waiting" ? (jsxs("div", { className: "eg-card", role: "status", "data-eg-card": "", children: [jsxs("div", { className: "eg-loading", children: [jsx("span", { className: "eg-spin", "aria-hidden": "true" }), "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14\u2026"] }), jsx("div", { className: "eg-row", children: jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }) })] })) : null, p.phase === "missing" ? (jsxs("div", { className: "eg-card eg-err", role: "alertdialog", "aria-labelledby": "eg-missing-t", "data-eg-card": "", tabIndex: -1, children: [jsx("p", { className: "eg-b-t", id: "eg-missing-t", children: "\u0E44\u0E21\u0E48\u0E1E\u0E1A\u0E2A\u0E48\u0E27\u0E19\u0E19\u0E35\u0E49\u0E1A\u0E19\u0E2B\u0E19\u0E49\u0E32" }), jsxs("div", { className: "eg-row", children: [jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onRetry, children: "\u0E25\u0E2D\u0E07\u0E2D\u0E35\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07" })] })] })) : null, p.phase === "away" ? (jsxs("div", { className: "eg-card", role: "dialog", "aria-modal": "false", "aria-labelledby": "eg-away-t", "data-eg-card": "", tabIndex: -1, children: [jsxs("div", { className: "eg-b-top", children: [jsxs("span", { className: "eg-mis", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", p.bubble.missionNo, " \u00B7 ", p.bubble.missionTitle, p.bubble.replay ? " (ทบทวน)" : ""] }), jsxs("span", { className: "eg-cnt", children: ["\u0E02\u0E31\u0E49\u0E19\u0E17\u0E35\u0E48 ", p.bubble.index + 1, "/", p.bubble.total] })] }), jsx("p", { className: "eg-b-t", id: "eg-away-t", style: { marginTop: 8 }, children: jsx(GuideTitle, { text: p.bubble.title }) }), jsxs("div", { className: "eg-row", children: [jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onGoResume, children: "\u0E17\u0E33\u0E15\u0E48\u0E2D" })] })] })) : null, p.confirmExit ? (jsx(ConfirmModal, { title: "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E44\u0E01\u0E14\u0E4C\u0E15\u0E2D\u0E19\u0E19\u0E35\u0E49?", line: "\u0E40\u0E1B\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E44\u0E14\u0E49\u0E17\u0E35\u0E48\u0E1B\u0E38\u0E48\u0E21 ? \u0E21\u0E38\u0E21\u0E02\u0E27\u0E32\u0E1A\u0E19", leaveLabel: "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E44\u0E01\u0E14\u0E4C", stayLabel: "\u0E17\u0E33\u0E15\u0E48\u0E2D", onLeave: p.onExitConfirm, onStay: p.onExitCancel })) : null] }));
5637
+ }
5638
+ function BubbleBody(p) {
5639
+ const b = p.bubble;
5640
+ const title = b.error ? b.error.title : b.title;
5641
+ const why = b.error ? (b.error.detail ?? "") : b.why;
5642
+ return (jsxs(Fragment$1, { children: [jsxs("div", { className: "eg-b-top", children: [jsxs("span", { className: "eg-mis", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", b.missionNo, " \u00B7 ", b.missionTitle, b.replay ? " (ทบทวน)" : ""] }), jsxs("span", { className: "eg-cnt", children: ["\u0E02\u0E31\u0E49\u0E19\u0E17\u0E35\u0E48 ", b.index + 1, "/", b.total] })] }), jsx("div", { className: "eg-pips", "aria-hidden": "true", children: Array.from({ length: b.total }, (_, i) => (jsx("i", { className: i < b.index ? "eg-d" : i === b.index ? "eg-c" : undefined }, i))) }), jsx("p", { className: "eg-b-t", id: BUBBLE_TITLE_ID, children: jsx(GuideTitle, { text: title }) }), jsx("p", { className: "eg-b-w", id: BUBBLE_WHY_ID, hidden: !why, children: jsx(GuideTitle, { text: why }) }), jsxs("div", { className: "eg-b-f", children: [jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: b.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsxs("span", { style: { display: "flex", gap: 6 }, children: [b.showEndWithoutSave ? (jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: p.onEndWithoutSave, children: "\u0E08\u0E1A\u0E42\u0E14\u0E22\u0E44\u0E21\u0E48\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01" })) : null, b.showNext ? (jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onNext, children: "\u0E16\u0E31\u0E14\u0E44\u0E1B" })) : null] })] })] }));
5643
+ }
5644
+ /** The fingertip at ≈62% across and down the target; upside down near the bottom. */
5645
+ function handPosition(spot, viewportHeight) {
5646
+ const { x, y, width: w, height: h } = spot;
5647
+ const px = x + Math.min(w * 0.62, w - 14);
5648
+ const py = y + h * 0.62;
5649
+ const flip = py + 50 > viewportHeight;
5650
+ return { left: px - 11.5, top: flip ? py - h * 0.3 - 42 : py - 4, flip };
5651
+ }
5652
+ /* ------------------------------------------------------------------ */
5653
+ /* Modals */
5654
+ /* ------------------------------------------------------------------ */
5655
+ function useAutoFocus() {
5656
+ const ref = useRef(null);
5657
+ useEffect(() => {
5658
+ ref.current?.focus({ preventScroll: true });
5659
+ }, []);
5660
+ return ref;
5661
+ }
5662
+ function ConfirmModal(p) {
5663
+ const stay = useAutoFocus();
5664
+ return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim eg-faint", "data-eg-block": "", onClick: p.onStay }), jsxs("div", { className: "eg-modal eg-confirm eg-pop", role: "alertdialog", "aria-modal": "true", "aria-labelledby": "eg-c-t", "aria-describedby": "eg-c-d", "data-eg-modal": "", children: [jsx("h2", { id: "eg-c-t", children: p.title }), jsx("p", { className: "eg-sub", id: "eg-c-d", style: { fontSize: 14 }, children: p.line }), jsxs("div", { className: "eg-actions", children: [jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: p.onLeave, children: p.leaveLabel }), jsx("button", { type: "button", ref: stay, className: "eg-btn eg-primary", onClick: p.onStay, children: p.stayLabel })] })] })] }));
5665
+ }
5666
+ function WelcomeModal(p) {
5667
+ const start = useAutoFocus();
5668
+ return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-w-t", "data-eg-modal": "", tabIndex: -1, children: [jsx("div", { className: "eg-badge", children: jsx(IconFlag, {}) }), jsx("p", { className: "eg-eyebrow", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsx("h2", { id: "eg-w-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsx("ol", { className: "eg-quests", children: p.missions.map((m, i) => (jsxs("li", { className: i === 0 ? "eg-first" : undefined, children: [jsx("span", { className: "eg-n", children: i + 1 }), jsx("span", { className: "eg-t", children: m.title }), jsxs("small", { children: [m.minutes, " \u0E19\u0E32\u0E17\u0E35"] })] }, i))) }), jsxs("div", { className: "eg-actions", children: [jsx("button", { type: "button", ref: start, className: "eg-btn eg-primary", onClick: p.onStart, children: "\u0E40\u0E23\u0E34\u0E48\u0E21\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E41\u0E23\u0E01" }), jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onSkip, children: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E1B\u0E01\u0E48\u0E2D\u0E19" })] })] }), p.confirm ? (jsx(ConfirmModal, { title: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E01\u0E14\u0E4C\u0E44\u0E1B\u0E01\u0E48\u0E2D\u0E19?", line: "\u0E40\u0E1B\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E44\u0E14\u0E49\u0E17\u0E35\u0E48\u0E1B\u0E38\u0E48\u0E21 ? \u0E21\u0E38\u0E21\u0E02\u0E27\u0E32\u0E1A\u0E19", leaveLabel: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E1B\u0E01\u0E48\u0E2D\u0E19", stayLabel: "\u0E40\u0E23\u0E34\u0E48\u0E21\u0E40\u0E25\u0E22", onLeave: p.onSkipConfirm, onStay: p.onSkipCancel })) : null] }));
5669
+ }
5670
+ function GateModal(p) {
5671
+ const go = useAutoFocus();
5672
+ return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-g-t", "data-eg-modal": "", tabIndex: -1, children: [jsx("div", { className: "eg-badge", children: jsx(IconFlag, {}) }), jsx("p", { className: "eg-eyebrow", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsx("h2", { id: "eg-g-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsxs("div", { className: "eg-actions", children: [jsx("a", { ref: go, className: "eg-btn eg-primary", href: p.href, style: { textDecoration: "none" }, children: p.actionLabel }), jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onLater, children: "\u0E44\u0E27\u0E49\u0E17\u0E35\u0E2B\u0E25\u0E31\u0E07" })] })] })] }));
5673
+ }
5674
+ const CONFETTI_COLOURS = ["#3b82f6", "#7db7ff", "#e6a417", "#ff7a6b", "#1d9a5f", "#b0d2ff"];
5675
+ function Confetti({ reduced }) {
5676
+ // Fixed per mount, so a re-render does not throw new pieces.
5677
+ const [pieces] = useState(() => Array.from({ length: 26 }, (_, i) => {
5678
+ const a = (Math.PI * 2 * i) / 26 + Math.random() * 0.3;
5679
+ const dist = 90 + Math.random() * 90;
5680
+ return {
5681
+ background: CONFETTI_COLOURS[i % CONFETTI_COLOURS.length],
5682
+ "--x": `${Math.cos(a) * dist}px`,
5683
+ "--y": `${Math.sin(a) * dist + 40}px`,
5684
+ "--r": `${Math.random() * 540 - 270}deg`,
5685
+ animationDelay: `${Math.random() * 0.12}s`,
5686
+ };
5687
+ }));
5688
+ if (reduced)
5689
+ return null;
5690
+ return (jsx("div", { className: "eg-burst", "aria-hidden": "true", children: pieces.map((s, i) => (jsx("span", { style: s }, i))) }));
5691
+ }
5692
+ function ProgressBar({ from, to, total, label }) {
5693
+ const [width, setWidth] = useState(total ? (from / total) * 100 : 0);
5694
+ useEffect(() => {
5695
+ // Two frames so the bar is drawn at `from` before it runs to `to`.
5696
+ let raf2 = 0;
5697
+ const raf1 = requestAnimationFrame(() => {
5698
+ raf2 = requestAnimationFrame(() => setWidth(total ? (to / total) * 100 : 0));
5699
+ });
5700
+ return () => {
5701
+ cancelAnimationFrame(raf1);
5702
+ cancelAnimationFrame(raf2);
5703
+ };
5704
+ }, [to, total]);
5705
+ return (jsxs("div", { className: "eg-prog", children: [jsx("div", { className: "eg-bar", children: jsx("i", { style: { width: `${width}%` } }) }), jsx("span", { children: label })] }));
5706
+ }
5707
+ function CelebrateModal(p) {
5708
+ const primary = useAutoFocus();
5709
+ return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim eg-light", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-cel-t", "data-eg-modal": "", tabIndex: -1, children: [jsx(Confetti, { reduced: p.reduced }), jsx("div", { className: "eg-medal", children: jsx(IconCheck, {}) }), jsxs("p", { className: "eg-eyebrow", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", p.missionNo, " \u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08"] }), jsx("h2", { id: "eg-cel-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsx(ProgressBar, { from: p.reduced ? p.done : Math.max(0, p.done - 1), to: p.done, total: p.total, label: `${p.done}/${p.total} ภารกิจ` }), jsxs("div", { className: "eg-actions", children: [p.nextTitle ? (jsxs("button", { type: "button", ref: primary, className: "eg-btn eg-primary", onClick: p.onNext, children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E16\u0E31\u0E14\u0E44\u0E1B: ", p.nextTitle] })) : null, jsx("button", { type: "button", ref: p.nextTitle ? undefined : primary, className: "eg-btn eg-link", onClick: p.onRest, children: "\u0E1E\u0E31\u0E01\u0E01\u0E48\u0E2D\u0E19" })] })] })] }));
5710
+ }
5711
+ function CompleteModal(p) {
5712
+ const primary = useAutoFocus();
5713
+ return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-f-t", "data-eg-modal": "", tabIndex: -1, children: [jsx(Confetti, { reduced: p.reduced }), jsx("div", { className: "eg-medal", children: jsx(IconTrophy, {}) }), jsxs("p", { className: "eg-eyebrow", children: ["\u0E04\u0E23\u0E1A ", p.total, " \u0E20\u0E32\u0E23\u0E01\u0E34\u0E08"] }), jsx("h2", { id: "eg-f-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsx("ol", { className: "eg-quests", children: p.missions.map((m, i) => (jsxs("li", { className: "eg-ok", children: [jsx("span", { className: "eg-n", children: jsx(IconCheck, {}) }), jsx("span", { className: "eg-t", children: m })] }, i))) }), jsxs("div", { className: "eg-actions", children: [jsx("button", { type: "button", ref: primary, className: "eg-btn eg-primary", onClick: p.onFinish, children: p.actionLabel }), p.secondary ? (jsx("a", { className: "eg-btn eg-ghost", href: p.secondary.href, style: { textDecoration: "none" }, children: p.secondary.label })) : null] })] })] }));
5714
+ }
5715
+ /* ------------------------------------------------------------------ */
5716
+ /* Quest chip and panel */
5717
+ /* ------------------------------------------------------------------ */
5718
+ function QuestChip({ done, total, pulse, onOpen }) {
5719
+ const ref = useRef(null);
5720
+ const first = useRef(pulse);
5721
+ useEffect(() => {
5722
+ if (pulse === first.current)
5723
+ return;
5724
+ const el = ref.current;
5725
+ if (!el)
5726
+ return;
5727
+ el.classList.remove("eg-hi");
5728
+ void el.offsetWidth;
5729
+ el.classList.add("eg-hi");
5730
+ }, [pulse]);
5731
+ const C = 2 * Math.PI * 14;
5732
+ const pct = total ? done / total : 0;
5733
+ return (jsxs("button", { ref: ref, type: "button", className: "eg-chip", onClick: onOpen, "aria-label": `ภารกิจเริ่มต้น เสร็จ ${done} จาก ${total}`, children: [jsxs("svg", { viewBox: "0 0 34 34", "aria-hidden": "true", children: [jsx("circle", { cx: "17", cy: "17", r: "14", fill: "none", stroke: "var(--eg-soft)", strokeWidth: "4" }), done ? (jsx("circle", { cx: "17", cy: "17", r: "14", fill: "none", stroke: "var(--eg-primary)", strokeWidth: "4", strokeLinecap: "round", strokeDasharray: `${C * pct} ${C}`, transform: "rotate(-90 17 17)" })) : null] }), "\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", done, "/", total] }));
5734
+ }
5735
+ function QuestPanel(p) {
5736
+ const ref = useAutoFocus();
5737
+ return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-panel-bd", onClick: p.onClose }), jsxs("section", { ref: ref, className: "eg-panel", role: "dialog", "aria-labelledby": "eg-q-t", tabIndex: -1, "data-eg-panel": "", children: [jsxs("div", { className: "eg-q-h", children: [jsx("h2", { id: "eg-q-t", children: "\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsxs("span", { className: "eg-n", children: [p.done, "/", p.total] }), jsx("button", { type: "button", className: "eg-x", onClick: p.onClose, "aria-label": "\u0E1B\u0E34\u0E14", children: jsx(IconX, {}) })] }), jsx("div", { className: "eg-prog", children: jsx("div", { className: "eg-bar", children: jsx("i", { style: { width: `${p.total ? (p.done / p.total) * 100 : 0}%` } }) }) }), jsx("ol", { className: "eg-q-list", children: p.items.map((it, i) => (jsx(QuestRow, { item: it, n: i + 1, just: p.justDone === it.key, gate: p.gate, onStart: p.onStart, onDismiss: p.onDismiss }, it.key))) }), p.canHideChip ? (jsx("div", { className: "eg-q-f", children: jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onHideChip, children: "\u0E0B\u0E48\u0E2D\u0E19\u0E1B\u0E38\u0E48\u0E21\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08" }) })) : null] })] }));
5738
+ }
5739
+ function QuestRow({ item, n, just, gate, onStart, onDismiss, }) {
5740
+ const v = item.view;
5741
+ const ticked = v === "done" || v === "already";
5742
+ const cls = "eg-q-item" +
5743
+ (ticked ? " eg-done" : v === "next" ? " eg-next" : "") +
5744
+ (v === "locked" || v === "waiting" ? " eg-dim" : "") +
5745
+ (just ? " eg-just" : "");
5746
+ let meta = `ประมาณ ${item.minutes} นาที`;
5747
+ if (v === "done")
5748
+ meta = item.completedAt ? `เสร็จ ${formatThaiDateTime(item.completedAt)}` : "เสร็จแล้ว";
5749
+ else if (v === "already")
5750
+ meta = "ทำไว้แล้ว";
5751
+ else if (v === "skipped")
5752
+ meta = jsx("span", { children: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E27\u0E49" });
5753
+ else if (v === "waiting" && gate)
5754
+ meta = gate.pending;
5755
+ // Locked: what to do first gets its own line under the title, so the title
5756
+ // keeps the row's width and the button stays short.
5757
+ const lockHint = v === "locked" && item.lockedBy ? `ทำ ${item.lockedBy} ก่อน` : null;
5758
+ let button;
5759
+ if (v === "done")
5760
+ button = jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: () => onStart(item.key, true), children: "\u0E17\u0E33\u0E0B\u0E49\u0E33" });
5761
+ else if (v === "already")
5762
+ button = jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: () => onStart(item.key, true), children: "\u0E14\u0E39\u0E27\u0E34\u0E18\u0E35\u0E17\u0E33" });
5763
+ else if (v === "waiting" && gate)
5764
+ button = (jsx("a", { className: "eg-btn eg-ghost", href: gate.href, style: { textDecoration: "none" }, children: gate.label }));
5765
+ else if (v === "locked")
5766
+ button = (jsx("button", { type: "button", className: "eg-btn eg-ghost", disabled: true, "aria-label": lockHint ? `เริ่ม (${lockHint})` : undefined, children: "\u0E40\u0E23\u0E34\u0E48\u0E21" }));
5767
+ else
5768
+ button = (jsx("button", { type: "button", className: "eg-btn " + (v === "next" ? "eg-primary" : "eg-ghost"), onClick: () => onStart(item.key, false), children: v === "skipped" || v === "active" ? "ทำต่อ" : "เริ่ม" }));
5769
+ const dismissable = item.optional && (v === "todo" || v === "next");
5770
+ return (jsxs("li", { className: cls, children: [jsx("span", { className: "eg-n", children: ticked ? jsx(IconCheck, {}) : n }), jsxs("div", { className: "eg-t", children: [jsx("b", { children: item.title }), lockHint ? jsx("small", { className: "eg-lock", children: lockHint }) : null, jsx("small", { className: v === "skipped" ? "eg-sk" : undefined, children: meta })] }), dismissable ? (jsxs("span", { className: "eg-q-acts", children: [button, jsx("button", { type: "button", className: "eg-btn eg-link", onClick: () => onDismiss(item.key), children: "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E49\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E19\u0E35\u0E49" })] })) : (button)] }));
5771
+ }
5772
+ function GuideToast({ text }) {
5773
+ return (jsx("div", { className: "eg-toast", role: "status", children: text }));
5774
+ }
5775
+
5776
+ const EMPLOYEE_RECORD_REQUIRED = "EMPLOYEE_RECORD_REQUIRED";
5777
+ const EMPLOYEE_RECORD_REQUIRED_EVENT = "erp:employee-record-required";
5778
+ const EMPLOYEE_RECORD_OK_EVENT = "erp:employee-record-ok";
5779
+ /**
5780
+ * Shown when the API refuses every request because the signed-in account has
5781
+ * no employee record in this organisation.
5782
+ *
5783
+ * A gate rather than a banner. Leave, attendance, approvals and payslips all
5784
+ * identify a person by that record, so once the server started enforcing it
5785
+ * every call fails — and without something that says so, the app becomes a
5786
+ * screen of error toasts with no explanation and no way forward.
5787
+ */
5788
+ function EmployeeRequiredGate({ platformBaseUrl, }) {
5789
+ const [blocked, setBlocked] = useState(false);
5790
+ const params = useParams();
5791
+ const code = params?.code ?? "";
5792
+ useEffect(() => {
5793
+ const onBlocked = () => setBlocked(true);
5794
+ const onOk = () => setBlocked(false);
5795
+ window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
5796
+ window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
5797
+ return () => {
5798
+ window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
5799
+ window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
5800
+ };
5801
+ }, []);
5802
+ if (!blocked)
5803
+ return null;
5804
+ const base = platformBaseUrl?.replace(/\/$/, "") ?? "";
5805
+ const createHref = code ? `${base}/${code}/employee/create` : `${base}/`;
5806
+ return (jsx("div", { className: "fixed inset-0 z-[100] flex items-center justify-center bg-background/95 p-6 backdrop-blur-sm", children: jsxs("div", { className: "w-full max-w-md space-y-5 text-center", children: [jsx(ContactRound, { className: "mx-auto h-12 w-12 text-muted-foreground" }), jsxs("div", { className: "space-y-2", children: [jsx("h1", { className: "text-lg font-semibold tracking-tight", children: "\u0E1A\u0E31\u0E0D\u0E0A\u0E35\u0E19\u0E35\u0E49\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E1C\u0E39\u0E01\u0E01\u0E31\u0E1A\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19" }), jsx("p", { className: "text-sm text-muted-foreground", children: "\u0E25\u0E32 \u0E25\u0E07\u0E40\u0E27\u0E25\u0E32 \u0E40\u0E1A\u0E34\u0E01\u0E40\u0E07\u0E34\u0E19 \u0E41\u0E25\u0E30\u0E01\u0E32\u0E23\u0E2D\u0E19\u0E38\u0E21\u0E31\u0E15\u0E34 \u0E23\u0E30\u0E1A\u0E38\u0E15\u0E31\u0E27\u0E04\u0E19\u0E08\u0E32\u0E01\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19 \u0E08\u0E36\u0E07\u0E22\u0E31\u0E07\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19\u0E43\u0E19\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23\u0E19\u0E35\u0E49\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49" })] }), jsxs("div", { className: "flex flex-wrap justify-center gap-2", children: [jsx(Button, { onClick: () => window.location.reload(), children: "\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48" }), jsx(Button, { variant: "outline", asChild: true, children: jsxs("a", { href: createHref, children: [jsx(UserPlus, { className: "mr-1 h-4 w-4" }), "\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19"] }) })] }), jsx("p", { className: "text-xs text-muted-foreground", children: "\u0E16\u0E49\u0E32\u0E04\u0E38\u0E13\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E41\u0E01\u0E49\u0E44\u0E02 \u0E43\u0E2B\u0E49\u0E41\u0E08\u0E49\u0E07\u0E1C\u0E39\u0E49\u0E14\u0E39\u0E41\u0E25\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" })] }) }));
5807
+ }
5808
+
5809
+ /* ------------------------------------------------------------------ */
5810
+ /* Fail-open wrappers */
5811
+ /* ------------------------------------------------------------------ */
5812
+ class GuideErrorBoundary extends React.Component {
5813
+ constructor() {
5814
+ super(...arguments);
5815
+ Object.defineProperty(this, "state", {
5816
+ enumerable: true,
5817
+ configurable: true,
5818
+ writable: true,
5819
+ value: { failed: false }
5820
+ });
5821
+ }
5822
+ static getDerivedStateFromError() {
5823
+ return { failed: true };
5824
+ }
5825
+ componentDidCatch(error) {
5826
+ if (typeof console !== "undefined")
5827
+ console.warn("[erp-shell guide] hidden after an error", error);
5828
+ try {
5829
+ publishGuideEntry(null, null);
5830
+ }
5831
+ catch {
5832
+ /* ignore */
5833
+ }
5834
+ }
5835
+ render() {
5836
+ return this.state.failed ? null : this.props.children;
5837
+ }
5838
+ }
5839
+ function GuideHost(props) {
5840
+ return (jsx(GuideErrorBoundary, { children: jsx(Suspense, { fallback: null, children: jsx(GuideHostInner, { ...props }) }) }));
5841
+ }
5842
+ let fallbackClient = null;
5843
+ function useShellQueryClient() {
5844
+ const provided = useContext(QueryClientContext);
5845
+ if (provided)
5846
+ return provided;
5847
+ fallbackClient ?? (fallbackClient = new QueryClient());
5848
+ return fallbackClient;
5849
+ }
5850
+ /* ------------------------------------------------------------------ */
5851
+ /* Session mirror (instant resume after F5) */
5852
+ /* ------------------------------------------------------------------ */
5853
+ const mirrorKey = (orgId, suite) => `erp-guide:${orgId}:${suite.key}`;
5854
+ function readMirror(orgId, suite) {
5855
+ try {
5856
+ const raw = sessionStorage.getItem(mirrorKey(orgId, suite));
5857
+ if (!raw)
5858
+ return null;
5859
+ const parsed = JSON.parse(raw);
5860
+ const row = parseRow(parsed);
5861
+ if (!row || row.guide_version !== suite.version)
5862
+ return null;
5863
+ return { ...row, server_status: parsed.server_status ?? null };
5864
+ }
5865
+ catch {
5866
+ return null;
5867
+ }
5868
+ }
5869
+ function writeMirror(orgId, suite, p) {
5870
+ try {
5871
+ sessionStorage.setItem(mirrorKey(orgId, suite), JSON.stringify(p));
5872
+ }
5873
+ catch {
5874
+ /* private mode: the server copy is enough */
5875
+ }
5876
+ }
5877
+ /* ------------------------------------------------------------------ */
5878
+ /* One tab at a time */
5879
+ /* ------------------------------------------------------------------ */
5880
+ /**
5881
+ * Whether this tab runs the tour. With two tabs open, the first holds a Web
5882
+ * Lock and the second shows nothing until the first goes away.
5883
+ */
5884
+ function usePrimaryTab(name) {
5885
+ const [primary, setPrimary] = useState(false);
5886
+ useEffect(() => {
5887
+ const locks = (typeof navigator !== "undefined" ? navigator.locks : undefined);
5888
+ if (!locks?.request) {
5889
+ setPrimary(true);
5890
+ return;
5891
+ }
5892
+ const abort = new AbortController();
5893
+ let release = null;
5894
+ locks
5895
+ .request(name, { signal: abort.signal }, () => {
5896
+ setPrimary(true);
5897
+ return new Promise(resolve => {
5898
+ release = resolve;
5899
+ });
5900
+ })
5901
+ .catch(() => {
5902
+ /* aborted on unmount */
5903
+ });
5904
+ return () => {
5905
+ abort.abort();
5906
+ release?.();
5907
+ setPrimary(false);
5908
+ };
5909
+ }, [name]);
5910
+ return primary;
5911
+ }
5912
+ /* ------------------------------------------------------------------ */
5913
+ /* Host */
5914
+ /* ------------------------------------------------------------------ */
5915
+ const TARGET_PAD = 6;
5916
+ const LOST_GRACE_MS = 350;
5917
+ const WAIT_MS = 8000;
5918
+ const WAIT_CAP_MS = 30000;
5919
+ const WELCOME_DELAY_MS = 500;
5920
+ const CELEBRATE_DELAY_MS = 450;
5921
+ const SAVE_DEBOUNCE_MS = 600;
5922
+ function GuideHostInner({ config, organizationId, code }) {
5923
+ const suite = config.suite;
5924
+ const client = useShellQueryClient();
5925
+ const pathname = usePathname() ?? "/";
5926
+ const searchParams = useSearchParams();
5927
+ const search = searchParams?.toString() ?? "";
5928
+ const router = useRouter();
5929
+ const { open: sidebarOpen } = useSidebar();
5930
+ const fetching = useIsFetching({ predicate: q => q.queryKey[0] !== "erp-shell" }, client);
5931
+ const primary = usePrimaryTab(`erp-guide:${organizationId}:${suite.key}`);
5932
+ // The shell's EmployeeRequiredGate is up: no tour over it.
5933
+ const [employeeBlocked, setEmployeeBlocked] = useState(false);
5934
+ useEffect(() => {
5935
+ const on = () => setEmployeeBlocked(true);
5936
+ const off = () => setEmployeeBlocked(false);
5937
+ window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, on);
5938
+ window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, off);
5939
+ return () => {
5940
+ window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, on);
5941
+ window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, off);
5942
+ };
5943
+ }, []);
5944
+ const query = useQuery({
5945
+ queryKey: ["erp-shell", "guides", organizationId, suite.app, suite.key, suite.version],
5946
+ queryFn: ({ signal }) => fetchGuides(organizationId, suite, signal),
5947
+ enabled: primary && config.ready !== false,
5948
+ staleTime: 5 * 60000,
5949
+ gcTime: 30 * 60000,
5950
+ retry: false,
5951
+ refetchOnWindowFocus: false,
5952
+ }, client);
5953
+ const answer = query.data ?? null;
5954
+ const live = !!answer && answer.audience !== "none" && !answer.newerOnServer && primary && config.ready !== false && !employeeBlocked;
5955
+ /* ---------------- machine ---------------- */
5956
+ const [state, setState] = useState(null);
5957
+ const stateRef = useRef(null);
5958
+ // What the server holds (payloadKey), so a save that would change nothing
5959
+ // is not sent and does not bump its rev.
5960
+ const savedKey = useRef(null);
5961
+ useEffect(() => {
5962
+ if (!answer || answer.audience === "none" || answer.newerOnServer) {
5963
+ stateRef.current = null;
5964
+ setState(null);
5965
+ return;
5966
+ }
5967
+ if (stateRef.current)
5968
+ return;
5969
+ savedKey.current = answer.progress && answer.progress.rev > 0 ? payloadKey(answer.progress, suite.app) : null;
5970
+ // Resume from whichever copy is further along: the server's, or this
5971
+ // tab's session copy from before a refresh (its rev is the server's).
5972
+ const mirror = readMirror(organizationId, suite);
5973
+ let progress = answer.progress;
5974
+ if (mirror && furtherProgress(mirror, progress) === mirror)
5975
+ progress = mergeProgress(mirror, progress);
5976
+ const s = initialGuideState(answer.audience, progress);
5977
+ stateRef.current = s;
5978
+ setState(s);
5979
+ }, [answer, organizationId, suite]);
5980
+ // The latest page facts, read by the machine through env.
5981
+ const pageRef = useRef({ pathname, search, sidebarOpen, facts: config.facts ?? {}, can: config.can });
5982
+ pageRef.current = { pathname, search, sidebarOpen, facts: config.facts ?? {}, can: config.can };
5983
+ const targetElRef = useRef(null);
5984
+ const env = useCallback(() => {
5985
+ const pg = pageRef.current;
5986
+ return {
5987
+ code,
5988
+ pathname: pg.pathname,
5989
+ search: new URLSearchParams(pg.search),
5990
+ facts: pg.facts,
5991
+ can: (key) => {
5992
+ try {
5993
+ return pg.can ? pg.can(key) : true;
5994
+ }
5995
+ catch {
5996
+ return true;
5997
+ }
5998
+ },
5999
+ isVisible: (anchor, id) => anchorVisible(anchor, id),
6000
+ sidebarOpen: pg.sidebarOpen,
6001
+ targetValue: () => fieldValue(targetElRef.current),
6002
+ };
6003
+ }, [code]);
6004
+ /* ---------------- effects: save, announce, toast, navigate ---------------- */
6005
+ const [liveText, setLiveText] = useState("");
6006
+ const [toast, setToast] = useState(null);
6007
+ const toastTimer = useRef(null);
6008
+ const saveTimer = useRef(null);
6009
+ const saving = useRef(null);
6010
+ const savePending = useRef(false);
6011
+ const flushSave = useCallback(async () => {
6012
+ if (saveTimer.current) {
6013
+ clearTimeout(saveTimer.current);
6014
+ saveTimer.current = null;
6015
+ }
6016
+ if (saving.current) {
6017
+ savePending.current = true;
6018
+ return;
6019
+ }
6020
+ const run = async () => {
6021
+ do {
6022
+ savePending.current = false;
6023
+ const cur = stateRef.current;
6024
+ if (!cur)
6025
+ return;
6026
+ if (payloadKey(cur.progress, suite.app) === savedKey.current)
6027
+ continue;
6028
+ const row = await saveGuides(organizationId, suite, cur.progress);
6029
+ if (row)
6030
+ savedKey.current = payloadKey(row, suite.app);
6031
+ if (row && stateRef.current) {
6032
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
6033
+ dispatchRef.current({ type: "serverRow", progress: row });
6034
+ }
6035
+ } while (savePending.current);
6036
+ };
6037
+ saving.current = run().finally(() => {
6038
+ saving.current = null;
6039
+ });
6040
+ }, [organizationId, suite]);
6041
+ const runEffects = useCallback((effects) => {
6042
+ for (const e of effects) {
6043
+ try {
6044
+ if (e.type === "save") {
6045
+ if (stateRef.current)
6046
+ writeMirror(organizationId, suite, stateRef.current.progress);
6047
+ if (e.immediate)
6048
+ void flushSave();
6049
+ else {
6050
+ if (saveTimer.current)
6051
+ clearTimeout(saveTimer.current);
6052
+ saveTimer.current = setTimeout(() => void flushSave(), SAVE_DEBOUNCE_MS);
6053
+ }
6054
+ }
6055
+ else if (e.type === "announce") {
6056
+ setLiveText("");
6057
+ setTimeout(() => setLiveText(e.text), 60);
6058
+ }
6059
+ else if (e.type === "toast") {
6060
+ setToast(e.text);
6061
+ if (toastTimer.current)
6062
+ clearTimeout(toastTimer.current);
6063
+ toastTimer.current = setTimeout(() => setToast(null), 3200);
6064
+ }
6065
+ else if (e.type === "navigate") {
6066
+ if (/^https?:\/\//i.test(e.href))
6067
+ window.location.assign(e.href);
6068
+ else
6069
+ router.push(e.href);
6070
+ }
6071
+ else if (e.type === "closeAppDialog") {
6072
+ // After this render takes the guard away, Escape to the app's
6073
+ // dialog (Radix listens on the document).
6074
+ setTimeout(() => {
6075
+ const t = document.activeElement ?? document.body;
6076
+ t.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true }));
6077
+ }, 60);
6078
+ }
6079
+ }
6080
+ catch {
6081
+ /* an effect never breaks the app */
6082
+ }
6083
+ }
6084
+ }, [flushSave, organizationId, router, suite]);
6085
+ const dispatch = useCallback((action) => {
6086
+ const cur = stateRef.current;
6087
+ if (!cur)
6088
+ return;
6089
+ let r;
6090
+ try {
6091
+ r = reduceGuide(cur, action, suite, env());
6092
+ }
6093
+ catch (err) {
6094
+ if (typeof console !== "undefined")
6095
+ console.warn("[erp-shell guide] stopped", err);
6096
+ stateRef.current = null;
6097
+ setState(null);
6098
+ return;
6099
+ }
6100
+ if (r.state !== cur) {
6101
+ stateRef.current = r.state;
6102
+ setState(r.state);
6103
+ }
6104
+ if (r.effects.length)
6105
+ runEffects(r.effects);
6106
+ }, [env, runEffects, suite]);
6107
+ const dispatchRef = useRef(dispatch);
6108
+ dispatchRef.current = dispatch;
6109
+ // Save what is pending when the page goes away.
6110
+ useEffect(() => {
6111
+ const flush = () => {
6112
+ if (saveTimer.current)
6113
+ void flushSave();
6114
+ };
6115
+ window.addEventListener("pagehide", flush);
6116
+ return () => {
6117
+ window.removeEventListener("pagehide", flush);
6118
+ flush();
6119
+ if (toastTimer.current)
6120
+ clearTimeout(toastTimer.current);
6121
+ };
6122
+ }, [flushSave]);
6123
+ /* ---------------- boot: resume, welcome ---------------- */
6124
+ const screen = state?.screen ?? { name: "idle" };
6125
+ const resumed = useRef(false);
6126
+ useEffect(() => {
6127
+ if (!live || !state || resumed.current)
6128
+ return;
6129
+ resumed.current = true;
6130
+ dispatch({ type: "resume" });
6131
+ }, [live, state, dispatch]);
6132
+ const welcomeRoutes = suite.welcomeRoutes ?? ["/[code]"];
6133
+ const onWelcomeRoute = welcomeRoutes.some(r => !!matchRoute(r, pathname, search, code));
6134
+ const due = !!state && live && welcomeDue(state, suite) && onWelcomeRoute && fetching === 0;
6135
+ const factsKey = useFactsKey(config.facts);
6136
+ useEffect(() => {
6137
+ if (!due)
6138
+ return;
6139
+ const t = setTimeout(() => dispatchRef.current({ type: "welcome" }), WELCOME_DELAY_MS);
6140
+ return () => clearTimeout(t);
6141
+ }, [due, factsKey]);
6142
+ /* ---------------- sync on route, sidebar, facts, DOM ---------------- */
6143
+ const inStep = live && screen.name === "step";
6144
+ useEffect(() => {
6145
+ if (inStep)
6146
+ dispatch({ type: "sync" });
6147
+ }, [inStep, pathname, search, sidebarOpen, factsKey, dispatch]);
6148
+ useEffect(() => {
6149
+ if (!inStep || typeof MutationObserver === "undefined")
6150
+ return;
6151
+ let raf = 0;
6152
+ const obs = new MutationObserver(records => {
6153
+ // Our own layer's changes are not the page's.
6154
+ if (records.every(r => inGuideLayer(r.target)))
6155
+ return;
6156
+ if (raf)
6157
+ return;
6158
+ raf = requestAnimationFrame(() => {
6159
+ raf = 0;
6160
+ dispatchRef.current({ type: "sync" });
6161
+ });
6162
+ });
6163
+ obs.observe(document.body, {
6164
+ childList: true,
6165
+ subtree: true,
6166
+ attributes: true,
6167
+ attributeFilter: ["data-state", "hidden", "aria-hidden", "class", "style", "open"],
6168
+ });
6169
+ return () => {
6170
+ obs.disconnect();
6171
+ if (raf)
6172
+ cancelAnimationFrame(raf);
6173
+ };
6174
+ }, [inStep]);
6175
+ /* ---------------- the current step ---------------- */
6176
+ const stepInfo = useMemo(() => {
6177
+ if (!state || screen.name !== "step")
6178
+ return null;
6179
+ const mission = findMission(suite, screen.mission);
6180
+ if (!mission)
6181
+ return null;
6182
+ const step = mission.steps[screen.index];
6183
+ if (!step)
6184
+ return null;
6185
+ const missionNo = suite.missions.indexOf(mission) + 1;
6186
+ return { mission, step, missionNo };
6187
+ }, [state, screen, suite]);
6188
+ const stepCtx = useMemo(() => {
6189
+ if (!state)
6190
+ return null;
6191
+ const e = env();
6192
+ const params = stepInfo?.step.route ? (matchRoute(stepInfo.step.route, e.pathname, e.search, code) ?? {}) : {};
6193
+ return guideContext(e, state.progress.context, params);
6194
+ // pathname/search/factsKey make it current.
6195
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6196
+ }, [state, stepInfo, env, code, pathname, search, factsKey]);
6197
+ const target = stepInfo && stepCtx && screen.name === "step"
6198
+ ? spotlightTarget(stepInfo.step, stepCtx, screen.bridge)
6199
+ : null;
6200
+ const targetKey = target ? `${target.anchor}|${target.id ?? ""}` : "";
6201
+ const phase = screen.name === "step" ? screen.phase : null;
6202
+ const stepId = screen.name === "step" ? `${screen.mission}:${screen.index}:${screen.bridge ? "b" : ""}` : "";
6203
+ /* Measure every frame while a step is shown: the spotlight follows
6204
+ scrolling, dialogs animating in, the drawer sliding, the keyboard. */
6205
+ const [layout, setLayout] = useState({
6206
+ spot: null,
6207
+ covered: false,
6208
+ holes: [],
6209
+ popovers: [],
6210
+ vw: 0,
6211
+ vh: 0,
6212
+ oy: 0,
6213
+ });
6214
+ useEffect(() => {
6215
+ if (!inStep) {
6216
+ targetElRef.current = null;
6217
+ return;
6218
+ }
6219
+ let raf = 0;
6220
+ let lostSince = null;
6221
+ let last = { spot: null, covered: false, holes: [], popovers: [], vw: 0, vh: 0, oy: 0 };
6222
+ targetElRef.current = target ? findAnchor(target.anchor, target.id) : null;
6223
+ const allow = stepInfo?.step.allow ?? [];
6224
+ // The spotlight is the part of the target a person can see: cut by the
6225
+ // scroll boxes around it (a row of tabs that scrolls sideways) and the
6226
+ // viewport. Wholly out of view (scrolled away up or down), its own box,
6227
+ // and the tour scrolls it back.
6228
+ let clipFor = null;
6229
+ let clips = [];
6230
+ const spotOf = (el) => {
6231
+ if (el !== clipFor) {
6232
+ clipFor = el;
6233
+ clips = clipAncestors(el);
6234
+ }
6235
+ return padRect(visibleRectOf(el, clips) ?? rectOf(el), TARGET_PAD);
6236
+ };
6237
+ const tick = () => {
6238
+ raf = requestAnimationFrame(tick);
6239
+ const vv = window.visualViewport;
6240
+ const vw = window.innerWidth;
6241
+ const vh = vv ? vv.height : window.innerHeight;
6242
+ const oy = vv ? vv.offsetTop : 0;
6243
+ let el = targetElRef.current;
6244
+ if (target && (!el || !el.isConnected)) {
6245
+ el = findAnchor(target.anchor, target.id);
6246
+ targetElRef.current = el;
6247
+ }
6248
+ let spot = null;
6249
+ if (target && el && isPresent(el)) {
6250
+ lostSince = null;
6251
+ spot = spotOf(el);
6252
+ }
6253
+ else if (target) {
6254
+ // Maybe re-rendered under another node.
6255
+ const again = findAnchor(target.anchor, target.id);
6256
+ if (again) {
6257
+ targetElRef.current = again;
6258
+ spot = spotOf(again);
6259
+ lostSince = null;
6260
+ }
6261
+ else if (phase === "ready") {
6262
+ lostSince ?? (lostSince = performance.now());
6263
+ if (performance.now() - lostSince > LOST_GRACE_MS) {
6264
+ lostSince = null;
6265
+ dispatchRef.current({ type: "targetLost" });
6266
+ }
6267
+ }
6268
+ }
6269
+ if (phase === "waiting" && spot)
6270
+ dispatchRef.current({ type: "sync" });
6271
+ const popovers = [];
6272
+ for (const p of openPoppers())
6273
+ popovers.push(padRect(rectOf(p), 2));
6274
+ const holes = [];
6275
+ for (const a of allow) {
6276
+ const ael = findAnchor(a);
6277
+ if (ael)
6278
+ holes.push(padRect(rectOf(ael), TARGET_PAD));
6279
+ }
6280
+ const covered = !!spot && coveredByDialog(targetElRef.current);
6281
+ const next = { spot, covered, holes, popovers, vw, vh, oy };
6282
+ const sameList = (a, b) => a.length === b.length && a.every((h, i) => sameRect(h, b[i]));
6283
+ if (!sameRect(next.spot, last.spot) ||
6284
+ next.covered !== last.covered ||
6285
+ next.vw !== last.vw ||
6286
+ next.vh !== last.vh ||
6287
+ next.oy !== last.oy ||
6288
+ !sameList(next.holes, last.holes) ||
6289
+ !sameList(next.popovers, last.popovers)) {
6290
+ last = next;
6291
+ setLayout(next);
6292
+ }
6293
+ };
6294
+ raf = requestAnimationFrame(tick);
6295
+ return () => cancelAnimationFrame(raf);
6296
+ // stepId/targetKey/phase restart the loop for a new step.
6297
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6298
+ }, [inStep, stepId, targetKey, phase]);
6299
+ /* Waiting for the target: 8 s of not-loading time (30 s at most). */
6300
+ const fetchingRef = useRef(fetching);
6301
+ fetchingRef.current = fetching;
6302
+ useEffect(() => {
6303
+ if (!inStep || phase !== "waiting")
6304
+ return;
6305
+ let idle = 0;
6306
+ const started = Date.now();
6307
+ const timeout = stepInfo?.step.timeoutMs ?? WAIT_MS;
6308
+ const iv = setInterval(() => {
6309
+ if (fetchingRef.current === 0 && document.visibilityState !== "hidden")
6310
+ idle += 250;
6311
+ if (idle >= timeout || Date.now() - started >= WAIT_CAP_MS) {
6312
+ clearInterval(iv);
6313
+ dispatchRef.current({ type: "timeout" });
6314
+ }
6315
+ }, 250);
6316
+ return () => clearInterval(iv);
6317
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6318
+ }, [inStep, stepId, phase, screen.name === "step" ? screen.misses : 0]);
6319
+ /* On a step becoming ready: bring the target into view, focus, describe. */
6320
+ const readyKey = inStep && phase === "ready" ? stepId : "";
6321
+ useEffect(() => {
6322
+ if (!readyKey || !stepInfo || screen.name !== "step")
6323
+ return;
6324
+ const el = targetElRef.current ?? (target ? findAnchor(target.anchor, target.id) : null);
6325
+ if (el)
6326
+ revealTarget(el);
6327
+ const isInput = !screen.bridge && stepKind(stepInfo.step) === "input";
6328
+ const t = setTimeout(() => {
6329
+ if (isInput && el) {
6330
+ const f = fieldOf(el);
6331
+ f?.focus({ preventScroll: true });
6332
+ }
6333
+ else {
6334
+ const b = document.querySelector(`[${GUIDE_LAYER_ATTRIBUTE}] [data-eg-bubble]`);
6335
+ b?.focus({ preventScroll: true });
6336
+ }
6337
+ }, 30);
6338
+ // The target is described by the bubble while the step lasts.
6339
+ const described = el ? (isInput ? fieldOf(el) : el) : null;
6340
+ const prev = described?.getAttribute("aria-describedby") ?? null;
6341
+ if (described)
6342
+ described.setAttribute("aria-describedby", [BUBBLE_TITLE_ID, BUBBLE_WHY_ID, prev].filter(Boolean).join(" "));
6343
+ return () => {
6344
+ clearTimeout(t);
6345
+ if (!described)
6346
+ return;
6347
+ if (prev)
6348
+ described.setAttribute("aria-describedby", prev);
6349
+ else
6350
+ described.removeAttribute("aria-describedby");
6351
+ };
6352
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6353
+ }, [readyKey]);
6354
+ /* Signals from the page: API answers, app events, presses, typing. */
6355
+ useEffect(() => {
6356
+ if (!inStep || !stepInfo)
6357
+ return;
6358
+ const onApi = (e) => {
6359
+ const d = e.detail;
6360
+ if (!d || typeof d.status !== "number")
6361
+ return;
6362
+ dispatchRef.current({ type: "signal", signal: { kind: "api", method: d.method, path: d.path, status: d.status, id: d.id, message: d.message } });
6363
+ };
6364
+ window.addEventListener(API_EVENT, onApi);
6365
+ const names = triggersOf(stepInfo.step).flatMap(t => ("event" in t ? [t.event] : []));
6366
+ const onApp = (name) => (e) => dispatchRef.current({ type: "signal", signal: { kind: "event", name, detail: e.detail ?? undefined } });
6367
+ const appHandlers = names.map(n => [GUIDE_EVENT_PREFIX + n, onApp(n)]);
6368
+ appHandlers.forEach(([n, h]) => window.addEventListener(n, h));
6369
+ const inTarget = (node) => {
6370
+ const el = targetElRef.current;
6371
+ return !!el && node instanceof Node && el.contains(node);
6372
+ };
6373
+ // After the app has handled it, so what it does comes first.
6374
+ const later = (a) => setTimeout(() => dispatchRef.current(a), 0);
6375
+ const onPress = (e) => {
6376
+ if (inTarget(e.target))
6377
+ later({ type: "signal", signal: { kind: "activate" } });
6378
+ };
6379
+ const onKey = (e) => {
6380
+ if ((e.key === "Enter" || e.key === " ") && inTarget(e.target) && stepKind(stepInfo.step) !== "input") {
6381
+ later({ type: "signal", signal: { kind: "activate" } });
6382
+ }
6383
+ };
6384
+ const onInput = (e) => {
6385
+ if (!inTarget(e.target))
6386
+ return;
6387
+ dispatchRef.current({ type: "signal", signal: { kind: "typing" } });
6388
+ later({ type: "signal", signal: { kind: "value", value: fieldValue(targetElRef.current) } });
6389
+ };
6390
+ document.addEventListener("pointerup", onPress, true);
6391
+ document.addEventListener("keydown", onKey, true);
6392
+ document.addEventListener("input", onInput, true);
6393
+ document.addEventListener("change", onInput, true);
6394
+ return () => {
6395
+ window.removeEventListener(API_EVENT, onApi);
6396
+ appHandlers.forEach(([n, h]) => window.removeEventListener(n, h));
6397
+ document.removeEventListener("pointerup", onPress, true);
6398
+ document.removeEventListener("keydown", onKey, true);
6399
+ document.removeEventListener("input", onInput, true);
6400
+ document.removeEventListener("change", onInput, true);
6401
+ };
6402
+ }, [inStep, stepInfo]);
6403
+ /* ---------------- the guard ---------------- */
6404
+ const modalScreen = live && (screen.name === "welcome" || screen.name === "gate" || screen.name === "celebrate" || screen.name === "complete");
6405
+ const panelOpen = live && !!state?.panelOpen;
6406
+ const guarding = inStep || modalScreen;
6407
+ const guardingRef = useRef(guarding);
6408
+ guardingRef.current = guarding;
6409
+ const modalRef = useRef(false);
6410
+ modalRef.current = modalScreen || (screen.name === "step" && (screen.confirmExit || screen.phase !== "ready"));
6411
+ const stepInfoRef = useRef(stepInfo);
6412
+ stepInfoRef.current = stepInfo;
6413
+ useEffect(() => {
6414
+ if (!live)
6415
+ return;
6416
+ const allowedTarget = (node) => {
6417
+ if (!(node instanceof Node))
6418
+ return false;
6419
+ const el = targetElRef.current;
6420
+ if (el && el.contains(node))
6421
+ return true;
6422
+ const elNode = node instanceof Element ? node : node.parentElement;
6423
+ if (!elNode)
6424
+ return false;
6425
+ if (elNode.closest(POPPER_SELECTOR) || elNode.closest(TOASTER_SELECTOR))
6426
+ return true;
6427
+ for (const a of stepInfoRef.current?.step.allow ?? []) {
6428
+ const ael = findAnchor(a);
6429
+ if (ael && ael.contains(node))
6430
+ return true;
6431
+ }
6432
+ return false;
6433
+ };
6434
+ const onPointer = (e) => {
6435
+ const t = e.target;
6436
+ if (inGuideLayer(t)) {
6437
+ // Our dim layer eats the press (and keeps focus where it is).
6438
+ if (t instanceof Element && t.closest("[data-eg-block]")) {
6439
+ e.preventDefault();
6440
+ if (e.type === "pointerdown")
6441
+ dispatchRef.current({ type: "blocked" });
6442
+ }
6443
+ // The app's open dialog or menu never hears the press (the click
6444
+ // itself goes on to our buttons).
6445
+ if (e.type !== "click")
6446
+ e.stopPropagation();
6447
+ return;
6448
+ }
6449
+ if (!guardingRef.current)
6450
+ return;
6451
+ if (modalRef.current || !allowedTarget(t)) {
6452
+ e.preventDefault();
6453
+ e.stopPropagation();
6454
+ if (e.type === "pointerdown")
6455
+ dispatchRef.current({ type: "blocked" });
6456
+ }
6457
+ };
6458
+ // Radix FocusScope pulls focus back into an open dialog; DismissableLayer
6459
+ // closes on focus outside. Neither may see focus moving to the tour.
6460
+ const onFocusIn = (e) => {
6461
+ if (inGuideLayer(e.target))
6462
+ e.stopPropagation();
6463
+ };
6464
+ const onFocusOut = (e) => {
6465
+ if (inGuideLayer(e.relatedTarget))
6466
+ e.stopPropagation();
6467
+ };
6468
+ const onKey = (e) => {
6469
+ const s = stateRef.current;
6470
+ if (!s)
6471
+ return;
6472
+ const sc = s.screen;
6473
+ const stop = () => {
6474
+ e.preventDefault();
6475
+ e.stopImmediatePropagation();
6476
+ };
6477
+ if (e.key === "Escape") {
6478
+ if (sc.name === "step") {
6479
+ stop();
6480
+ if (sc.confirmExit)
6481
+ dispatchRef.current({ type: "exitCancel" });
6482
+ else
6483
+ dispatchRef.current({ type: "exit" });
6484
+ }
6485
+ else if (sc.name === "welcome") {
6486
+ stop();
6487
+ dispatchRef.current({ type: sc.confirm ? "welcomeSkipCancel" : "welcomeSkip" });
6488
+ }
6489
+ else if (sc.name === "gate") {
6490
+ stop();
6491
+ dispatchRef.current({ type: "gateLater" });
6492
+ }
6493
+ else if (sc.name === "celebrate") {
6494
+ stop();
6495
+ dispatchRef.current({ type: "rest" });
6496
+ }
6497
+ else if (sc.name === "complete") {
6498
+ stop();
6499
+ dispatchRef.current({ type: "finish" });
6500
+ }
6501
+ else if (s.panelOpen) {
6502
+ stop();
6503
+ dispatchRef.current({ type: "closePanel" });
6504
+ }
6505
+ return;
6506
+ }
6507
+ if (!guardingRef.current)
6508
+ return;
6509
+ const layer = layerRef.current;
6510
+ if (e.key === "Tab") {
6511
+ // Tab stays on what the step is about: the target and the bubble, or
6512
+ // the open card.
6513
+ const modals = layer ? Array.from(layer.querySelectorAll("[data-eg-modal],[data-eg-card]")) : [];
6514
+ let list;
6515
+ if (sc.name === "step" && !sc.confirmExit && sc.phase === "ready") {
6516
+ const el = targetElRef.current;
6517
+ const step = stepInfoRef.current?.step;
6518
+ const isInput = !!step && !sc.bridge && stepKind(step) === "input";
6519
+ const inTargetList = el ? focusablesIn(isInput ? (fieldOf(el) ?? el) : el) : [];
6520
+ const bubble = layer?.querySelector("[data-eg-bubble]") ?? null;
6521
+ list = [...inTargetList, ...(bubble ? Array.from(bubble.querySelectorAll(FOCUSABLE)) : [])];
6522
+ for (const p of openPoppers())
6523
+ list.push(...focusablesIn(p));
6524
+ }
6525
+ else {
6526
+ const last = modals[modals.length - 1] ?? null;
6527
+ list = last ? Array.from(last.querySelectorAll(FOCUSABLE)) : [];
6528
+ }
6529
+ if (!list.length)
6530
+ return;
6531
+ stop();
6532
+ const i = list.indexOf(document.activeElement);
6533
+ const n = e.shiftKey ? (i <= 0 ? list.length - 1 : i - 1) : i === -1 || i === list.length - 1 ? 0 : i + 1;
6534
+ list[n].focus();
6535
+ return;
6536
+ }
6537
+ if (e.key === "Enter" || e.key === " ") {
6538
+ const active = document.activeElement;
6539
+ if (inGuideLayer(active))
6540
+ return;
6541
+ if (sc.name === "step" && sc.phase === "ready" && !sc.confirmExit && e.key === "Enter") {
6542
+ const step = stepInfoRef.current?.step;
6543
+ const el = targetElRef.current;
6544
+ if (step && stepKind(step) === "input" && el && active instanceof Node && el.contains(active) && !(active instanceof HTMLTextAreaElement)) {
6545
+ // During the tour Enter is ถัดไป, not "submit the form".
6546
+ stop();
6547
+ dispatchRef.current({ type: "next" });
6548
+ return;
6549
+ }
6550
+ }
6551
+ if (modalRef.current || !allowedTarget(active))
6552
+ stop();
6553
+ }
6554
+ };
6555
+ window.addEventListener("pointerdown", onPointer, true);
6556
+ window.addEventListener("mousedown", onPointer, true);
6557
+ window.addEventListener("touchstart", onPointer, { capture: true, passive: false });
6558
+ window.addEventListener("click", onPointer, true);
6559
+ window.addEventListener("focusin", onFocusIn, true);
6560
+ window.addEventListener("focusout", onFocusOut, true);
6561
+ window.addEventListener("keydown", onKey, true);
6562
+ return () => {
6563
+ window.removeEventListener("pointerdown", onPointer, true);
6564
+ window.removeEventListener("mousedown", onPointer, true);
6565
+ window.removeEventListener("touchstart", onPointer, true);
6566
+ window.removeEventListener("click", onPointer, true);
6567
+ window.removeEventListener("focusin", onFocusIn, true);
6568
+ window.removeEventListener("focusout", onFocusOut, true);
6569
+ window.removeEventListener("keydown", onKey, true);
6570
+ };
6571
+ }, [live]);
6572
+ /* Focus comes back to where it was when the tour lets go. */
6573
+ const lastFocus = useRef(null);
6574
+ const engaged = guarding || panelOpen;
6575
+ useLayoutEffect(() => {
6576
+ if (engaged) {
6577
+ if (!lastFocus.current) {
6578
+ const a = document.activeElement;
6579
+ lastFocus.current = a instanceof HTMLElement && !inGuideLayer(a) ? a : null;
6580
+ }
6581
+ return;
6582
+ }
6583
+ const back = lastFocus.current;
6584
+ lastFocus.current = null;
6585
+ if (back && back.isConnected)
6586
+ back.focus({ preventScroll: true });
6587
+ }, [engaged]);
6588
+ /* ---------------- the layer ---------------- */
6589
+ const [layer, setLayer] = useState(null);
6590
+ const layerRef = useRef(null);
6591
+ useEffect(() => {
6592
+ const el = document.createElement("div");
6593
+ el.setAttribute(GUIDE_LAYER_ATTRIBUTE, "");
6594
+ document.body.appendChild(el);
6595
+ layerRef.current = el;
6596
+ setLayer(el);
6597
+ // A Radix modal hides everything else from screen readers; not us.
6598
+ const obs = new MutationObserver(() => {
6599
+ if (el.getAttribute("aria-hidden") === "true")
6600
+ el.removeAttribute("aria-hidden");
6601
+ if (el.hasAttribute("data-aria-hidden"))
6602
+ el.removeAttribute("data-aria-hidden");
6603
+ if (el.hasAttribute("inert"))
6604
+ el.removeAttribute("inert");
6605
+ });
6606
+ obs.observe(el, { attributes: true, attributeFilter: ["aria-hidden", "data-aria-hidden", "inert"] });
6607
+ return () => {
6608
+ obs.disconnect();
6609
+ el.remove();
6610
+ layerRef.current = null;
6611
+ };
6612
+ }, []);
6613
+ const [phone, setPhone] = useState(false);
6614
+ const [reduced, setReduced] = useState(false);
6615
+ useEffect(() => {
6616
+ const sync = () => {
6617
+ setPhone(isPhoneWidth());
6618
+ setReduced(prefersReducedMotion());
6619
+ };
6620
+ sync();
6621
+ window.addEventListener("resize", sync);
6622
+ return () => window.removeEventListener("resize", sync);
6623
+ }, []);
6624
+ // The celebration waits a beat, so the new row can be seen first.
6625
+ const [celebrateShown, setCelebrateShown] = useState(false);
6626
+ const celebrateKey = screen.name === "celebrate" || screen.name === "complete" ? screen.name + (screen.name === "celebrate" ? screen.mission : "") : "";
6627
+ useEffect(() => {
6628
+ setCelebrateShown(false);
6629
+ if (!celebrateKey)
6630
+ return;
6631
+ const t = setTimeout(() => setCelebrateShown(true), CELEBRATE_DELAY_MS);
6632
+ return () => clearTimeout(t);
6633
+ }, [celebrateKey]);
6634
+ // Ring moves smoothly only right after a step change.
6635
+ const [moving, setMoving] = useState(false);
6636
+ useEffect(() => {
6637
+ if (!stepId)
6638
+ return;
6639
+ setMoving(true);
6640
+ const t = setTimeout(() => setMoving(false), 320);
6641
+ return () => clearTimeout(t);
6642
+ }, [stepId]);
6643
+ /* ---------------- the "?" menu entry ---------------- */
6644
+ const ctxIdle = useMemo(() => (state ? guideContext(env(), state.progress.context) : null), [state, env, factsKey, pathname]); // eslint-disable-line react-hooks/exhaustive-deps
6645
+ const done = state && ctxIdle ? settledCount(suite, state.progress, ctxIdle) : 0;
6646
+ const total = suite.missions.length;
6647
+ useEffect(() => {
6648
+ if (!live || !state) {
6649
+ publishGuideEntry(null, null);
6650
+ return;
6651
+ }
6652
+ publishGuideEntry({ done, total }, () => dispatchRef.current({ type: "openPanel" }));
6653
+ }, [live, state, done, total]);
6654
+ useEffect(() => () => publishGuideEntry(null, null), []);
6655
+ if (!live || !state || !layer || !ctxIdle)
6656
+ return null;
6657
+ /* ---------------- render ---------------- */
6658
+ const views = missionViews(suite, state.progress, ctxIdle);
6659
+ const gate = suite.gate;
6660
+ const gateHref = gate ? resolveText(gate.action.href, ctxIdle) : "";
6661
+ const gateFailing = gate ? gateState(suite, ctxIdle) === false : false;
6662
+ let content = null;
6663
+ if (screen.name === "welcome") {
6664
+ content = (jsx(WelcomeModal, { title: resolveText(suite.welcome.title, ctxIdle), subtitle: resolveText(suite.welcome.subtitle, ctxIdle) || `มาตั้งค่าบริษัทให้พร้อมใน ${total} ภารกิจ`, missions: suite.missions.map(m => ({ title: m.title, minutes: m.minutes })), confirm: screen.confirm, onStart: () => dispatch({ type: "welcomeStart" }), onSkip: () => dispatch({ type: "welcomeSkip" }), onSkipConfirm: () => dispatch({ type: "welcomeSkipConfirm" }), onSkipCancel: () => dispatch({ type: "welcomeSkipCancel" }) }));
6665
+ }
6666
+ else if (screen.name === "gate" && gate) {
6667
+ content = (jsx(GateModal, { title: gate.title, subtitle: gate.subtitle, actionLabel: gate.action.label, href: gateHref, onLater: () => dispatch({ type: "gateLater" }) }));
6668
+ }
6669
+ else if (screen.name === "step" && stepInfo && stepCtx) {
6670
+ const { mission, step, missionNo } = stepInfo;
6671
+ const kind = stepKind(step);
6672
+ const bridge = screen.bridge;
6673
+ content = (jsx(StepLayer, { spot: layout.spot, holes: layout.holes, popovers: layout.popovers, covered: layout.covered, viewport: { width: layout.vw || window.innerWidth, height: layout.vh || window.innerHeight, offsetTop: layout.oy }, phone: phone, showHand: bridge || (kind !== "input" && kind !== "view"), bubble: {
6674
+ missionNo,
6675
+ missionTitle: mission.title,
6676
+ replay: screen.replay,
6677
+ index: screen.index,
6678
+ total: mission.steps.length,
6679
+ title: bridge ? "กดปุ่มเมนู" : resolveText(step.title, stepCtx),
6680
+ why: bridge ? `เมนูทั้งหมดของ ${suite.appName} อยู่ในนี้` : resolveText(step.why, stepCtx),
6681
+ error: screen.error,
6682
+ showNext: !bridge && (kind === "input" || kind === "view"),
6683
+ showEndWithoutSave: !bridge && screen.replay && kind === "commit",
6684
+ }, hasTarget: bridge || !!step.target, phase: screen.phase, confirmExit: screen.confirmExit, nudge: state.nudge, moving: moving, onExit: () => dispatch({ type: "exit" }), onNext: () => dispatch({ type: "next" }), onEndWithoutSave: () => dispatch({ type: "endWithoutSave" }), onRetry: () => dispatch({ type: "retry" }), onGoResume: () => dispatch({ type: "goResume" }), onExitConfirm: () => dispatch({ type: "exitConfirm" }), onExitCancel: () => dispatch({ type: "exitCancel" }) }));
6685
+ }
6686
+ else if (screen.name === "celebrate" && celebrateShown) {
6687
+ const mission = findMission(suite, screen.mission);
6688
+ const next = findMission(suite, nextMissionKey(suite, state.progress, ctxIdle));
6689
+ if (mission) {
6690
+ content = (jsx(CelebrateModal, { missionNo: suite.missions.indexOf(mission) + 1, title: resolveText(mission.done?.title, ctxIdle) || `${mission.title}แล้ว`, subtitle: resolveText(mission.done?.subtitle, ctxIdle), done: done, total: total, nextTitle: next?.title ?? null, reduced: reduced, onNext: () => dispatch({ type: "celebrateNext" }), onRest: () => dispatch({ type: "rest" }) }));
6691
+ }
6692
+ }
6693
+ else if (screen.name === "complete" && celebrateShown) {
6694
+ const secondary = suite.complete.secondary;
6695
+ let secondaryHref;
6696
+ try {
6697
+ secondaryHref = secondary ? (typeof secondary.href === "function" ? secondary.href(ctxIdle) : secondary.href) : undefined;
6698
+ }
6699
+ catch {
6700
+ secondaryHref = undefined;
6701
+ }
6702
+ content = (jsx(CompleteModal, { total: total, title: resolveText(suite.complete.title, ctxIdle) || "บริษัทพร้อมใช้งานแล้ว", subtitle: resolveText(suite.complete.subtitle, ctxIdle), missions: suite.missions.map(m => m.title), actionLabel: suite.complete.action.label, secondary: secondary && secondaryHref ? { label: secondary.label, href: secondaryHref } : null, reduced: reduced, onFinish: () => dispatch({ type: "finish" }) }));
6703
+ }
6704
+ const items = views.map(v => ({
6705
+ key: v.mission.key,
6706
+ title: v.mission.title,
6707
+ minutes: v.mission.minutes,
6708
+ view: v.view,
6709
+ optional: !!v.mission.optional,
6710
+ completedAt: v.entry?.completed_at ?? null,
6711
+ lockedBy: v.view === "locked"
6712
+ ? (v.mission.after ?? [])
6713
+ .map(k => findMission(suite, k)?.title)
6714
+ .filter(Boolean)
6715
+ .join(", ")
6716
+ : undefined,
6717
+ }));
6718
+ const showChip = chipVisible(state, suite, ctxIdle);
6719
+ return createPortal(jsxs(Fragment$1, { children: [jsx("style", { children: GUIDE_CSS }), jsx("div", { className: "eg-sr", "aria-live": "polite", role: "status", children: liveText }), content, showChip ? jsx(QuestChip, { done: done, total: total, pulse: state.chipPulse, onOpen: () => dispatch({ type: "openPanel" }) }) : null, state.panelOpen && screen.name === "idle" ? (jsx(QuestPanel, { items: items, done: done, total: total, justDone: state.justDone, gate: gate && gateFailing ? { label: gate.action.label, pending: gate.pending, href: gateHref } : null, canHideChip: !state.progress.chip_hidden && state.progress.status !== "completed", onClose: () => dispatch({ type: "closePanel" }), onStart: (key, replayIt) => dispatch({ type: "start", mission: key, replay: replayIt }), onDismiss: key => dispatch({ type: "dismissMission", mission: key }), onHideChip: () => dispatch({ type: "hideChip" }) })) : null, toast ? jsx(GuideToast, { text: toast }) : null] }), layer);
6720
+ }
6721
+ /** A stable key for the facts object, so effects re-run when they change. */
6722
+ function useFactsKey(facts) {
6723
+ return useMemo(() => {
6724
+ try {
6725
+ return JSON.stringify(facts ?? {});
6726
+ }
6727
+ catch {
6728
+ return String(Math.random());
6729
+ }
6730
+ }, [facts]);
6731
+ }
6732
+
6733
+ /**
6734
+ * Top-level app chrome: sticky header, sidebar slot, content gutter and the
6735
+ * session/org-context plumbing that both Accounting and HR need. Apps wrap
6736
+ * it inside their `SidebarProvider` (server-rendered with the cookie-backed
6737
+ * `defaultOpen`) and their `ERPProvider`, then pass app-specific bits as
6738
+ * props.
6739
+ *
6740
+ * The padding contract is deliberately owned here so future style tweaks
6741
+ * (e.g. the recent left/right/bottom gutter pass) propagate to both apps via
6742
+ * an erp-shell bump — domain components must NOT add their own root padding
6743
+ * or content gets indented twice.
6744
+ */
6745
+ function AppLayoutShell({ children, sidebar, loadingComponent, breadcrumb, permissionProvider, organizationId, setOrganizationId, organizations, organizationsStatus, notMemberComponent, signInUrl, selectOrganizationUrl, chrome = "brand", workspaceHeader = "brand", headerEnd, mobileBrand, showHelp = true, helpApp, guides, }) {
6746
+ const { data: session, status } = useSession();
6747
+ const { open, setOpen } = useSidebar();
6748
+ const router = useRouter();
6749
+ const params = useParams();
6750
+ const code = params?.code;
6751
+ const extendedSession = session;
6752
+ // Track once-authenticated so a transient accessToken drop during the
6753
+ // periodic session refresh (SessionRefreshTrigger every 4 min) doesn't
6754
+ // blank the whole page. The initial-load gate below still handles cold
6755
+ // start; once we've seen a real token we render children optimistically
6756
+ // and let the API layer surface a real 401 if the token actually died.
6757
+ const hasSeenAccessTokenRef = useRef(false);
6758
+ useEffect(() => {
6759
+ if (extendedSession?.accessToken)
6760
+ hasSeenAccessTokenRef.current = true;
6761
+ }, [extendedSession?.accessToken]);
6762
+ // The URL's `[code]` is authoritative: the page mounts only once the active
6763
+ // organisation is the one it names (see url-org-gate.ts).
6764
+ //
6765
+ // The gate used to start only when the code had resolved AND an active id
6766
+ // existed, which left two holes. While the organisation list loaded, the
6767
+ // page mounted at once and its first requests carried the previous
6768
+ // organisation — /O26000021/procurement/purchase-requisition/<id> fetched
6769
+ // the document from O26000019 before the switch. And a code naming none of
6770
+ // the user's organisations never resolved, so the page rendered the
6771
+ // previous organisation's data under it.
6772
+ const urlOrgGate = resolveUrlOrgGate({
6773
+ code,
6774
+ organizations,
6775
+ organizationsStatus,
6776
+ organizationId,
6777
+ });
6778
+ const switchTargetId = urlOrgGate.state === "switching" ? urlOrgGate.targetId : null;
6779
+ // Switch the active organisation to the URL's. Once per target: the setter
6780
+ // writes the cookie through a server action, and re-firing it on every
6781
+ // render while that round trip is in flight only queues duplicates.
6782
+ const requestedSwitchRef = useRef(null);
6783
+ useEffect(() => {
6784
+ if (!switchTargetId) {
6785
+ requestedSwitchRef.current = null;
6786
+ return;
6787
+ }
6788
+ if (requestedSwitchRef.current === switchTargetId)
6789
+ return;
6790
+ requestedSwitchRef.current = switchTargetId;
6791
+ void setOrganizationId(switchTargetId);
6792
+ }, [switchTargetId, setOrganizationId]);
6793
+ // Once the user's organisations are known, requests prefer a stored
6794
+ // organisation that is one of them (getRequestOrganizationId).
6795
+ const organizationsLoaded = (organizationsStatus ??
6796
+ (organizations.length > 0 ? "success" : undefined)) === "success";
6797
+ useEffect(() => {
6798
+ if (organizationsLoaded) {
6799
+ setKnownOrganizationIds(organizations.map(org => org.id));
6800
+ }
6801
+ }, [organizationsLoaded, organizations]);
6802
+ // An active organisation that is not one of the user's — deleted, or left —
6803
+ // is replaced, so it stops being sent with every request. The URL's
6804
+ // organisation, when the user is a member, is the gate's switch above;
6805
+ // otherwise the user's only organisation, or none (they pick one: the
6806
+ // refusal below offers it, and a path without a code goes to the picker).
6807
+ // Once per stale id and target, so a setter that does not take cannot loop.
6808
+ const staleRecovery = resolveStaleOrganization({
6809
+ code,
6810
+ organizations,
6811
+ organizationsStatus,
6812
+ organizationId,
3574
6813
  });
3575
6814
  const staleRecoveryTarget = staleRecovery.action === "forget"
3576
6815
  ? null
@@ -3697,11 +6936,11 @@ function AppLayoutShell({ children, sidebar, loadingComponent, breadcrumb, permi
3697
6936
  // As in the design: the mark, then a menu button, and the
3698
6937
  // organisation on the right — no trail, no title, so the
3699
6938
  // organisation's name has the room it needs on a phone.
3700
- jsxs(Fragment$1, { children: [mobileBrand ? (jsx("div", { className: "shrink-0", children: mobileBrand })) : null, jsx("button", { type: "button", onClick: () => setOpen(!open), "aria-label": open ? "ปิดเมนู" : "เปิดเมนู", className: "grid size-[34px] shrink-0 place-items-center rounded-lg text-[var(--header-fg-muted)] transition-colors hover:bg-[var(--header-hover)] hover:text-[var(--header-fg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--header-fg-muted)]", children: jsx(LayoutGrid, { className: "size-5", strokeWidth: 1.65 }) })] })) : (jsx(SidebarTrigger, { className: "shrink-0 text-[var(--header-fg-muted)] hover:bg-[var(--header-hover)] hover:text-[var(--header-fg)] [&_svg]:!text-current" })), jsxs("div", { className: "flex min-w-0 flex-1 flex-col justify-center gap-0.5", children: [jsx("div", { className: "hidden min-w-0 sm:block", children: trail }), jsx("div", { id: "header-title", className: "min-w-0 max-sm:hidden" })] }), headerEnd || showHelp ? (jsxs("div", { className: "flex shrink-0 items-center gap-3 sm:gap-5", children: [headerEnd, showHelp ? jsx(HelpButton, {}) : null] })) : null] })] })) : (jsxs("div", { className: "sticky top-0 z-30 shrink-0 w-full", children: [jsx(HeaderBackground, {}), jsxs("header", { className: "relative shrink-0 gap-2 py-4 h-auto min-h-[123.5px] w-full z-10", children: [jsxs("div", { className: "flex w-full items-center gap-2 px-3 sm:px-4 lg:px-6", children: [jsx(SidebarTrigger, { className: "shrink-0 text-white hover:bg-white/10" }), jsx("div", { className: "flex-1 min-w-0", children: trail }), headerEnd || showHelp ? (jsxs("div", { className: "flex shrink-0 items-center gap-3", children: [headerEnd, showHelp ? jsx(HelpButton, {}) : null] })) : null] }), jsx("div", { id: "header-title" })] })] })), jsx(Suspense, { fallback: jsx("div", { className: "relative z-10 min-h-[calc(100vh-8rem)]", children: jsx("div", { className: "flex h-full items-center justify-center", children: jsxs("div", { className: "space-y-4 text-center", children: [jsx("div", { className: "mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary" }), jsx("p", { className: "text-sm text-muted-foreground", children: "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14..." })] }) }) }), children: jsx("div", { className: workspace
6939
+ jsxs(Fragment$1, { children: [mobileBrand ? (jsx("div", { className: "shrink-0", children: mobileBrand })) : null, jsx("button", { type: "button", onClick: () => setOpen(!open), "aria-label": open ? "ปิดเมนู" : "เปิดเมนู", ...guideAnchor("shell.menu-toggle"), className: "grid size-[34px] shrink-0 place-items-center rounded-lg text-[var(--header-fg-muted)] transition-colors hover:bg-[var(--header-hover)] hover:text-[var(--header-fg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--header-fg-muted)]", children: jsx(LayoutGrid, { className: "size-5", strokeWidth: 1.65 }) })] })) : (jsx(SidebarTrigger, { className: "shrink-0 text-[var(--header-fg-muted)] hover:bg-[var(--header-hover)] hover:text-[var(--header-fg)] [&_svg]:!text-current" })), jsxs("div", { className: "flex min-w-0 flex-1 flex-col justify-center gap-0.5", children: [jsx("div", { className: "hidden min-w-0 sm:block", children: trail }), jsx("div", { id: "header-title", className: "min-w-0 max-sm:hidden" })] }), headerEnd || showHelp ? (jsxs("div", { className: "flex shrink-0 items-center gap-3 sm:gap-5", children: [headerEnd, showHelp ? jsx(HelpButton, {}) : null] })) : null] })] })) : (jsxs("div", { className: "sticky top-0 z-30 shrink-0 w-full", children: [jsx(HeaderBackground, {}), jsxs("header", { className: "relative shrink-0 gap-2 py-4 h-auto min-h-[123.5px] w-full z-10", children: [jsxs("div", { className: "flex w-full items-center gap-2 px-3 sm:px-4 lg:px-6", children: [jsx(SidebarTrigger, { className: "shrink-0 text-white hover:bg-white/10" }), jsx("div", { className: "flex-1 min-w-0", children: trail }), headerEnd || showHelp ? (jsxs("div", { className: "flex shrink-0 items-center gap-3", children: [headerEnd, showHelp ? jsx(HelpButton, {}) : null] })) : null] }), jsx("div", { id: "header-title" })] })] })), jsx(Suspense, { fallback: jsx("div", { className: "relative z-10 min-h-[calc(100vh-8rem)]", children: jsx("div", { className: "flex h-full items-center justify-center", children: jsxs("div", { className: "space-y-4 text-center", children: [jsx("div", { className: "mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary" }), jsx("p", { className: "text-sm text-muted-foreground", children: "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14..." })] }) }) }), children: jsx("div", { className: workspace
3701
6940
  ? "relative z-10 px-[18px] pt-[26px] pb-4 sm:px-6 lg:px-10 lg:pt-[38px]"
3702
6941
  : cx("relative z-10 pr-6", needsLeftGutter && "pl-6"), children: refusePage
3703
6942
  ? (notMemberComponent ?? (jsx(AccessDenied, { title: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E40\u0E02\u0E49\u0E32\u0E16\u0E36\u0E07\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23\u0E19\u0E35\u0E49", message: `บัญชีนี้ไม่ได้เป็นสมาชิกขององค์กร ${code}`, homeHref: selectOrganizationUrl, homeLabel: "\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" })))
3704
- : wrap(children) }, `org-${contentOrgKey}`) })] }) }), showHelp ? jsx(HelpDialogHost, { app: helpApp, orgCode: code }) : null] }));
6943
+ : wrap(children) }, `org-${contentOrgKey}`) })] }) }), showHelp ? jsx(HelpDialogHost, { app: helpApp, orgCode: code }) : null, guides && !refusePage && urlOrgGate.state === "ready" && organizationId != null && String(organizationId).trim() !== "" ? (jsx(GuideHost, { config: guides, organizationId: String(organizationId), code: code }, `guide-${String(organizationId)}`)) : null] }));
3705
6944
  }
3706
6945
  /** Local tiny classnames helper — avoids pulling clsx/tailwind-merge into
3707
6946
  * the shell just for the layout file. Falsy values are skipped. */
@@ -3740,39 +6979,6 @@ function SidebarHelpLink({ label, href, icon, className }) {
3740
6979
  return external ? (jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: cls, children: body })) : (jsx(Link, { href: href, className: cls, children: body }));
3741
6980
  }
3742
6981
 
3743
- const EMPLOYEE_RECORD_REQUIRED = "EMPLOYEE_RECORD_REQUIRED";
3744
- const EMPLOYEE_RECORD_REQUIRED_EVENT = "erp:employee-record-required";
3745
- const EMPLOYEE_RECORD_OK_EVENT = "erp:employee-record-ok";
3746
- /**
3747
- * Shown when the API refuses every request because the signed-in account has
3748
- * no employee record in this organisation.
3749
- *
3750
- * A gate rather than a banner. Leave, attendance, approvals and payslips all
3751
- * identify a person by that record, so once the server started enforcing it
3752
- * every call fails — and without something that says so, the app becomes a
3753
- * screen of error toasts with no explanation and no way forward.
3754
- */
3755
- function EmployeeRequiredGate({ platformBaseUrl, }) {
3756
- const [blocked, setBlocked] = useState(false);
3757
- const params = useParams();
3758
- const code = params?.code ?? "";
3759
- useEffect(() => {
3760
- const onBlocked = () => setBlocked(true);
3761
- const onOk = () => setBlocked(false);
3762
- window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
3763
- window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
3764
- return () => {
3765
- window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
3766
- window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
3767
- };
3768
- }, []);
3769
- if (!blocked)
3770
- return null;
3771
- const base = platformBaseUrl?.replace(/\/$/, "") ?? "";
3772
- const createHref = code ? `${base}/${code}/employee/create` : `${base}/`;
3773
- return (jsx("div", { className: "fixed inset-0 z-[100] flex items-center justify-center bg-background/95 p-6 backdrop-blur-sm", children: jsxs("div", { className: "w-full max-w-md space-y-5 text-center", children: [jsx(ContactRound, { className: "mx-auto h-12 w-12 text-muted-foreground" }), jsxs("div", { className: "space-y-2", children: [jsx("h1", { className: "text-lg font-semibold tracking-tight", children: "\u0E1A\u0E31\u0E0D\u0E0A\u0E35\u0E19\u0E35\u0E49\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E1C\u0E39\u0E01\u0E01\u0E31\u0E1A\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19" }), jsx("p", { className: "text-sm text-muted-foreground", children: "\u0E25\u0E32 \u0E25\u0E07\u0E40\u0E27\u0E25\u0E32 \u0E40\u0E1A\u0E34\u0E01\u0E40\u0E07\u0E34\u0E19 \u0E41\u0E25\u0E30\u0E01\u0E32\u0E23\u0E2D\u0E19\u0E38\u0E21\u0E31\u0E15\u0E34 \u0E23\u0E30\u0E1A\u0E38\u0E15\u0E31\u0E27\u0E04\u0E19\u0E08\u0E32\u0E01\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19 \u0E08\u0E36\u0E07\u0E22\u0E31\u0E07\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19\u0E43\u0E19\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23\u0E19\u0E35\u0E49\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49" })] }), jsxs("div", { className: "flex flex-wrap justify-center gap-2", children: [jsx(Button, { onClick: () => window.location.reload(), children: "\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48" }), jsx(Button, { variant: "outline", asChild: true, children: jsxs("a", { href: createHref, children: [jsx(UserPlus, { className: "mr-1 h-4 w-4" }), "\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19"] }) })] }), jsx("p", { className: "text-xs text-muted-foreground", children: "\u0E16\u0E49\u0E32\u0E04\u0E38\u0E13\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E41\u0E01\u0E49\u0E44\u0E02 \u0E43\u0E2B\u0E49\u0E41\u0E08\u0E49\u0E07\u0E1C\u0E39\u0E49\u0E14\u0E39\u0E41\u0E25\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" })] }) }));
3774
- }
3775
-
3776
6982
  const shellClassName = "flex min-w-0 flex-1 flex-col gap-6 overflow-x-hidden";
3777
6983
  /**
3778
6984
  * Shared layout for “กำลังตรวจสอบสิทธิ์” (skeleton) and “ไม่มีสิทธิ์” (message).
@@ -4299,5 +7505,5 @@ const getAxiosErrorMessage = (error) => {
4299
7505
  return String(error);
4300
7506
  };
4301
7507
 
4302
- export { AccessDenied, ApiError, AppBreadcrumb, AppLayoutShell, AppSidebar, EMPLOYEE_RECORD_OK_EVENT, EMPLOYEE_RECORD_REQUIRED, EMPLOYEE_RECORD_REQUIRED_EVENT, EmployeeRequiredGate, FOR_ORGANIZATION_FIELD, FeatureFlagsProvider, HeaderBackground, HelpButton, HelpDialogHost, NavMain, NavTools, NavUser, OWNER_CHIP, OrganizationSwitcher, PLAN_FEATURES, PermissionGateShell, PermissionProvider, PermissionRulesProvider, ReactQueryProvider, SHELL_VERSION, SessionBackedProfileCacheSeeder, SessionRefreshTrigger, SidebarContent, SidebarFooter, SidebarHeader, SidebarHelpCard, SidebarHelpLink, SidebarProvider, SidebarTrigger, TapMenu, ThemeProvider, WITHOUT_ORGANIZATION_FLAG, WORKSPACE_HEADER_VARS, WORKSPACE_LIGHT_HEADER_VARS, WorkspaceBrand, accountSettingsHref, instance as axiosInstance, buildSystemLinks, buildUrlWithCode, canAccessNavPermissionRoute, clearAccessTokenCache, clearOrganizationId, clearStoredOrganization, closeHelp, decodeJWT, describeAttached, describeBrowser, detectHelpApp, filterNavigationModulesByPermission, filterNavigationToolsByPermission, findOrganizationForCode, getAccessToken, getActiveModule, getActiveSubModule, getAxiosErrorMessage, getOrganizationId, getQueryClientConfig, getRequestOrganizationId, getRequiredChildGroups, getStoredOrganizationIds, getTabOrganizationId, hasPlanFeature, isKnownStaleOrganizationId, isLikelyTransientNetworkError, isPathActive, myRolesQueryKey, normalizePathnameForPermissionRules, openHelp, organizationScopedQueryHash, parseMyRoles, platformBaseUrl, resolveActiveNav, resolveSidebarNav, resolveStaleOrganization, resolveUiRoutePermission, resolveUrlOrgGate, retryWithStoredOrganizations, roleSummary, runGlobalRequestPrecheck, runWithTransientRetry, setKnownOrganizationIds, setOrganizationId, setTabOrganizationId, shouldRetryQuery, toApiError, unwrapApiResponse, updateOrganizationId, useClearOrgOnUserChange, useFeatureFlag, useFeatureFlags, useInvalidateQueriesOnOrgChange, useKeycloakRoles, useMyRoles, useOrganizationIdState, usePermissionRules, useSessionRefresh, useSidebar, useSidebarToggle, withoutOrganization };
7508
+ export { AccessDenied, ApiError, AppBreadcrumb, AppLayoutShell, AppSidebar, EMPLOYEE_RECORD_OK_EVENT, EMPLOYEE_RECORD_REQUIRED, EMPLOYEE_RECORD_REQUIRED_EVENT, EmployeeRequiredGate, FOR_ORGANIZATION_FIELD, FeatureFlagsProvider, API_EVENT as GUIDE_API_EVENT, GUIDE_EVENT_PREFIX, GUIDE_LAYER_ATTRIBUTE, GuideHost, HeaderBackground, HelpButton, HelpDialogHost, NavMain, NavTools, NavUser, OWNER_CHIP, OrganizationSwitcher, PLAN_FEATURES, PermissionGateShell, PermissionProvider, PermissionRulesProvider, ReactQueryProvider, SHELL_VERSION, SessionBackedProfileCacheSeeder, SessionRefreshTrigger, SidebarContent, SidebarFooter, SidebarHeader, SidebarHelpCard, SidebarHelpLink, SidebarProvider, SidebarTrigger, TapMenu, ThemeProvider, WITHOUT_ORGANIZATION_FLAG, WORKSPACE_HEADER_VARS, WORKSPACE_LIGHT_HEADER_VARS, WorkspaceBrand, accountSettingsHref, instance as axiosInstance, buildSystemLinks, buildUrlWithCode, canAccessNavPermissionRoute, clearAccessTokenCache, clearOrganizationId, clearStoredOrganization, closeHelp, decodeJWT, describeAttached, describeBrowser, detectHelpApp, emitGuideEvent, filterNavigationModulesByPermission, filterNavigationToolsByPermission, findOrganizationForCode, getAccessToken, getActiveModule, getActiveSubModule, getAxiosErrorMessage, getOrganizationId, getQueryClientConfig, getRequestOrganizationId, getRequiredChildGroups, getStoredOrganizationIds, getTabOrganizationId, guideAnchor, hasPlanFeature, isKnownStaleOrganizationId, isLikelyTransientNetworkError, isPathActive, myRolesQueryKey, normalizePathnameForPermissionRules, openGuidePanel, openHelp, organizationScopedQueryHash, parseMyRoles, platformBaseUrl, reportApiEvent, resolveActiveNav, resolveSidebarNav, resolveStaleOrganization, resolveUiRoutePermission, resolveUrlOrgGate, retryWithStoredOrganizations, roleSummary, runGlobalRequestPrecheck, runWithTransientRetry, setKnownOrganizationIds, setOrganizationId, setTabOrganizationId, shouldRetryQuery, toApiError, unwrapApiResponse, updateOrganizationId, useClearOrgOnUserChange, useFeatureFlag, useFeatureFlags, useGuideEntry, useInvalidateQueriesOnOrgChange, useKeycloakRoles, useMyRoles, useOrganizationIdState, usePermissionRules, useSessionRefresh, useSidebar, useSidebarToggle, withoutOrganization };
4303
7509
  //# sourceMappingURL=index.esm.js.map