@eintrek/erp-shell 0.1.51 → 0.1.53

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,20 +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, useTransition, Suspense } from 'react';
3
+ import React__default, { useRef, useEffect, useMemo, useState, useCallback, createContext, useContext, Fragment, useSyncExternalStore, useTransition, Suspense } from 'react';
4
4
  import { useSession, signOut } from 'next-auth/react';
5
- import { useQueryClient, MutationCache, QueryCache, QueryClient, QueryClientProvider } from '@tanstack/react-query';
5
+ import { useQueryClient, useQuery, QueryClientContext, QueryClient, MutationCache, QueryCache, QueryClientProvider } from '@tanstack/react-query';
6
6
  import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
7
- import { cn, Button, Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbSeparator, BreadcrumbPage, Avatar, AvatarImage, AvatarFallback, Collapsible, CollapsibleTrigger, CollapsibleContent, Badge, DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuLabel, DropdownMenuItem, DropdownMenuSeparator, Skeleton, Card, CardHeader, CardContent } from '@eintrek/erp-theme';
8
- import { PanelLeftClose, Menu, ChevronRight, Building2, Palette, ChevronUp, Sun, Moon, Monitor, Globe, User, LayoutGrid, ExternalLink, Loader2, LogOut, ChevronsUpDown, Calculator, Warehouse, FolderKanban, Users, ChevronDown, Plus, ArrowRight, Compass, ArrowUpRight, Ban, Home, Headset, ContactRound, UserPlus } from 'lucide-react';
7
+ import { cn, Button, 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, User, LayoutGrid, ExternalLink, CircleHelp, Loader2, LogOut, ChevronsUpDown, Calculator, Warehouse, FolderKanban, Users, ChevronDown, Plus, ImagePlus, X, CircleCheck, ArrowLeft, ArrowRight, Compass, ArrowUpRight, Ban, Home, Headset, ContactRound, UserPlus } from 'lucide-react';
9
9
  import { create } from 'zustand';
10
10
  import { persist, createJSONStorage } from 'zustand/middleware';
11
11
  import { useRouter, usePathname, useParams } 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
- import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
16
15
  import axios, { isAxiosError, AxiosHeaders } from 'axios';
17
16
  export { isAxiosError } from 'axios';
17
+ import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
18
18
 
19
19
  /**
20
20
  * Interval (ms) between session updates to trigger JWT callback and refresh
@@ -803,270 +803,982 @@ function isRecordID(segment) {
803
803
  /^[0-9a-f]{24,}$/i.test(segment));
804
804
  }
805
805
 
806
- function isExternalHref(href) {
807
- return /^https?:\/\//i.test(href) || href.startsWith("//");
808
- }
809
- function NavUser({ organization, avatarSrc, profileHref, selectOrganizationHref = "/select-organization", signInRedirectHref = "/auth/signin", systemLinks, showSelectOrganization = true, showLanguageSwitch = true, variant = "brand", } = {}) {
810
- const { data: session, status } = useSession();
811
- const router = useRouter();
812
- const { theme, setTheme } = useTheme();
813
- const [isSigningOut, setIsSigningOut] = useState(false);
814
- const [isOpen, setIsOpen] = useState(false);
815
- const [showThemeMenu, setShowThemeMenu] = useState(false);
816
- const [showLanguageMenu, setShowLanguageMenu] = useState(false);
817
- const [showAppsMenu, setShowAppsMenu] = useState(false);
818
- const buttonRef = useRef(null);
819
- const [position, setPosition] = useState({ top: 0, left: 0 });
820
- const user = session?.user
821
- ? {
822
- name: session.user.name || "ผู้ใช้",
823
- email: session.user.email || "",
824
- // avatarSrc first: the NextAuth session carries no picture unless the
825
- // host app deliberately puts one in the JWT, so relying on
826
- // session.user.image alone left every user on their initials forever.
827
- avatar: avatarSrc || session.user.image || undefined,
828
- }
829
- : null;
830
- const getInitials = (name) => {
831
- if (!name)
832
- return "U";
833
- return name
834
- .split(" ")
835
- .map(n => n[0])
836
- .join("")
837
- .toUpperCase()
838
- .slice(0, 2);
839
- };
840
- const handleSignOut = async () => {
841
- setIsSigningOut(true);
842
- try {
843
- await signOut({ callbackUrl: signInRedirectHref, redirect: true });
844
- }
845
- catch (error) {
846
- console.error("Sign out error:", error);
847
- window.location.href = signInRedirectHref;
848
- }
849
- finally {
850
- setIsSigningOut(false);
851
- }
852
- };
853
- const handleSelectOrganization = () => {
854
- setIsOpen(false);
855
- router.push(selectOrganizationHref);
856
- };
857
- const handleProfile = () => {
858
- setIsOpen(false);
859
- if (profileHref)
860
- router.push(profileHref);
861
- };
862
- const handleSystemLink = (href) => {
863
- setIsOpen(false);
864
- if (isExternalHref(href)) {
865
- window.location.assign(href);
866
- return;
867
- }
868
- router.push(href);
806
+ let open = false;
807
+ let hosts = 0;
808
+ let declaredApp = null;
809
+ // The message the dialog should open on (the ตอบกลับ link's ?help=H1004),
810
+ // until it is closed or left.
811
+ let pendingRef = null;
812
+ const listeners = new Set();
813
+ function emit() {
814
+ listeners.forEach(l => l());
815
+ }
816
+ function subscribe(l) {
817
+ listeners.add(l);
818
+ return () => {
819
+ listeners.delete(l);
869
820
  };
870
- const handleThemeChange = (newTheme) => {
871
- setTheme(newTheme);
872
- setShowThemeMenu(false);
873
- };
874
- const handleLanguageChange = (language) => {
875
- console.log("Change language to:", language);
876
- setShowLanguageMenu(false);
877
- };
878
- useEffect(() => {
879
- if (isOpen && buttonRef.current) {
880
- const rect = buttonRef.current.getBoundingClientRect();
881
- setPosition({ top: rect.bottom, left: rect.right + 8 });
882
- }
883
- }, [isOpen]);
884
- useEffect(() => {
885
- if (!isOpen)
886
- return;
887
- const handleClickOutside = (event) => {
888
- if (buttonRef.current &&
889
- !buttonRef.current.contains(event.target) &&
890
- !event.target.closest('[data-dropdown="nav-user"]')) {
891
- setIsOpen(false);
892
- }
893
- };
894
- document.addEventListener("mousedown", handleClickOutside);
895
- return () => document.removeEventListener("mousedown", handleClickOutside);
896
- }, [isOpen]);
897
- if (status === "loading") {
898
- return (jsx("div", { className: "p-2", children: jsxs("div", { className: "flex items-center gap-2 p-2 rounded-md", children: [jsx("div", { className: "h-8 w-8 rounded-lg bg-sidebar-accent animate-pulse" }), jsxs("div", { className: "flex-1 space-y-1", children: [jsx("div", { className: "h-4 w-24 bg-sidebar-accent rounded animate-pulse" }), jsx("div", { className: "h-3 w-32 bg-sidebar-accent rounded animate-pulse" })] })] }) }));
821
+ }
822
+ /** Opens the dialog — a no-op when no layout has mounted one. */
823
+ function openHelp() {
824
+ if (!open) {
825
+ open = true;
826
+ emit();
899
827
  }
900
- if (!user)
901
- return null;
902
- const visibleSystemLinks = (systemLinks ?? []).filter(link => link.href && link.label);
903
- const dropdownContent = isOpen ? (jsxs("div", { "data-dropdown": "nav-user", className: "fixed w-52 sm:w-60 md:w-80 rounded-lg bg-sidebar border border-sidebar-border shadow-xl z-50 overflow-hidden\n -translate-x-[65%] -translate-y-[110%] sm:translate-x-0 sm:-translate-y-full", style: { top: `${position.top}px`, left: `${position.left}px` }, children: [organization && (jsx("div", { className: "p-4 border-b border-sidebar-border bg-sidebar-accent/30", children: jsxs("div", { className: "flex items-center gap-3", children: [organization.logoUrl ? (
904
- // eslint-disable-next-line @next/next/no-img-element
905
- jsx("img", { src: organization.logoUrl, alt: organization.name ?? "โลโก้บริษัท", className: "h-8 w-8 flex-shrink-0 rounded object-contain bg-white",
906
- // A dead logo URL must not leave a broken-image glyph in the
907
- // sidebar; drop back to the generic icon's empty slot.
908
- onError: e => {
909
- e.currentTarget.style.display = "none";
910
- } })) : (jsx(Building2, { className: "h-5 w-5 text-sidebar-foreground/70 flex-shrink-0" })), jsxs("div", { className: "flex-1 min-w-0", children: [jsx("div", { className: "font-medium text-sm sm:truncate", children: organization.name }), organization.description && (jsx("div", { className: "text-xs text-sidebar-foreground/70 truncate mt-0.5", children: organization.description }))] })] }) })), jsxs("div", { className: "p-2", children: [jsxs("div", { className: "relative", children: [jsxs("button", { onClick: () => {
911
- setShowThemeMenu(!showThemeMenu);
912
- setShowLanguageMenu(false);
913
- setShowAppsMenu(false);
914
- }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Palette, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E18\u0E35\u0E21" }), jsx(ChevronUp, { className: `h-4 w-4 transition-transform ${showThemeMenu ? "rotate-180" : ""}` })] }), showThemeMenu && (jsx("div", { className: "mt-1 ml-4 space-y-1", children: [
915
- { key: "light", label: "สว่าง", Icon: Sun },
916
- { key: "dark", label: "มืด", Icon: Moon },
917
- { key: "system", label: "ตามระบบ", Icon: Monitor },
918
- ].map(({ key, label, Icon }) => (jsxs("button", { onClick: () => handleThemeChange(key), className: "flex w-full items-center gap-3 px-3 py-2 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Icon, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: label }), theme === key && (jsx("div", { className: "h-2 w-2 rounded-full bg-primary" }))] }, key))) }))] }), showLanguageSwitch && (jsxs("div", { className: "relative", children: [jsxs("button", { onClick: () => {
919
- setShowLanguageMenu(!showLanguageMenu);
920
- setShowThemeMenu(false);
921
- setShowAppsMenu(false);
922
- }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Globe, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E20\u0E32\u0E29\u0E32" }), jsx(ChevronUp, { className: `h-4 w-4 transition-transform ${showLanguageMenu ? "rotate-180" : ""}` })] }), showLanguageMenu && (jsx("div", { className: "mt-1 ml-4 space-y-1", children: [
923
- { code: "th", label: "ไทย" },
924
- { code: "en", label: "English" },
925
- { code: "zh", label: "中文" },
926
- { code: "ja", label: "日本語" },
927
- ].map(({ code, label }) => (jsxs("button", { onClick: () => handleLanguageChange(code), className: "flex w-full items-center gap-3 px-3 py-2 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx("span", { className: "flex-1 text-left", children: label }), organization?.language === code && (jsx("div", { className: "h-2 w-2 rounded-full bg-primary" }))] }, code))) }))] })), profileHref && (jsxs("button", { onClick: handleProfile, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(User, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E2A\u0E48\u0E27\u0E19\u0E15\u0E31\u0E27" })] })), showSelectOrganization && (jsxs("button", { onClick: handleSelectOrganization, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Building2, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E18\u0E38\u0E23\u0E01\u0E34\u0E08" })] })), visibleSystemLinks.length > 0 && (jsxs("div", { className: "relative", children: [jsxs("button", { onClick: () => {
928
- setShowAppsMenu(!showAppsMenu);
929
- setShowThemeMenu(false);
930
- setShowLanguageMenu(false);
931
- }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(LayoutGrid, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E41\u0E2D\u0E1B\u0E1E\u0E25\u0E34\u0E40\u0E04\u0E0A\u0E31\u0E19" }), jsx(ChevronUp, { className: `h-4 w-4 transition-transform ${showAppsMenu ? "rotate-180" : ""}` })] }), showAppsMenu && (jsx("div", { className: "mt-1 ml-4 space-y-1", children: visibleSystemLinks.map(link => (jsxs("button", { type: "button", onClick: () => handleSystemLink(link.href), className: "flex w-full items-center gap-3 px-3 py-2 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [link.icon ?? jsx(ExternalLink, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: link.label }), link.active && (jsx("div", { className: "h-2 w-2 rounded-full bg-primary" }))] }, `${link.label}:${link.href}`))) }))] })), jsx("button", { onClick: handleSignOut, disabled: isSigningOut, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed mt-1", children: isSigningOut ? (jsxs(Fragment$1, { children: [jsx(Loader2, { className: "h-4 w-4 animate-spin" }), jsx("span", { className: "flex-1 text-left", children: "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A..." })] })) : (jsxs(Fragment$1, { children: [jsx(LogOut, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A" })] })) })] })] })) : null;
932
- if (variant === "workspace") {
933
- return (jsx("div", { className: "mt-3.5 border-t border-sidebar-border pt-3", children: jsxs("div", { className: "relative", children: [jsxs("button", { ref: buttonRef, onClick: () => setIsOpen(!isOpen), "aria-expanded": isOpen, className: "flex w-full items-center gap-[11px] rounded-lg px-3 py-1.5 text-left transition-colors hover:bg-sidebar-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring", children: [jsxs(Avatar, { className: "size-[34px] shrink-0 rounded-full border-[3px] border-sidebar-accent", children: [user.avatar ? (jsx(AvatarImage, { src: user.avatar, alt: user.name })) : null, jsx(AvatarFallback, { className: "rounded-full bg-sidebar-accent text-sm font-medium text-sidebar-accent-foreground", children: getInitials(user.name) })] }), jsxs("span", { className: "grid min-w-0 flex-1 leading-tight", children: [jsx("strong", { className: "truncate text-[13px] font-semibold", title: user.name, children: user.name }), jsx("small", { className: "truncate text-[11px] text-muted-foreground", title: user.email, children: user.email })] }), jsx(ChevronsUpDown, { className: "size-3.5 shrink-0 text-muted-foreground" })] }), typeof window !== "undefined" &&
934
- createPortal(dropdownContent, document.body)] }) }));
828
+ }
829
+ function closeHelp() {
830
+ pendingRef = null;
831
+ if (open) {
832
+ open = false;
833
+ emit();
935
834
  }
936
- return (jsx("div", { className: "p-2", children: jsxs("div", { className: "relative", children: [jsxs("button", { ref: buttonRef, onClick: () => setIsOpen(!isOpen), className: "flex w-full items-center gap-2 p-2 rounded-md transition-colors", children: [jsxs(Avatar, { className: "h-8 w-8 rounded-lg", children: [user.avatar ? (jsx(AvatarImage, { src: user.avatar, alt: user.name })) : null, jsx(AvatarFallback, { className: "rounded-lg bg-primary text-primary-foreground w-8 h-8", children: getInitials(user.name) })] }), jsxs("div", { className: "grid flex-1 text-left text-sm leading-tight", children: [jsx("span", { className: "truncate font-medium", title: user.name, children: user.name }), jsx("span", { className: "truncate text-xs text-sidebar-foreground/70", title: user.email, children: user.email })] }), jsx(ChevronUp, { className: `ml-auto size-4 transition-transform ${isOpen ? "rotate-180" : ""}` })] }), typeof window !== "undefined" &&
937
- createPortal(dropdownContent, document.body)] }) }));
938
835
  }
939
-
836
+ /** Opens the dialog on one of the person's messages, by id or "H1004". */
837
+ function openHelpOn(ref) {
838
+ pendingRef = ref;
839
+ open = true;
840
+ emit();
841
+ }
842
+ /** The message the dialog was asked to open on, if it has not been left. */
843
+ function pendingHelpRef() {
844
+ return pendingRef;
845
+ }
846
+ /** The dialog moved on from the message it was opened on. */
847
+ function clearPendingHelpRef() {
848
+ pendingRef = null;
849
+ }
940
850
  /**
941
- * Plan feature keys (billable entitlements). Mirror of platform-apis plan.go.
942
- *
943
- * This lives in the shell because every app gates on the same keys, and five
944
- * private copies of the same list drift: the app-switcher list did exactly
945
- * that before it moved here.
851
+ * Called by the dialog host on mount; returns its unmount. A host that
852
+ * mounts while a message is waiting to be shown (a page that mounted its
853
+ * layout twice) opens the dialog again.
946
854
  */
947
- const PLAN_FEATURES = {
948
- ORG_CHART: "org_chart",
949
- APPROVAL_WORKFLOW: "approval_workflow",
950
- API_ACCESS: "api_access",
951
- SSO: "sso",
952
- BASIC_ACCOUNTING_HR: "basic_accounting_hr",
953
- MODULE_PLATFORM: "module.platform",
954
- MODULE_HR: "module.hr",
955
- MODULE_ACCOUNTING: "module.accounting",
956
- MODULE_SALES: "module.sales",
957
- MODULE_PURCHASING: "module.purchasing",
958
- MODULE_INVENTORY: "module.inventory",
959
- MODULE_PROJECT: "module.project",
960
- MODULE_SECRETARIAT: "module.secretariat",
961
- /** AI pack (paid or trial): AI calls on AntNiti's key while credits remain. */
962
- AI: "ai",
963
- };
964
- /** Keys the Accounx add-on carries with it (same alias as org_effective_features). */
965
- const ACCOUNTING_SUB_KEYS = [
966
- PLAN_FEATURES.MODULE_SALES,
967
- PLAN_FEATURES.MODULE_PURCHASING,
968
- PLAN_FEATURES.MODULE_SECRETARIAT,
969
- ];
855
+ function registerHelpHost() {
856
+ hosts += 1;
857
+ if (pendingRef)
858
+ open = true;
859
+ emit();
860
+ return () => {
861
+ hosts -= 1;
862
+ if (hosts <= 0) {
863
+ hosts = 0;
864
+ open = false;
865
+ }
866
+ emit();
867
+ };
868
+ }
869
+ function useHelpOpen() {
870
+ return useSyncExternalStore(subscribe, () => open, () => false);
871
+ }
872
+ /** True while a dialog host is mounted, i.e. the ช่วยเหลือ entry works. */
873
+ function useHelpAvailable() {
874
+ return useSyncExternalStore(subscribe, () => hosts > 0, () => false);
875
+ }
970
876
  /**
971
- * True when plan features include key. Aliases, mirroring the backend:
972
- * legacy basic_accounting_hr → module.hr + module.accounting (+ its sub-keys);
973
- * module.accounting → module.sales, module.purchasing, module.secretariat.
877
+ * Every app names itself when it builds its app-switcher links
878
+ * (buildSystemLinks({ activeApp })); the dialog reads that to say which app
879
+ * a message came from without each app passing it again.
974
880
  */
975
- function hasPlanFeature(features, feature) {
976
- if (!features?.length)
977
- return false;
978
- if (features.includes(feature))
979
- return true;
980
- if ((feature === PLAN_FEATURES.MODULE_HR ||
981
- feature === PLAN_FEATURES.MODULE_ACCOUNTING ||
982
- ACCOUNTING_SUB_KEYS.includes(feature)) &&
983
- features.includes(PLAN_FEATURES.BASIC_ACCOUNTING_HR)) {
984
- return true;
985
- }
986
- if (ACCOUNTING_SUB_KEYS.includes(feature) &&
987
- features.includes(PLAN_FEATURES.MODULE_ACCOUNTING)) {
988
- return true;
989
- }
990
- if (feature === PLAN_FEATURES.BASIC_ACCOUNTING_HR &&
991
- features.includes(PLAN_FEATURES.MODULE_HR) &&
992
- features.includes(PLAN_FEATURES.MODULE_ACCOUNTING)) {
993
- return true;
994
- }
995
- return false;
881
+ function declareHelpApp(app) {
882
+ declaredApp = app;
996
883
  }
997
-
998
- function normaliseBase(value, fallback) {
999
- return (value ?? fallback).replace(/\/$/, "");
884
+ function declaredHelpApp() {
885
+ return declaredApp;
1000
886
  }
887
+
1001
888
  /**
1002
- * One list, in display order, for the whole suite.
889
+ * The caller's roles in the current organisation, as platform-api answers
890
+ * GET /organizations/:id/my-roles, and how the user card words them.
1003
891
  *
1004
- * It used to be copied into every app's own nav-user.tsx, which is how Invenx
1005
- * shipped without a link to Plannex: five copies, one of them edited by hand.
1006
- * Adding the sixth app is now a change here plus a version bump.
892
+ * No runtime imports: the tests run this file in Node as it is.
1007
893
  */
1008
- const APPS = [
1009
- {
1010
- id: "platform",
1011
- label: "แพลตฟอร์ม",
1012
- icon: jsx(Building2, { className: "h-4 w-4 shrink-0" }),
1013
- features: null,
1014
- baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_PLATFORM_URL, "https://platform.antniti.com"),
1015
- },
1016
- {
1017
- id: "accounx",
1018
- label: "Accounx",
1019
- icon: jsx(Calculator, { className: "h-4 w-4 shrink-0" }),
1020
- features: [PLAN_FEATURES.MODULE_ACCOUNTING],
1021
- baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_ACCOUNTING_URL, "https://accounx.antniti.com"),
1022
- },
1023
- {
1024
- id: "invenx",
1025
- label: "Invenx",
1026
- icon: jsx(Warehouse, { className: "h-4 w-4 shrink-0" }),
1027
- features: [PLAN_FEATURES.MODULE_INVENTORY],
1028
- baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_INVENX_URL, "https://invenx.antniti.com"),
1029
- },
1030
- {
1031
- id: "plannex",
1032
- label: "Plannex",
1033
- icon: jsx(FolderKanban, { className: "h-4 w-4 shrink-0" }),
1034
- // Tasks, day-logs and work records are free with HR; projects need the add-on.
1035
- features: [PLAN_FEATURES.MODULE_HR, PLAN_FEATURES.MODULE_PROJECT],
1036
- baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_PLANNEX_URL, "https://plannex.antniti.com"),
1037
- },
1038
- {
1039
- id: "peoplx",
1040
- label: "Peoplx",
1041
- icon: jsx(Users, { className: "h-4 w-4 shrink-0" }),
1042
- features: [PLAN_FEATURES.MODULE_HR],
1043
- baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_HR_URL, "https://peoplx.antniti.com"),
1044
- },
1045
- ];
894
+ /** The owner's chip. Ownership is a flag, not a role. */
895
+ const OWNER_CHIP = "เจ้าของ";
896
+ /** How many role names the card spells out before counting the rest. */
897
+ const CARD_ROLE_LIMIT = 2;
898
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1046
899
  /**
1047
- * Builds the cross-app link list for <NavUser systemLinks>.
1048
- *
1049
- * The current app is always present even when the org's plan no longer covers
1050
- * it — the user is looking at it, so hiding the link would only make the menu
1051
- * disagree with the screen.
900
+ * The answer, checked. Anything that is not the shape the card needs — an
901
+ * older API, a proxy's error page, another organisation's answer — is null,
902
+ * and the card shows no role line.
1052
903
  */
1053
- function buildSystemLinks({ orgCode, activeApp, features, }) {
1054
- if (!orgCode)
1055
- return [];
1056
- return APPS.filter(app => app.id === activeApp ||
1057
- app.features === null ||
1058
- app.features.some(key => hasPlanFeature(features, key))).map(app => ({
1059
- label: app.label,
1060
- icon: app.icon,
1061
- // Same-app link stays relative so it never leaves the current origin.
1062
- href: app.id === activeApp ? `/${orgCode}` : `${app.baseUrl()}/${orgCode}`,
1063
- ...(app.id === activeApp ? { active: true } : {}),
1064
- }));
1065
- }
1066
-
1067
- // Helper function to check if pathname matches a URL pattern
1068
- // This prevents false matches like /reports/sales matching /sales
1069
- // Handles paths with or without [code] prefix
904
+ function parseMyRoles(payload, organizationId) {
905
+ if (!isRecord(payload))
906
+ return null;
907
+ // Envelope { success, data } or the bare data.
908
+ const data = isRecord(payload.data) ? payload.data : payload;
909
+ if (!Array.isArray(data.roles))
910
+ return null;
911
+ if (typeof data.organization_id === "string" && data.organization_id !== organizationId) {
912
+ return null;
913
+ }
914
+ const roles = [];
915
+ const seen = new Set();
916
+ for (const r of data.roles) {
917
+ if (!isRecord(r))
918
+ continue;
919
+ const name = typeof r.name_th === "string" ? r.name_th.trim() : "";
920
+ const key = typeof r.key === "string" ? r.key : "";
921
+ // A role with no name is left out, never shown by its key.
922
+ if (!name || seen.has(name))
923
+ continue;
924
+ seen.add(name);
925
+ roles.push({
926
+ key,
927
+ name_th: name,
928
+ app: typeof r.app === "string" ? r.app : "",
929
+ kind: typeof r.kind === "string" ? r.kind : "",
930
+ });
931
+ }
932
+ return { organizationId, isOwner: data.is_owner === true, roles };
933
+ }
934
+ /** The card names the first two roles and counts the rest. */
935
+ function cardRoleLine(roles, limit = CARD_ROLE_LIMIT) {
936
+ const names = roles.map(r => r.name_th);
937
+ return { shown: names.slice(0, limit), more: Math.max(0, names.length - limit) };
938
+ }
939
+ /** Everything, for the tooltip: "เจ้าของ · ผู้ดูแลสูงสุด · พนักงานทั่วไป". */
940
+ function roleSummary(my) {
941
+ return [...(my.isOwner ? [OWNER_CHIP] : []), ...my.roles.map(r => r.name_th)].join(" · ");
942
+ }
943
+ /** Whether there is anything to show at all. */
944
+ function hasRoleLine(my) {
945
+ return !!my && (my.isOwner || my.roles.length > 0);
946
+ }
947
+
948
+ const TOKEN_TTL_MS = 30000;
949
+ let cachedToken = null;
950
+ let cachedAt = 0;
951
+ let inFlightTokenPromise = null;
952
+ const readSessionToken = async () => {
953
+ const response = await fetch("/api/auth/session", {
954
+ credentials: "include",
955
+ cache: "no-store",
956
+ });
957
+ if (!response.ok)
958
+ return null;
959
+ const session = (await response.json());
960
+ return session.accessToken ?? null;
961
+ };
962
+ const getAccessToken = async (forceRefresh = false) => {
963
+ const now = Date.now();
964
+ if (!forceRefresh && cachedToken && now - cachedAt < TOKEN_TTL_MS) {
965
+ return cachedToken;
966
+ }
967
+ if (!inFlightTokenPromise) {
968
+ inFlightTokenPromise = readSessionToken()
969
+ .then(token => {
970
+ cachedToken = token;
971
+ cachedAt = Date.now();
972
+ return token;
973
+ })
974
+ .finally(() => {
975
+ inFlightTokenPromise = null;
976
+ });
977
+ }
978
+ return inFlightTokenPromise;
979
+ };
980
+ const clearAccessTokenCache = () => {
981
+ cachedToken = null;
982
+ cachedAt = 0;
983
+ };
984
+
985
+ class ApiError extends Error {
986
+ constructor(message, options) {
987
+ super(message);
988
+ Object.defineProperty(this, "status", {
989
+ enumerable: true,
990
+ configurable: true,
991
+ writable: true,
992
+ value: void 0
993
+ });
994
+ Object.defineProperty(this, "code", {
995
+ enumerable: true,
996
+ configurable: true,
997
+ writable: true,
998
+ value: void 0
999
+ });
1000
+ Object.defineProperty(this, "field", {
1001
+ enumerable: true,
1002
+ configurable: true,
1003
+ writable: true,
1004
+ value: void 0
1005
+ });
1006
+ Object.defineProperty(this, "details", {
1007
+ enumerable: true,
1008
+ configurable: true,
1009
+ writable: true,
1010
+ value: void 0
1011
+ });
1012
+ this.name = "ApiError";
1013
+ this.status = options?.status;
1014
+ this.code = options?.code;
1015
+ this.field = options?.field;
1016
+ this.details = options?.details;
1017
+ }
1018
+ }
1019
+ const toApiError = (error) => {
1020
+ if (error instanceof ApiError)
1021
+ return error;
1022
+ if (isAxiosError(error)) {
1023
+ const axiosErr = error;
1024
+ const message = axiosErr.response?.data?.message ||
1025
+ axiosErr.response?.data?.error ||
1026
+ axiosErr.message ||
1027
+ "Request failed";
1028
+ return new ApiError(message, {
1029
+ status: axiosErr.response?.status,
1030
+ code: axiosErr.response?.data?.code,
1031
+ field: axiosErr.response?.data?.field,
1032
+ details: axiosErr.response?.data?.details,
1033
+ });
1034
+ }
1035
+ if (error instanceof Error) {
1036
+ return new ApiError(error.message);
1037
+ }
1038
+ return new ApiError(String(error));
1039
+ };
1040
+
1041
+ const isPlainObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
1042
+ const visit = (value, cb) => {
1043
+ if (Array.isArray(value)) {
1044
+ value.forEach(item => visit(item, cb));
1045
+ return;
1046
+ }
1047
+ if (!isPlainObject(value)) {
1048
+ return;
1049
+ }
1050
+ cb(value);
1051
+ Object.values(value).forEach(item => visit(item, cb));
1052
+ };
1053
+ const validateGoodsReceiptChecks = (data) => {
1054
+ let invalidPath = null;
1055
+ const isCheckStatus = (v) => v === undefined || v === null || v === "pass" || v === "fail";
1056
+ const isCompareStatus = (v) => v === undefined || v === null || v === "match" || v === "mismatch";
1057
+ visit(data, node => {
1058
+ if (invalidPath)
1059
+ return;
1060
+ if ("quantity_check" in node && !isCheckStatus(node.quantity_check)) {
1061
+ invalidPath = "quantity_check";
1062
+ return;
1063
+ }
1064
+ if ("quality_check" in node && !isCheckStatus(node.quality_check)) {
1065
+ invalidPath = "quality_check";
1066
+ return;
1067
+ }
1068
+ if ("compare_with_reference" in node &&
1069
+ !isCompareStatus(node.compare_with_reference)) {
1070
+ invalidPath = "compare_with_reference";
1071
+ }
1072
+ });
1073
+ if (invalidPath) {
1074
+ return {
1075
+ valid: false,
1076
+ message: "รูปแบบข้อมูลไม่ถูกต้อง: ฟิลด์ตรวจรับต้องเป็น enum string (quantity/quality: pass|fail, compare: match|mismatch)",
1077
+ };
1078
+ }
1079
+ return { valid: true };
1080
+ };
1081
+ const runGlobalRequestPrecheck = (config) => {
1082
+ const method = (config.method || "get").toLowerCase();
1083
+ const isWriteMethod = ["post", "put", "patch"].includes(method);
1084
+ if (!isWriteMethod || config.data === undefined || config.data === null) {
1085
+ return { valid: true };
1086
+ }
1087
+ if (typeof FormData !== "undefined" && config.data instanceof FormData) {
1088
+ return { valid: true };
1089
+ }
1090
+ return validateGoodsReceiptChecks(config.data);
1091
+ };
1092
+
1093
+ const isBrowser = () => typeof window !== "undefined";
1094
+ const isAuthEndpoint = (url) => !!url && url.includes("/api/auth/");
1095
+ const isAuthPage = () => isBrowser() && window.location.pathname.startsWith("/auth/");
1096
+ const getOrgFromCookie = () => {
1097
+ if (!isBrowser())
1098
+ return null;
1099
+ const cookies = document.cookie.split(";").map(cookie => cookie.trim());
1100
+ const orgCookie = cookies.find(cookie => cookie.startsWith("erp.organizationId="));
1101
+ if (!orgCookie)
1102
+ return null;
1103
+ const raw = orgCookie.substring("erp.organizationId=".length);
1104
+ return raw ? decodeURIComponent(raw) : null;
1105
+ };
1106
+ const redirectToLogout = async () => {
1107
+ if (!isBrowser() || isAuthPage())
1108
+ return;
1109
+ localStorage.clear();
1110
+ sessionStorage.clear();
1111
+ setOrganizationId(null);
1112
+ clearAccessTokenCache();
1113
+ await signOut({ callbackUrl: "/auth/signin" });
1114
+ };
1115
+ const instance = axios.create({
1116
+ baseURL: process.env.NEXT_PUBLIC_API_URL,
1117
+ headers: { "Content-Type": "application/json" },
1118
+ paramsSerializer: params => {
1119
+ const searchParams = new URLSearchParams();
1120
+ Object.entries(params || {}).forEach(([key, value]) => {
1121
+ if (Array.isArray(value)) {
1122
+ value.forEach(v => searchParams.append(key, String(v)));
1123
+ }
1124
+ else if (value !== undefined && value !== null) {
1125
+ searchParams.append(key, String(value));
1126
+ }
1127
+ });
1128
+ return searchParams.toString();
1129
+ },
1130
+ });
1131
+ instance.interceptors.request.use(async (config) => {
1132
+ if (!config.headers) {
1133
+ config.headers = new AxiosHeaders();
1134
+ }
1135
+ if (config.data instanceof FormData && config.headers) {
1136
+ delete config.headers["Content-Type"];
1137
+ }
1138
+ if (!isBrowser())
1139
+ return config;
1140
+ const token = await getAccessToken(false);
1141
+ if (token) {
1142
+ config.headers.Authorization = `Bearer ${token}`;
1143
+ }
1144
+ // localStorage first, cookie second.
1145
+ //
1146
+ // Both are written by the same state machine, but not at the same moment:
1147
+ // setOrganizationId writes localStorage synchronously and then awaits a
1148
+ // server action for the cookie. Preferring the cookie meant every request
1149
+ // fired during that round trip carried the previous organisation — while
1150
+ // the query params, built from React state, already carried the new one.
1151
+ //
1152
+ // The backend scopes by this header and ignores organization_id in the
1153
+ // query, so those requests asked for organisation A and were handed B, and
1154
+ // the answer landed in the cache under A's key. No amount of cache clearing
1155
+ // reaches that: the entry is wrong, not stale.
1156
+ const organizationId = getOrganizationId() || getOrgFromCookie();
1157
+ if (organizationId) {
1158
+ config.headers["X-Organization-ID"] = organizationId;
1159
+ }
1160
+ const precheck = runGlobalRequestPrecheck(config);
1161
+ if (!precheck.valid) {
1162
+ throw new ApiError(precheck.message || "Invalid request payload");
1163
+ }
1164
+ return config;
1165
+ });
1166
+ let refreshPromise = null;
1167
+ const refreshTokenSingleFlight = async () => {
1168
+ if (!refreshPromise) {
1169
+ refreshPromise = getAccessToken(true).finally(() => {
1170
+ refreshPromise = null;
1171
+ });
1172
+ }
1173
+ return refreshPromise;
1174
+ };
1175
+ instance.interceptors.response.use(response => {
1176
+ // Any successful call means the session can act in this organisation
1177
+ // after all. Without this the gate, once raised, stayed up through a
1178
+ // whole working session — including the seconds between an administrator
1179
+ // adding somebody and the employee record existing.
1180
+ if (typeof window !== "undefined") {
1181
+ window.dispatchEvent(new CustomEvent("erp:employee-record-ok"));
1182
+ }
1183
+ return response;
1184
+ }, async (error) => {
1185
+ const originalRequest = error.config;
1186
+ const requestUrl = originalRequest?.url || error.config?.url;
1187
+ if (error.response?.status === 401 &&
1188
+ originalRequest &&
1189
+ !originalRequest._retry &&
1190
+ !isAuthEndpoint(requestUrl) &&
1191
+ !isAuthPage()) {
1192
+ originalRequest._retry = true;
1193
+ const newToken = await refreshTokenSingleFlight();
1194
+ if (newToken && originalRequest.headers) {
1195
+ originalRequest.headers.Authorization = `Bearer ${newToken}`;
1196
+ return instance(originalRequest);
1197
+ }
1198
+ await redirectToLogout();
1199
+ return Promise.reject(toApiError(error));
1200
+ }
1201
+ // The server refuses every organisation-scoped call when the account has
1202
+ // no employee record. Announce it once so a gate can explain it, instead
1203
+ // of letting each failed query raise its own toast.
1204
+ if (error.response?.status === 403) {
1205
+ const body = error.response.data;
1206
+ if (body?.code === "EMPLOYEE_RECORD_REQUIRED" && typeof window !== "undefined") {
1207
+ window.dispatchEvent(new CustomEvent("erp:employee-record-required"));
1208
+ }
1209
+ }
1210
+ return Promise.reject(toApiError(error));
1211
+ });
1212
+
1213
+ /**
1214
+ * Where platform-api is, for the calls the shell itself makes to it (the
1215
+ * help channel, the user card's roles). Every app already calls it with the
1216
+ * user's token and the organisation header, and its CORS admits every app.
1217
+ */
1218
+ const DEFAULT_PLATFORM_API_URL = "https://platform-api.antniti.com/api/v1";
1219
+ function platformApiBase(app) {
1220
+ const explicit = process.env.NEXT_PUBLIC_PLATFORM_API_URL?.trim();
1221
+ if (explicit)
1222
+ return explicit.replace(/\/$/, "");
1223
+ // Platform's own API is platform-api.
1224
+ if (app === "platform") {
1225
+ const own = process.env.NEXT_PUBLIC_API_URL?.trim();
1226
+ if (own)
1227
+ return own.replace(/\/$/, "");
1228
+ }
1229
+ return DEFAULT_PLATFORM_API_URL;
1230
+ }
1231
+
1232
+ /**
1233
+ * This package's version, attached to help messages so the back office can
1234
+ * tell which shell a report came from. Keep in step with package.json.
1235
+ */
1236
+ const SHELL_VERSION = "0.1.53";
1237
+
1238
+ const HELP_APP_LABEL = {
1239
+ platform: "แพลตฟอร์ม",
1240
+ accounx: "Accounx",
1241
+ peoplx: "Peoplx",
1242
+ plannex: "Plannex",
1243
+ invenx: "Invenx",
1244
+ other: "อื่น ๆ",
1245
+ };
1246
+ function originOf(value) {
1247
+ if (!value)
1248
+ return null;
1249
+ try {
1250
+ return new URL(value).origin;
1251
+ }
1252
+ catch {
1253
+ return null;
1254
+ }
1255
+ }
1256
+ /**
1257
+ * Which app this page is: what the host said, what the app declared to the
1258
+ * app switcher, then the production sub-domain, then the app URLs the build
1259
+ * was given (local development). "other" when none of them tells.
1260
+ */
1261
+ function detectHelpApp(explicit) {
1262
+ if (explicit)
1263
+ return explicit;
1264
+ const declared = declaredHelpApp();
1265
+ if (declared)
1266
+ return declared;
1267
+ if (typeof window === "undefined")
1268
+ return "other";
1269
+ const host = window.location.hostname.toLowerCase();
1270
+ if (/^(accounx|erp|www\.erp)\./.test(host))
1271
+ return "accounx";
1272
+ if (/^(peoplx|hr)\./.test(host))
1273
+ return "peoplx";
1274
+ if (host.startsWith("plannex."))
1275
+ return "plannex";
1276
+ if (host.startsWith("invenx."))
1277
+ return "invenx";
1278
+ if (host.startsWith("platform.") || host === "antniti.com" || host === "www.antniti.com") {
1279
+ return "platform";
1280
+ }
1281
+ const here = window.location.origin;
1282
+ const configured = [
1283
+ ["platform", process.env.NEXT_PUBLIC_PLATFORM_URL],
1284
+ ["accounx", process.env.NEXT_PUBLIC_ACCOUNTING_URL],
1285
+ ["invenx", process.env.NEXT_PUBLIC_INVENX_URL],
1286
+ ["plannex", process.env.NEXT_PUBLIC_PLANNEX_URL],
1287
+ ["peoplx", process.env.NEXT_PUBLIC_HR_URL],
1288
+ ];
1289
+ for (const [id, url] of configured) {
1290
+ if (originOf(url) === here)
1291
+ return id;
1292
+ }
1293
+ return "other";
1294
+ }
1295
+ /** "Chrome 141" and "macOS" from a user agent — enough to reproduce. */
1296
+ function describeBrowser(ua) {
1297
+ const pick = (re) => ua.match(re)?.[1] ?? "";
1298
+ let browser = "";
1299
+ if (/\bLine\//i.test(ua))
1300
+ browser = `LINE ${pick(/\bLine\/([\d.]+)/i)}`;
1301
+ else if (/\bEdg(A|iOS)?\//.test(ua))
1302
+ browser = `Edge ${pick(/\bEdg(?:A|iOS)?\/(\d+)/)}`;
1303
+ else if (/\bOPR\//.test(ua))
1304
+ browser = `Opera ${pick(/\bOPR\/(\d+)/)}`;
1305
+ else if (/SamsungBrowser\//.test(ua))
1306
+ browser = `Samsung Internet ${pick(/SamsungBrowser\/(\d+)/)}`;
1307
+ else if (/\b(Firefox|FxiOS)\//.test(ua))
1308
+ browser = `Firefox ${pick(/\b(?:Firefox|FxiOS)\/(\d+)/)}`;
1309
+ else if (/\bCriOS\//.test(ua))
1310
+ browser = `Chrome ${pick(/\bCriOS\/(\d+)/)}`;
1311
+ else if (/(\b|Headless)Chrome\//.test(ua))
1312
+ browser = `Chrome ${pick(/(?:\b|Headless)Chrome\/(\d+)/)}`;
1313
+ else if (/\bSafari\//.test(ua))
1314
+ browser = `Safari ${pick(/\bVersion\/([\d.]+)/)}`;
1315
+ let platform = "";
1316
+ if (/\b(iPhone|iPad|iPod)\b/.test(ua)) {
1317
+ platform = `iOS ${pick(/\bOS (\d+[_\d]*)/).replace(/_/g, ".")}`;
1318
+ }
1319
+ else if (/\bAndroid\b/.test(ua)) {
1320
+ platform = `Android ${pick(/\bAndroid ([\d.]+)/)}`;
1321
+ }
1322
+ else if (/\bWindows\b/.test(ua)) {
1323
+ platform = "Windows";
1324
+ }
1325
+ else if (/\bMac OS X\b/.test(ua)) {
1326
+ platform = "macOS";
1327
+ }
1328
+ else if (/\bCrOS\b/.test(ua)) {
1329
+ platform = "ChromeOS";
1330
+ }
1331
+ else if (/\bLinux\b/.test(ua)) {
1332
+ platform = "Linux";
1333
+ }
1334
+ return { browser: browser.trim(), platform: platform.trim() };
1335
+ }
1336
+ /**
1337
+ * The deployed build: NEXT_PUBLIC_APP_VERSION when the app sets one, else
1338
+ * the Next build id in the page's own script paths (the build time, as every
1339
+ * app's generateBuildId writes it).
1340
+ */
1341
+ function readAppVersion() {
1342
+ const declared = process.env.NEXT_PUBLIC_APP_VERSION?.trim();
1343
+ if (declared)
1344
+ return declared;
1345
+ if (typeof document === "undefined")
1346
+ return "";
1347
+ const ignore = new Set(["chunks", "css", "media", "development", "webpack"]);
1348
+ for (const s of Array.from(document.querySelectorAll("script[src]"))) {
1349
+ const m = s.src.match(/\/_next\/static\/([^/]+)\//);
1350
+ if (m && !ignore.has(m[1]))
1351
+ return m[1];
1352
+ }
1353
+ return "";
1354
+ }
1355
+ function pageUrl() {
1356
+ if (typeof window === "undefined")
1357
+ return "";
1358
+ const { origin, pathname, search } = window.location;
1359
+ return `${origin}${pathname}${search}`;
1360
+ }
1361
+ /** Everything attached to a message, read at the moment it is sent. */
1362
+ function collectHelpContext(orgCode) {
1363
+ if (typeof window === "undefined")
1364
+ return { shell_version: SHELL_VERSION };
1365
+ const { browser, platform } = describeBrowser(window.navigator.userAgent || "");
1366
+ let timeZone = "";
1367
+ try {
1368
+ timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
1369
+ }
1370
+ catch {
1371
+ timeZone = "";
1372
+ }
1373
+ const ctx = {
1374
+ page_url: pageUrl(),
1375
+ page_title: document.title || undefined,
1376
+ org_code: orgCode || undefined,
1377
+ app_version: readAppVersion() || undefined,
1378
+ shell_version: SHELL_VERSION,
1379
+ browser: browser || undefined,
1380
+ platform: platform || undefined,
1381
+ screen: `${window.screen.width}x${window.screen.height}`,
1382
+ viewport: `${window.innerWidth}x${window.innerHeight}`,
1383
+ language: window.navigator.language || undefined,
1384
+ time_zone: timeZone || undefined,
1385
+ };
1386
+ return ctx;
1387
+ }
1388
+ /** The short line under the form, "ข้อมูลที่แนบ: …". */
1389
+ function describeAttached(app, ctx, email) {
1390
+ let path = "";
1391
+ if (ctx.page_url) {
1392
+ try {
1393
+ path = new URL(ctx.page_url).pathname;
1394
+ }
1395
+ catch {
1396
+ path = ctx.page_url;
1397
+ }
1398
+ }
1399
+ // The organisation code is shown on its own; the path after it says where.
1400
+ if (ctx.org_code && path.startsWith(`/${ctx.org_code}`)) {
1401
+ path = path.slice(ctx.org_code.length + 1);
1402
+ }
1403
+ if (path === "/")
1404
+ path = "";
1405
+ const browser = [ctx.browser, ctx.platform && `(${ctx.platform})`].filter(Boolean).join(" ");
1406
+ return [
1407
+ HELP_APP_LABEL[app],
1408
+ ctx.org_code,
1409
+ path,
1410
+ email || undefined,
1411
+ browser || undefined,
1412
+ ctx.app_version,
1413
+ ]
1414
+ .filter(Boolean)
1415
+ .join(" · ");
1416
+ }
1417
+
1418
+ const myRolesQueryKey = (organizationId) => ["erp-shell", "my-roles", organizationId];
1419
+ // Only for a host that renders NavUser outside a QueryClientProvider: the
1420
+ // card still works there instead of throwing.
1421
+ let fallbackClient = null;
1422
+ function useShellQueryClient() {
1423
+ const provided = useContext(QueryClientContext);
1424
+ if (provided)
1425
+ return provided;
1426
+ fallbackClient ?? (fallbackClient = new QueryClient());
1427
+ return fallbackClient;
1428
+ }
1429
+ function subscribeStorage(onChange) {
1430
+ window.addEventListener("storage", onChange);
1431
+ return () => window.removeEventListener("storage", onChange);
1432
+ }
1433
+ /**
1434
+ * The organisation the API client sends (X-Organization-ID). Null while
1435
+ * server-rendering and hydrating, so the first client render matches the
1436
+ * server's.
1437
+ */
1438
+ function useStoredOrganizationId() {
1439
+ return useSyncExternalStore(subscribeStorage, getOrganizationId, () => null);
1440
+ }
1441
+ /**
1442
+ * The signed-in person's roles in an organisation, from platform-api
1443
+ * (GET /organizations/:id/my-roles). Cached per organisation; a different
1444
+ * organisation is a different query. A failure, or an API too old to have
1445
+ * the route, leaves `data` empty — the caller shows nothing.
1446
+ */
1447
+ function useMyRoles(organizationId, enabled = true) {
1448
+ const orgId = organizationId !== null &&
1449
+ organizationId !== undefined &&
1450
+ String(organizationId).trim() !== ""
1451
+ ? String(organizationId).trim()
1452
+ : null;
1453
+ const client = useShellQueryClient();
1454
+ return useQuery({
1455
+ queryKey: myRolesQueryKey(orgId),
1456
+ queryFn: async ({ signal }) => {
1457
+ const base = platformApiBase(detectHelpApp());
1458
+ const res = await instance.get(`${base}/organizations/${encodeURIComponent(orgId)}/my-roles`, { signal });
1459
+ return parseMyRoles(res.data, orgId);
1460
+ },
1461
+ enabled: enabled && orgId !== null,
1462
+ staleTime: 60000,
1463
+ gcTime: 30 * 60000,
1464
+ // A refusal or a missing route will not be different a second later;
1465
+ // the next focus or organisation change asks again.
1466
+ retry: false,
1467
+ refetchOnWindowFocus: true,
1468
+ }, client);
1469
+ }
1470
+
1471
+ /** The owner's chip: the app's accent, tinted. */
1472
+ function OwnerChip({ size = "card" }) {
1473
+ return (jsx("span", { className: size === "menu"
1474
+ ? "inline-flex shrink-0 items-center rounded-md bg-primary/10 px-2 py-0.5 text-xs font-semibold text-primary"
1475
+ : "inline-flex shrink-0 items-center rounded-full bg-primary/10 px-1.5 text-[11px] font-semibold leading-[17px] text-primary", children: OWNER_CHIP }));
1476
+ }
1477
+ /**
1478
+ * The card's role line: the owner's chip, then two role names and a count of
1479
+ * the rest. Wraps between names rather than inside one, and truncates a name
1480
+ * that is wider than the card on its own; the tooltip has everything.
1481
+ */
1482
+ function CardRoles({ my, className }) {
1483
+ const { shown, more } = cardRoleLine(my.roles);
1484
+ return (jsxs("span", { className: `flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0.5 ${className}`, title: roleSummary(my), children: [my.isOwner ? jsx(OwnerChip, {}) : null, shown.map((name, i) => {
1485
+ const last = i === shown.length - 1;
1486
+ return (jsxs("span", { className: "flex min-w-0 max-w-full items-baseline", children: [jsx("span", { className: "truncate", children: name }), !last ? (jsx("span", { "aria-hidden": "true", className: "shrink-0 pl-1 opacity-60", children: "\u00B7" })) : null, last && more > 0 ? (jsxs("span", { className: "shrink-0 pl-1 opacity-70", children: ["+", more] })) : null] }, name));
1487
+ })] }));
1488
+ }
1489
+ /** Every role in full, for the menu. */
1490
+ function MenuRoles({ my }) {
1491
+ return (jsxs("div", { className: "flex flex-wrap gap-1.5", children: [my.isOwner ? jsx(OwnerChip, { size: "menu" }) : null, my.roles.map(r => (jsx("span", { className: "rounded-md border border-sidebar-border px-2 py-0.5 text-xs text-sidebar-foreground", children: r.name_th }, r.key || r.name_th)))] }));
1492
+ }
1493
+ function isExternalHref(href) {
1494
+ return /^https?:\/\//i.test(href) || href.startsWith("//");
1495
+ }
1496
+ function NavUser({ organization, avatarSrc, profileHref, selectOrganizationHref = "/select-organization", signInRedirectHref = "/auth/signin", systemLinks, showSelectOrganization = true, showLanguageSwitch = true, variant = "brand", showRoles, organizationId, } = {}) {
1497
+ const { data: session, status } = useSession();
1498
+ const storedOrganizationId = useStoredOrganizationId();
1499
+ const rolesOrganizationId = organizationId !== null &&
1500
+ organizationId !== undefined &&
1501
+ String(organizationId).trim() !== ""
1502
+ ? organizationId
1503
+ : storedOrganizationId;
1504
+ const rolesOn = (showRoles ?? showSelectOrganization) && status === "authenticated";
1505
+ const { data: rolesData, fetchStatus: rolesFetchStatus } = useMyRoles(rolesOrganizationId, rolesOn);
1506
+ const myRoles = rolesOn && hasRoleLine(rolesData) ? rolesData : null;
1507
+ // First load only: hold the line's place so the card does not jump when
1508
+ // the roles arrive. A failure drops it.
1509
+ const rolesLoading = rolesOn && !!rolesOrganizationId && rolesData === undefined && rolesFetchStatus === "fetching";
1510
+ // With a role line the card is three lines or more: the chevron moves up
1511
+ // to the name so the lines under it get the card's full width.
1512
+ const cardTall = !!myRoles || rolesLoading;
1513
+ const router = useRouter();
1514
+ const { theme, setTheme } = useTheme();
1515
+ const [isSigningOut, setIsSigningOut] = useState(false);
1516
+ const [isOpen, setIsOpen] = useState(false);
1517
+ const [showThemeMenu, setShowThemeMenu] = useState(false);
1518
+ const [showLanguageMenu, setShowLanguageMenu] = useState(false);
1519
+ const [showAppsMenu, setShowAppsMenu] = useState(false);
1520
+ const buttonRef = useRef(null);
1521
+ const [position, setPosition] = useState({ top: 0, left: 0 });
1522
+ // Shown where a layout has mounted the help dialog (AppLayoutShell).
1523
+ const helpAvailable = useHelpAvailable();
1524
+ const user = session?.user
1525
+ ? {
1526
+ name: session.user.name || "ผู้ใช้",
1527
+ email: session.user.email || "",
1528
+ // avatarSrc first: the NextAuth session carries no picture unless the
1529
+ // host app deliberately puts one in the JWT, so relying on
1530
+ // session.user.image alone left every user on their initials forever.
1531
+ avatar: avatarSrc || session.user.image || undefined,
1532
+ }
1533
+ : null;
1534
+ const getInitials = (name) => {
1535
+ if (!name)
1536
+ return "U";
1537
+ return name
1538
+ .split(" ")
1539
+ .map(n => n[0])
1540
+ .join("")
1541
+ .toUpperCase()
1542
+ .slice(0, 2);
1543
+ };
1544
+ const handleSignOut = async () => {
1545
+ setIsSigningOut(true);
1546
+ try {
1547
+ await signOut({ callbackUrl: signInRedirectHref, redirect: true });
1548
+ }
1549
+ catch (error) {
1550
+ console.error("Sign out error:", error);
1551
+ window.location.href = signInRedirectHref;
1552
+ }
1553
+ finally {
1554
+ setIsSigningOut(false);
1555
+ }
1556
+ };
1557
+ const handleSelectOrganization = () => {
1558
+ setIsOpen(false);
1559
+ router.push(selectOrganizationHref);
1560
+ };
1561
+ const handleProfile = () => {
1562
+ setIsOpen(false);
1563
+ if (profileHref)
1564
+ router.push(profileHref);
1565
+ };
1566
+ const handleSystemLink = (href) => {
1567
+ setIsOpen(false);
1568
+ if (isExternalHref(href)) {
1569
+ window.location.assign(href);
1570
+ return;
1571
+ }
1572
+ router.push(href);
1573
+ };
1574
+ const handleThemeChange = (newTheme) => {
1575
+ setTheme(newTheme);
1576
+ setShowThemeMenu(false);
1577
+ };
1578
+ const handleLanguageChange = (language) => {
1579
+ console.log("Change language to:", language);
1580
+ setShowLanguageMenu(false);
1581
+ };
1582
+ useEffect(() => {
1583
+ if (isOpen && buttonRef.current) {
1584
+ const rect = buttonRef.current.getBoundingClientRect();
1585
+ setPosition({ top: rect.bottom, left: rect.right + 8 });
1586
+ }
1587
+ }, [isOpen]);
1588
+ useEffect(() => {
1589
+ if (!isOpen)
1590
+ return;
1591
+ const handleClickOutside = (event) => {
1592
+ if (buttonRef.current &&
1593
+ !buttonRef.current.contains(event.target) &&
1594
+ !event.target.closest('[data-dropdown="nav-user"]')) {
1595
+ setIsOpen(false);
1596
+ }
1597
+ };
1598
+ document.addEventListener("mousedown", handleClickOutside);
1599
+ return () => document.removeEventListener("mousedown", handleClickOutside);
1600
+ }, [isOpen]);
1601
+ if (status === "loading") {
1602
+ return (jsx("div", { className: "p-2", children: jsxs("div", { className: "flex items-center gap-2 p-2 rounded-md", children: [jsx("div", { className: "h-8 w-8 rounded-lg bg-sidebar-accent animate-pulse" }), jsxs("div", { className: "flex-1 space-y-1", children: [jsx("div", { className: "h-4 w-24 bg-sidebar-accent rounded animate-pulse" }), jsx("div", { className: "h-3 w-32 bg-sidebar-accent rounded animate-pulse" })] })] }) }));
1603
+ }
1604
+ if (!user)
1605
+ return null;
1606
+ const visibleSystemLinks = (systemLinks ?? []).filter(link => link.href && link.label);
1607
+ const dropdownContent = isOpen ? (jsxs("div", { "data-dropdown": "nav-user", className: "fixed w-52 sm:w-60 md:w-80 rounded-lg bg-sidebar border border-sidebar-border shadow-xl z-50 overflow-hidden\n -translate-x-[65%] -translate-y-[110%] sm:translate-x-0 sm:-translate-y-full", style: { top: `${position.top}px`, left: `${position.left}px` }, children: [organization && (jsx("div", { className: "p-4 border-b border-sidebar-border bg-sidebar-accent/30", children: jsxs("div", { className: `flex gap-3 ${myRoles ? "items-start" : "items-center"}`, children: [organization.logoUrl ? (
1608
+ // eslint-disable-next-line @next/next/no-img-element
1609
+ jsx("img", { src: organization.logoUrl, alt: organization.name ?? "โลโก้บริษัท", className: "h-8 w-8 flex-shrink-0 rounded object-contain bg-white",
1610
+ // A dead logo URL must not leave a broken-image glyph in the
1611
+ // sidebar; drop back to the generic icon's empty slot.
1612
+ onError: e => {
1613
+ e.currentTarget.style.display = "none";
1614
+ } })) : (jsx(Building2, { className: "h-5 w-5 text-sidebar-foreground/70 flex-shrink-0" })), jsxs("div", { className: "flex-1 min-w-0", children: [jsx("div", { className: "font-medium text-sm sm:truncate", children: organization.name }), organization.description && (jsx("div", { className: "text-xs text-sidebar-foreground/70 truncate mt-0.5", children: organization.description })), myRoles ? (jsx("div", { className: "mt-2.5", children: jsx(MenuRoles, { my: myRoles }) })) : null] })] }) })), !organization && myRoles ? (jsx("div", { className: "p-4 border-b border-sidebar-border bg-sidebar-accent/30", children: jsx(MenuRoles, { my: myRoles }) })) : null, jsxs("div", { className: "p-2", children: [jsxs("div", { className: "relative", children: [jsxs("button", { onClick: () => {
1615
+ setShowThemeMenu(!showThemeMenu);
1616
+ setShowLanguageMenu(false);
1617
+ setShowAppsMenu(false);
1618
+ }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Palette, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E18\u0E35\u0E21" }), jsx(ChevronUp, { className: `h-4 w-4 transition-transform ${showThemeMenu ? "rotate-180" : ""}` })] }), showThemeMenu && (jsx("div", { className: "mt-1 ml-4 space-y-1", children: [
1619
+ { key: "light", label: "สว่าง", Icon: Sun },
1620
+ { key: "dark", label: "มืด", Icon: Moon },
1621
+ { key: "system", label: "ตามระบบ", Icon: Monitor },
1622
+ ].map(({ key, label, Icon }) => (jsxs("button", { onClick: () => handleThemeChange(key), className: "flex w-full items-center gap-3 px-3 py-2 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Icon, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: label }), theme === key && (jsx("div", { className: "h-2 w-2 rounded-full bg-primary" }))] }, key))) }))] }), showLanguageSwitch && (jsxs("div", { className: "relative", children: [jsxs("button", { onClick: () => {
1623
+ setShowLanguageMenu(!showLanguageMenu);
1624
+ setShowThemeMenu(false);
1625
+ setShowAppsMenu(false);
1626
+ }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Globe, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E20\u0E32\u0E29\u0E32" }), jsx(ChevronUp, { className: `h-4 w-4 transition-transform ${showLanguageMenu ? "rotate-180" : ""}` })] }), showLanguageMenu && (jsx("div", { className: "mt-1 ml-4 space-y-1", children: [
1627
+ { code: "th", label: "ไทย" },
1628
+ { code: "en", label: "English" },
1629
+ { code: "zh", label: "中文" },
1630
+ { code: "ja", label: "日本語" },
1631
+ ].map(({ code, label }) => (jsxs("button", { onClick: () => handleLanguageChange(code), className: "flex w-full items-center gap-3 px-3 py-2 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx("span", { className: "flex-1 text-left", children: label }), organization?.language === code && (jsx("div", { className: "h-2 w-2 rounded-full bg-primary" }))] }, code))) }))] })), profileHref && (jsxs("button", { onClick: handleProfile, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(User, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E2A\u0E48\u0E27\u0E19\u0E15\u0E31\u0E27" })] })), showSelectOrganization && (jsxs("button", { onClick: handleSelectOrganization, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(Building2, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E18\u0E38\u0E23\u0E01\u0E34\u0E08" })] })), visibleSystemLinks.length > 0 && (jsxs("div", { className: "relative", children: [jsxs("button", { onClick: () => {
1632
+ setShowAppsMenu(!showAppsMenu);
1633
+ setShowThemeMenu(false);
1634
+ setShowLanguageMenu(false);
1635
+ }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(LayoutGrid, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E41\u0E2D\u0E1B\u0E1E\u0E25\u0E34\u0E40\u0E04\u0E0A\u0E31\u0E19" }), jsx(ChevronUp, { className: `h-4 w-4 transition-transform ${showAppsMenu ? "rotate-180" : ""}` })] }), showAppsMenu && (jsx("div", { className: "mt-1 ml-4 space-y-1", children: visibleSystemLinks.map(link => (jsxs("button", { type: "button", onClick: () => handleSystemLink(link.href), className: "flex w-full items-center gap-3 px-3 py-2 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [link.icon ?? jsx(ExternalLink, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: link.label }), link.active && (jsx("div", { className: "h-2 w-2 rounded-full bg-primary" }))] }, `${link.label}:${link.href}`))) }))] })), helpAvailable && (jsxs("button", { type: "button", onClick: () => {
1636
+ setIsOpen(false);
1637
+ openHelp();
1638
+ }, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors", children: [jsx(CircleHelp, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D" })] })), jsx("button", { onClick: handleSignOut, disabled: isSigningOut, className: "flex w-full items-center gap-3 px-3 py-2.5 text-sm text-sidebar-foreground hover:bg-sidebar-accent rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed mt-1", children: isSigningOut ? (jsxs(Fragment$1, { children: [jsx(Loader2, { className: "h-4 w-4 animate-spin" }), jsx("span", { className: "flex-1 text-left", children: "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A..." })] })) : (jsxs(Fragment$1, { children: [jsx(LogOut, { className: "h-4 w-4" }), jsx("span", { className: "flex-1 text-left", children: "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E23\u0E30\u0E1A\u0E1A" })] })) })] })] })) : null;
1639
+ if (variant === "workspace") {
1640
+ return (jsx("div", { className: "mt-3.5 border-t border-sidebar-border pt-3", children: jsxs("div", { className: "relative", children: [jsxs("button", { ref: buttonRef, onClick: () => setIsOpen(!isOpen), "aria-expanded": isOpen, className: `relative flex w-full gap-[11px] rounded-lg px-3 py-1.5 text-left transition-colors hover:bg-sidebar-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring ${cardTall ? "items-start" : "items-center"}`, children: [jsxs(Avatar, { className: "size-[34px] shrink-0 rounded-full border-[3px] border-sidebar-accent", children: [user.avatar ? (jsx(AvatarImage, { src: user.avatar, alt: user.name })) : null, jsx(AvatarFallback, { className: "rounded-full bg-sidebar-accent text-sm font-medium text-sidebar-accent-foreground", children: getInitials(user.name) })] }), jsxs("span", { className: `grid min-w-0 flex-1 leading-tight ${cardTall ? "gap-0.5" : ""}`, children: [jsx("strong", { className: `truncate text-[13px] font-semibold ${cardTall ? "pr-5" : ""}`, title: user.name, children: user.name }), myRoles ? (jsx(CardRoles, { my: myRoles, className: "text-[12px] font-medium leading-[17px] text-sidebar-foreground/80" })) : rolesLoading ? (jsx("span", { className: "my-[3px] block h-[11px] w-20 animate-pulse rounded bg-sidebar-accent" })) : null, jsx("small", { className: "truncate text-[11px] text-muted-foreground", title: user.email, children: user.email })] }), jsx(ChevronsUpDown, { className: cardTall
1641
+ ? "absolute right-3 top-[9px] size-3.5 text-muted-foreground"
1642
+ : "size-3.5 shrink-0 text-muted-foreground" })] }), typeof window !== "undefined" &&
1643
+ createPortal(dropdownContent, document.body)] }) }));
1644
+ }
1645
+ return (jsx("div", { className: "p-2", children: jsxs("div", { className: "relative", children: [jsxs("button", { ref: buttonRef, onClick: () => setIsOpen(!isOpen), className: `relative flex w-full gap-2 p-2 rounded-md transition-colors ${cardTall ? "items-start" : "items-center"}`, children: [jsxs(Avatar, { className: "h-8 w-8 shrink-0 rounded-lg", children: [user.avatar ? (jsx(AvatarImage, { src: user.avatar, alt: user.name })) : null, jsx(AvatarFallback, { className: "rounded-lg bg-primary text-primary-foreground w-8 h-8", children: getInitials(user.name) })] }), jsxs("div", { className: `grid min-w-0 flex-1 text-left text-sm leading-tight ${cardTall ? "gap-0.5" : ""}`, children: [jsx("span", { className: `truncate font-medium ${cardTall ? "pr-6" : ""}`, title: user.name, children: user.name }), myRoles ? (jsx(CardRoles, { my: myRoles, className: "text-xs font-medium text-sidebar-foreground/85" })) : rolesLoading ? (jsx("span", { className: "my-0.5 block h-3 w-24 animate-pulse rounded bg-sidebar-accent" })) : null, jsx("span", { className: "truncate text-xs text-sidebar-foreground/70", title: user.email, children: user.email })] }), jsx(ChevronUp, { className: `size-4 transition-transform ${isOpen ? "rotate-180" : ""} ${cardTall ? "absolute right-2 top-2.5" : "ml-auto shrink-0"}` })] }), typeof window !== "undefined" &&
1646
+ createPortal(dropdownContent, document.body)] }) }));
1647
+ }
1648
+
1649
+ /**
1650
+ * Plan feature keys (billable entitlements). Mirror of platform-apis plan.go.
1651
+ *
1652
+ * This lives in the shell because every app gates on the same keys, and five
1653
+ * private copies of the same list drift: the app-switcher list did exactly
1654
+ * that before it moved here.
1655
+ */
1656
+ const PLAN_FEATURES = {
1657
+ ORG_CHART: "org_chart",
1658
+ APPROVAL_WORKFLOW: "approval_workflow",
1659
+ API_ACCESS: "api_access",
1660
+ SSO: "sso",
1661
+ BASIC_ACCOUNTING_HR: "basic_accounting_hr",
1662
+ MODULE_PLATFORM: "module.platform",
1663
+ MODULE_HR: "module.hr",
1664
+ MODULE_ACCOUNTING: "module.accounting",
1665
+ MODULE_SALES: "module.sales",
1666
+ MODULE_PURCHASING: "module.purchasing",
1667
+ MODULE_INVENTORY: "module.inventory",
1668
+ MODULE_PROJECT: "module.project",
1669
+ MODULE_SECRETARIAT: "module.secretariat",
1670
+ /** AI pack (paid or trial): AI calls on AntNiti's key while credits remain. */
1671
+ AI: "ai",
1672
+ };
1673
+ /** Keys the Accounx add-on carries with it (same alias as org_effective_features). */
1674
+ const ACCOUNTING_SUB_KEYS = [
1675
+ PLAN_FEATURES.MODULE_SALES,
1676
+ PLAN_FEATURES.MODULE_PURCHASING,
1677
+ PLAN_FEATURES.MODULE_SECRETARIAT,
1678
+ ];
1679
+ /**
1680
+ * True when plan features include key. Aliases, mirroring the backend:
1681
+ * legacy basic_accounting_hr → module.hr + module.accounting (+ its sub-keys);
1682
+ * module.accounting → module.sales, module.purchasing, module.secretariat.
1683
+ */
1684
+ function hasPlanFeature(features, feature) {
1685
+ if (!features?.length)
1686
+ return false;
1687
+ if (features.includes(feature))
1688
+ return true;
1689
+ if ((feature === PLAN_FEATURES.MODULE_HR ||
1690
+ feature === PLAN_FEATURES.MODULE_ACCOUNTING ||
1691
+ ACCOUNTING_SUB_KEYS.includes(feature)) &&
1692
+ features.includes(PLAN_FEATURES.BASIC_ACCOUNTING_HR)) {
1693
+ return true;
1694
+ }
1695
+ if (ACCOUNTING_SUB_KEYS.includes(feature) &&
1696
+ features.includes(PLAN_FEATURES.MODULE_ACCOUNTING)) {
1697
+ return true;
1698
+ }
1699
+ if (feature === PLAN_FEATURES.BASIC_ACCOUNTING_HR &&
1700
+ features.includes(PLAN_FEATURES.MODULE_HR) &&
1701
+ features.includes(PLAN_FEATURES.MODULE_ACCOUNTING)) {
1702
+ return true;
1703
+ }
1704
+ return false;
1705
+ }
1706
+
1707
+ function normaliseBase(value, fallback) {
1708
+ return (value ?? fallback).replace(/\/$/, "");
1709
+ }
1710
+ /**
1711
+ * One list, in display order, for the whole suite.
1712
+ *
1713
+ * It used to be copied into every app's own nav-user.tsx, which is how Invenx
1714
+ * shipped without a link to Plannex: five copies, one of them edited by hand.
1715
+ * Adding the sixth app is now a change here plus a version bump.
1716
+ */
1717
+ const APPS = [
1718
+ {
1719
+ id: "platform",
1720
+ label: "แพลตฟอร์ม",
1721
+ icon: jsx(Building2, { className: "h-4 w-4 shrink-0" }),
1722
+ features: null,
1723
+ baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_PLATFORM_URL, "https://platform.antniti.com"),
1724
+ },
1725
+ {
1726
+ id: "accounx",
1727
+ label: "Accounx",
1728
+ icon: jsx(Calculator, { className: "h-4 w-4 shrink-0" }),
1729
+ features: [PLAN_FEATURES.MODULE_ACCOUNTING],
1730
+ baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_ACCOUNTING_URL, "https://accounx.antniti.com"),
1731
+ },
1732
+ {
1733
+ id: "invenx",
1734
+ label: "Invenx",
1735
+ icon: jsx(Warehouse, { className: "h-4 w-4 shrink-0" }),
1736
+ features: [PLAN_FEATURES.MODULE_INVENTORY],
1737
+ baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_INVENX_URL, "https://invenx.antniti.com"),
1738
+ },
1739
+ {
1740
+ id: "plannex",
1741
+ label: "Plannex",
1742
+ icon: jsx(FolderKanban, { className: "h-4 w-4 shrink-0" }),
1743
+ // Tasks, day-logs and work records are free with HR; projects need the add-on.
1744
+ features: [PLAN_FEATURES.MODULE_HR, PLAN_FEATURES.MODULE_PROJECT],
1745
+ baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_PLANNEX_URL, "https://plannex.antniti.com"),
1746
+ },
1747
+ {
1748
+ id: "peoplx",
1749
+ label: "Peoplx",
1750
+ icon: jsx(Users, { className: "h-4 w-4 shrink-0" }),
1751
+ features: [PLAN_FEATURES.MODULE_HR],
1752
+ baseUrl: () => normaliseBase(process.env.NEXT_PUBLIC_HR_URL, "https://peoplx.antniti.com"),
1753
+ },
1754
+ ];
1755
+ /**
1756
+ * Builds the cross-app link list for <NavUser systemLinks>.
1757
+ *
1758
+ * The current app is always present even when the org's plan no longer covers
1759
+ * it — the user is looking at it, so hiding the link would only make the menu
1760
+ * disagree with the screen.
1761
+ */
1762
+ function buildSystemLinks({ orgCode, activeApp, features, }) {
1763
+ // The app names itself here; the help dialog says which app a message
1764
+ // came from by it.
1765
+ declareHelpApp(activeApp);
1766
+ if (!orgCode)
1767
+ return [];
1768
+ return APPS.filter(app => app.id === activeApp ||
1769
+ app.features === null ||
1770
+ app.features.some(key => hasPlanFeature(features, key))).map(app => ({
1771
+ label: app.label,
1772
+ icon: app.icon,
1773
+ // Same-app link stays relative so it never leaves the current origin.
1774
+ href: app.id === activeApp ? `/${orgCode}` : `${app.baseUrl()}/${orgCode}`,
1775
+ ...(app.id === activeApp ? { active: true } : {}),
1776
+ }));
1777
+ }
1778
+
1779
+ // Helper function to check if pathname matches a URL pattern
1780
+ // This prevents false matches like /reports/sales matching /sales
1781
+ // Handles paths with or without [code] prefix
1070
1782
  function isPathActive(pathname, url) {
1071
1783
  // Exact match
1072
1784
  if (pathname === url) {
@@ -1322,993 +2034,1556 @@ const WORKSPACE_LIGHT_HEADER_VARS = {
1322
2034
  };
1323
2035
 
1324
2036
  /**
1325
- * Top-level app chrome: sticky header, sidebar slot, content gutter and the
1326
- * session/org-context plumbing that both Accounting and HR need. Apps wrap
1327
- * it inside their `SidebarProvider` (server-rendered with the cookie-backed
1328
- * `defaultOpen`) and their `ERPProvider`, then pass app-specific bits as
1329
- * props.
2037
+ * The ช่วยเหลือ button in the top bar. Drawn in the header's ink (the
2038
+ * --header-* variables of the workspace chrome, white on the brand chrome).
2039
+ */
2040
+ function HelpButton({ className }) {
2041
+ 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)]" +
2042
+ (className ? ` ${className}` : ""), children: jsx(CircleHelp, { className: "size-5", strokeWidth: 1.65 }) }));
2043
+ }
2044
+
2045
+ const hasPaginationShape = (payload) => {
2046
+ return ("total" in payload ||
2047
+ "page" in payload ||
2048
+ "per_page" in payload ||
2049
+ "total_pages" in payload ||
2050
+ "has_next" in payload ||
2051
+ "has_prev" in payload ||
2052
+ "pagination" in payload);
2053
+ };
2054
+ const isEnvelope = (payload) => {
2055
+ return ("success" in payload || "message" in payload) && !hasPaginationShape(payload);
2056
+ };
2057
+ const unwrapApiResponse = (payload) => {
2058
+ if (!payload || typeof payload !== "object") {
2059
+ return payload;
2060
+ }
2061
+ const record = payload;
2062
+ if ("data" in record &&
2063
+ record.data !== undefined &&
2064
+ isEnvelope(record)) {
2065
+ return record.data;
2066
+ }
2067
+ return payload;
2068
+ };
2069
+
2070
+ /**
2071
+ * The images on a help message (and on a follow-up): what was added, what is
2072
+ * uploading, what is ready to send, and what was refused and why.
1330
2073
  *
1331
- * The padding contract is deliberately owned here so future style tweaks
1332
- * (e.g. the recent left/right/bottom gutter pass) propagate to both apps via
1333
- * an erp-shell bump — domain components must NOT add their own root padding
1334
- * or content gets indented twice.
2074
+ * Plain state with no React and no network of its own — the uploader is
2075
+ * handed in — so the rules are tested on their own (help-attach.test.ts):
2076
+ * PNG, JPEG, WebP or GIF; at most 5 MB each; at most three; a paste or a drop
2077
+ * adds the same way the file picker does; ส่ง waits for what is uploading.
2078
+ *
2079
+ * Kept free of imports: the tests load it straight from source.
1335
2080
  */
1336
- function AppLayoutShell({ children, sidebar, loadingComponent, breadcrumb, permissionProvider, organizationId, setOrganizationId, organizations, signInUrl, selectOrganizationUrl, chrome = "brand", workspaceHeader = "brand", headerEnd, mobileBrand, }) {
1337
- const { data: session, status } = useSession();
1338
- const { open, setOpen } = useSidebar();
1339
- const router = useRouter();
1340
- const params = useParams();
1341
- const code = params?.code;
1342
- const extendedSession = session;
1343
- // Track once-authenticated so a transient accessToken drop during the
1344
- // periodic session refresh (SessionRefreshTrigger every 4 min) doesn't
1345
- // blank the whole page. The initial-load gate below still handles cold
1346
- // start; once we've seen a real token we render children optimistically
1347
- // and let the API layer surface a real 401 if the token actually died.
1348
- const hasSeenAccessTokenRef = useRef(false);
1349
- useEffect(() => {
1350
- if (extendedSession?.accessToken)
1351
- hasSeenAccessTokenRef.current = true;
1352
- }, [extendedSession?.accessToken]);
1353
- // Find the org from the URL `[code]` so we can detect a context mismatch
1354
- // (the user bookmarked a different org than the cookie remembers).
1355
- const orgFromCode = React.useMemo(() => {
1356
- if (!code || !organizations.length)
1357
- return null;
1358
- return (organizations.find(org => org.code === code || String(org.id) === code) ?? null);
1359
- }, [code, organizations]);
1360
- // Sync state: when the URL code points at a different org than the cookie,
1361
- // trust the URL and update the cookie. Otherwise do nothing — the user
1362
- // wins ties via the in-app org switcher.
1363
- useEffect(() => {
1364
- if (!code)
1365
- return;
1366
- if (!organizations.length)
1367
- return;
1368
- if (!orgFromCode)
1369
- return;
1370
- if (String(organizationId) !== String(orgFromCode.id)) {
1371
- void setOrganizationId(orgFromCode.id);
2081
+ const HELP_IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
2082
+ const HELP_IMAGE_ACCEPT = HELP_IMAGE_TYPES.join(",");
2083
+ const HELP_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
2084
+ const HELP_IMAGE_MAX_COUNT = 3;
2085
+ /** The words for each refusal, per file. */
2086
+ const HELP_IMAGE_ERRORS = {
2087
+ tooLarge: "ใหญ่เกิน 5 MB",
2088
+ notImage: "ไม่ใช่ไฟล์รูปภาพ (PNG, JPEG, WebP หรือ GIF)",
2089
+ tooMany: "แนบได้ไม่เกิน 3 รูป",
2090
+ failed: "อัปโหลดไม่สำเร็จ",
2091
+ };
2092
+ /** The declared type, as one of the four, or "". */
2093
+ function helpImageType(type) {
2094
+ const t = (type || "").toLowerCase().split(";")[0].trim();
2095
+ if (t === "image/jpg" || t === "image/pjpeg")
2096
+ return "image/jpeg";
2097
+ return HELP_IMAGE_TYPES.includes(t) ? t : "";
2098
+ }
2099
+ /** Why a file cannot be attached, or null when it can. */
2100
+ function checkHelpImage(file) {
2101
+ if (!helpImageType(file.type) || file.size <= 0)
2102
+ return HELP_IMAGE_ERRORS.notImage;
2103
+ if (file.size > HELP_IMAGE_MAX_BYTES)
2104
+ return HELP_IMAGE_ERRORS.tooLarge;
2105
+ return null;
2106
+ }
2107
+ /**
2108
+ * The files a paste carries, when it is a paste of a picture: a screenshot
2109
+ * or a copied image. A paste that carries text is text — copying a cell from
2110
+ * a spreadsheet also puts a picture of it on the clipboard, and that is not
2111
+ * an attachment.
2112
+ */
2113
+ function filesFromPaste(data) {
2114
+ if (!data)
2115
+ return [];
2116
+ const text = data.getData?.("text/plain") ?? "";
2117
+ if (text.trim() !== "")
2118
+ return [];
2119
+ const out = [];
2120
+ if (data.files && data.files.length > 0) {
2121
+ for (let i = 0; i < data.files.length; i++)
2122
+ out.push(data.files[i]);
2123
+ return out;
2124
+ }
2125
+ if (data.items) {
2126
+ for (let i = 0; i < data.items.length; i++) {
2127
+ const it = data.items[i];
2128
+ if (it.kind !== "file")
2129
+ continue;
2130
+ const f = it.getAsFile();
2131
+ if (f)
2132
+ out.push(f);
1372
2133
  }
1373
- }, [
1374
- orgFromCode,
1375
- organizationId,
1376
- setOrganizationId,
1377
- code,
1378
- organizations.length,
1379
- ]);
1380
- // Key for the content subtree. It exists so switching organizations throws
1381
- // away the previous org's component state — but it must react ONLY to a real
1382
- // switch. organizationId legitimately passes through null while the context
1383
- // re-settles (session resolving, cookie write in flight), and keying on that
1384
- // unmounted and remounted the entire page: forms lost their loaded values,
1385
- // in-flight edits vanished, and settings pickers snapped back to defaults.
1386
- //
1387
- // Holding the last known id makes a transient null a no-op while a genuine
1388
- // org-to-org switch still changes the key.
1389
- const lastOrgKeyRef = React.useRef("no-org");
1390
- const currentOrgKey = organizationId === null ||
1391
- organizationId === undefined ||
1392
- String(organizationId).trim() === ""
1393
- ? null
1394
- : String(organizationId);
1395
- if (currentOrgKey !== null) {
1396
- lastOrgKeyRef.current = currentOrgKey;
1397
- }
1398
- const contentOrgKey = lastOrgKeyRef.current;
1399
- // Hold the page back until the active organisation is the one the URL names.
1400
- //
1401
- // The sync effect above writes the cookie through a server action, which is
1402
- // a round trip. Until it lands, getOrgFromCookie() still answers with the
1403
- // previous organisation and every request the page fires on mount carries
1404
- // it — so /O26000021/work-record asked about O26000033 and was correctly
1405
- // told there was nothing there. An empty table is the mild version: the
1406
- // create form posts to the same header, so a record could be filed against
1407
- // a company the user was not looking at.
1408
- //
1409
- // Only while the two genuinely disagree. A code naming no organisation of
1410
- // the caller's is left to the app to refuse, and a page with no code in its
1411
- // path is unaffected.
1412
- const orgContextIsStale = !!orgFromCode &&
1413
- organizationId !== null &&
1414
- organizationId !== undefined &&
1415
- String(organizationId) !== String(orgFromCode.id);
1416
- // ≤1024px: sidebar renders as a modal overlay (backdrop dims content). >1024px:
1417
- // sidebar is docked and the content gets a left margin to clear it.
1418
- const [isSidebarModalLayout, setIsSidebarModalLayout] = React.useState(false);
1419
- useEffect(() => {
1420
- const mq = window.matchMedia("(max-width: 1024px)");
1421
- const sync = () => setIsSidebarModalLayout(mq.matches);
1422
- sync();
1423
- mq.addEventListener("change", sync);
1424
- return () => mq.removeEventListener("change", sync);
1425
- }, []);
1426
- // Wait for session to load (initial load only). When refetching/updating we
1427
- // already have a session — don't flash the full-screen loader.
1428
- if (status === "loading" && !session) {
1429
- return jsx(Fragment$1, { children: loadingComponent });
1430
2134
  }
1431
- // Session loaded but no accessToken AND we've never seen one → real auth
1432
- // failure (token refresh gave nothing back on cold start), bounce through
1433
- // signin. If we HAVE seen one before, the drop is almost certainly the
1434
- // in-flight periodic refresh (SessionRefreshTrigger). Don't redirect on
1435
- // that transient — the JWT callback will settle in a moment and API
1436
- // calls will keep working with the still-valid cookie.
1437
- if (status === "authenticated" &&
1438
- !extendedSession?.accessToken &&
1439
- !hasSeenAccessTokenRef.current) {
1440
- if (typeof window !== "undefined") {
1441
- const url = new URL(signInUrl, window.location.origin);
1442
- url.searchParams.set("error", "NoAccessToken");
1443
- url.searchParams.set("callbackUrl", window.location.pathname);
1444
- window.location.href = url.toString();
2135
+ return out;
2136
+ }
2137
+ /** True while what is dragged over the dialog includes files. */
2138
+ function dragHasFiles(dt) {
2139
+ if (!dt?.types)
2140
+ return false;
2141
+ for (let i = 0; i < dt.types.length; i++)
2142
+ if (dt.types[i] === "Files")
2143
+ return true;
2144
+ return false;
2145
+ }
2146
+ /** The files a drop carries. */
2147
+ function filesFromDrop(dt) {
2148
+ const out = [];
2149
+ if (!dt?.files)
2150
+ return out;
2151
+ for (let i = 0; i < dt.files.length; i++)
2152
+ out.push(dt.files[i]);
2153
+ return out;
2154
+ }
2155
+ let seq = 0;
2156
+ /**
2157
+ * The images being attached to one message. Subscribe to redraw; every
2158
+ * change replaces items and rejections with new arrays.
2159
+ */
2160
+ class HelpAttachments {
2161
+ constructor(uploader, opts = {}) {
2162
+ Object.defineProperty(this, "list", {
2163
+ enumerable: true,
2164
+ configurable: true,
2165
+ writable: true,
2166
+ value: []
2167
+ });
2168
+ Object.defineProperty(this, "refused", {
2169
+ enumerable: true,
2170
+ configurable: true,
2171
+ writable: true,
2172
+ value: []
2173
+ });
2174
+ Object.defineProperty(this, "listeners", {
2175
+ enumerable: true,
2176
+ configurable: true,
2177
+ writable: true,
2178
+ value: new Set()
2179
+ });
2180
+ Object.defineProperty(this, "running", {
2181
+ enumerable: true,
2182
+ configurable: true,
2183
+ writable: true,
2184
+ value: new Map()
2185
+ });
2186
+ Object.defineProperty(this, "uploader", {
2187
+ enumerable: true,
2188
+ configurable: true,
2189
+ writable: true,
2190
+ value: void 0
2191
+ });
2192
+ Object.defineProperty(this, "opts", {
2193
+ enumerable: true,
2194
+ configurable: true,
2195
+ writable: true,
2196
+ value: void 0
2197
+ });
2198
+ this.uploader = uploader;
2199
+ this.opts = opts;
2200
+ }
2201
+ get items() {
2202
+ return this.list;
2203
+ }
2204
+ /** The files the last add, paste or drop refused, each with its reason. */
2205
+ get rejections() {
2206
+ return this.refused;
2207
+ }
2208
+ get max() {
2209
+ return this.opts.max ?? HELP_IMAGE_MAX_COUNT;
2210
+ }
2211
+ /** True while any image is still uploading. */
2212
+ get uploading() {
2213
+ return this.list.some(i => i.status === "uploading");
2214
+ }
2215
+ /** How many more can be added. */
2216
+ get room() {
2217
+ return Math.max(0, this.max - this.list.length);
2218
+ }
2219
+ subscribe(fn) {
2220
+ this.listeners.add(fn);
2221
+ return () => {
2222
+ this.listeners.delete(fn);
2223
+ };
2224
+ }
2225
+ emit() {
2226
+ this.listeners.forEach(l => l());
2227
+ }
2228
+ patch(key, change) {
2229
+ let changed = false;
2230
+ this.list = this.list.map(i => {
2231
+ if (i.key !== key)
2232
+ return i;
2233
+ changed = true;
2234
+ return { ...i, ...change };
2235
+ });
2236
+ if (changed)
2237
+ this.emit();
2238
+ }
2239
+ /**
2240
+ * Adds files: each is checked, the first ones that fit are uploaded at
2241
+ * once, and every one refused is named with its reason.
2242
+ */
2243
+ add(files) {
2244
+ const refused = [];
2245
+ const added = [];
2246
+ let room = this.room;
2247
+ for (const file of files) {
2248
+ const why = checkHelpImage(file);
2249
+ if (why) {
2250
+ refused.push({ name: file.name || "image", message: why });
2251
+ continue;
2252
+ }
2253
+ if (room <= 0) {
2254
+ refused.push({ name: file.name || "image", message: HELP_IMAGE_ERRORS.tooMany });
2255
+ continue;
2256
+ }
2257
+ room--;
2258
+ seq += 1;
2259
+ const item = {
2260
+ key: `img-${Date.now().toString(36)}-${seq}`,
2261
+ name: file.name || "image",
2262
+ size: file.size,
2263
+ preview: this.opts.preview ? this.opts.preview(file) : "",
2264
+ status: "uploading",
2265
+ progress: 0,
2266
+ id: null,
2267
+ error: null,
2268
+ };
2269
+ added.push({ item, file });
1445
2270
  }
1446
- return jsx(Fragment$1, { children: loadingComponent });
2271
+ this.refused = refused;
2272
+ this.list = [...this.list, ...added.map(a => a.item)];
2273
+ this.emit();
2274
+ for (const { item, file } of added)
2275
+ this.start(item.key, file);
2276
+ }
2277
+ start(key, file) {
2278
+ const abort = new AbortController();
2279
+ const done = this.uploader
2280
+ .upload(file, {
2281
+ signal: abort.signal,
2282
+ onProgress: p => {
2283
+ if (!abort.signal.aborted)
2284
+ this.patch(key, { progress: Math.max(0, Math.min(1, p)) });
2285
+ },
2286
+ onId: id => {
2287
+ if (abort.signal.aborted) {
2288
+ this.uploader.discard?.(id);
2289
+ return;
2290
+ }
2291
+ this.patch(key, { id });
2292
+ },
2293
+ })
2294
+ .then(res => {
2295
+ if (abort.signal.aborted) {
2296
+ this.uploader.discard?.(res.id);
2297
+ return;
2298
+ }
2299
+ this.patch(key, { status: "ready", progress: 1, id: res.id, error: null });
2300
+ }, (err) => {
2301
+ if (abort.signal.aborted)
2302
+ return;
2303
+ const message = err instanceof Error && err.message ? err.message : HELP_IMAGE_ERRORS.failed;
2304
+ this.patch(key, { status: "failed", error: message });
2305
+ })
2306
+ .finally(() => {
2307
+ this.running.delete(key);
2308
+ });
2309
+ this.running.set(key, { abort, done });
1447
2310
  }
1448
- // Only blank the page when we've never seen a token — otherwise the
1449
- // periodic session refresh would visibly flash the loader every 4 min.
1450
- if (!extendedSession?.accessToken && !hasSeenAccessTokenRef.current) {
1451
- return jsx(Fragment$1, { children: loadingComponent });
2311
+ /** Takes an image off: stops its upload and forgets it on the server. */
2312
+ remove(key) {
2313
+ const item = this.list.find(i => i.key === key);
2314
+ if (!item)
2315
+ return;
2316
+ const run = this.running.get(key);
2317
+ if (run)
2318
+ run.abort.abort();
2319
+ if (item.id)
2320
+ this.uploader.discard?.(item.id);
2321
+ if (item.preview)
2322
+ this.opts.revoke?.(item.preview);
2323
+ this.list = this.list.filter(i => i.key !== key);
2324
+ this.emit();
2325
+ }
2326
+ /** Marks the image platform-api refused on sending (it names it by id). */
2327
+ refuse(id, message) {
2328
+ const item = this.list.find(i => i.id === id);
2329
+ if (item)
2330
+ this.patch(item.key, { status: "failed", error: message });
2331
+ }
2332
+ dismissRejections() {
2333
+ if (this.refused.length === 0)
2334
+ return;
2335
+ this.refused = [];
2336
+ this.emit();
2337
+ }
2338
+ /**
2339
+ * Waits until nothing is uploading, then says what can be sent: the ids
2340
+ * of the ready images in the order they are shown, and the ones that
2341
+ * failed. ส่ง calls this, so a send never leaves without its images.
2342
+ */
2343
+ async settled() {
2344
+ while (this.running.size > 0) {
2345
+ await Promise.all(Array.from(this.running.values(), r => r.done));
2346
+ }
2347
+ return {
2348
+ ids: this.list.filter(i => i.status === "ready" && i.id).map(i => i.id),
2349
+ failed: this.list.filter(i => i.status === "failed"),
2350
+ };
1452
2351
  }
1453
- if (!code) {
1454
- router.push(selectOrganizationUrl);
1455
- return jsx(Fragment$1, { children: loadingComponent });
2352
+ /**
2353
+ * Empties the list. sent: the images went with a message — nothing to
2354
+ * forget on the server. Otherwise every upload made is discarded.
2355
+ */
2356
+ clear(sent = false) {
2357
+ for (const [, run] of this.running)
2358
+ run.abort.abort();
2359
+ for (const item of this.list) {
2360
+ if (!sent && item.id)
2361
+ this.uploader.discard?.(item.id);
2362
+ if (item.preview)
2363
+ this.opts.revoke?.(item.preview);
2364
+ }
2365
+ this.list = [];
2366
+ this.refused = [];
2367
+ this.emit();
1456
2368
  }
1457
- // When the sidebar is docked-open it consumes 21.5rem on the left; otherwise
1458
- // the content takes the full width and we add a left gutter inside.
1459
- const workspace = chrome === "workspace";
1460
- const contentMargin = open && !isSidebarModalLayout
1461
- ? workspace
1462
- ? "ml-[244px]"
1463
- : "ml-[21.5rem]"
1464
- : "";
1465
- const needsLeftGutter = workspace || !(open && !isSidebarModalLayout);
1466
- const wrap = permissionProvider ?? ((c) => c);
1467
- return (jsxs("div", { className: "flex min-h-screen w-full bg-background", children: [open && (jsx("div", { className: "fixed left-0 top-0 z-50 h-screen", children: sidebar })), open && isSidebarModalLayout && (jsx("button", { type: "button", "aria-label": "\u0E1B\u0E34\u0E14\u0E40\u0E21\u0E19\u0E39", className: "fixed inset-0 z-40 bg-black/50", onClick: () => setOpen(false) })), jsx("div", { className: cx("relative flex min-w-0 flex-1 flex-col transition-all", contentMargin), children: jsxs("main", { className: cx("flex flex-1 flex-col min-h-screen", workspace ? "gap-0" : "gap-4"), children: [workspace ? (jsxs("div", { className: cx("sticky top-0 z-30 shrink-0 w-full", workspaceHeader === "light" &&
1468
- "border-b border-border bg-card/85 backdrop-blur-sm"), style: workspaceHeader === "light"
1469
- ? WORKSPACE_LIGHT_HEADER_VARS
1470
- : WORKSPACE_HEADER_VARS, children: [workspaceHeader === "light" ? null : (jsx(HeaderBackground, { className: "rounded-none" })), jsxs("header", { className: cx("relative z-10 flex w-full items-center gap-3 text-[var(--header-fg)]", workspaceHeader === "light"
1471
- ? "min-h-[66px] px-3 py-2 sm:min-h-[72px] sm:px-[22px] lg:min-h-[82px] lg:px-8"
1472
- : "min-h-[72px] px-[18px] py-3 sm:px-6 lg:min-h-[88px] lg:px-10"), children: [isSidebarModalLayout ? (
1473
- // As in the design: the mark, then a menu button, and the
1474
- // organisation on the right — no trail, no title, so the
1475
- // organisation's name has the room it needs on a phone.
1476
- 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: breadcrumb }), jsx("div", { id: "header-title", className: "min-w-0 max-sm:hidden" })] }), headerEnd ? (jsx("div", { className: "flex shrink-0 items-center gap-3 sm:gap-5", children: headerEnd })) : 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: breadcrumb }), headerEnd ? (jsx("div", { className: "flex shrink-0 items-center gap-3", children: headerEnd })) : 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
1477
- ? "relative z-10 px-[18px] pt-[26px] pb-4 sm:px-6 lg:px-10 lg:pt-[38px]"
1478
- : cx("relative z-10 pr-6", needsLeftGutter && "pl-6"), children: orgContextIsStale ? loadingComponent : wrap(children) }, `org-${contentOrgKey}`) })] }) })] }));
1479
- }
1480
- /** Local tiny classnames helper — avoids pulling clsx/tailwind-merge into
1481
- * the shell just for the layout file. Falsy values are skipped. */
1482
- function cx(...parts) {
1483
- return parts.filter(Boolean).join(" ");
1484
2369
  }
1485
2370
 
1486
2371
  /**
1487
- * The product mark at the top of the workspace sidebar: the app icon, the
1488
- * name, and a spaced caption beneath it.
2372
+ * The help channel lives on platform-api (POST /support/messages). The shared
2373
+ * axios instance carries the user's token and the organisation header, and
2374
+ * refreshes a stale token.
1489
2375
  */
1490
- function WorkspaceBrand({ name, caption, mark, href, compact = false, className, }) {
1491
- const body = (jsxs(Fragment$1, { children: [jsx("span", { className: cn("grid shrink-0 place-items-center overflow-hidden rounded-[14px] [&>img]:size-full [&>img]:object-cover", compact ? "size-9 rounded-[11px]" : "size-11"), children: mark }), compact ? (jsx("span", { className: "sr-only", children: name })) : (jsxs("span", { className: "min-w-0", children: [jsx("span", { className: "block truncate text-[25px] leading-tight font-extrabold tracking-[-0.05em]", children: name }), caption ? (jsx("small", { className: "-mt-0.5 block truncate text-[9px] font-semibold tracking-[0.29em] text-muted-foreground", children: caption })) : null] }))] }));
1492
- const cls = cn("flex items-center gap-[11px] rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", !compact && "px-4", className);
1493
- return href ? (jsx(Link, { href: href, className: cls, "aria-label": compact ? name : undefined, children: body })) : (jsx("div", { className: cls, children: body }));
2376
+ function helpApiBase(app) {
2377
+ return platformApiBase(app);
2378
+ }
2379
+ /** The thread of m, oldest first, from whichever shape platform-api sent. */
2380
+ function helpThread(m) {
2381
+ if (m.thread)
2382
+ return m.thread;
2383
+ return m.replies.map((r, i) => ({ id: `${m.id}-${i}`, author: "staff", body: r.body, created_at: r.created_at, images: [] }));
2384
+ }
2385
+ /** A failure the dialog shows as is; attachmentId names the image it is about. */
2386
+ class HelpSendError extends Error {
2387
+ constructor(message, status, attachmentId) {
2388
+ super(message);
2389
+ Object.defineProperty(this, "status", {
2390
+ enumerable: true,
2391
+ configurable: true,
2392
+ writable: true,
2393
+ value: void 0
2394
+ });
2395
+ Object.defineProperty(this, "attachmentId", {
2396
+ enumerable: true,
2397
+ configurable: true,
2398
+ writable: true,
2399
+ value: void 0
2400
+ });
2401
+ this.name = "HelpSendError";
2402
+ this.status = status;
2403
+ this.attachmentId = attachmentId;
2404
+ }
1494
2405
  }
1495
-
1496
- function isExternal(href) {
1497
- return /^https?:\/\//i.test(href);
2406
+ function attachmentIdOf(err) {
2407
+ const data = err?.response?.data?.data;
2408
+ return typeof data?.attachment_id === "string" ? data.attachment_id : undefined;
1498
2409
  }
1499
- /**
1500
- * The card at the foot of the workspace sidebar that points someone who
1501
- * does not know where to start at the place that will tell them.
1502
- */
1503
- function SidebarHelpCard({ title, description, actionLabel, href, icon, className, }) {
1504
- const external = isExternal(href);
1505
- const action = (jsxs(Fragment$1, { children: [actionLabel, jsx(ArrowRight, { className: "size-[15px]" })] }));
1506
- const actionClass = "mt-3 flex w-full items-center justify-between text-xs font-semibold text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded";
1507
- return (jsxs("div", { className: cn("mx-1.5 mb-5 rounded-[13px] border border-primary/10 bg-gradient-to-br from-primary/[0.06] to-primary/[0.02] px-3.5 py-4", className), children: [jsx("span", { className: "mb-[7px] block text-primary/70", children: icon ?? jsx(Compass, { className: "size-6", strokeWidth: 1.6 }) }), jsx("strong", { className: "block text-xs font-semibold", children: title }), description ? (jsx("p", { className: "mt-[7px] text-xs leading-[1.7] text-muted-foreground", children: description })) : null, external ? (jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: actionClass, children: action })) : (jsx(Link, { href: href, className: actionClass, children: action }))] }));
2410
+ function friendly(err, fallback) {
2411
+ const e = toApiError(err);
2412
+ const attachmentId = attachmentIdOf(err);
2413
+ if (e.status === 429) {
2414
+ return new HelpSendError(e.message && e.message !== "Request failed with status code 429" ? e.message : "ส่งบ่อยเกินไป กรุณาลองใหม่ภายหลัง", 429);
2415
+ }
2416
+ if (e.status && e.status >= 400 && e.status < 500 && e.message && e.status !== 401 && (e.status !== 404 || attachmentId)) {
2417
+ return new HelpSendError(e.message, e.status, attachmentId);
2418
+ }
2419
+ if (e.status === 503 && e.message) {
2420
+ return new HelpSendError(e.message, e.status);
2421
+ }
2422
+ return new HelpSendError(fallback, e.status, attachmentId);
1508
2423
  }
1509
- /** A quiet row under the help card — the manual, the support chat. */
1510
- function SidebarHelpLink({ label, href, icon, className }) {
1511
- const external = isExternal(href);
1512
- const cls = cn("flex w-full items-center gap-3 rounded-[10px] px-3.5 py-[11px] text-xs font-medium text-sidebar-foreground/70 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", className);
1513
- const body = (jsxs(Fragment$1, { children: [icon ? jsx("span", { className: "shrink-0 [&>svg]:size-[18px]", children: icon }) : null, jsx("span", { className: "flex-1 truncate", children: label }), external ? jsx(ArrowUpRight, { className: "size-4 shrink-0" }) : null] }));
1514
- return external ? (jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: cls, children: body })) : (jsx(Link, { href: href, className: cls, children: body }));
2424
+ async function sendHelpMessage(input) {
2425
+ try {
2426
+ const res = await instance.post(`${helpApiBase(input.app)}/support/messages`, {
2427
+ kind: input.kind,
2428
+ message: input.message,
2429
+ app: input.app === "other" ? "" : input.app,
2430
+ context: input.context,
2431
+ attachment_ids: input.attachmentIds ?? [],
2432
+ });
2433
+ return unwrapApiResponse(res.data);
2434
+ }
2435
+ catch (err) {
2436
+ throw friendly(err, "ส่งไม่สำเร็จ");
2437
+ }
1515
2438
  }
1516
-
1517
- /**
1518
- * Central "no access" screen shared by every policy check (route-level
1519
- * PermissionProvider and page-level PermissionGateShell). One look everywhere:
1520
- * an illustration, a 403 headline, the page-specific reason, and recovery
1521
- * actions.
1522
- */
1523
- function AccessDenied({ title = "ขออภัย, คุณไม่มีสิทธิ์เข้าถึงหน้านี้ (403)", message = "คุณไม่มีสิทธิ์เข้าถึงหน้านี้ ขออภัยในความไม่สะดวก", homeHref, homeLabel = "กลับไปหน้าหลัก", supportHref, supportLabel = "ติดต่อฝ่ายสนับสนุน", fullScreen = true, className, }) {
1524
- // "/" is not the home page inside an app — it bounces to organization
1525
- // selection, so the button read "กลับไปหน้าหลัก" and dropped the user into a
1526
- // picker for the org they were already in. Send them to that org's home.
1527
- const params = useParams();
1528
- const code = typeof params?.code === "string" ? params.code : "";
1529
- const homeTarget = homeHref ?? (code ? `/${code}` : "/");
1530
- const go = (href) => {
1531
- if (typeof window !== "undefined")
1532
- window.location.href = href;
1533
- };
1534
- const wrapperClass = [
1535
- "flex min-w-0 flex-1 items-center justify-center p-4",
1536
- fullScreen ? "min-h-[70vh]" : "",
1537
- className ?? "",
1538
- ]
1539
- .filter(Boolean)
1540
- .join(" ");
1541
- return (jsx("div", { className: wrapperClass, children: jsx("div", { className: "relative w-full max-w-3xl overflow-hidden rounded-2xl border border-border/60 bg-card/60 p-8 shadow-sm backdrop-blur sm:p-10", children: jsxs("div", { className: "flex flex-col items-center gap-8 text-center sm:flex-row sm:text-left", children: [jsxs("div", { className: "relative shrink-0", children: [jsx("div", { className: "absolute inset-0 rounded-full bg-destructive/20 blur-2xl" }), jsx("div", { className: "relative flex h-28 w-28 items-center justify-center rounded-3xl border border-border/60 bg-gradient-to-br from-muted/40 to-background shadow-inner", children: jsx("div", { className: "flex h-16 w-16 items-center justify-center rounded-full border border-destructive/40 bg-destructive/10", children: jsx(Ban, { className: "h-8 w-8 text-destructive", strokeWidth: 2.5 }) }) })] }), jsxs("div", { className: "min-w-0 flex-1", children: [jsx("h1", { className: "text-xl font-bold text-foreground sm:text-2xl", children: title }), message ? (jsx("p", { className: "mt-3 whitespace-pre-line text-sm leading-relaxed text-muted-foreground sm:text-base", children: message })) : null, jsxs("div", { className: "mt-6 flex flex-col gap-3 sm:flex-row", children: [jsxs(Button, { type: "button", onClick: () => go(homeTarget), className: "w-full sm:w-auto", children: [jsx(Home, { className: "mr-2 h-4 w-4" }), homeLabel] }), supportHref ? (jsxs(Button, { type: "button", variant: "outline", onClick: () => go(supportHref), className: "w-full sm:w-auto", children: [jsx(Headset, { className: "mr-2 h-4 w-4" }), supportLabel] })) : null] })] })] }) }) }));
2439
+ /** One of the caller's messages by id or reference number ("H1004"). */
2440
+ async function getMyHelpMessage(app, key) {
2441
+ try {
2442
+ const res = await instance.get(`${helpApiBase(app)}/support/messages/${encodeURIComponent(key)}`);
2443
+ return unwrapApiResponse(res.data);
2444
+ }
2445
+ catch (err) {
2446
+ if (toApiError(err).status === 404)
2447
+ throw new HelpSendError("ไม่พบข้อความ", 404);
2448
+ throw friendly(err, "โหลดข้อมูลไม่สำเร็จ");
2449
+ }
1542
2450
  }
1543
-
1544
- const EMPLOYEE_RECORD_REQUIRED = "EMPLOYEE_RECORD_REQUIRED";
1545
- const EMPLOYEE_RECORD_REQUIRED_EVENT = "erp:employee-record-required";
1546
- const EMPLOYEE_RECORD_OK_EVENT = "erp:employee-record-ok";
1547
- /**
1548
- * Shown when the API refuses every request because the signed-in account has
1549
- * no employee record in this organisation.
1550
- *
1551
- * A gate rather than a banner. Leave, attendance, approvals and payslips all
1552
- * identify a person by that record, so once the server started enforcing it
1553
- * every call fails — and without something that says so, the app becomes a
1554
- * screen of error toasts with no explanation and no way forward.
1555
- */
1556
- function EmployeeRequiredGate({ platformBaseUrl, }) {
1557
- const [blocked, setBlocked] = useState(false);
1558
- const params = useParams();
1559
- const code = params?.code ?? "";
1560
- useEffect(() => {
1561
- const onBlocked = () => setBlocked(true);
1562
- const onOk = () => setBlocked(false);
1563
- window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
1564
- window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
1565
- return () => {
1566
- window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
1567
- window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
2451
+ /** The author writes again on their own message. */
2452
+ async function sendHelpFollowUp(input) {
2453
+ try {
2454
+ const res = await instance.post(`${helpApiBase(input.app)}/support/messages/${encodeURIComponent(input.key)}/replies`, { message: input.message, attachment_ids: input.attachmentIds ?? [] });
2455
+ return unwrapApiResponse(res.data);
2456
+ }
2457
+ catch (err) {
2458
+ throw friendly(err, "ส่งไม่สำเร็จ");
2459
+ }
2460
+ }
2461
+ /** PUTs the file to the presigned URL, reporting progress. No credentials go with it. */
2462
+ function putFile(ticket, file, onProgress, signal) {
2463
+ return new Promise((resolve, reject) => {
2464
+ const xhr = new XMLHttpRequest();
2465
+ xhr.open(ticket.method || "PUT", ticket.upload_url);
2466
+ for (const [k, v] of Object.entries(ticket.headers ?? {}))
2467
+ xhr.setRequestHeader(k, v);
2468
+ xhr.upload.onprogress = e => {
2469
+ if (e.lengthComputable && e.total > 0)
2470
+ onProgress(e.loaded / e.total);
1568
2471
  };
1569
- }, []);
1570
- if (!blocked)
1571
- return null;
1572
- const base = platformBaseUrl?.replace(/\/$/, "") ?? "";
1573
- const createHref = code ? `${base}/${code}/employee/create` : `${base}/`;
1574
- 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" })] }) }));
2472
+ xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new HelpSendError("อัปโหลดไม่สำเร็จ", xhr.status)));
2473
+ xhr.onerror = () => reject(new HelpSendError("อัปโหลดไม่สำเร็จ"));
2474
+ xhr.onabort = () => reject(new HelpSendError("ยกเลิกแล้ว"));
2475
+ if (signal.aborted) {
2476
+ reject(new HelpSendError("ยกเลิกแล้ว"));
2477
+ return;
2478
+ }
2479
+ signal.addEventListener("abort", () => xhr.abort(), { once: true });
2480
+ xhr.send(file);
2481
+ });
1575
2482
  }
1576
-
1577
- const shellClassName = "flex min-w-0 flex-1 flex-col gap-6 overflow-x-hidden";
1578
2483
  /**
1579
- * Shared layout for “กำลังตรวจสอบสิทธิ์” (skeleton) and “ไม่มีสิทธิ์” (message).
1580
- * Renders `children` only when policy is loaded and access is granted.
2484
+ * The uploader the dialog uses: an upload URL from platform-api, the bytes
2485
+ * straight to the bucket, then platform-api reads them to say whether they
2486
+ * are an image it will take.
1581
2487
  */
1582
- function PermissionGateShell({ policyLoading, hasPolicyAccess, deniedMessage, children, skeletonCount = 6, skeletonGridClassName = "grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3", skeletonVariant = "kpi", }) {
1583
- if (policyLoading) {
1584
- return (jsx("div", { className: shellClassName, children: jsx("div", { className: skeletonGridClassName, children: Array.from({ length: skeletonCount }).map((_, i) => (jsx(Card, { children: skeletonVariant === "kpi" ? (jsxs(Fragment$1, { children: [jsxs(CardHeader, { className: "flex flex-row items-center justify-between pb-2", children: [jsx(Skeleton, { className: "h-4 w-24" }), jsx(Skeleton, { className: "h-4 w-4 rounded" })] }), jsxs(CardContent, { children: [jsx(Skeleton, { className: "h-8 w-32 mb-2" }), jsx(Skeleton, { className: "h-3 w-20" })] })] })) : (jsxs(Fragment$1, { children: [jsx(CardHeader, { className: "pb-2", children: jsx(Skeleton, { className: "h-4 w-24" }) }), jsx(CardContent, { children: jsx(Skeleton, { className: "h-8 w-16" }) })] })) }, i))) }) }));
2488
+ function helpUploader(app) {
2489
+ const base = () => helpApiBase(app);
2490
+ return {
2491
+ async upload(file, hooks) {
2492
+ let ticket;
2493
+ try {
2494
+ const res = await instance.post(`${base()}/support/attachments`, { file_name: file.name, content_type: helpImageType(file.type), size: file.size }, { signal: hooks.signal });
2495
+ ticket = unwrapApiResponse(res.data);
2496
+ }
2497
+ catch (err) {
2498
+ throw friendly(err, "อัปโหลดไม่สำเร็จ");
2499
+ }
2500
+ hooks.onId(ticket.id);
2501
+ hooks.onProgress(0.02);
2502
+ await putFile(ticket, file, p => hooks.onProgress(0.02 + p * 0.93), hooks.signal);
2503
+ try {
2504
+ await instance.post(`${base()}/support/attachments/${ticket.id}/check`, null, { signal: hooks.signal });
2505
+ }
2506
+ catch (err) {
2507
+ throw friendly(err, "อัปโหลดไม่สำเร็จ");
2508
+ }
2509
+ return { id: ticket.id };
2510
+ },
2511
+ discard(id) {
2512
+ void instance.delete(`${base()}/support/attachments/${encodeURIComponent(id)}`).catch(() => undefined);
2513
+ },
2514
+ };
2515
+ }
2516
+ async function listMyHelpMessages(app) {
2517
+ try {
2518
+ const res = await instance.get(`${helpApiBase(app)}/support/messages`, {
2519
+ params: { limit: 20 },
2520
+ });
2521
+ const data = unwrapApiResponse(res.data);
2522
+ return data?.messages ?? [];
1585
2523
  }
1586
- if (!hasPolicyAccess) {
1587
- return (jsx("div", { className: shellClassName, children: jsx(AccessDenied, { message: deniedMessage }) }));
2524
+ catch (err) {
2525
+ throw friendly(err, "โหลดข้อมูลไม่สำเร็จ");
1588
2526
  }
1589
- return jsx(Fragment$1, { children: children });
1590
2527
  }
1591
2528
 
1592
- const PermissionRulesContext = createContext(undefined);
2529
+ /** One message's images, uploading as they are added. */
2530
+ function useHelpAttachments(app) {
2531
+ const attach = React.useMemo(() => new HelpAttachments(helpUploader(app), {
2532
+ preview: f => typeof URL !== "undefined" && typeof URL.createObjectURL === "function" && f instanceof Blob
2533
+ ? URL.createObjectURL(f)
2534
+ : "",
2535
+ revoke: u => {
2536
+ if (u.startsWith("blob:"))
2537
+ URL.revokeObjectURL(u);
2538
+ },
2539
+ }), [app]);
2540
+ const snap = React.useRef({
2541
+ items: attach.items,
2542
+ rejections: attach.rejections,
2543
+ });
2544
+ const read = React.useCallback(() => {
2545
+ if (snap.current.items !== attach.items || snap.current.rejections !== attach.rejections) {
2546
+ snap.current = { items: attach.items, rejections: attach.rejections };
2547
+ }
2548
+ return snap.current;
2549
+ }, [attach]);
2550
+ const state = React.useSyncExternalStore(React.useCallback(l => attach.subscribe(l), [attach]), read, read);
2551
+ // Leaving the page: what was uploaded and not sent is forgotten.
2552
+ React.useEffect(() => () => attach.clear(), [attach]);
2553
+ return { attach, items: state.items, rejections: state.rejections };
2554
+ }
1593
2555
  /**
1594
- * Generic provider — the consumer app passes in `data` (live fetch) and
1595
- * `fallbackPolicies` (static JSON). All apps share the same mapping logic
1596
- * (build a flat map of route_key/policy_key → required child groups).
2556
+ * Paste and drop for a form that takes images: spread onto the form. A
2557
+ * pasted screenshot or a dropped file is added like a picked one.
1597
2558
  */
1598
- function PermissionRulesProvider({ children, data, isLoading = false, isError = false, fallbackPolicies = [], }) {
1599
- const rulesMap = useMemo(() => {
1600
- const m = {};
1601
- if (!data?.routes)
1602
- return m;
1603
- for (const row of data.routes) {
1604
- m[row.route_key] = row.required_child_groups ?? [];
1605
- }
1606
- return m;
1607
- }, [data]);
1608
- const policiesMap = useMemo(() => {
1609
- const m = {};
1610
- for (const row of fallbackPolicies) {
1611
- m[row.policy_key] = row.required_child_groups ?? [];
1612
- }
1613
- if (data?.policies?.length) {
1614
- for (const row of data.policies) {
1615
- m[row.policy_key] = row.required_child_groups ?? [];
1616
- }
1617
- }
1618
- return m;
1619
- }, [data, fallbackPolicies]);
1620
- const value = useMemo(() => ({
1621
- rulesMap,
1622
- policiesMap,
1623
- isLoading,
1624
- isError,
1625
- updatedAt: data?.updated_at ?? null,
1626
- }), [rulesMap, policiesMap, isLoading, isError, data?.updated_at]);
1627
- return (jsx(PermissionRulesContext.Provider, { value: value, children: children }));
2559
+ function useHelpImageDrop(attach, enabled) {
2560
+ const [over, setOver] = React.useState(false);
2561
+ const depth = React.useRef(0);
2562
+ const props = {
2563
+ onPaste: (e) => {
2564
+ if (!enabled)
2565
+ return;
2566
+ const files = filesFromPaste(e.clipboardData);
2567
+ if (files.length === 0)
2568
+ return;
2569
+ e.preventDefault();
2570
+ attach.add(files);
2571
+ },
2572
+ onDragEnter: (e) => {
2573
+ if (!enabled || !dragHasFiles(e.dataTransfer))
2574
+ return;
2575
+ e.preventDefault();
2576
+ depth.current += 1;
2577
+ setOver(true);
2578
+ },
2579
+ onDragOver: (e) => {
2580
+ if (!enabled || !dragHasFiles(e.dataTransfer))
2581
+ return;
2582
+ e.preventDefault();
2583
+ e.dataTransfer.dropEffect = "copy";
2584
+ },
2585
+ onDragLeave: (e) => {
2586
+ if (!enabled || !dragHasFiles(e.dataTransfer))
2587
+ return;
2588
+ depth.current = Math.max(0, depth.current - 1);
2589
+ if (depth.current === 0)
2590
+ setOver(false);
2591
+ },
2592
+ onDrop: (e) => {
2593
+ if (!enabled)
2594
+ return;
2595
+ depth.current = 0;
2596
+ setOver(false);
2597
+ const files = filesFromDrop(e.dataTransfer);
2598
+ if (files.length === 0)
2599
+ return;
2600
+ e.preventDefault();
2601
+ attach.add(files);
2602
+ },
2603
+ };
2604
+ return { over, props };
2605
+ }
2606
+ function kb(size) {
2607
+ if (size >= 1024 * 1024)
2608
+ return `${(size / (1024 * 1024)).toFixed(1)} MB`;
2609
+ return `${Math.max(1, Math.round(size / 1024))} KB`;
1628
2610
  }
1629
2611
  /**
1630
- * Read the permission rules. Outside the provider, report loading so
1631
- * fail-closed consumers (nav / gates) do not treat empty maps as "allow all".
2612
+ * แนบรูป: the button that opens the file picker (on a phone, the photo
2613
+ * library or the camera), the thumbnails with their progress and a remove
2614
+ * button each, and a line per file that was refused.
1632
2615
  */
1633
- function usePermissionRules() {
1634
- const ctx = useContext(PermissionRulesContext);
1635
- if (!ctx) {
1636
- return {
1637
- rulesMap: {},
1638
- policiesMap: {},
1639
- isLoading: true,
1640
- isError: false,
1641
- updatedAt: null,
1642
- };
2616
+ function HelpAttachField({ state, disabled, id }) {
2617
+ const { attach, items, rejections } = state;
2618
+ const input = React.useRef(null);
2619
+ const full = items.length >= attach.max;
2620
+ const problems = [
2621
+ ...items.filter(i => i.status === "failed").map(i => ({ key: i.key, name: i.name, message: i.error ?? "" })),
2622
+ ...rejections.map((r, n) => ({ key: `refused-${n}`, name: r.name, message: r.message })),
2623
+ ];
2624
+ return (jsxs("div", { className: "grid gap-2", children: [jsxs("div", { className: "flex flex-wrap items-start gap-2", children: [items.map(it => (jsx(AttachThumb, { item: it, onRemove: () => attach.remove(it.key), disabled: disabled }, it.key))), jsxs(Button, { type: "button", variant: "outline", size: "sm", disabled: disabled || full, onClick: () => {
2625
+ attach.dismissRejections();
2626
+ input.current?.click();
2627
+ }, "aria-controls": id, className: items.length > 0 ? "h-16 w-16 flex-col gap-1 p-1 text-[11px]" : "gap-1.5", children: [jsx(ImagePlus, { className: "h-4 w-4" }), "\u0E41\u0E19\u0E1A\u0E23\u0E39\u0E1B"] }), jsx("input", { ref: input, id: id, type: "file", accept: HELP_IMAGE_ACCEPT, multiple: true, tabIndex: -1, "aria-hidden": "true", className: "sr-only", onChange: e => {
2628
+ const files = e.currentTarget.files;
2629
+ if (files && files.length > 0)
2630
+ attach.add(Array.from(files));
2631
+ e.currentTarget.value = "";
2632
+ } })] }), problems.length > 0 ? (jsx("ul", { role: "alert", className: "grid gap-0.5 text-xs text-destructive", children: problems.map(p => (jsxs("li", { className: "break-words", children: [p.name, ": ", p.message] }, p.key))) })) : null] }));
2633
+ }
2634
+ function AttachThumb({ item, onRemove, disabled }) {
2635
+ const failed = item.status === "failed";
2636
+ return (jsxs("figure", { className: "relative m-0 w-16", children: [jsxs("div", { className: "relative h-16 w-16 overflow-hidden rounded-md border bg-muted " +
2637
+ (failed ? "border-destructive" : "border-border"), children: [item.preview ? (
2638
+ // eslint-disable-next-line @next/next/no-img-element
2639
+ jsx("img", { src: item.preview, alt: item.name, className: "h-full w-full object-cover" })) : null, item.status === "uploading" ? (jsx("div", { role: "progressbar", "aria-label": `กำลังอัปโหลด ${item.name}`, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(item.progress * 100), className: "absolute inset-x-1 bottom-1 h-1.5 overflow-hidden rounded-full bg-background/80", children: jsx("div", { className: "h-full bg-primary transition-[width]", style: { width: `${Math.round(item.progress * 100)}%` } }) })) : null] }), jsx("button", { type: "button", onClick: onRemove, disabled: disabled, "aria-label": `ลบรูป ${item.name}`, title: "\u0E25\u0E1A\u0E23\u0E39\u0E1B", className: "absolute -right-1.5 -top-1.5 grid size-5 place-items-center rounded-full border border-border bg-background text-muted-foreground shadow-sm hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50", children: jsx(X, { className: "h-3 w-3" }) }), jsx("figcaption", { className: "mt-0.5 truncate text-[10px] leading-tight text-muted-foreground", title: item.name, children: failed ? jsx("span", { className: "text-destructive", children: "\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08" }) : kb(item.size) })] }));
2640
+ }
2641
+ /** Images already sent: thumbnails that open the full image. */
2642
+ function HelpImageStrip({ images, size = "md" }) {
2643
+ if (!images || images.length === 0)
2644
+ return null;
2645
+ const box = size === "sm" ? "h-12 w-12" : "h-20 w-20";
2646
+ return (jsx("ul", { className: "mt-2 flex flex-wrap gap-2", children: images.map(img => (jsx("li", { children: img.url ? (jsx("a", { href: img.url, target: "_blank", rel: "noopener noreferrer", "aria-label": `เปิดรูป ${img.file_name || ""}`.trim(), className: `block ${box} overflow-hidden rounded-md border border-border bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`, children: jsx("img", { src: img.url, alt: img.file_name || "รูปที่แนบ", loading: "lazy", className: "h-full w-full object-cover" }) })) : (jsx("span", { className: `block ${box} rounded-md border border-border bg-muted`, "aria-label": img.file_name })) }, img.id))) }));
2647
+ }
2648
+
2649
+ /**
2650
+ * The ตอบกลับ link in a staff answer e-mail opens the app with ?help=H1004:
2651
+ * the shell's ช่วยเหลือ dialog then opens on that message. Any app page
2652
+ * with the shell's layout works; the e-mail uses Platform.
2653
+ *
2654
+ * Kept free of imports: the tests load it straight from source.
2655
+ */
2656
+ const HELP_LINK_PARAM = "help";
2657
+ const REF = /^H\d{1,12}$/;
2658
+ /** The message a page address asks the dialog to open, or null. */
2659
+ function helpRefFromSearch(search) {
2660
+ if (!search)
2661
+ return null;
2662
+ let params;
2663
+ try {
2664
+ params = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
1643
2665
  }
1644
- return ctx;
2666
+ catch {
2667
+ return null;
2668
+ }
2669
+ const raw = (params.get(HELP_LINK_PARAM) ?? "").trim().toUpperCase();
2670
+ return REF.test(raw) ? raw : null;
1645
2671
  }
1646
-
1647
2672
  /**
1648
- * Strip the org `[code]` prefix from a pathname so we can look it up in the
1649
- * permission rules map. `/O12345/setting/foo` → `/setting/foo`. Single-segment
1650
- * paths (e.g. `/select-organization`) keep their leading slash.
1651
- *
1652
- * Also normalizes the user-role subtab aliases — both `purchase-doc` and
1653
- * `sales-doc` are gated by the same `members` rule because the UI shows
1654
- * the same management screen with different filters.
2673
+ * The same address without ?help=, so a reload or a shared link does not
2674
+ * open the dialog again. Everything else in it is kept.
1655
2675
  */
1656
- function normalizePathnameForPermissionRules(pathname) {
1657
- const parts = pathname.split("/").filter(Boolean);
1658
- const path = parts.length <= 1 ? "/" : "/" + parts.slice(1).join("/");
1659
- return path.replace(/\/user-role\/(purchase-doc|sales-doc)$/, "/user-role/members");
2676
+ function withoutHelpParam(href) {
2677
+ let u;
2678
+ try {
2679
+ u = new URL(href);
2680
+ }
2681
+ catch {
2682
+ return href;
2683
+ }
2684
+ if (!u.searchParams.has(HELP_LINK_PARAM))
2685
+ return href;
2686
+ u.searchParams.delete(HELP_LINK_PARAM);
2687
+ return u.toString();
1660
2688
  }
1661
- function hasRule(rulesMap, routeKey) {
1662
- return Object.prototype.hasOwnProperty.call(rulesMap, routeKey);
2689
+
2690
+ const KINDS = [
2691
+ { value: "help", label: "ขอความช่วยเหลือ", placeholder: "ต้องการให้ช่วยเรื่องอะไร" },
2692
+ { value: "problem", label: "แจ้งปัญหา", placeholder: "เกิดอะไรขึ้น และกำลังทำอะไรอยู่" },
2693
+ { value: "feedback", label: "ข้อเสนอแนะ", placeholder: "อยากให้ปรับหรือเพิ่มอะไร" },
2694
+ ];
2695
+ const KIND_LABEL = Object.fromEntries(KINDS.map(k => [k.value, k.label]));
2696
+ const STATUS_LABEL = {
2697
+ new: "รอตอบ",
2698
+ answered: "ตอบแล้ว",
2699
+ closed: "ปิดแล้ว",
2700
+ };
2701
+ const STATUS_TONE = {
2702
+ new: "bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-200",
2703
+ answered: "bg-emerald-100 text-emerald-900 dark:bg-emerald-950 dark:text-emerald-200",
2704
+ closed: "bg-muted text-muted-foreground",
2705
+ };
2706
+ const MAX_MESSAGE = 4000;
2707
+ const LINK_BUTTON = "rounded text-sm text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
2708
+ function when(iso) {
2709
+ const d = new Date(iso);
2710
+ if (Number.isNaN(d.getTime()))
2711
+ return "";
2712
+ return d.toLocaleString("th-TH", {
2713
+ day: "numeric",
2714
+ month: "short",
2715
+ year: "numeric",
2716
+ hour: "2-digit",
2717
+ minute: "2-digit",
2718
+ hour12: false,
2719
+ });
2720
+ }
2721
+ function errorText(e, fallback) {
2722
+ return e instanceof Error && e.message ? e.message : fallback;
1663
2723
  }
1664
2724
  /**
1665
- * Resolve UI route permissions for a pathname.
1666
- *
1667
- * - Exact / `[param]` pattern match → matched
1668
- * - Parent-prefix inherit only when the parent rule has a **non-empty**
1669
- * role list (restrictive inherit). Explicitly public parents (`[]`) do
1670
- * not open all children.
1671
- * - No match → `{ matched: false }` (fail closed — never treat as public)
2725
+ * Sends a message with its images: waits for what is still uploading, then
2726
+ * sends; an image platform-api refuses is marked on its thumbnail.
1672
2727
  */
1673
- function resolveUiRoutePermission(pathname, rulesMap) {
1674
- const normalized = normalizePathnameForPermissionRules(pathname);
1675
- if (hasRule(rulesMap, normalized)) {
1676
- return { matched: true, roles: rulesMap[normalized] ?? [] };
1677
- }
1678
- const pathSegments = normalized.split("/").filter(Boolean);
1679
- for (const [pattern, roles] of Object.entries(rulesMap)) {
1680
- const patternSegments = pattern.split("/").filter(Boolean);
1681
- if (patternSegments.length !== pathSegments.length)
1682
- continue;
1683
- let matches = true;
1684
- for (let i = 0; i < patternSegments.length; i++) {
1685
- const patternSegment = patternSegments[i];
1686
- const pathSegment = pathSegments[i];
1687
- if (patternSegment.startsWith("[") && patternSegment.endsWith("]")) {
1688
- if (!pathSegment) {
1689
- matches = false;
1690
- break;
1691
- }
1692
- }
1693
- else if (patternSegment !== pathSegment) {
1694
- matches = false;
1695
- break;
1696
- }
1697
- }
1698
- if (matches) {
1699
- return { matched: true, roles: roles ?? [] };
1700
- }
2728
+ async function sendWithImages(state, send) {
2729
+ const { ids, failed } = await state.attach.settled();
2730
+ if (failed.length > 0)
2731
+ throw new HelpSendError("มีรูปที่อัปโหลดไม่สำเร็จ");
2732
+ try {
2733
+ const res = await send(ids);
2734
+ state.attach.clear(true);
2735
+ return res;
1701
2736
  }
1702
- // Parent-prefix: /leave/types/abc → /leave/types (non-empty roles only)
1703
- for (let len = pathSegments.length - 1; len >= 1; len--) {
1704
- const parent = "/" + pathSegments.slice(0, len).join("/");
1705
- if (hasRule(rulesMap, parent) && (rulesMap[parent]?.length ?? 0) > 0) {
1706
- return { matched: true, roles: rulesMap[parent] ?? [] };
1707
- }
2737
+ catch (err) {
2738
+ if (err instanceof HelpSendError && err.attachmentId)
2739
+ state.attach.refuse(err.attachmentId, err.message);
2740
+ throw err;
1708
2741
  }
1709
- return { matched: false, roles: [] };
1710
2742
  }
1711
2743
  /**
1712
- * Returns the required child-group segments for a page pathname.
1713
- *
1714
- * Prefer {@link resolveUiRoutePermission} when you need to distinguish
1715
- * "explicitly public (`[]`)" from "no rule (deny)". This helper returns
1716
- * `[]` for both cases and is kept for backward compatibility.
2744
+ * The ช่วยเหลือ dialog. AppLayoutShell mounts one; the top-bar button and
2745
+ * the user menu open it with openHelp(), and a page address with
2746
+ * ?help=H1004 (the ตอบกลับ button in a staff answer) opens it on that
2747
+ * message. It sends to platform-api, which puts the message in the back
2748
+ * office's queue on admin.antniti.com.
1717
2749
  */
1718
- function getRequiredChildGroups(pathname, rulesMap) {
1719
- return resolveUiRoutePermission(pathname, rulesMap).roles;
2750
+ function HelpDialogHost({ app, orgCode }) {
2751
+ const open = useHelpOpen();
2752
+ const { data: session } = useSession();
2753
+ const [view, setView] = React.useState("form");
2754
+ const [kind, setKind] = React.useState("help");
2755
+ const [message, setMessage] = React.useState("");
2756
+ const [sending, setSending] = React.useState(false);
2757
+ const [error, setError] = React.useState(null);
2758
+ const [sent, setSent] = React.useState(null);
2759
+ const [mine, setMine] = React.useState(null);
2760
+ const [mineError, setMineError] = React.useState(null);
2761
+ const [threadKey, setThreadKey] = React.useState(null);
2762
+ const [thread, setThread] = React.useState(null);
2763
+ const [threadError, setThreadError] = React.useState(null);
2764
+ const [followDraft, setFollowDraft] = React.useState("");
2765
+ const [following, setFollowing] = React.useState(false);
2766
+ const [followError, setFollowError] = React.useState(null);
2767
+ React.useEffect(() => registerHelpHost(), []);
2768
+ // The ตอบกลับ link: ?help=H1004 opens the dialog on that message. The
2769
+ // parameter comes off the address so a reload does not open it again.
2770
+ React.useEffect(() => {
2771
+ if (typeof window === "undefined")
2772
+ return;
2773
+ const ref = helpRefFromSearch(window.location.search);
2774
+ if (!ref)
2775
+ return;
2776
+ window.history.replaceState(null, "", withoutHelpParam(window.location.href));
2777
+ openHelpOn(ref);
2778
+ }, []);
2779
+ // Read when the dialog opens: the page and the window as they are now.
2780
+ // open is a dependency on purpose: the app is read again each time.
2781
+ const appId = React.useMemo(() => detectHelpApp(app), [app, open]);
2782
+ const context = React.useMemo(() => (open ? collectHelpContext(orgCode) : null), [open, orgCode]);
2783
+ const images = useHelpAttachments(appId);
2784
+ const followImages = useHelpAttachments(appId);
2785
+ const formDrop = useHelpImageDrop(images.attach, view === "form" && !sending);
2786
+ const followDrop = useHelpImageDrop(followImages.attach, view === "thread" && !following && !!thread);
2787
+ const openThread = React.useCallback((key) => {
2788
+ setView("thread");
2789
+ setThreadKey(key);
2790
+ setThread(null);
2791
+ setThreadError(null);
2792
+ setFollowError(null);
2793
+ getMyHelpMessage(appId, key)
2794
+ .then(setThread)
2795
+ .catch((e) => setThreadError(errorText(e, "โหลดข้อมูลไม่สำเร็จ")));
2796
+ }, [appId]);
2797
+ React.useEffect(() => {
2798
+ if (!open)
2799
+ return;
2800
+ setError(null);
2801
+ const key = pendingHelpRef();
2802
+ if (key)
2803
+ openThread(key);
2804
+ else
2805
+ setView("form");
2806
+ }, [open, openThread]);
2807
+ const loadMine = React.useCallback(() => {
2808
+ clearPendingHelpRef();
2809
+ setView("mine");
2810
+ setMine(null);
2811
+ setMineError(null);
2812
+ listMyHelpMessages(appId)
2813
+ .then(setMine)
2814
+ .catch((e) => setMineError(errorText(e, "โหลดข้อมูลไม่สำเร็จ")));
2815
+ }, [appId]);
2816
+ const trimmed = message.trim();
2817
+ const canSend = trimmed.length > 0 && !sending;
2818
+ const send = async (e) => {
2819
+ e?.preventDefault();
2820
+ if (!canSend || !context)
2821
+ return;
2822
+ setSending(true);
2823
+ setError(null);
2824
+ try {
2825
+ const res = await sendWithImages(images, ids => sendHelpMessage({ app: appId, kind, message: trimmed, context, attachmentIds: ids }));
2826
+ setSent(res);
2827
+ setMessage("");
2828
+ setKind("help");
2829
+ setView("sent");
2830
+ }
2831
+ catch (err) {
2832
+ setError(errorText(err, "ส่งไม่สำเร็จ"));
2833
+ }
2834
+ finally {
2835
+ setSending(false);
2836
+ }
2837
+ };
2838
+ const followTrimmed = followDraft.trim();
2839
+ const sendFollowUp = async (e) => {
2840
+ e?.preventDefault();
2841
+ if (!thread || !followTrimmed || following)
2842
+ return;
2843
+ setFollowing(true);
2844
+ setFollowError(null);
2845
+ try {
2846
+ await sendWithImages(followImages, ids => sendHelpFollowUp({ app: appId, key: thread.id, message: followTrimmed, attachmentIds: ids }));
2847
+ setFollowDraft("");
2848
+ setMine(null);
2849
+ setThread(await getMyHelpMessage(appId, thread.id));
2850
+ }
2851
+ catch (err) {
2852
+ setFollowError(errorText(err, "ส่งไม่สำเร็จ"));
2853
+ }
2854
+ finally {
2855
+ setFollowing(false);
2856
+ }
2857
+ };
2858
+ const email = session?.user?.email ?? null;
2859
+ const placeholder = KINDS.find(k => k.value === kind)?.placeholder;
2860
+ const dropRing = (over) => (over ? " rounded-lg ring-2 ring-primary ring-offset-4 ring-offset-background" : "");
2861
+ return (jsx(Dialog, { open: open, onOpenChange: o => (o ? openHelp() : closeHelp()), children: jsxs(DialogContent, { className: "max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-lg", children: [view === "form" ? (jsxs("form", { onSubmit: send, className: "grid gap-4" + dropRing(formDrop.over), ...formDrop.props, children: [jsx(DialogHeader, { children: jsx(DialogTitle, { children: "\u0E0A\u0E48\u0E27\u0E22\u0E40\u0E2B\u0E25\u0E37\u0E2D" }) }), jsxs("div", { className: "grid gap-2", children: [jsx(Label, { id: "erp-help-kind", children: "\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17" }), jsx("div", { role: "radiogroup", "aria-labelledby": "erp-help-kind", className: "flex gap-1 rounded-lg bg-muted p-1", children: KINDS.map(k => (jsx("button", { type: "button", role: "radio", "aria-checked": kind === k.value, onClick: () => setKind(k.value), className: "flex-auto whitespace-nowrap rounded-md px-2 py-2 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm " +
2862
+ (kind === k.value
2863
+ ? "bg-background text-foreground shadow-sm"
2864
+ : "text-muted-foreground hover:text-foreground"), children: k.label }, k.value))) })] }), jsxs("div", { className: "grid gap-2", children: [jsx(Label, { htmlFor: "erp-help-message", children: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21" }), jsx(Textarea, { id: "erp-help-message", rows: 6, maxLength: MAX_MESSAGE, required: true, value: message, placeholder: placeholder, onChange: e => setMessage(e.target.value), className: "min-h-[140px] resize-y" })] }), jsx(HelpAttachField, { state: images, disabled: sending, id: "erp-help-images" }), context ? (jsxs("p", { className: "break-words text-xs leading-relaxed text-muted-foreground", children: ["\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E41\u0E19\u0E1A: ", describeAttached(appId, context, email)] })) : null, error ? (jsx("p", { role: "alert", className: "text-sm text-destructive", children: error })) : null, jsxs(DialogFooter, { className: "flex-row items-center gap-2 sm:justify-between", children: [jsx("button", { type: "button", onClick: loadMine, className: "mr-auto " + LINK_BUTTON, children: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E17\u0E35\u0E48\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27" }), jsxs("div", { className: "flex gap-2", children: [jsx(Button, { type: "button", variant: "outline", onClick: closeHelp, children: "\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01" }), jsxs(Button, { type: "submit", disabled: !canSend, children: [sending ? jsx(Loader2, { className: "mr-1 h-4 w-4 animate-spin" }) : null, "\u0E2A\u0E48\u0E07"] })] })] })] })) : null, view === "sent" && sent ? (jsxs("div", { className: "grid gap-4", children: [jsxs("div", { className: "flex flex-col items-center gap-2 py-4 text-center", children: [jsx(CircleCheck, { className: "h-12 w-12 text-primary", strokeWidth: 1.6 }), jsx(DialogTitle, { className: "text-lg font-semibold", children: "\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27" }), jsxs("p", { className: "text-sm text-muted-foreground", children: ["\u0E40\u0E25\u0E02\u0E17\u0E35\u0E48\u0E2D\u0E49\u0E32\u0E07\u0E2D\u0E34\u0E07", " ", jsx("span", { className: "font-mono text-base font-semibold text-foreground", children: sent.ref })] })] }), jsxs(DialogFooter, { className: "flex-row items-center gap-2 sm:justify-between", children: [jsx("button", { type: "button", onClick: loadMine, className: "mr-auto " + LINK_BUTTON, children: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E17\u0E35\u0E48\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27" }), jsx(Button, { type: "button", onClick: closeHelp, children: "\u0E1B\u0E34\u0E14" })] })] })) : null, view === "mine" ? (jsxs("div", { className: "grid gap-4", children: [jsx(DialogHeader, { children: jsxs(DialogTitle, { className: "flex items-center gap-2", children: [jsx(BackButton, { onClick: () => setView("form") }), "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E17\u0E35\u0E48\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27"] }) }), mine === null && !mineError ? jsx(Loading, {}) : null, mineError ? (jsx("p", { role: "alert", className: "text-sm text-destructive", children: mineError })) : null, mine && mine.length === 0 ? (jsx("p", { className: "py-6 text-sm text-muted-foreground", children: "\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21" })) : null, mine && mine.length > 0 ? (jsx("ul", { className: "grid gap-3", children: mine.map(m => {
2865
+ const entries = helpThread(m);
2866
+ const last = entries[entries.length - 1];
2867
+ return (jsxs("li", { className: "rounded-lg border border-border", children: [jsxs("button", { type: "button", onClick: () => openThread(m.id), "aria-label": `เปิด ${m.ref}`, className: "block w-full rounded-lg p-3 text-left hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", children: [jsxs("span", { className: "flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground", children: [jsx("span", { className: "font-mono font-semibold text-foreground", children: m.ref }), jsx("span", { children: KIND_LABEL[m.kind] ?? m.kind }), jsx("span", { children: when(m.created_at) }), jsx("span", { className: `ml-auto rounded-full px-2 py-0.5 font-medium ${STATUS_TONE[m.status] ?? ""}`, children: STATUS_LABEL[m.status] ?? m.status }), jsx(ChevronRight, { className: "h-4 w-4", "aria-hidden": "true" })] }), jsx("span", { className: "mt-2 line-clamp-3 block whitespace-pre-wrap break-words text-sm", children: m.message }), last ? (jsxs("span", { className: "mt-2 line-clamp-2 block rounded-md bg-muted px-3 py-2 text-xs", children: [jsxs("span", { className: "text-muted-foreground", children: [last.author === "staff" ? "ทีม AntNiti" : "คุณ", " \u00B7 ", when(last.created_at)] }), jsx("span", { className: "mt-0.5 block whitespace-pre-wrap break-words text-sm", children: last.body })] })) : null] }), m.images && m.images.length > 0 ? (jsx("div", { className: "px-3 pb-3", children: jsx(HelpImageStrip, { images: m.images, size: "sm" }) })) : null] }, m.id));
2868
+ }) })) : null] })) : null, view === "thread" ? (jsxs("div", { className: "grid gap-4", children: [jsx(DialogHeader, { children: jsxs(DialogTitle, { className: "flex items-center gap-2", children: [jsx(BackButton, { onClick: loadMine }), jsx("span", { className: "font-mono", children: thread?.ref ?? threadKey }), thread ? (jsx("span", { className: `ml-auto mr-7 rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_TONE[thread.status] ?? ""}`, children: STATUS_LABEL[thread.status] ?? thread.status })) : null] }) }), thread === null && !threadError ? jsx(Loading, {}) : null, threadError ? (jsx("p", { role: "alert", className: "text-sm text-destructive", children: threadError })) : null, thread ? (jsxs(Fragment$1, { children: [jsxs("ol", { className: "grid gap-3", "aria-label": "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21", children: [jsx(ThreadBubble, { mine: true, label: `คุณ · ${KIND_LABEL[thread.kind] ?? thread.kind}`, at: thread.created_at, body: thread.message, images: thread.images }), helpThread(thread).map(e => (jsx(ThreadBubble, { mine: e.author === "customer", label: e.author === "staff" ? "ทีม AntNiti" : "คุณ", at: e.created_at, body: e.body, images: e.images }, e.id)))] }), jsxs("form", { onSubmit: sendFollowUp, className: "grid gap-3 border-t border-border pt-4" + dropRing(followDrop.over), ...followDrop.props, children: [jsxs("div", { className: "grid gap-2", children: [jsx(Label, { htmlFor: "erp-help-followup", children: "\u0E15\u0E2D\u0E1A\u0E01\u0E25\u0E31\u0E1A" }), jsx(Textarea, { id: "erp-help-followup", rows: 3, maxLength: MAX_MESSAGE, required: true, value: followDraft, onChange: e => setFollowDraft(e.target.value), className: "min-h-[88px] resize-y" })] }), jsx(HelpAttachField, { state: followImages, disabled: following, id: "erp-help-followup-images" }), followError ? (jsx("p", { role: "alert", className: "text-sm text-destructive", children: followError })) : null, jsx(DialogFooter, { className: "flex-row items-center justify-end gap-2", children: jsxs(Button, { type: "submit", disabled: !followTrimmed || following, children: [following ? jsx(Loader2, { className: "mr-1 h-4 w-4 animate-spin" }) : null, "\u0E2A\u0E48\u0E07"] }) })] })] })) : null] })) : null] }) }));
2869
+ }
2870
+ function BackButton({ onClick }) {
2871
+ return (jsx("button", { type: "button", "aria-label": "\u0E01\u0E25\u0E31\u0E1A", onClick: onClick, className: "-ml-1 grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", children: jsx(ArrowLeft, { className: "h-4 w-4" }) }));
2872
+ }
2873
+ function Loading() {
2874
+ return (jsxs("div", { className: "flex items-center gap-2 py-6 text-sm text-muted-foreground", children: [jsx(Loader2, { className: "h-4 w-4 animate-spin" }), "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14"] }));
2875
+ }
2876
+ /** One message in the thread: the author's own on the right, AntNiti's on the left. */
2877
+ function ThreadBubble({ mine, label, at, body, images, }) {
2878
+ return (jsx("li", { className: "flex " + (mine ? "justify-end pl-6" : "justify-start pr-6"), children: jsxs("div", { className: "min-w-0 max-w-full rounded-lg px-3 py-2 " +
2879
+ (mine ? "border border-primary/30 bg-primary/5" : "bg-muted"), children: [jsxs("p", { className: "text-xs text-muted-foreground", children: [label, " \u00B7 ", when(at)] }), jsx("p", { className: "mt-1 whitespace-pre-wrap break-words text-sm", children: body }), jsx(HelpImageStrip, { images: images })] }) }));
1720
2880
  }
1721
2881
 
1722
- function DeniedCard() {
1723
- return (jsx(AccessDenied, { message: "\u0E04\u0E38\u0E13\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E40\u0E02\u0E49\u0E32\u0E16\u0E36\u0E07\u0E2B\u0E19\u0E49\u0E32\u0E19\u0E35\u0E49 \u0E2B\u0E32\u0E01\u0E04\u0E34\u0E14\u0E27\u0E48\u0E32\u0E04\u0E27\u0E23\u0E40\u0E02\u0E49\u0E32\u0E16\u0E36\u0E07\u0E44\u0E14\u0E49 \u0E01\u0E23\u0E38\u0E13\u0E32\u0E15\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E1C\u0E39\u0E49\u0E14\u0E39\u0E41\u0E25\u0E23\u0E30\u0E1A\u0E1A\u0E02\u0E2D\u0E07\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" }));
1724
- }
1725
2882
  /**
1726
- * Permission gate for a page subtree. Looks up the current pathname in the
1727
- * permission rules map (live rules from `PermissionRulesProvider`, layered
1728
- * over the optional `fallbackRulesMap`), passes the resolved required roles
1729
- * into the host's `usePermission` probe, and renders one of:
2883
+ * Top-level app chrome: sticky header, sidebar slot, content gutter and the
2884
+ * session/org-context plumbing that both Accounting and HR need. Apps wrap
2885
+ * it inside their `SidebarProvider` (server-rendered with the cookie-backed
2886
+ * `defaultOpen`) and their `ERPProvider`, then pass app-specific bits as
2887
+ * props.
1730
2888
  *
1731
- * 1. rules / probe still loading → `null` on FIRST load only (let Suspense /
1732
- * loading.tsx show); once this subtree has been granted access, a later
1733
- * loading state keeps the children mounted — see the note below
1734
- * 2. no rule covers this path → deny (fail closed)
1735
- * 3. rule is explicit public (`[]`) → children
1736
- * 4. probe says no access → deny card
1737
- * 5. otherwise → children
2889
+ * The padding contract is deliberately owned here so future style tweaks
2890
+ * (e.g. the recent left/right/bottom gutter pass) propagate to both apps via
2891
+ * an erp-shell bump — domain components must NOT add their own root padding
2892
+ * or content gets indented twice.
1738
2893
  */
1739
- function PermissionProvider({ children, usePermission, fallbackRulesMap, }) {
1740
- const pathname = usePathname();
1741
- const { rulesMap, isLoading: rulesLoading } = usePermissionRules();
1742
- const mergedMap = useMemo(() => {
1743
- if (!fallbackRulesMap)
1744
- return rulesMap;
1745
- // live rules win over fallback when both define the same key
1746
- return { ...fallbackRulesMap, ...rulesMap };
1747
- }, [rulesMap, fallbackRulesMap]);
1748
- const lookup = useMemo(() => resolveUiRoutePermission(pathname, mergedMap), [pathname, mergedMap]);
1749
- // Hook must run unconditionally (rules of hooks).
1750
- const { hasPermission, isLoading } = usePermission({
1751
- requiredRoles: lookup.roles,
1752
- });
1753
- // Returning null unmounts the page. That is fine before anything has been
1754
- // shown, and destructive afterwards: next-auth flips its status back to
1755
- // "loading" on every session update() — one runs every 4 minutes — and a
1756
- // rules hook that reports loading on that transient took the page down with
1757
- // it. Users filling a long form watched everything they had typed vanish,
1758
- // which reads as a spontaneous page refresh.
1759
- //
1760
- // So a loading state only blanks the subtree until access has been granted
1761
- // once. After that the children stay mounted while the check re-settles; the
1762
- // API still enforces access on every request, and a genuine loss of
1763
- // permission surfaces as a denied response rather than a wiped form.
2894
+ function AppLayoutShell({ children, sidebar, loadingComponent, breadcrumb, permissionProvider, organizationId, setOrganizationId, organizations, signInUrl, selectOrganizationUrl, chrome = "brand", workspaceHeader = "brand", headerEnd, mobileBrand, showHelp = true, helpApp, }) {
2895
+ const { data: session, status } = useSession();
2896
+ const { open, setOpen } = useSidebar();
2897
+ const router = useRouter();
2898
+ const params = useParams();
2899
+ const code = params?.code;
2900
+ const extendedSession = session;
2901
+ // Track once-authenticated so a transient accessToken drop during the
2902
+ // periodic session refresh (SessionRefreshTrigger every 4 min) doesn't
2903
+ // blank the whole page. The initial-load gate below still handles cold
2904
+ // start; once we've seen a real token we render children optimistically
2905
+ // and let the API layer surface a real 401 if the token actually died.
2906
+ const hasSeenAccessTokenRef = useRef(false);
2907
+ useEffect(() => {
2908
+ if (extendedSession?.accessToken)
2909
+ hasSeenAccessTokenRef.current = true;
2910
+ }, [extendedSession?.accessToken]);
2911
+ // Find the org from the URL `[code]` so we can detect a context mismatch
2912
+ // (the user bookmarked a different org than the cookie remembers).
2913
+ const orgFromCode = React.useMemo(() => {
2914
+ if (!code || !organizations.length)
2915
+ return null;
2916
+ return (organizations.find(org => org.code === code || String(org.id) === code) ?? null);
2917
+ }, [code, organizations]);
2918
+ // Sync state: when the URL code points at a different org than the cookie,
2919
+ // trust the URL and update the cookie. Otherwise do nothing — the user
2920
+ // wins ties via the in-app org switcher.
2921
+ useEffect(() => {
2922
+ if (!code)
2923
+ return;
2924
+ if (!organizations.length)
2925
+ return;
2926
+ if (!orgFromCode)
2927
+ return;
2928
+ if (String(organizationId) !== String(orgFromCode.id)) {
2929
+ void setOrganizationId(orgFromCode.id);
2930
+ }
2931
+ }, [
2932
+ orgFromCode,
2933
+ organizationId,
2934
+ setOrganizationId,
2935
+ code,
2936
+ organizations.length,
2937
+ ]);
2938
+ // Key for the content subtree. It exists so switching organizations throws
2939
+ // away the previous org's component state — but it must react ONLY to a real
2940
+ // switch. organizationId legitimately passes through null while the context
2941
+ // re-settles (session resolving, cookie write in flight), and keying on that
2942
+ // unmounted and remounted the entire page: forms lost their loaded values,
2943
+ // in-flight edits vanished, and settings pickers snapped back to defaults.
1764
2944
  //
1765
- // The grant is remembered per pathname, not per mount. This provider lives in
1766
- // the layout, so it survives every in-app navigation — a bare boolean would
1767
- // carry one page's grant onto the next route and flash a page the user may
1768
- // not be allowed to see while its own check is still running.
1769
- const grantedForPathRef = useRef(null);
1770
- const grantedHere = grantedForPathRef.current === pathname;
1771
- if (rulesLoading && !grantedHere) {
1772
- return null;
1773
- }
1774
- // Unknown route → deny. Only explicit `required_child_groups: []` is public.
1775
- if (!lookup.matched) {
1776
- return jsx(DeniedCard, {});
2945
+ // Holding the last known id makes a transient null a no-op while a genuine
2946
+ // org-to-org switch still changes the key.
2947
+ const lastOrgKeyRef = React.useRef("no-org");
2948
+ const currentOrgKey = organizationId === null ||
2949
+ organizationId === undefined ||
2950
+ String(organizationId).trim() === ""
2951
+ ? null
2952
+ : String(organizationId);
2953
+ if (currentOrgKey !== null) {
2954
+ lastOrgKeyRef.current = currentOrgKey;
1777
2955
  }
1778
- if (lookup.roles.length === 0) {
1779
- grantedForPathRef.current = pathname;
1780
- return jsx(Fragment$1, { children: children });
2956
+ const contentOrgKey = lastOrgKeyRef.current;
2957
+ // Hold the page back until the active organisation is the one the URL names.
2958
+ //
2959
+ // The sync effect above writes the cookie through a server action, which is
2960
+ // a round trip. Until it lands, getOrgFromCookie() still answers with the
2961
+ // previous organisation and every request the page fires on mount carries
2962
+ // it — so /O26000021/work-record asked about O26000033 and was correctly
2963
+ // told there was nothing there. An empty table is the mild version: the
2964
+ // create form posts to the same header, so a record could be filed against
2965
+ // a company the user was not looking at.
2966
+ //
2967
+ // Only while the two genuinely disagree. A code naming no organisation of
2968
+ // the caller's is left to the app to refuse, and a page with no code in its
2969
+ // path is unaffected.
2970
+ const orgContextIsStale = !!orgFromCode &&
2971
+ organizationId !== null &&
2972
+ organizationId !== undefined &&
2973
+ String(organizationId) !== String(orgFromCode.id);
2974
+ // ≤1024px: sidebar renders as a modal overlay (backdrop dims content). >1024px:
2975
+ // sidebar is docked and the content gets a left margin to clear it.
2976
+ const [isSidebarModalLayout, setIsSidebarModalLayout] = React.useState(false);
2977
+ useEffect(() => {
2978
+ const mq = window.matchMedia("(max-width: 1024px)");
2979
+ const sync = () => setIsSidebarModalLayout(mq.matches);
2980
+ sync();
2981
+ mq.addEventListener("change", sync);
2982
+ return () => mq.removeEventListener("change", sync);
2983
+ }, []);
2984
+ // Help opened from the drawer's user menu: the drawer steps aside so the
2985
+ // dialog is the only thing on a phone's screen.
2986
+ const helpOpen = useHelpOpen();
2987
+ useEffect(() => {
2988
+ if (helpOpen && isSidebarModalLayout && open)
2989
+ setOpen(false);
2990
+ }, [helpOpen, isSidebarModalLayout, open, setOpen]);
2991
+ // Wait for session to load (initial load only). When refetching/updating we
2992
+ // already have a session — don't flash the full-screen loader.
2993
+ if (status === "loading" && !session) {
2994
+ return jsx(Fragment$1, { children: loadingComponent });
1781
2995
  }
1782
- if (isLoading && !grantedHere) {
1783
- return null;
2996
+ // Session loaded but no accessToken AND we've never seen one → real auth
2997
+ // failure (token refresh gave nothing back on cold start), bounce through
2998
+ // signin. If we HAVE seen one before, the drop is almost certainly the
2999
+ // in-flight periodic refresh (SessionRefreshTrigger). Don't redirect on
3000
+ // that transient — the JWT callback will settle in a moment and API
3001
+ // calls will keep working with the still-valid cookie.
3002
+ if (status === "authenticated" &&
3003
+ !extendedSession?.accessToken &&
3004
+ !hasSeenAccessTokenRef.current) {
3005
+ if (typeof window !== "undefined") {
3006
+ const url = new URL(signInUrl, window.location.origin);
3007
+ url.searchParams.set("error", "NoAccessToken");
3008
+ url.searchParams.set("callbackUrl", window.location.pathname);
3009
+ window.location.href = url.toString();
3010
+ }
3011
+ return jsx(Fragment$1, { children: loadingComponent });
1784
3012
  }
1785
- if (!hasPermission && !isLoading) {
1786
- return jsx(DeniedCard, {});
3013
+ // Only blank the page when we've never seen a token — otherwise the
3014
+ // periodic session refresh would visibly flash the loader every 4 min.
3015
+ if (!extendedSession?.accessToken && !hasSeenAccessTokenRef.current) {
3016
+ return jsx(Fragment$1, { children: loadingComponent });
1787
3017
  }
1788
- grantedForPathRef.current = pathname;
1789
- return jsx(Fragment$1, { children: children });
1790
- }
1791
-
1792
- /** Cookie name for the cross-subdomain theme choice. */
1793
- const THEME_COOKIE = "erp-theme";
1794
- /**
1795
- * Parent domain to scope the cookie to, so every `*.antniti.com` app reads the
1796
- * same value. Returns `null` on localhost / bare IPs (host-only cookie).
1797
- */
1798
- function sharedCookieDomain() {
1799
- if (typeof window === "undefined")
1800
- return null;
1801
- const host = window.location.hostname;
1802
- if (host === "localhost" || /^[0-9.]+$/.test(host))
1803
- return null;
1804
- const parts = host.split(".");
1805
- if (parts.length < 2)
1806
- return null;
1807
- return "." + parts.slice(-2).join(".");
1808
- }
1809
- function readThemeCookie() {
1810
- if (typeof document === "undefined")
1811
- return null;
1812
- const match = document.cookie.match(new RegExp("(?:^|; )" + THEME_COOKIE + "=([^;]*)"));
1813
- return match ? decodeURIComponent(match[1]) : null;
3018
+ if (!code) {
3019
+ router.push(selectOrganizationUrl);
3020
+ return jsx(Fragment$1, { children: loadingComponent });
3021
+ }
3022
+ // When the sidebar is docked-open it consumes 21.5rem on the left; otherwise
3023
+ // the content takes the full width and we add a left gutter inside.
3024
+ const workspace = chrome === "workspace";
3025
+ const contentMargin = open && !isSidebarModalLayout
3026
+ ? workspace
3027
+ ? "ml-[244px]"
3028
+ : "ml-[21.5rem]"
3029
+ : "";
3030
+ const needsLeftGutter = workspace || !(open && !isSidebarModalLayout);
3031
+ const wrap = permissionProvider ?? ((c) => c);
3032
+ return (jsxs("div", { className: "flex min-h-screen w-full bg-background", children: [open && (jsx("div", { className: "fixed left-0 top-0 z-50 h-screen", children: sidebar })), open && isSidebarModalLayout && (jsx("button", { type: "button", "aria-label": "\u0E1B\u0E34\u0E14\u0E40\u0E21\u0E19\u0E39", className: "fixed inset-0 z-40 bg-black/50", onClick: () => setOpen(false) })), jsx("div", { className: cx("relative flex min-w-0 flex-1 flex-col transition-all", contentMargin), children: jsxs("main", { className: cx("flex flex-1 flex-col min-h-screen", workspace ? "gap-0" : "gap-4"), children: [workspace ? (jsxs("div", { className: cx("sticky top-0 z-30 shrink-0 w-full", workspaceHeader === "light" &&
3033
+ "border-b border-border bg-card/85 backdrop-blur-sm"), style: workspaceHeader === "light"
3034
+ ? WORKSPACE_LIGHT_HEADER_VARS
3035
+ : WORKSPACE_HEADER_VARS, children: [workspaceHeader === "light" ? null : (jsx(HeaderBackground, { className: "rounded-none" })), jsxs("header", { className: cx("relative z-10 flex w-full items-center gap-3 text-[var(--header-fg)]", workspaceHeader === "light"
3036
+ ? "min-h-[66px] px-3 py-2 sm:min-h-[72px] sm:px-[22px] lg:min-h-[82px] lg:px-8"
3037
+ : "min-h-[72px] px-[18px] py-3 sm:px-6 lg:min-h-[88px] lg:px-10"), children: [isSidebarModalLayout ? (
3038
+ // As in the design: the mark, then a menu button, and the
3039
+ // organisation on the right — no trail, no title, so the
3040
+ // organisation's name has the room it needs on a phone.
3041
+ 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: breadcrumb }), 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: breadcrumb }), 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
3042
+ ? "relative z-10 px-[18px] pt-[26px] pb-4 sm:px-6 lg:px-10 lg:pt-[38px]"
3043
+ : cx("relative z-10 pr-6", needsLeftGutter && "pl-6"), children: orgContextIsStale ? loadingComponent : wrap(children) }, `org-${contentOrgKey}`) })] }) }), showHelp ? jsx(HelpDialogHost, { app: helpApp, orgCode: code }) : null] }));
1814
3044
  }
1815
- function writeThemeCookie(value) {
1816
- if (typeof document === "undefined")
1817
- return;
1818
- const domain = sharedCookieDomain();
1819
- const parts = [
1820
- `${THEME_COOKIE}=${encodeURIComponent(value)}`,
1821
- "path=/",
1822
- "max-age=31536000", // 1 year
1823
- "SameSite=Lax",
1824
- ];
1825
- if (domain)
1826
- parts.push(`domain=${domain}`);
1827
- document.cookie = parts.join("; ");
3045
+ /** Local tiny classnames helper — avoids pulling clsx/tailwind-merge into
3046
+ * the shell just for the layout file. Falsy values are skipped. */
3047
+ function cx(...parts) {
3048
+ return parts.filter(Boolean).join(" ");
1828
3049
  }
3050
+
1829
3051
  /**
1830
- * Bridges next-themes (per-origin localStorage) with a cookie scoped to the
1831
- * parent domain, so the light/dark/system choice is shared across the
1832
- * accounting / HR / platform subdomains.
1833
- *
1834
- * Local storage wins when it already has a value (H57): adopting the shared
1835
- * cookie first used to overwrite an explicit choice — including one set via
1836
- * DevTools — and write `theme=light` back on every load whenever the cookie
1837
- * still said light. Push the local value into the cookie instead so sibling
1838
- * apps catch up.
3052
+ * The product mark at the top of the workspace sidebar: the app icon, the
3053
+ * name, and a spaced caption beneath it.
1839
3054
  */
1840
- function ThemeCookieSync() {
1841
- const { theme, setTheme } = useTheme();
1842
- const skipFirstWrite = React.useRef(true);
1843
- React.useEffect(() => {
1844
- const local = typeof window !== "undefined"
1845
- ? window.localStorage.getItem("theme")
1846
- : null;
1847
- const cookie = readThemeCookie();
1848
- if (local) {
1849
- if (local !== theme)
1850
- setTheme(local);
1851
- writeThemeCookie(local);
1852
- }
1853
- else if (cookie) {
1854
- if (cookie !== theme)
1855
- setTheme(cookie);
1856
- }
1857
- else if (theme) {
1858
- writeThemeCookie(theme);
1859
- }
1860
- // Run once on mount — `theme` is intentionally not a dependency here.
1861
- // eslint-disable-next-line react-hooks/exhaustive-deps
1862
- }, []);
1863
- React.useEffect(() => {
1864
- // Skip the initial render; only persist genuine changes (incl. the
1865
- // setTheme() triggered by adopting storage above — harmless re-write).
1866
- if (skipFirstWrite.current) {
1867
- skipFirstWrite.current = false;
1868
- return;
1869
- }
1870
- if (theme)
1871
- writeThemeCookie(theme);
1872
- }, [theme]);
1873
- return null;
1874
- }
1875
- function ThemeProvider({ children, ...props }) {
1876
- return (jsxs(ThemeProvider$1, { ...props, children: [jsx(ThemeCookieSync, {}), children] }));
3055
+ function WorkspaceBrand({ name, caption, mark, href, compact = false, className, }) {
3056
+ const body = (jsxs(Fragment$1, { children: [jsx("span", { className: cn("grid shrink-0 place-items-center overflow-hidden rounded-[14px] [&>img]:size-full [&>img]:object-cover", compact ? "size-9 rounded-[11px]" : "size-11"), children: mark }), compact ? (jsx("span", { className: "sr-only", children: name })) : (jsxs("span", { className: "min-w-0", children: [jsx("span", { className: "block truncate text-[25px] leading-tight font-extrabold tracking-[-0.05em]", children: name }), caption ? (jsx("small", { className: "-mt-0.5 block truncate text-[9px] font-semibold tracking-[0.29em] text-muted-foreground", children: caption })) : null] }))] }));
3057
+ const cls = cn("flex items-center gap-[11px] rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", !compact && "px-4", className);
3058
+ return href ? (jsx(Link, { href: href, className: cls, "aria-label": compact ? name : undefined, children: body })) : (jsx("div", { className: cls, children: body }));
1877
3059
  }
1878
3060
 
1879
- const defaultFlags = {
1880
- enableAdvancedReporting: true,
1881
- enableMultiCurrency: false,
1882
- enableThaiTaxCalculation: true,
1883
- enableProcurementWorkflow: true,
1884
- enableInventoryTracking: true,
1885
- enableAuditTrail: true,
1886
- enableAdvancedFilter: true,
1887
- filterFlag: false,
1888
- setFilterFlag: () => { },
1889
- };
1890
- const FeatureFlagsContext = createContext(defaultFlags);
1891
- function FeatureFlagsProvider({ children, flags = {}, }) {
1892
- const [filterFlag, setFilterFlag] = useState(false);
1893
- const mergedFlags = {
1894
- ...defaultFlags,
1895
- ...flags,
1896
- filterFlag: flags.filterFlag ?? filterFlag,
1897
- setFilterFlag: (flag) => {
1898
- setFilterFlag(flag);
1899
- if (typeof flags.setFilterFlag === "function") {
1900
- flags.setFilterFlag(flag);
1901
- }
1902
- },
1903
- };
1904
- return (jsx(FeatureFlagsContext.Provider, { value: mergedFlags, children: children }));
1905
- }
1906
- function useFeatureFlags() {
1907
- const context = useContext(FeatureFlagsContext);
1908
- if (!context) {
1909
- throw new Error("useFeatureFlags must be used within a FeatureFlagsProvider");
1910
- }
1911
- return context;
1912
- }
1913
- function useFeatureFlag(flag) {
1914
- const flags = useFeatureFlags();
1915
- return flags[flag];
3061
+ function isExternal(href) {
3062
+ return /^https?:\/\//i.test(href);
1916
3063
  }
1917
-
1918
- const getAxiosErrorMessage$1 = (error) => {
1919
- if (error.response?.data?.message) {
1920
- return error.response.data.message;
1921
- }
1922
- if (error.message) {
1923
- return error.message;
1924
- }
1925
- return "An unknown error occurred";
1926
- };
1927
- const formatError = (handlerName, error) => {
1928
- const axiosError = error;
1929
- const message = getAxiosErrorMessage$1(axiosError);
1930
- const isOrgRequired = message.includes("Organization context is required") ||
1931
- message.includes("organization_id") ||
1932
- message.includes("X-Organization-ID");
1933
- if (isOrgRequired) {
1934
- // Expected when no org selected yet (e.g. select-organization page).
1935
- console.warn(`[React Query] ${handlerName} skipped (no organization context): ${message}`);
1936
- return;
1937
- }
1938
- };
1939
3064
  /**
1940
- * Default React Query config used across ERP apps:
1941
- * - 2 retries on queries / 1 on mutations, exponential backoff
1942
- * - 5 min staleTime, refetchOnWindowFocus
1943
- * - swallows "no org context" errors to silence noise on the
1944
- * select-organization page
1945
- *
1946
- * Apps can compose on top of this — pass the returned config to `new QueryClient(...)`
1947
- * directly or spread + override default options.
3065
+ * The card at the foot of the workspace sidebar that points someone who
3066
+ * does not know where to start at the place that will tell them.
1948
3067
  */
1949
- const getQueryClientConfig = () => ({
1950
- defaultOptions: {
1951
- queries: {
1952
- retry: 2,
1953
- retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
1954
- staleTime: 5 * 60 * 1000,
1955
- refetchOnWindowFocus: true,
1956
- },
1957
- mutations: {
1958
- // NEVER auto-retry a mutation. Unlike a query, a mutation is a side
1959
- // effect on a non-idempotent endpoint (submit, create, approve), and
1960
- // React Query cannot tell "the network dropped" from "the server
1961
- // rejected this on business grounds".
1962
- //
1963
- // With retry: 1 every failed mutation fired twice. Two visible
1964
- // consequences: a rejected submit showed up as two failed POSTs in the
1965
- // network tab, and — far worse — a create whose response was lost in
1966
- // flight would be re-sent and duplicate the record server-side.
1967
- //
1968
- // Retrying is the caller's decision, not a global default: the user
1969
- // sees the error and presses the button again.
1970
- retry: 0,
1971
- },
1972
- },
1973
- queryCache: new QueryCache({
1974
- onError: error => formatError("Query", error),
1975
- }),
1976
- mutationCache: new MutationCache({
1977
- onError: error => formatError("Mutation", error),
1978
- }),
1979
- });
3068
+ function SidebarHelpCard({ title, description, actionLabel, href, icon, className, }) {
3069
+ const external = isExternal(href);
3070
+ const action = (jsxs(Fragment$1, { children: [actionLabel, jsx(ArrowRight, { className: "size-[15px]" })] }));
3071
+ const actionClass = "mt-3 flex w-full items-center justify-between text-xs font-semibold text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded";
3072
+ return (jsxs("div", { className: cn("mx-1.5 mb-5 rounded-[13px] border border-primary/10 bg-gradient-to-br from-primary/[0.06] to-primary/[0.02] px-3.5 py-4", className), children: [jsx("span", { className: "mb-[7px] block text-primary/70", children: icon ?? jsx(Compass, { className: "size-6", strokeWidth: 1.6 }) }), jsx("strong", { className: "block text-xs font-semibold", children: title }), description ? (jsx("p", { className: "mt-[7px] text-xs leading-[1.7] text-muted-foreground", children: description })) : null, external ? (jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: actionClass, children: action })) : (jsx(Link, { href: href, className: actionClass, children: action }))] }));
3073
+ }
3074
+ /** A quiet row under the help card — the manual, the support chat. */
3075
+ function SidebarHelpLink({ label, href, icon, className }) {
3076
+ const external = isExternal(href);
3077
+ const cls = cn("flex w-full items-center gap-3 rounded-[10px] px-3.5 py-[11px] text-xs font-medium text-sidebar-foreground/70 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", className);
3078
+ const body = (jsxs(Fragment$1, { children: [icon ? jsx("span", { className: "shrink-0 [&>svg]:size-[18px]", children: icon }) : null, jsx("span", { className: "flex-1 truncate", children: label }), external ? jsx(ArrowUpRight, { className: "size-4 shrink-0" }) : null] }));
3079
+ return external ? (jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: cls, children: body })) : (jsx(Link, { href: href, className: cls, children: body }));
3080
+ }
1980
3081
 
1981
- function ReactQueryProvider({ children }) {
1982
- // Create a new QueryClient instance for each render to avoid SSR issues.
1983
- const [queryClient] = useState(() => new QueryClient(getQueryClientConfig()));
1984
- return (jsxs(QueryClientProvider, { client: queryClient, children: [children, jsx(ReactQueryDevtools, { client: queryClient, initialIsOpen: false })] }));
3082
+ /**
3083
+ * Central "no access" screen shared by every policy check (route-level
3084
+ * PermissionProvider and page-level PermissionGateShell). One look everywhere:
3085
+ * an illustration, a 403 headline, the page-specific reason, and recovery
3086
+ * actions.
3087
+ */
3088
+ function AccessDenied({ title = "ขออภัย, คุณไม่มีสิทธิ์เข้าถึงหน้านี้ (403)", message = "คุณไม่มีสิทธิ์เข้าถึงหน้านี้ ขออภัยในความไม่สะดวก", homeHref, homeLabel = "กลับไปหน้าหลัก", supportHref, supportLabel = "ติดต่อฝ่ายสนับสนุน", fullScreen = true, className, }) {
3089
+ // "/" is not the home page inside an app — it bounces to organization
3090
+ // selection, so the button read "กลับไปหน้าหลัก" and dropped the user into a
3091
+ // picker for the org they were already in. Send them to that org's home.
3092
+ const params = useParams();
3093
+ const code = typeof params?.code === "string" ? params.code : "";
3094
+ const homeTarget = homeHref ?? (code ? `/${code}` : "/");
3095
+ const go = (href) => {
3096
+ if (typeof window !== "undefined")
3097
+ window.location.href = href;
3098
+ };
3099
+ const wrapperClass = [
3100
+ "flex min-w-0 flex-1 items-center justify-center p-4",
3101
+ fullScreen ? "min-h-[70vh]" : "",
3102
+ className ?? "",
3103
+ ]
3104
+ .filter(Boolean)
3105
+ .join(" ");
3106
+ return (jsx("div", { className: wrapperClass, children: jsx("div", { className: "relative w-full max-w-3xl overflow-hidden rounded-2xl border border-border/60 bg-card/60 p-8 shadow-sm backdrop-blur sm:p-10", children: jsxs("div", { className: "flex flex-col items-center gap-8 text-center sm:flex-row sm:text-left", children: [jsxs("div", { className: "relative shrink-0", children: [jsx("div", { className: "absolute inset-0 rounded-full bg-destructive/20 blur-2xl" }), jsx("div", { className: "relative flex h-28 w-28 items-center justify-center rounded-3xl border border-border/60 bg-gradient-to-br from-muted/40 to-background shadow-inner", children: jsx("div", { className: "flex h-16 w-16 items-center justify-center rounded-full border border-destructive/40 bg-destructive/10", children: jsx(Ban, { className: "h-8 w-8 text-destructive", strokeWidth: 2.5 }) }) })] }), jsxs("div", { className: "min-w-0 flex-1", children: [jsx("h1", { className: "text-xl font-bold text-foreground sm:text-2xl", children: title }), message ? (jsx("p", { className: "mt-3 whitespace-pre-line text-sm leading-relaxed text-muted-foreground sm:text-base", children: message })) : null, jsxs("div", { className: "mt-6 flex flex-col gap-3 sm:flex-row", children: [jsxs(Button, { type: "button", onClick: () => go(homeTarget), className: "w-full sm:w-auto", children: [jsx(Home, { className: "mr-2 h-4 w-4" }), homeLabel] }), supportHref ? (jsxs(Button, { type: "button", variant: "outline", onClick: () => go(supportHref), className: "w-full sm:w-auto", children: [jsx(Headset, { className: "mr-2 h-4 w-4" }), supportLabel] })) : null] })] })] }) }) }));
1985
3107
  }
1986
3108
 
3109
+ const EMPLOYEE_RECORD_REQUIRED = "EMPLOYEE_RECORD_REQUIRED";
3110
+ const EMPLOYEE_RECORD_REQUIRED_EVENT = "erp:employee-record-required";
3111
+ const EMPLOYEE_RECORD_OK_EVENT = "erp:employee-record-ok";
1987
3112
  /**
1988
- * Renders nothing. Runs during render (after SessionProvider, inside
1989
- * QueryClientProvider) to seed the cached profile slot from the JWT-backed
1990
- * session — so `useMyProfile` doesn't fire a redundant GET on initial load.
3113
+ * Shown when the API refuses every request because the signed-in account has
3114
+ * no employee record in this organisation.
1991
3115
  *
1992
- * Generic over the profile shape; each app passes its own queryKey + mapper.
3116
+ * A gate rather than a banner. Leave, attendance, approvals and payslips all
3117
+ * identify a person by that record, so once the server started enforcing it
3118
+ * every call fails — and without something that says so, the app becomes a
3119
+ * screen of error toasts with no explanation and no way forward.
1993
3120
  */
1994
- function SessionBackedProfileCacheSeeder({ queryKey, mapper, }) {
1995
- const { data: session, status } = useSession();
1996
- const queryClient = useQueryClient();
1997
- if (status === "authenticated" && session) {
1998
- const mapped = mapper(session);
1999
- if (mapped) {
2000
- const existing = queryClient.getQueryData(queryKey);
2001
- if (!existing) {
2002
- // updatedAt: 0 → immediately stale so observers still GET /myprofile
2003
- // for fields the JWT seed omits (avatar/signature paths).
2004
- queryClient.setQueryData(queryKey, mapped, { updatedAt: 0 });
2005
- }
2006
- else {
2007
- // Only overwrite when the mapped id changed — we don't know T's shape
2008
- // so we rely on a shallow id check via JSON tag if present.
2009
- const existingId = existing?.id;
2010
- const mappedId = mapped?.id;
2011
- if (existingId !== mappedId) {
2012
- queryClient.setQueryData(queryKey, mapped, { updatedAt: 0 });
2013
- }
2014
- }
2015
- }
2016
- }
2017
- if (status === "unauthenticated") {
2018
- queryClient.removeQueries({ queryKey });
2019
- }
2020
- return null;
3121
+ function EmployeeRequiredGate({ platformBaseUrl, }) {
3122
+ const [blocked, setBlocked] = useState(false);
3123
+ const params = useParams();
3124
+ const code = params?.code ?? "";
3125
+ useEffect(() => {
3126
+ const onBlocked = () => setBlocked(true);
3127
+ const onOk = () => setBlocked(false);
3128
+ window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
3129
+ window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
3130
+ return () => {
3131
+ window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
3132
+ window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
3133
+ };
3134
+ }, []);
3135
+ if (!blocked)
3136
+ return null;
3137
+ const base = platformBaseUrl?.replace(/\/$/, "") ?? "";
3138
+ const createHref = code ? `${base}/${code}/employee/create` : `${base}/`;
3139
+ 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" })] }) }));
2021
3140
  }
2022
3141
 
2023
- const TOKEN_TTL_MS = 30000;
2024
- let cachedToken = null;
2025
- let cachedAt = 0;
2026
- let inFlightTokenPromise = null;
2027
- const readSessionToken = async () => {
2028
- const response = await fetch("/api/auth/session", {
2029
- credentials: "include",
2030
- cache: "no-store",
2031
- });
2032
- if (!response.ok)
2033
- return null;
2034
- const session = (await response.json());
2035
- return session.accessToken ?? null;
2036
- };
2037
- const getAccessToken = async (forceRefresh = false) => {
2038
- const now = Date.now();
2039
- if (!forceRefresh && cachedToken && now - cachedAt < TOKEN_TTL_MS) {
2040
- return cachedToken;
3142
+ const shellClassName = "flex min-w-0 flex-1 flex-col gap-6 overflow-x-hidden";
3143
+ /**
3144
+ * Shared layout for “กำลังตรวจสอบสิทธิ์” (skeleton) and “ไม่มีสิทธิ์” (message).
3145
+ * Renders `children` only when policy is loaded and access is granted.
3146
+ */
3147
+ function PermissionGateShell({ policyLoading, hasPolicyAccess, deniedMessage, children, skeletonCount = 6, skeletonGridClassName = "grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3", skeletonVariant = "kpi", }) {
3148
+ if (policyLoading) {
3149
+ return (jsx("div", { className: shellClassName, children: jsx("div", { className: skeletonGridClassName, children: Array.from({ length: skeletonCount }).map((_, i) => (jsx(Card, { children: skeletonVariant === "kpi" ? (jsxs(Fragment$1, { children: [jsxs(CardHeader, { className: "flex flex-row items-center justify-between pb-2", children: [jsx(Skeleton, { className: "h-4 w-24" }), jsx(Skeleton, { className: "h-4 w-4 rounded" })] }), jsxs(CardContent, { children: [jsx(Skeleton, { className: "h-8 w-32 mb-2" }), jsx(Skeleton, { className: "h-3 w-20" })] })] })) : (jsxs(Fragment$1, { children: [jsx(CardHeader, { className: "pb-2", children: jsx(Skeleton, { className: "h-4 w-24" }) }), jsx(CardContent, { children: jsx(Skeleton, { className: "h-8 w-16" }) })] })) }, i))) }) }));
2041
3150
  }
2042
- if (!inFlightTokenPromise) {
2043
- inFlightTokenPromise = readSessionToken()
2044
- .then(token => {
2045
- cachedToken = token;
2046
- cachedAt = Date.now();
2047
- return token;
2048
- })
2049
- .finally(() => {
2050
- inFlightTokenPromise = null;
2051
- });
3151
+ if (!hasPolicyAccess) {
3152
+ return (jsx("div", { className: shellClassName, children: jsx(AccessDenied, { message: deniedMessage }) }));
2052
3153
  }
2053
- return inFlightTokenPromise;
2054
- };
2055
- const clearAccessTokenCache = () => {
2056
- cachedToken = null;
2057
- cachedAt = 0;
2058
- };
3154
+ return jsx(Fragment$1, { children: children });
3155
+ }
2059
3156
 
2060
- class ApiError extends Error {
2061
- constructor(message, options) {
2062
- super(message);
2063
- Object.defineProperty(this, "status", {
2064
- enumerable: true,
2065
- configurable: true,
2066
- writable: true,
2067
- value: void 0
2068
- });
2069
- Object.defineProperty(this, "code", {
2070
- enumerable: true,
2071
- configurable: true,
2072
- writable: true,
2073
- value: void 0
2074
- });
2075
- Object.defineProperty(this, "field", {
2076
- enumerable: true,
2077
- configurable: true,
2078
- writable: true,
2079
- value: void 0
2080
- });
2081
- Object.defineProperty(this, "details", {
2082
- enumerable: true,
2083
- configurable: true,
2084
- writable: true,
2085
- value: void 0
2086
- });
2087
- this.name = "ApiError";
2088
- this.status = options?.status;
2089
- this.code = options?.code;
2090
- this.field = options?.field;
2091
- this.details = options?.details;
2092
- }
3157
+ const PermissionRulesContext = createContext(undefined);
3158
+ /**
3159
+ * Generic provider — the consumer app passes in `data` (live fetch) and
3160
+ * `fallbackPolicies` (static JSON). All apps share the same mapping logic
3161
+ * (build a flat map of route_key/policy_key → required child groups).
3162
+ */
3163
+ function PermissionRulesProvider({ children, data, isLoading = false, isError = false, fallbackPolicies = [], }) {
3164
+ const rulesMap = useMemo(() => {
3165
+ const m = {};
3166
+ if (!data?.routes)
3167
+ return m;
3168
+ for (const row of data.routes) {
3169
+ m[row.route_key] = row.required_child_groups ?? [];
3170
+ }
3171
+ return m;
3172
+ }, [data]);
3173
+ const policiesMap = useMemo(() => {
3174
+ const m = {};
3175
+ for (const row of fallbackPolicies) {
3176
+ m[row.policy_key] = row.required_child_groups ?? [];
3177
+ }
3178
+ if (data?.policies?.length) {
3179
+ for (const row of data.policies) {
3180
+ m[row.policy_key] = row.required_child_groups ?? [];
3181
+ }
3182
+ }
3183
+ return m;
3184
+ }, [data, fallbackPolicies]);
3185
+ const value = useMemo(() => ({
3186
+ rulesMap,
3187
+ policiesMap,
3188
+ isLoading,
3189
+ isError,
3190
+ updatedAt: data?.updated_at ?? null,
3191
+ }), [rulesMap, policiesMap, isLoading, isError, data?.updated_at]);
3192
+ return (jsx(PermissionRulesContext.Provider, { value: value, children: children }));
2093
3193
  }
2094
- const toApiError = (error) => {
2095
- if (error instanceof ApiError)
2096
- return error;
2097
- if (isAxiosError(error)) {
2098
- const axiosErr = error;
2099
- const message = axiosErr.response?.data?.message ||
2100
- axiosErr.response?.data?.error ||
2101
- axiosErr.message ||
2102
- "Request failed";
2103
- return new ApiError(message, {
2104
- status: axiosErr.response?.status,
2105
- code: axiosErr.response?.data?.code,
2106
- field: axiosErr.response?.data?.field,
2107
- details: axiosErr.response?.data?.details,
2108
- });
2109
- }
2110
- if (error instanceof Error) {
2111
- return new ApiError(error.message);
3194
+ /**
3195
+ * Read the permission rules. Outside the provider, report loading so
3196
+ * fail-closed consumers (nav / gates) do not treat empty maps as "allow all".
3197
+ */
3198
+ function usePermissionRules() {
3199
+ const ctx = useContext(PermissionRulesContext);
3200
+ if (!ctx) {
3201
+ return {
3202
+ rulesMap: {},
3203
+ policiesMap: {},
3204
+ isLoading: true,
3205
+ isError: false,
3206
+ updatedAt: null,
3207
+ };
2112
3208
  }
2113
- return new ApiError(String(error));
2114
- };
3209
+ return ctx;
3210
+ }
2115
3211
 
2116
- const isPlainObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
2117
- const visit = (value, cb) => {
2118
- if (Array.isArray(value)) {
2119
- value.forEach(item => visit(item, cb));
2120
- return;
2121
- }
2122
- if (!isPlainObject(value)) {
2123
- return;
3212
+ /**
3213
+ * Strip the org `[code]` prefix from a pathname so we can look it up in the
3214
+ * permission rules map. `/O12345/setting/foo` → `/setting/foo`. Single-segment
3215
+ * paths (e.g. `/select-organization`) keep their leading slash.
3216
+ *
3217
+ * Also normalizes the user-role subtab aliases — both `purchase-doc` and
3218
+ * `sales-doc` are gated by the same `members` rule because the UI shows
3219
+ * the same management screen with different filters.
3220
+ */
3221
+ function normalizePathnameForPermissionRules(pathname) {
3222
+ const parts = pathname.split("/").filter(Boolean);
3223
+ const path = parts.length <= 1 ? "/" : "/" + parts.slice(1).join("/");
3224
+ return path.replace(/\/user-role\/(purchase-doc|sales-doc)$/, "/user-role/members");
3225
+ }
3226
+ function hasRule(rulesMap, routeKey) {
3227
+ return Object.prototype.hasOwnProperty.call(rulesMap, routeKey);
3228
+ }
3229
+ /**
3230
+ * Resolve UI route permissions for a pathname.
3231
+ *
3232
+ * - Exact / `[param]` pattern match → matched
3233
+ * - Parent-prefix inherit only when the parent rule has a **non-empty**
3234
+ * role list (restrictive inherit). Explicitly public parents (`[]`) do
3235
+ * not open all children.
3236
+ * - No match → `{ matched: false }` (fail closed — never treat as public)
3237
+ */
3238
+ function resolveUiRoutePermission(pathname, rulesMap) {
3239
+ const normalized = normalizePathnameForPermissionRules(pathname);
3240
+ if (hasRule(rulesMap, normalized)) {
3241
+ return { matched: true, roles: rulesMap[normalized] ?? [] };
2124
3242
  }
2125
- cb(value);
2126
- Object.values(value).forEach(item => visit(item, cb));
2127
- };
2128
- const validateGoodsReceiptChecks = (data) => {
2129
- let invalidPath = null;
2130
- const isCheckStatus = (v) => v === undefined || v === null || v === "pass" || v === "fail";
2131
- const isCompareStatus = (v) => v === undefined || v === null || v === "match" || v === "mismatch";
2132
- visit(data, node => {
2133
- if (invalidPath)
2134
- return;
2135
- if ("quantity_check" in node && !isCheckStatus(node.quantity_check)) {
2136
- invalidPath = "quantity_check";
2137
- return;
3243
+ const pathSegments = normalized.split("/").filter(Boolean);
3244
+ for (const [pattern, roles] of Object.entries(rulesMap)) {
3245
+ const patternSegments = pattern.split("/").filter(Boolean);
3246
+ if (patternSegments.length !== pathSegments.length)
3247
+ continue;
3248
+ let matches = true;
3249
+ for (let i = 0; i < patternSegments.length; i++) {
3250
+ const patternSegment = patternSegments[i];
3251
+ const pathSegment = pathSegments[i];
3252
+ if (patternSegment.startsWith("[") && patternSegment.endsWith("]")) {
3253
+ if (!pathSegment) {
3254
+ matches = false;
3255
+ break;
3256
+ }
3257
+ }
3258
+ else if (patternSegment !== pathSegment) {
3259
+ matches = false;
3260
+ break;
3261
+ }
2138
3262
  }
2139
- if ("quality_check" in node && !isCheckStatus(node.quality_check)) {
2140
- invalidPath = "quality_check";
2141
- return;
3263
+ if (matches) {
3264
+ return { matched: true, roles: roles ?? [] };
2142
3265
  }
2143
- if ("compare_with_reference" in node &&
2144
- !isCompareStatus(node.compare_with_reference)) {
2145
- invalidPath = "compare_with_reference";
3266
+ }
3267
+ // Parent-prefix: /leave/types/abc → /leave/types (non-empty roles only)
3268
+ for (let len = pathSegments.length - 1; len >= 1; len--) {
3269
+ const parent = "/" + pathSegments.slice(0, len).join("/");
3270
+ if (hasRule(rulesMap, parent) && (rulesMap[parent]?.length ?? 0) > 0) {
3271
+ return { matched: true, roles: rulesMap[parent] ?? [] };
2146
3272
  }
3273
+ }
3274
+ return { matched: false, roles: [] };
3275
+ }
3276
+ /**
3277
+ * Returns the required child-group segments for a page pathname.
3278
+ *
3279
+ * Prefer {@link resolveUiRoutePermission} when you need to distinguish
3280
+ * "explicitly public (`[]`)" from "no rule (deny)". This helper returns
3281
+ * `[]` for both cases and is kept for backward compatibility.
3282
+ */
3283
+ function getRequiredChildGroups(pathname, rulesMap) {
3284
+ return resolveUiRoutePermission(pathname, rulesMap).roles;
3285
+ }
3286
+
3287
+ function DeniedCard() {
3288
+ return (jsx(AccessDenied, { message: "\u0E04\u0E38\u0E13\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E40\u0E02\u0E49\u0E32\u0E16\u0E36\u0E07\u0E2B\u0E19\u0E49\u0E32\u0E19\u0E35\u0E49 \u0E2B\u0E32\u0E01\u0E04\u0E34\u0E14\u0E27\u0E48\u0E32\u0E04\u0E27\u0E23\u0E40\u0E02\u0E49\u0E32\u0E16\u0E36\u0E07\u0E44\u0E14\u0E49 \u0E01\u0E23\u0E38\u0E13\u0E32\u0E15\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E1C\u0E39\u0E49\u0E14\u0E39\u0E41\u0E25\u0E23\u0E30\u0E1A\u0E1A\u0E02\u0E2D\u0E07\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" }));
3289
+ }
3290
+ /**
3291
+ * Permission gate for a page subtree. Looks up the current pathname in the
3292
+ * permission rules map (live rules from `PermissionRulesProvider`, layered
3293
+ * over the optional `fallbackRulesMap`), passes the resolved required roles
3294
+ * into the host's `usePermission` probe, and renders one of:
3295
+ *
3296
+ * 1. rules / probe still loading → `null` on FIRST load only (let Suspense /
3297
+ * loading.tsx show); once this subtree has been granted access, a later
3298
+ * loading state keeps the children mounted — see the note below
3299
+ * 2. no rule covers this path → deny (fail closed)
3300
+ * 3. rule is explicit public (`[]`) → children
3301
+ * 4. probe says no access → deny card
3302
+ * 5. otherwise → children
3303
+ */
3304
+ function PermissionProvider({ children, usePermission, fallbackRulesMap, }) {
3305
+ const pathname = usePathname();
3306
+ const { rulesMap, isLoading: rulesLoading } = usePermissionRules();
3307
+ const mergedMap = useMemo(() => {
3308
+ if (!fallbackRulesMap)
3309
+ return rulesMap;
3310
+ // live rules win over fallback when both define the same key
3311
+ return { ...fallbackRulesMap, ...rulesMap };
3312
+ }, [rulesMap, fallbackRulesMap]);
3313
+ const lookup = useMemo(() => resolveUiRoutePermission(pathname, mergedMap), [pathname, mergedMap]);
3314
+ // Hook must run unconditionally (rules of hooks).
3315
+ const { hasPermission, isLoading } = usePermission({
3316
+ requiredRoles: lookup.roles,
2147
3317
  });
2148
- if (invalidPath) {
2149
- return {
2150
- valid: false,
2151
- message: "รูปแบบข้อมูลไม่ถูกต้อง: ฟิลด์ตรวจรับต้องเป็น enum string (quantity/quality: pass|fail, compare: match|mismatch)",
2152
- };
3318
+ // Returning null unmounts the page. That is fine before anything has been
3319
+ // shown, and destructive afterwards: next-auth flips its status back to
3320
+ // "loading" on every session update() — one runs every 4 minutes — and a
3321
+ // rules hook that reports loading on that transient took the page down with
3322
+ // it. Users filling a long form watched everything they had typed vanish,
3323
+ // which reads as a spontaneous page refresh.
3324
+ //
3325
+ // So a loading state only blanks the subtree until access has been granted
3326
+ // once. After that the children stay mounted while the check re-settles; the
3327
+ // API still enforces access on every request, and a genuine loss of
3328
+ // permission surfaces as a denied response rather than a wiped form.
3329
+ //
3330
+ // The grant is remembered per pathname, not per mount. This provider lives in
3331
+ // the layout, so it survives every in-app navigation — a bare boolean would
3332
+ // carry one page's grant onto the next route and flash a page the user may
3333
+ // not be allowed to see while its own check is still running.
3334
+ const grantedForPathRef = useRef(null);
3335
+ const grantedHere = grantedForPathRef.current === pathname;
3336
+ if (rulesLoading && !grantedHere) {
3337
+ return null;
2153
3338
  }
2154
- return { valid: true };
2155
- };
2156
- const runGlobalRequestPrecheck = (config) => {
2157
- const method = (config.method || "get").toLowerCase();
2158
- const isWriteMethod = ["post", "put", "patch"].includes(method);
2159
- if (!isWriteMethod || config.data === undefined || config.data === null) {
2160
- return { valid: true };
3339
+ // Unknown route → deny. Only explicit `required_child_groups: []` is public.
3340
+ if (!lookup.matched) {
3341
+ return jsx(DeniedCard, {});
2161
3342
  }
2162
- if (typeof FormData !== "undefined" && config.data instanceof FormData) {
2163
- return { valid: true };
3343
+ if (lookup.roles.length === 0) {
3344
+ grantedForPathRef.current = pathname;
3345
+ return jsx(Fragment$1, { children: children });
2164
3346
  }
2165
- return validateGoodsReceiptChecks(config.data);
2166
- };
3347
+ if (isLoading && !grantedHere) {
3348
+ return null;
3349
+ }
3350
+ if (!hasPermission && !isLoading) {
3351
+ return jsx(DeniedCard, {});
3352
+ }
3353
+ grantedForPathRef.current = pathname;
3354
+ return jsx(Fragment$1, { children: children });
3355
+ }
2167
3356
 
2168
- const isBrowser = () => typeof window !== "undefined";
2169
- const isAuthEndpoint = (url) => !!url && url.includes("/api/auth/");
2170
- const isAuthPage = () => isBrowser() && window.location.pathname.startsWith("/auth/");
2171
- const getOrgFromCookie = () => {
2172
- if (!isBrowser())
3357
+ /** Cookie name for the cross-subdomain theme choice. */
3358
+ const THEME_COOKIE = "erp-theme";
3359
+ /**
3360
+ * Parent domain to scope the cookie to, so every `*.antniti.com` app reads the
3361
+ * same value. Returns `null` on localhost / bare IPs (host-only cookie).
3362
+ */
3363
+ function sharedCookieDomain() {
3364
+ if (typeof window === "undefined")
2173
3365
  return null;
2174
- const cookies = document.cookie.split(";").map(cookie => cookie.trim());
2175
- const orgCookie = cookies.find(cookie => cookie.startsWith("erp.organizationId="));
2176
- if (!orgCookie)
3366
+ const host = window.location.hostname;
3367
+ if (host === "localhost" || /^[0-9.]+$/.test(host))
2177
3368
  return null;
2178
- const raw = orgCookie.substring("erp.organizationId=".length);
2179
- return raw ? decodeURIComponent(raw) : null;
2180
- };
2181
- const redirectToLogout = async () => {
2182
- if (!isBrowser() || isAuthPage())
3369
+ const parts = host.split(".");
3370
+ if (parts.length < 2)
3371
+ return null;
3372
+ return "." + parts.slice(-2).join(".");
3373
+ }
3374
+ function readThemeCookie() {
3375
+ if (typeof document === "undefined")
3376
+ return null;
3377
+ const match = document.cookie.match(new RegExp("(?:^|; )" + THEME_COOKIE + "=([^;]*)"));
3378
+ return match ? decodeURIComponent(match[1]) : null;
3379
+ }
3380
+ function writeThemeCookie(value) {
3381
+ if (typeof document === "undefined")
2183
3382
  return;
2184
- localStorage.clear();
2185
- sessionStorage.clear();
2186
- setOrganizationId(null);
2187
- clearAccessTokenCache();
2188
- await signOut({ callbackUrl: "/auth/signin" });
3383
+ const domain = sharedCookieDomain();
3384
+ const parts = [
3385
+ `${THEME_COOKIE}=${encodeURIComponent(value)}`,
3386
+ "path=/",
3387
+ "max-age=31536000", // 1 year
3388
+ "SameSite=Lax",
3389
+ ];
3390
+ if (domain)
3391
+ parts.push(`domain=${domain}`);
3392
+ document.cookie = parts.join("; ");
3393
+ }
3394
+ /**
3395
+ * Bridges next-themes (per-origin localStorage) with a cookie scoped to the
3396
+ * parent domain, so the light/dark/system choice is shared across the
3397
+ * accounting / HR / platform subdomains.
3398
+ *
3399
+ * Local storage wins when it already has a value (H57): adopting the shared
3400
+ * cookie first used to overwrite an explicit choice — including one set via
3401
+ * DevTools — and write `theme=light` back on every load whenever the cookie
3402
+ * still said light. Push the local value into the cookie instead so sibling
3403
+ * apps catch up.
3404
+ */
3405
+ function ThemeCookieSync() {
3406
+ const { theme, setTheme } = useTheme();
3407
+ const skipFirstWrite = React.useRef(true);
3408
+ React.useEffect(() => {
3409
+ const local = typeof window !== "undefined"
3410
+ ? window.localStorage.getItem("theme")
3411
+ : null;
3412
+ const cookie = readThemeCookie();
3413
+ if (local) {
3414
+ if (local !== theme)
3415
+ setTheme(local);
3416
+ writeThemeCookie(local);
3417
+ }
3418
+ else if (cookie) {
3419
+ if (cookie !== theme)
3420
+ setTheme(cookie);
3421
+ }
3422
+ else if (theme) {
3423
+ writeThemeCookie(theme);
3424
+ }
3425
+ // Run once on mount — `theme` is intentionally not a dependency here.
3426
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3427
+ }, []);
3428
+ React.useEffect(() => {
3429
+ // Skip the initial render; only persist genuine changes (incl. the
3430
+ // setTheme() triggered by adopting storage above — harmless re-write).
3431
+ if (skipFirstWrite.current) {
3432
+ skipFirstWrite.current = false;
3433
+ return;
3434
+ }
3435
+ if (theme)
3436
+ writeThemeCookie(theme);
3437
+ }, [theme]);
3438
+ return null;
3439
+ }
3440
+ function ThemeProvider({ children, ...props }) {
3441
+ return (jsxs(ThemeProvider$1, { ...props, children: [jsx(ThemeCookieSync, {}), children] }));
3442
+ }
3443
+
3444
+ const defaultFlags = {
3445
+ enableAdvancedReporting: true,
3446
+ enableMultiCurrency: false,
3447
+ enableThaiTaxCalculation: true,
3448
+ enableProcurementWorkflow: true,
3449
+ enableInventoryTracking: true,
3450
+ enableAuditTrail: true,
3451
+ enableAdvancedFilter: true,
3452
+ filterFlag: false,
3453
+ setFilterFlag: () => { },
2189
3454
  };
2190
- const instance = axios.create({
2191
- baseURL: process.env.NEXT_PUBLIC_API_URL,
2192
- headers: { "Content-Type": "application/json" },
2193
- paramsSerializer: params => {
2194
- const searchParams = new URLSearchParams();
2195
- Object.entries(params || {}).forEach(([key, value]) => {
2196
- if (Array.isArray(value)) {
2197
- value.forEach(v => searchParams.append(key, String(v)));
2198
- }
2199
- else if (value !== undefined && value !== null) {
2200
- searchParams.append(key, String(value));
3455
+ const FeatureFlagsContext = createContext(defaultFlags);
3456
+ function FeatureFlagsProvider({ children, flags = {}, }) {
3457
+ const [filterFlag, setFilterFlag] = useState(false);
3458
+ const mergedFlags = {
3459
+ ...defaultFlags,
3460
+ ...flags,
3461
+ filterFlag: flags.filterFlag ?? filterFlag,
3462
+ setFilterFlag: (flag) => {
3463
+ setFilterFlag(flag);
3464
+ if (typeof flags.setFilterFlag === "function") {
3465
+ flags.setFilterFlag(flag);
2201
3466
  }
2202
- });
2203
- return searchParams.toString();
2204
- },
2205
- });
2206
- instance.interceptors.request.use(async (config) => {
2207
- if (!config.headers) {
2208
- config.headers = new AxiosHeaders();
2209
- }
2210
- if (config.data instanceof FormData && config.headers) {
2211
- delete config.headers["Content-Type"];
2212
- }
2213
- if (!isBrowser())
2214
- return config;
2215
- const token = await getAccessToken(false);
2216
- if (token) {
2217
- config.headers.Authorization = `Bearer ${token}`;
2218
- }
2219
- // localStorage first, cookie second.
2220
- //
2221
- // Both are written by the same state machine, but not at the same moment:
2222
- // setOrganizationId writes localStorage synchronously and then awaits a
2223
- // server action for the cookie. Preferring the cookie meant every request
2224
- // fired during that round trip carried the previous organisation — while
2225
- // the query params, built from React state, already carried the new one.
2226
- //
2227
- // The backend scopes by this header and ignores organization_id in the
2228
- // query, so those requests asked for organisation A and were handed B, and
2229
- // the answer landed in the cache under A's key. No amount of cache clearing
2230
- // reaches that: the entry is wrong, not stale.
2231
- const organizationId = getOrganizationId() || getOrgFromCookie();
2232
- if (organizationId) {
2233
- config.headers["X-Organization-ID"] = organizationId;
3467
+ },
3468
+ };
3469
+ return (jsx(FeatureFlagsContext.Provider, { value: mergedFlags, children: children }));
3470
+ }
3471
+ function useFeatureFlags() {
3472
+ const context = useContext(FeatureFlagsContext);
3473
+ if (!context) {
3474
+ throw new Error("useFeatureFlags must be used within a FeatureFlagsProvider");
2234
3475
  }
2235
- const precheck = runGlobalRequestPrecheck(config);
2236
- if (!precheck.valid) {
2237
- throw new ApiError(precheck.message || "Invalid request payload");
3476
+ return context;
3477
+ }
3478
+ function useFeatureFlag(flag) {
3479
+ const flags = useFeatureFlags();
3480
+ return flags[flag];
3481
+ }
3482
+
3483
+ const getAxiosErrorMessage$1 = (error) => {
3484
+ if (error.response?.data?.message) {
3485
+ return error.response.data.message;
2238
3486
  }
2239
- return config;
2240
- });
2241
- let refreshPromise = null;
2242
- const refreshTokenSingleFlight = async () => {
2243
- if (!refreshPromise) {
2244
- refreshPromise = getAccessToken(true).finally(() => {
2245
- refreshPromise = null;
2246
- });
3487
+ if (error.message) {
3488
+ return error.message;
2247
3489
  }
2248
- return refreshPromise;
3490
+ return "An unknown error occurred";
2249
3491
  };
2250
- instance.interceptors.response.use(response => {
2251
- // Any successful call means the session can act in this organisation
2252
- // after all. Without this the gate, once raised, stayed up through a
2253
- // whole working session — including the seconds between an administrator
2254
- // adding somebody and the employee record existing.
2255
- if (typeof window !== "undefined") {
2256
- window.dispatchEvent(new CustomEvent("erp:employee-record-ok"));
2257
- }
2258
- return response;
2259
- }, async (error) => {
2260
- const originalRequest = error.config;
2261
- const requestUrl = originalRequest?.url || error.config?.url;
2262
- if (error.response?.status === 401 &&
2263
- originalRequest &&
2264
- !originalRequest._retry &&
2265
- !isAuthEndpoint(requestUrl) &&
2266
- !isAuthPage()) {
2267
- originalRequest._retry = true;
2268
- const newToken = await refreshTokenSingleFlight();
2269
- if (newToken && originalRequest.headers) {
2270
- originalRequest.headers.Authorization = `Bearer ${newToken}`;
2271
- return instance(originalRequest);
2272
- }
2273
- await redirectToLogout();
2274
- return Promise.reject(toApiError(error));
2275
- }
2276
- // The server refuses every organisation-scoped call when the account has
2277
- // no employee record. Announce it once so a gate can explain it, instead
2278
- // of letting each failed query raise its own toast.
2279
- if (error.response?.status === 403) {
2280
- const body = error.response.data;
2281
- if (body?.code === "EMPLOYEE_RECORD_REQUIRED" && typeof window !== "undefined") {
2282
- window.dispatchEvent(new CustomEvent("erp:employee-record-required"));
2283
- }
3492
+ const formatError = (handlerName, error) => {
3493
+ const axiosError = error;
3494
+ const message = getAxiosErrorMessage$1(axiosError);
3495
+ const isOrgRequired = message.includes("Organization context is required") ||
3496
+ message.includes("organization_id") ||
3497
+ message.includes("X-Organization-ID");
3498
+ if (isOrgRequired) {
3499
+ // Expected when no org selected yet (e.g. select-organization page).
3500
+ console.warn(`[React Query] ${handlerName} skipped (no organization context): ${message}`);
3501
+ return;
2284
3502
  }
2285
- return Promise.reject(toApiError(error));
3503
+ };
3504
+ /**
3505
+ * Default React Query config used across ERP apps:
3506
+ * - 2 retries on queries / 1 on mutations, exponential backoff
3507
+ * - 5 min staleTime, refetchOnWindowFocus
3508
+ * - swallows "no org context" errors to silence noise on the
3509
+ * select-organization page
3510
+ *
3511
+ * Apps can compose on top of this — pass the returned config to `new QueryClient(...)`
3512
+ * directly or spread + override default options.
3513
+ */
3514
+ const getQueryClientConfig = () => ({
3515
+ defaultOptions: {
3516
+ queries: {
3517
+ retry: 2,
3518
+ retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
3519
+ staleTime: 5 * 60 * 1000,
3520
+ refetchOnWindowFocus: true,
3521
+ },
3522
+ mutations: {
3523
+ // NEVER auto-retry a mutation. Unlike a query, a mutation is a side
3524
+ // effect on a non-idempotent endpoint (submit, create, approve), and
3525
+ // React Query cannot tell "the network dropped" from "the server
3526
+ // rejected this on business grounds".
3527
+ //
3528
+ // With retry: 1 every failed mutation fired twice. Two visible
3529
+ // consequences: a rejected submit showed up as two failed POSTs in the
3530
+ // network tab, and — far worse — a create whose response was lost in
3531
+ // flight would be re-sent and duplicate the record server-side.
3532
+ //
3533
+ // Retrying is the caller's decision, not a global default: the user
3534
+ // sees the error and presses the button again.
3535
+ retry: 0,
3536
+ },
3537
+ },
3538
+ queryCache: new QueryCache({
3539
+ onError: error => formatError("Query", error),
3540
+ }),
3541
+ mutationCache: new MutationCache({
3542
+ onError: error => formatError("Mutation", error),
3543
+ }),
2286
3544
  });
2287
3545
 
2288
- const hasPaginationShape = (payload) => {
2289
- return ("total" in payload ||
2290
- "page" in payload ||
2291
- "per_page" in payload ||
2292
- "total_pages" in payload ||
2293
- "has_next" in payload ||
2294
- "has_prev" in payload ||
2295
- "pagination" in payload);
2296
- };
2297
- const isEnvelope = (payload) => {
2298
- return ("success" in payload || "message" in payload) && !hasPaginationShape(payload);
2299
- };
2300
- const unwrapApiResponse = (payload) => {
2301
- if (!payload || typeof payload !== "object") {
2302
- return payload;
3546
+ function ReactQueryProvider({ children }) {
3547
+ // Create a new QueryClient instance for each render to avoid SSR issues.
3548
+ const [queryClient] = useState(() => new QueryClient(getQueryClientConfig()));
3549
+ return (jsxs(QueryClientProvider, { client: queryClient, children: [children, jsx(ReactQueryDevtools, { client: queryClient, initialIsOpen: false })] }));
3550
+ }
3551
+
3552
+ /**
3553
+ * Renders nothing. Runs during render (after SessionProvider, inside
3554
+ * QueryClientProvider) to seed the cached profile slot from the JWT-backed
3555
+ * session — so `useMyProfile` doesn't fire a redundant GET on initial load.
3556
+ *
3557
+ * Generic over the profile shape; each app passes its own queryKey + mapper.
3558
+ */
3559
+ function SessionBackedProfileCacheSeeder({ queryKey, mapper, }) {
3560
+ const { data: session, status } = useSession();
3561
+ const queryClient = useQueryClient();
3562
+ if (status === "authenticated" && session) {
3563
+ const mapped = mapper(session);
3564
+ if (mapped) {
3565
+ const existing = queryClient.getQueryData(queryKey);
3566
+ if (!existing) {
3567
+ // updatedAt: 0 → immediately stale so observers still GET /myprofile
3568
+ // for fields the JWT seed omits (avatar/signature paths).
3569
+ queryClient.setQueryData(queryKey, mapped, { updatedAt: 0 });
3570
+ }
3571
+ else {
3572
+ // Only overwrite when the mapped id changed — we don't know T's shape
3573
+ // so we rely on a shallow id check via JSON tag if present.
3574
+ const existingId = existing?.id;
3575
+ const mappedId = mapped?.id;
3576
+ if (existingId !== mappedId) {
3577
+ queryClient.setQueryData(queryKey, mapped, { updatedAt: 0 });
3578
+ }
3579
+ }
3580
+ }
2303
3581
  }
2304
- const record = payload;
2305
- if ("data" in record &&
2306
- record.data !== undefined &&
2307
- isEnvelope(record)) {
2308
- return record.data;
3582
+ if (status === "unauthenticated") {
3583
+ queryClient.removeQueries({ queryKey });
2309
3584
  }
2310
- return payload;
2311
- };
3585
+ return null;
3586
+ }
2312
3587
 
2313
3588
  // Hooks
2314
3589
  const updateOrganizationId = (organizationId) => {
@@ -2324,5 +3599,5 @@ const getAxiosErrorMessage = (error) => {
2324
3599
  return String(error);
2325
3600
  };
2326
3601
 
2327
- export { AccessDenied, ApiError, AppBreadcrumb, AppLayoutShell, AppSidebar, EMPLOYEE_RECORD_OK_EVENT, EMPLOYEE_RECORD_REQUIRED, EMPLOYEE_RECORD_REQUIRED_EVENT, EmployeeRequiredGate, FeatureFlagsProvider, HeaderBackground, NavMain, NavTools, NavUser, OrganizationSwitcher, PLAN_FEATURES, PermissionGateShell, PermissionProvider, PermissionRulesProvider, ReactQueryProvider, SessionBackedProfileCacheSeeder, SessionRefreshTrigger, SidebarContent, SidebarFooter, SidebarHeader, SidebarHelpCard, SidebarHelpLink, SidebarProvider, SidebarTrigger, TapMenu, ThemeProvider, WORKSPACE_HEADER_VARS, WORKSPACE_LIGHT_HEADER_VARS, WorkspaceBrand, instance as axiosInstance, buildSystemLinks, buildUrlWithCode, canAccessNavPermissionRoute, clearAccessTokenCache, clearOrganizationId, decodeJWT, filterNavigationModulesByPermission, filterNavigationToolsByPermission, getAccessToken, getActiveModule, getActiveSubModule, getAxiosErrorMessage, getOrganizationId, getQueryClientConfig, getRequiredChildGroups, hasPlanFeature, isLikelyTransientNetworkError, isPathActive, normalizePathnameForPermissionRules, resolveUiRoutePermission, runGlobalRequestPrecheck, runWithTransientRetry, setOrganizationId, toApiError, unwrapApiResponse, updateOrganizationId, useClearOrgOnUserChange, useFeatureFlag, useFeatureFlags, useInvalidateQueriesOnOrgChange, useKeycloakRoles, useOrganizationIdState, usePermissionRules, useSessionRefresh, useSidebar, useSidebarToggle };
3602
+ export { AccessDenied, ApiError, AppBreadcrumb, AppLayoutShell, AppSidebar, EMPLOYEE_RECORD_OK_EVENT, EMPLOYEE_RECORD_REQUIRED, EMPLOYEE_RECORD_REQUIRED_EVENT, EmployeeRequiredGate, 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, WORKSPACE_HEADER_VARS, WORKSPACE_LIGHT_HEADER_VARS, WorkspaceBrand, instance as axiosInstance, buildSystemLinks, buildUrlWithCode, canAccessNavPermissionRoute, clearAccessTokenCache, clearOrganizationId, closeHelp, decodeJWT, describeAttached, describeBrowser, detectHelpApp, filterNavigationModulesByPermission, filterNavigationToolsByPermission, getAccessToken, getActiveModule, getActiveSubModule, getAxiosErrorMessage, getOrganizationId, getQueryClientConfig, getRequiredChildGroups, hasPlanFeature, isLikelyTransientNetworkError, isPathActive, myRolesQueryKey, normalizePathnameForPermissionRules, openHelp, parseMyRoles, resolveUiRoutePermission, roleSummary, runGlobalRequestPrecheck, runWithTransientRetry, setOrganizationId, toApiError, unwrapApiResponse, updateOrganizationId, useClearOrgOnUserChange, useFeatureFlag, useFeatureFlags, useInvalidateQueriesOnOrgChange, useKeycloakRoles, useMyRoles, useOrganizationIdState, usePermissionRules, useSessionRefresh, useSidebar, useSidebarToggle };
2328
3603
  //# sourceMappingURL=index.esm.js.map