Skip to content

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

fix: refactor

Sidwebworksa080c61ab65f
diff --git a/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx
index 89576dca78..4f9ef57b79 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx
@@ -557,8 +557,7 @@ function TermsConfig({ block }: { block: TermsBlock }) {
return (
<div className="flex flex-col gap-3">
<p className="text-xs text-muted-foreground">
- Starts from your company's default terms. Edits apply to this document
- only.
+ The terms &amp; conditions printed on this document.
</p>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
diff --git a/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsx b/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsx
index 971206898f..b569dee0b0 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsx
@@ -1,6 +1,6 @@
import { Spinner } from "@carbon/react";
import { useEffect, useRef, useState } from "react";
-import { useDocumentTemplate } from "./context";
+import { useDocumentTemplate, useEditorStore } from "./context";
const PREVIEW_DEBOUNCE_MS = 500;
@@ -17,14 +17,15 @@ export function TemplatePreview({ previewPath }: { previewPath: string }) {
settings,
headerSectionId,
footerSectionId,
- sections,
+ headerConfig,
previewId
} = useDocumentTemplate();
+ const previewNonce = useEditorStore((s) => s.previewNonce);
const [url, setUrl] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const urlRef = useRef<string | null>(null);
- // biome-ignore lint/correctness/useExhaustiveDependencies: `sections` is intentionally a dep so editing a header/footer section re-renders the preview.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `previewNonce` is a manual retrigger — bumped by the toolbar refresh button to re-run the fetch.
useEffect(() => {
const controller = new AbortController();
const handle = setTimeout(async () => {
@@ -36,6 +37,7 @@ export function TemplatePreview({ previewPath }: { previewPath: string }) {
formData.append("settings", JSON.stringify(settings));
formData.append("headerSectionId", headerSectionId ?? "");
formData.append("footerSectionId", footerSectionId ?? "");
+ formData.append("headerConfig", JSON.stringify(headerConfig));
if (previewId) formData.append("previewId", previewId);
const response = await fetch(previewPath, {
method: "post",
@@ -59,17 +61,18 @@ export function TemplatePreview({ previewPath }: { previewPath: string }) {
controller.abort();
clearTimeout(handle);
};
- // `sections` is included so editing a header/footer section (which the
- // preview route resolves server-side) retriggers a fresh render.
+ // `headerConfig` is a dep so logo/header edits (sent in the payload and
+ // applied server-side) retrigger a fresh render without a save round-trip.
}, [
blocks,
theme,
settings,
headerSectionId,
footerSectionId,
- sections,
+ headerConfig,
previewId,
- previewPath
+ previewPath,
+ previewNonce
]);
// Revoke the last object URL on unmount.
diff --git a/apps/erp/app/components/DocumentTemplateEditor/context.tsx b/apps/erp/app/components/DocumentTemplateEditor/context.tsx
index 1b38f2c24b..6719713998 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/context.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/context.tsx
@@ -1,10 +1,12 @@
-import type {
- DocumentBlock,
- DocumentBlockType,
- DocumentSettings,
- DocumentTemplateType,
- DocumentTheme,
- HeaderOptions
+import {
+ BUILT_IN_SECTION_IDS,
+ DEFAULT_HEADER_OPTIONS,
+ type DocumentBlock,
+ type DocumentBlockType,
+ type DocumentSettings,
+ type DocumentTemplateType,
+ type DocumentTheme,
+ type HeaderOptions
} from "@carbon/documents/template";
import type { JSONContent } from "@carbon/react";
import { arrayMove } from "@dnd-kit/sortable";
@@ -16,12 +18,14 @@ import {
useContext,
useEffect,
useMemo,
- useRef,
- useState
+ useRef
} from "react";
import { useFetcher } from "react-router";
+import type { StoreApi } from "zustand";
+import { createStore, useStore } from "zustand";
+import { useShallow } from "zustand/react/shallow";
-type AddableBlockType = Extract<
+export type AddableBlockType = Extract<
DocumentBlockType,
"richText" | "keyValue" | "spacer"
>;
@@ -54,19 +58,24 @@ export interface PreviewEntity {
label: string;
}
-/**
- * Generic editor interface: state + actions + meta. The provider is the only
- * place that knows blocks live in React state and persist via a fetcher;
- * consumers depend on this shape, not the implementation.
- */
-interface DocumentTemplateContextValue {
- // state
- documentType: DocumentTemplateType;
+/** The persisted shape — what `isDirty` compares and what `save` writes. */
+interface EditorSnapshot {
blocks: DocumentBlock[];
theme: DocumentTheme;
settings: DocumentSettings;
headerSectionId: string | null;
footerSectionId: string | null;
+ /**
+ * Live header layout config (logo variant/crop/height, which fields show).
+ * Backed by the company-global header section, but edited inline here and
+ * persisted on Save — not autosaved — so it participates in `isDirty`.
+ */
+ headerConfig: HeaderOptions;
+}
+
+interface EditorState extends EditorSnapshot {
+ // immutable context (from the loader)
+ documentType: DocumentTemplateType;
/** All shared sections available to reference (id, name, placement). */
sections: SectionRef[];
/** Custom fields available to insert as blocks. */
@@ -77,12 +86,19 @@ interface DocumentTemplateContextValue {
previewEntities: PreviewEntity[];
/** Whether the company has a watermark logo set (gates the watermark toggle). */
hasWatermark: boolean;
+ // ui state
+ selectedId: string | null;
/** Selected record id for live-data preview (null = sample data). */
previewId: string | null;
- setPreviewId: (id: string | null) => void;
- selectedId: string | null;
+ /** Bumped to force the preview to re-render on demand (manual refresh). */
+ previewNonce: number;
+ /** Snapshot of the last-saved state; drives `isDirty` and `reset`. */
+ baseline: EditorSnapshot;
// actions
select: (id: string | null) => void;
+ setPreviewId: (id: string | null) => void;
+ /** Force a fresh preview render without changing any template state. */
+ refreshPreview: () => void;
addBlock: (type: AddableBlockType) => void;
addSharedBlock: (sectionId: string) => void;
addCustomFieldBlock: (fieldId: string, label: string) => void;
@@ -99,24 +115,46 @@ interface DocumentTemplateContextValue {
) => void;
setHeaderSection: (sectionId: string | null) => void;
setFooterSection: (sectionId: string | null) => void;
+ setHeaderConfig: (patch: Partial<HeaderOptions>) => void;
reset: () => void;
- save: () => void;
- // meta
- isDirty: boolean;
- isSaving: boolean;
+ /** Mark the current state as saved (clears `isDirty`). */
+ rebaseline: () => void;
}
-const DocumentTemplateContext =
- createContext<DocumentTemplateContextValue | null>(null);
+export interface DocumentTemplateProps {
+ documentType: DocumentTemplateType;
+ actionPath: string;
+ initialBlocks: DocumentBlock[];
+ initialTheme: DocumentTheme;
+ initialSettings: DocumentSettings;
+ initialHeaderSectionId: string | null;
+ initialFooterSectionId: string | null;
+ sections: SectionRef[];
+ customFields: CustomFieldRef[];
+ previewEntities: PreviewEntity[];
+ termsSeed?: JSONContent;
+ hasWatermark: boolean;
+}
-export function useDocumentTemplate() {
- const ctx = useContext(DocumentTemplateContext);
- if (!ctx) {
- throw new Error(
- "useDocumentTemplate must be used within a DocumentTemplateProvider"
- );
- }
- return ctx;
+function snapshot(s: EditorSnapshot): EditorSnapshot {
+ return {
+ blocks: s.blocks,
+ theme: s.theme,
+ settings: s.settings,
+ headerSectionId: s.headerSectionId,
+ footerSectionId: s.footerSectionId,
+ headerConfig: s.headerConfig
+ };
+}
+
+/** Live header config seeded from the referenced header section's stored config. */
+function seedHeaderConfig(
+ sections: SectionRef[],
+ headerSectionId: string | null
+): HeaderOptions {
+ const id = headerSectionId ?? BUILT_IN_SECTION_IDS.header;
+ const stored = sections.find((s) => s.id === id)?.config;
+ return { ...DEFAULT_HEADER_OPTIONS, ...(stored ?? {}) };
}
function createBlock(type: AddableBlockType): DocumentBlock {
@@ -131,275 +169,219 @@ function createBlock(type: AddableBlockType): DocumentBlock {
}
}
-export function DocumentTemplateProvider({
- documentType,
- actionPath,
- initialBlocks,
- initialTheme,
- initialSettings,
- initialHeaderSectionId,
- initialFooterSectionId,
- sections,
- customFields,
- previewEntities,
- termsSeed,
- hasWatermark,
- children
-}: PropsWithChildren<{
- documentType: DocumentTemplateType;
- actionPath: string;
- initialBlocks: DocumentBlock[];
- initialTheme: DocumentTheme;
- initialSettings: DocumentSettings;
- initialHeaderSectionId: string | null;
- initialFooterSectionId: string | null;
- sections: SectionRef[];
- customFields: CustomFieldRef[];
- previewEntities: PreviewEntity[];
- termsSeed?: JSONContent;
- hasWatermark: boolean;
-}>) {
- const fetcher = useFetcher<{ success?: boolean }>();
- const [blocks, setBlocks] = useState<DocumentBlock[]>(initialBlocks);
- const [theme, setTheme] = useState<DocumentTheme>(initialTheme);
- const [settings, setSettings] = useState<DocumentSettings>(initialSettings);
- const [headerSectionId, setHeaderSectionId] = useState<string | null>(
- initialHeaderSectionId
- );
- const [footerSectionId, setFooterSectionId] = useState<string | null>(
- initialFooterSectionId
- );
- const [selectedId, setSelectedId] = useState<string | null>(null);
- const [previewId, setPreviewId] = useState<string | null>(null);
- const submittedRef = useRef(false);
+function createEditorStore(props: DocumentTemplateProps) {
+ const initial: EditorSnapshot = {
+ blocks: props.initialBlocks,
+ theme: props.initialTheme,
+ settings: props.initialSettings,
+ headerSectionId: props.initialHeaderSectionId,
+ footerSectionId: props.initialFooterSectionId,
+ headerConfig: seedHeaderConfig(props.sections, props.initialHeaderSectionId)
+ };
- const isSaving = fetcher.state !== "idle";
+ return createStore<EditorState>((set, get) => ({
+ ...initial,
+ baseline: snapshot(initial),
+ documentType: props.documentType,
+ sections: props.sections,
+ customFields: props.customFields,
+ termsSeed: props.termsSeed,
+ previewEntities: props.previewEntities,
+ hasWatermark: props.hasWatermark,
+ selectedId: null,
+ previewId: null,
+ previewNonce: 0,
- const isDirty = useMemo(
- () =>
- JSON.stringify(blocks) !== JSON.stringify(initialBlocks) ||
- JSON.stringify(theme) !== JSON.stringify(initialTheme) ||
- JSON.stringify(settings) !== JSON.stringify(initialSettings) ||
- headerSectionId !== initialHeaderSectionId ||
- footerSectionId !== initialFooterSectionId,
- [
- blocks,
- theme,
- settings,
- headerSectionId,
- footerSectionId,
- initialBlocks,
- initialTheme,
- initialSettings,
- initialHeaderSectionId,
- initialFooterSectionId
- ]
- );
+ select: (id) => set({ selectedId: id }),
+ setPreviewId: (id) => set({ previewId: id }),
+ refreshPreview: () => set((s) => ({ previewNonce: s.previewNonce + 1 })),
- const addBlock = useCallback((type: AddableBlockType) => {
- const block = createBlock(type);
- setBlocks((prev) => [...prev, block]);
- setSelectedId(block.id);
- }, []);
+ addBlock: (type) => {
+ const block = createBlock(type);
+ set((s) => ({ blocks: [...s.blocks, block], selectedId: block.id }));
+ },
+ addSharedBlock: (sectionId) => {
+ const block: DocumentBlock = {
+ id: nanoid(),
+ type: "shared",
+ visible: true,
+ sectionId
+ };
+ set((s) => ({ blocks: [...s.blocks, block], selectedId: block.id }));
+ },
+ addCustomFieldBlock: (fieldId, label) => {
+ const block: DocumentBlock = {
+ id: nanoid(),
+ type: "customField",
+ visible: true,
+ fieldId,
+ label
+ };
+ set((s) => ({ blocks: [...s.blocks, block], selectedId: block.id }));
+ },
+ addField: (withLabel) => {
+ const block: DocumentBlock = {
+ id: nanoid(),
+ type: "field",
+ visible: true,
+ value: "",
+ ...(withLabel ? { label: "" } : {})
+ };
+ set((s) => ({ blocks: [...s.blocks, block], selectedId: block.id }));
+ },
+ removeBlock: (id) =>
+ set((s) => ({
+ blocks: s.blocks.filter((b) => b.id !== id),
+ selectedId: s.selectedId === id ? null : s.selectedId
+ })),
+ toggleVisible: (id) =>
+ set((s) => ({
+ blocks: s.blocks.map((b) =>
+ b.id === id ? { ...b, visible: !b.visible } : b
+ )
+ })),
+ reorder: (activeId, overId) =>
+ set((s) => {
+ const from = s.blocks.findIndex((b) => b.id === activeId);
+ const to = s.blocks.findIndex((b) => b.id === overId);
+ if (from === -1 || to === -1) return {};
+ return { blocks: arrayMove(s.blocks, from, to) };
+ }),
+ updateBlock: (id, patch) =>
+ set((s) => ({
+ blocks: s.blocks.map((b) =>
+ b.id === id ? ({ ...b, ...patch } as DocumentBlock) : b
+ )
+ })),
+ setThemeColor: (key, value) =>
+ set((s) => ({ theme: { ...s.theme, [key]: value } })),
+ setSetting: (key, value) =>
+ set((s) => ({ settings: { ...s.settings, [key]: value } })),
+ setHeaderSection: (sectionId) => set({ headerSectionId: sectionId }),
+ setFooterSection: (sectionId) => set({ footerSectionId: sectionId }),
+ setHeaderConfig: (patch) =>
+ set((s) => ({ headerConfig: { ...s.headerConfig, ...patch } })),
- const addSharedBlock = useCallback((sectionId: string) => {
- const block: DocumentBlock = {
- id: nanoid(),
- type: "shared",
- visible: true,
- sectionId
- };
- setBlocks((prev) => [...prev, block]);
- setSelectedId(block.id);
- }, []);
+ reset: () => {
+ const { baseline } = get();
+ set({ ...baseline, selectedId: null });
+ },
+ rebaseline: () => set((s) => ({ baseline: snapshot(s) }))
+ }));
+}
- const addCustomFieldBlock = useCallback((fieldId: string, label: string) => {
- const block: DocumentBlock = {
- id: nanoid(),
- type: "customField",
- visible: true,
- fieldId,
- label
- };
- setBlocks((prev) => [...prev, block]);
- setSelectedId(block.id);
- }, []);
+/** True when the editable state diverges from the last-saved baseline. */
+function selectIsDirty(s: EditorState): boolean {
+ return JSON.stringify(snapshot(s)) !== JSON.stringify(s.baseline);
+}
- const addField = useCallback((withLabel: boolean) => {
- const block: DocumentBlock = {
- id: nanoid(),
- type: "field",
- visible: true,
- value: "",
- ...(withLabel ? { label: "" } : {})
- };
- setBlocks((prev) => [...prev, block]);
- setSelectedId(block.id);
- }, []);
+interface EditorContextValue {
+ store: StoreApi<EditorState>;
+ save: () => void;
+ isSaving: boolean;
+}
- const removeBlock = useCallback((id: string) => {
- setBlocks((prev) => prev.filter((b) => b.id !== id));
- setSelectedId((current) => (current === id ? null : current));
- }, []);
+const EditorContext = createContext<EditorContextValue | null>(null);
- const toggleVisible = useCallback((id: string) => {
- setBlocks((prev) =>
- prev.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b))
+function useEditorContext(): EditorContextValue {
+ const ctx = useContext(EditorContext);
+ if (!ctx) {
+ throw new Error(
+ "Document template hooks must be used within a DocumentTemplateProvider"
);
- }, []);
-
- const reorder = useCallback((activeId: string, overId: string) => {
- setBlocks((prev) => {
- const from = prev.findIndex((b) => b.id === activeId);
- const to = prev.findIndex((b) => b.id === overId);
- if (from === -1 || to === -1) return prev;
- return arrayMove(prev, from, to);
- });
- }, []);
-
- const updateBlock = useCallback(
- (id: string, patch: Partial<DocumentBlock>) => {
- setBlocks((prev) =>
- prev.map((b) =>
- b.id === id ? ({ ...b, ...patch } as DocumentBlock) : b
- )
- );
- },
- []
- );
+ }
+ return ctx;
+}
- const setThemeColor = useCallback(
- (key: keyof DocumentTheme, value: string) => {
- setTheme((prev) => ({ ...prev, [key]: value }));
- },
- []
- );
+/** Subscribe to a slice of the editor store (preferred for new code). */
+export function useEditorStore<T>(selector: (s: EditorState) => T): T {
+ return useStore(useEditorContext().store, selector);
+}
- const setSetting = useCallback(
- <K extends keyof DocumentSettings>(key: K, value: DocumentSettings[K]) => {
- setSettings((prev) => ({ ...prev, [key]: value }));
- },
- []
- );
+export function DocumentTemplateProvider({
+ children,
+ ...props
+}: PropsWithChildren<DocumentTemplateProps>) {
+ const storeRef = useRef<StoreApi<EditorState> | null>(null);
+ if (!storeRef.current) storeRef.current = createEditorStore(props);
+ const store = storeRef.current;
- const reset = useCallback(() => {
- setBlocks(initialBlocks);
- setTheme(initialTheme);
- setSettings(initialSettings);
- setHeaderSectionId(initialHeaderSectionId);
- setFooterSectionId(initialFooterSectionId);
- setSelectedId(null);
- }, [
- initialBlocks,
- initialTheme,
- initialSettings,
- initialHeaderSectionId,
- initialFooterSectionId
- ]);
+ const fetcher = useFetcher<{ success?: boolean }>();
+ const isSaving = fetcher.state !== "idle";
+ const savedRef = useRef(false);
const save = useCallback(() => {
+ const s = store.getState();
const formData = new FormData();
- formData.append("documentType", documentType);
- formData.append("blocks", JSON.stringify(blocks));
- formData.append("theme", JSON.stringify(theme));
- formData.append("settings", JSON.stringify(settings));
- formData.append("headerSectionId", headerSectionId ?? "");
- formData.append("footerSectionId", footerSectionId ?? "");
- submittedRef.current = true;
- fetcher.submit(formData, { method: "post", action: actionPath });
- }, [
- actionPath,
- blocks,
- theme,
- settings,
- headerSectionId,
- footerSectionId,
- documentType,
- fetcher
- ]);
+ formData.append("documentType", s.documentType);
+ formData.append("blocks", JSON.stringify(s.blocks));
+ formData.append("theme", JSON.stringify(s.theme));
+ formData.append("settings", JSON.stringify(s.settings));
+ formData.append("headerSectionId", s.headerSectionId ?? "");
+ formData.append("footerSectionId", s.footerSectionId ?? "");
+ formData.append("headerConfig", JSON.stringify(s.headerConfig));
+ savedRef.current = true;
+ fetcher.submit(formData, { method: "post", action: props.actionPath });
+ }, [store, fetcher, props.actionPath]);
- // Clear the dirty baseline once our save resolves: react-router revalidates
- // the loader, so `initialBlocks` updates and isDirty falls back to false.
+ // Once our save resolves, clear the dirty baseline to the just-saved state.
useEffect(() => {
- if (
- submittedRef.current &&
- fetcher.state === "idle" &&
- fetcher.data?.success
- ) {
- submittedRef.current = false;
+ if (savedRef.current && fetcher.state === "idle" && fetcher.data?.success) {
+ savedRef.current = false;
+ store.getState().rebaseline();
}
- }, [fetcher.data, fetcher.state]);
+ }, [fetcher.data, fetcher.state, store]);
- const value = useMemo<DocumentTemplateContextValue>(
- () => ({
- documentType,
- blocks,
- theme,
- settings,
- headerSectionId,
- footerSectionId,
- sections,
- customFields,
- termsSeed,
- previewEntities,
- hasWatermark,
- previewId,
- setPreviewId,
- selectedId,
- select: setSelectedId,
- addBlock,
- addSharedBlock,
- addCustomFieldBlock,
- addField,
- removeBlock,
- toggleVisible,
- reorder,
- updateBlock,
- setThemeColor,
- setSetting,
- setHeaderSection: setHeaderSectionId,
- setFooterSection: setFooterSectionId,
- reset,
- save,
- isDirty,
- isSaving
- }),
- [
- documentType,
- blocks,
- theme,
- settings,
- headerSectionId,
- footerSectionId,
- sections,
- customFields,
- termsSeed,
- previewEntities,
- hasWatermark,
- previewId,
- selectedId,
- addBlock,
- addSharedBlock,
- addCustomFieldBlock,
- addField,
- removeBlock,
- toggleVisible,
- reorder,
- updateBlock,
- setThemeColor,
- setSetting,
- reset,
- save,
- isDirty,
- isSaving
- ]
+ const value = useMemo(
+ () => ({ store, save, isSaving }),
+ [store, save, isSaving]
);
return (
- <DocumentTemplateContext.Provider value={value}>
- {children}
- </DocumentTemplateContext.Provider>
+ <EditorContext.Provider value={value}>{children}</EditorContext.Provider>
);
}
-export type { AddableBlockType };
+/**
+ * Back-compat accessor returning the full editor API in one object. New code
+ * should prefer `useEditorStore(selector)` to subscribe to a narrow slice.
+ */
+export function useDocumentTemplate() {
+ const { save, isSaving } = useEditorContext();
+ const state = useEditorStore(
+ useShallow((s) => ({
+ documentType: s.documentType,
+ blocks: s.blocks,
+ theme: s.theme,
+ settings: s.settings,
+ headerSectionId: s.headerSectionId,
+ footerSectionId: s.footerSectionId,
+ headerConfig: s.headerConfig,
+ sections: s.sections,
+ customFields: s.customFields,
+ termsSeed: s.termsSeed,
+ previewEntities: s.previewEntities,
+ hasWatermark: s.hasWatermark,
+ previewId: s.previewId,
+ selectedId: s.selectedId,
+ select: s.select,
+ setPreviewId: s.setPreviewId,
+ addBlock: s.addBlock,
+ addSharedBlock: s.addSharedBlock,
+ addCustomFieldBlock: s.addCustomFieldBlock,
+ addField: s.addField,
+ removeBlock: s.removeBlock,
+ toggleVisible: s.toggleVisible,
+ reorder: s.reorder,
+ updateBlock: s.updateBlock,
+ setThemeColor: s.setThemeColor,
+ setSetting: s.setSetting,
+ setHeaderSection: s.setHeaderSection,
+ setFooterSection: s.setFooterSection,
+ setHeaderConfig: s.setHeaderConfig,
+ reset: s.reset,
+ isDirty: selectIsDirty(s)
+ }))
+ );
+ return { ...state, save, isSaving };
+}
diff --git a/apps/erp/app/components/DocumentTemplateEditor/index.tsx b/apps/erp/app/components/DocumentTemplateEditor/index.tsx
index c114baaa27..a31e1778e7 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/index.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/index.tsx
@@ -10,6 +10,7 @@ import {
Button,
Combobox,
Heading,
+ IconButton,
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
@@ -20,16 +21,21 @@ import {
TabsTrigger
} from "@carbon/react";
import { type ReactNode, useState } from "react";
-import { LuArrowLeft, LuPalette } from "react-icons/lu";
+import { LuArrowLeft, LuPalette, LuRefreshCw } from "react-icons/lu";
import { Link } from "react-router";
import { path } from "~/utils/path";
import { BlockConfig } from "./BlockConfig";
import { BlockList } from "./BlockList";
import type { CustomFieldRef, PreviewEntity, SectionRef } from "./context";
-import { DocumentTemplateProvider, useDocumentTemplate } from "./context";
+import {
+ DocumentTemplateProvider,
+ useDocumentTemplate,
+ useEditorStore
+} from "./context";
import { FontConfig } from "./FontConfig";
import { TemplatePreview } from "./TemplatePreview";
import { ThemeConfig } from "./ThemeConfig";
+import { useTemplateConflict } from "./useTemplateConflict";
export function DocumentTemplateEditor({
documentType,
@@ -80,6 +86,7 @@ export function DocumentTemplateEditor({
title={getDocumentLabel(documentType)}
canEdit={canEdit}
/>
+ <ConflictBanner documentType={documentType} />
<ResizablePanelGroup
direction="horizontal"
autoSaveId="document-template-editor"
@@ -138,6 +145,10 @@ const RAIL_HEADING =
*/
function ControlRail() {
const [tab, setTab] = useState<"style">("style");
+ // Labels render on monochrome thermal stock — theme colors don't apply.
+ const showThemeColors = useEditorStore(
+ (s) => s.documentType !== "trackingLabel"
+ );
return (
<ScrollArea className="h-full bg-card">
@@ -160,10 +171,12 @@ function ControlRail() {
<h3 className={RAIL_HEADING}>Typography</h3>
<FontConfig />
</section>
- <section className="flex flex-col gap-2">
- <h3 className={RAIL_HEADING}>Theme colors</h3>
- <ThemeConfig />
- </section>
+ {showThemeColors && (
+ <section className="flex flex-col gap-2">
+ <h3 className={RAIL_HEADING}>Theme colors</h3>
+ <ThemeConfig />
+ </section>
+ )}
</TabsContent>
</Tabs>
</div>
@@ -192,6 +205,37 @@ function UnderlineTab({
);
}
+/**
+ * Realtime warning shown when another user saves this template while it's open.
+ * The editor never auto-reloads (that would discard in-progress edits) — the
+ * user chooses to refresh to their version or keep editing (overwrite on save).
+ */
+function ConflictBanner({
+ documentType
+}: {
+ documentType: DocumentTemplateType;
+}) {
+ const { conflict, dismiss } = useTemplateConflict(documentType);
+ if (!conflict) return null;
+
+ return (
+ <div className="flex items-center justify-between gap-3 border-b border-amber-500/40 bg-amber-500/10 px-4 py-2">
+ <p className="text-sm text-amber-700 dark:text-amber-400">
+ Someone else just saved this template. Refresh to load their version, or
+ keep editing to overwrite it when you save.
+ </p>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button variant="secondary" size="sm" onClick={dismiss}>
+ Keep mine
+ </Button>
+ <Button size="sm" onClick={() => window.location.reload()}>
+ Refresh
+ </Button>
+ </div>
+ </div>
+ );
+}
+
function EditorToolbar({
title,
canEdit
@@ -208,6 +252,7 @@ function EditorToolbar({
previewId,
setPreviewId
} = useDocumentTemplate();
+ const refreshPreview = useEditorStore((s) => s.refreshPreview);
return (
<div className="flex items-center justify-between gap-3 border-b bg-card px-4 py-3">
@@ -241,6 +286,12 @@ function EditorToolbar({
)}
{canEdit && (
<div className="flex items-center gap-2">
+ <IconButton
+ aria-label="Refresh preview"
+ variant="secondary"
+ icon={<LuRefreshCw />}
+ onClick={refreshPreview}
+ />
<Button
variant="secondary"
onClick={reset}
diff --git a/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsx b/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsx
index 22011389ec..dd27221ef5 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsx
@@ -15,7 +15,6 @@ import {
SelectTrigger,
SelectValue
} from "@carbon/react";
-import { useEffect, useState } from "react";
import { useUser } from "~/hooks";
import { ToggleRow } from "./configHelpers";
import { useDocumentTemplate } from "./context";
@@ -138,28 +137,13 @@ export function LabelBarcodeConfig({ block }: { block: LabelBarcodeBlock }) {
}
/**
- * The document header logo, edited inline (no dialog). Local draft for snappy
- * UI; persists to the header section (debounced) so the crop drag doesn't spam
- * the server. The preview refreshes once the section save revalidates.
+ * The document header logo, edited inline (no dialog). Edits live in the editor
+ * store (`headerConfig`), so the preview reflects them instantly and they
+ * persist with the template on Save.
*/
export function HeaderLogoConfig() {
const { company } = useUser();
- const { section, config, submit } = useHeaderConfig();
- const [draft, setDraft] = useState(config);
-
- // Re-seed when the persisted config changes (revalidation / external edit).
- // biome-ignore lint/correctness/useExhaustiveDependencies: seed on server value only
- useEffect(() => {
- setDraft(config);
- }, [JSON.stringify(config)]);
-
- // Debounced persist — only when the draft actually diverges from the server
- // value, so re-seeding after a save can't loop back into another submit.
- useEffect(() => {
- if (JSON.stringify(draft) === JSON.stringify(config)) return;
- const t = setTimeout(() => submit(draft), 400);
- return () => clearTimeout(t);
- }, [draft, config, submit]);
+ const { section, config, patch } = useHeaderConfig();
if (!section) {
return (
@@ -169,17 +153,15 @@ export function HeaderLogoConfig() {
);
}
- const variant = draft.logoVariant ?? "mark";
+ const variant = config.logoVariant ?? "mark";
const src =
variant === "icon"
? (company?.logoLightIcon ?? company?.logoLight)
: (company?.logoLight ?? company?.logoLightIcon);
- const set = (patch: Partial<typeof draft>) =>
- setDraft((prev) => ({ ...prev, ...patch }));
return (
<div className="flex flex-col gap-3">
- {!draft.showLogo && (
+ {!config.showLogo && (
<p className="text-xs text-muted-foreground">
Logo is hidden — turn it on with the eye toggle in the list.
</p>
@@ -190,8 +172,8 @@ export function HeaderLogoConfig() {
value={variant}
onValueChange={(value) =>
// Switching source invalidates the crop aspect.
- set({
- logoVariant: value as typeof draft.logoVariant,
+ patch({
+ logoVariant: value as typeof config.logoVariant,
logoCrop: undefined
})
}
@@ -208,8 +190,8 @@ export function HeaderLogoConfig() {
{src ? (
<LogoCropper
src={src}
- crop={draft.logoCrop}
- onChange={(crop) => set({ logoCrop: crop })}
+ crop={config.logoCrop}
+ onChange={(crop) => patch({ logoCrop: crop })}
/>
) : (
<p className="text-xs text-muted-foreground">
@@ -220,8 +202,8 @@ export function HeaderLogoConfig() {
label="Height (pt)"
minValue={16}
maxValue={120}
- value={draft.logoHeight ?? DEFAULT_HEADER_OPTIONS.logoHeight}
- onChange={(v) => set({ logoHeight: v })}
+ value={config.logoHeight ?? DEFAULT_HEADER_OPTIONS.logoHeight}
+ onChange={(v) => patch({ logoHeight: v })}
/>
</div>
);
diff --git a/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsx
index 3e2d7ee56f..b453771b13 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsx
@@ -1,57 +1,33 @@
import {
BUILT_IN_SECTION_IDS,
- DEFAULT_HEADER_OPTIONS,
type HeaderOptions
} from "@carbon/documents/template";
-import { useCallback, useMemo } from "react";
-import { useFetcher } from "react-router";
-import { path } from "~/utils/path";
-import { useDocumentTemplate } from "./context";
+import { useCallback } from "react";
+import { useEditorStore } from "./context";
/** Synthetic selection id for the header's Logo child node in the block tree. */
export const HEADER_LOGO_ID = "__header_logo__";
/**
- * Read + persist the document header's layout config (logo + which fields
- * show). The header is a global shared section, so its config is saved through
- * the `documentSections` action (same as the edit dialog) — the loader then
- * revalidates and the preview re-renders. `patch` merges into the current
- * config so independent fields (logo vs. address toggles) don't clobber.
+ * Read + edit the document header's layout config (logo + which fields show).
+ * The config is live editor state (see the store's `headerConfig`); it persists
+ * with the rest of the template on Save, so edits show in the preview instantly
+ * and mark the template dirty. `section` resolves the referenced header section
+ * (for its name / existence check).
*/
export function useHeaderConfig() {
- const { sections } = useDocumentTemplate();
- const fetcher = useFetcher();
- const section = sections.find((s) => s.id === BUILT_IN_SECTION_IDS.header);
- const config = useMemo<HeaderOptions>(
- () => ({ ...DEFAULT_HEADER_OPTIONS, ...(section?.config ?? {}) }),
- [section?.config]
+ const section = useEditorStore((s) =>
+ s.sections.find(
+ (x) => x.id === (s.headerSectionId ?? BUILT_IN_SECTION_IDS.header)
+ )
);
+ const config = useEditorStore((s) => s.headerConfig);
+ const setHeaderConfig = useEditorStore((s) => s.setHeaderConfig);
- const submit = useCallback(
- (next: HeaderOptions) => {
- if (!section) return;
- const data = new FormData();
- if (section.id) data.set("id", section.id);
- data.set("name", section.name);
- data.set("placement", section.placement);
- data.set(
- "content",
- JSON.stringify(section.content ?? { type: "doc", content: [] })
- );
- data.set("config", JSON.stringify(next));
- fetcher.submit(data, {
- method: "post",
- action: path.to.documentSections
- });
- },
- [section, fetcher]
- );
-
- /** Merge a partial change into the current config and persist (one-shot). */
const patch = useCallback(
- (partial: Partial<HeaderOptions>) => submit({ ...config, ...partial }),
- [submit, config]
+ (partial: Partial<HeaderOptions>) => setHeaderConfig(partial),
+ [setHeaderConfig]
);
- return { section, config, submit, patch };
+ return { section, config, patch };
}
diff --git a/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsx b/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsx
new file mode 100644
index 0000000000..dc76115f93
--- /dev/null
+++ b/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsx
@@ -0,0 +1,45 @@
+import { useRealtimeChannel } from "@carbon/react";
+import { useState } from "react";
+import { useUser } from "~/hooks";
+
+/**
+ * Watches the company's `documentTemplate` rows over realtime and flags when
+ * *another* user saves the template currently open in the editor. Own writes
+ * (matched by `updatedBy`) are ignored, so saving here — or editing in another
+ * of your own tabs — never raises a false conflict.
+ *
+ * The editor does not auto-revalidate on the event (that would silently discard
+ * in-progress edits); it surfaces a banner letting the user refresh or keep
+ * their version.
+ */
+export function useTemplateConflict(documentType: string) {
+ const { id: userId, company } = useUser();
+ const [conflict, setConflict] = useState(false);
+
+ useRealtimeChannel({
+ topic: `document-template-conflict:${documentType}`,
+ dependencies: [company.id, documentType, userId],
+ setup(channel) {
+ return channel.on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "documentTemplate",
+ filter: `companyId=eq.${company.id}`
+ },
+ (payload) => {
+ const row = payload.new as
+ | { documentType?: string; updatedBy?: string }
+ | undefined;
+ // Only this template, and only someone else's write.
+ if (!row || row.documentType !== documentType) return;
+ if (!row.updatedBy || row.updatedBy === userId) return;
+ setConflict(true);
+ }
+ );
+ }
+ });
+
+ return { conflict, dismiss: () => setConflict(false) };
+}
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 678dac7e93..012a5d3a58 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -367,7 +367,13 @@ export const documentTemplateValidator = zfd.formData({
theme: jsonField(themeSchema, "Invalid document theme"),
settings: jsonField(documentSettingsSchema, "Invalid document settings"),
headerSectionId: zfd.text(z.string().optional()),
- footerSectionId: zfd.text(z.string().optional())
+ footerSectionId: zfd.text(z.string().optional()),
+ // Header layout config (logo) is edited inline and saved with the template;
+ // the action upserts it onto the referenced header section.
+ headerConfig: jsonField(
+ sectionConfigSchema,
+ "Invalid header config"
+ ).optional()
});
export const documentSectionValidator = zfd.formData({
diff --git a/apps/erp/app/routes/x+/templates+/$type.preview.tsx b/apps/erp/app/routes/x+/templates+/$type.preview.tsx
index f3fed96ffc..d088bfcc32 100644
--- a/apps/erp/app/routes/x+/templates+/$type.preview.tsx
+++ b/apps/erp/app/routes/x+/templates+/$type.preview.tsx
@@ -7,6 +7,7 @@ import {
DEFAULT_DOCUMENT_SETTINGS,
documentSettingsSchema,
documentTemplateTypeSchema,
+ sectionConfigSchema,
themeSchema
} from "@carbon/documents/template";
import { getPreferenceHeaders } from "@carbon/react";
@@ -58,6 +59,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
collectSectionIds({ blocks: parsed.data, headerSectionId, footerSectionId })
);
+ // Apply the live (unsaved) header config draft so logo/header edits show in
+ // the preview instantly, without waiting for a Save + revalidation.
+ const headerConfig = sectionConfigSchema.safeParse(
+ JSON.parse(String(formData.get("headerConfig") ?? "{}"))
+ );
+ if (headerConfig.success && headerSectionId && sections[headerSectionId]) {
+ sections[headerSectionId] = {
+ ...sections[headerSectionId],
+ config: {
+ ...sections[headerSectionId].config,
+ ...headerConfig.data
+ }
+ };
+ }
+
const { locale } = getPreferenceHeaders(request);
await ensureFont(settings.fontFamily);
diff --git a/apps/erp/app/routes/x+/templates+/$type.tsx b/apps/erp/app/routes/x+/templates+/$type.tsx
index 0e94e7ce3c..1fa1bb5700 100644
--- a/apps/erp/app/routes/x+/templates+/$type.tsx
+++ b/apps/erp/app/routes/x+/templates+/$type.tsx
@@ -24,6 +24,8 @@ import {
getDocumentSections,
getDocumentTemplate,
getTerms,
+ resolveSections,
+ upsertDocumentSection,
upsertDocumentTemplate
} from "~/modules/settings";
import { listPreviewEntities } from "~/modules/settings/documentPreview.server";
@@ -142,9 +144,36 @@ export async function action({ request }: ActionFunctionArgs) {
theme,
settings,
headerSectionId,
- footerSectionId
+ footerSectionId,
+ headerConfig
} = validation.data;
+ // The logo/header layout is edited inline but lives on the (company-global)
+ // header section. Persist it onto that section first, preserving its current
+ // name/content, so the change applies wherever the header is referenced.
+ if (headerConfig && headerSectionId) {
+ const resolved = await resolveSections(client, companyId, [
+ headerSectionId
+ ]);
+ const header = resolved[headerSectionId];
+ const section = await upsertDocumentSection(client, {
+ id: headerSectionId,
+ companyId,
+ name: header?.name ?? "Default Header",
+ placement: "header",
+ content: (header?.content ?? { type: "doc", content: [] }) as JSONContent,
+ config: headerConfig as Record<string, unknown>,
+ createdBy: userId,
+ updatedBy: userId
+ });
+ if (section.error) {
+ return data(
+ { success: false },
+ await flash(request, error(section.error, "Failed to save header"))
+ );
+ }
+ }
+
const upsert = await upsertDocumentTemplate(client, {
companyId,
documentType,
diff --git a/packages/database/supabase/migrations/20260612174839_document-template-realtime.sql b/packages/database/supabase/migrations/20260612174839_document-template-realtime.sql
new file mode 100644
index 0000000000..c2c2e5a000
--- /dev/null
+++ b/packages/database/supabase/migrations/20260612174839_document-template-realtime.sql
@@ -0,0 +1,5 @@
+-- Surface documentTemplate writes over realtime so the layout editor can warn
+-- when another user saves the same template while you're editing it. Default
+-- replica identity (primary key) is enough — the editor only reads the new
+-- row's documentType/updatedBy from the payload.
+ALTER PUBLICATION supabase_realtime ADD TABLE "documentTemplate";