Skip to content

Examples

Generated Resource frontend

Follow real generated list, record, query, contract, and discovery code.

Example type Recipe

Overview

Generated Resource frontend

These files show the actual output of the App and Resource generators for a Legal Entity-owned Note. They use public SDK host components, tenant-specific query keys, authorized organization targets, loading/error states, and explicit read/create/edit behavior. They are a connected example, not independent drop-in files: the generated backend, manifest, routes, translations, and other App files are required.

Generate a fresh copy with the installed nexia CLI and current compatible devtools. The exact emitted code can change by version; check the installed SDK and host compatibility before adapting it.

Code example
Shell
nexia create app reference-example --name ReferenceExample --vendor sample --family other --key reference-example
cd reference-example
nexia make resource Note --label-ko '노트' --record-owner legal_entity
nexia check

Read index.ts for discovery, the Resource contract for identifiers and routes, the query module for requests and cache keys, ListSurface for permission and list scope, and RecordSurface for read/create/edit, forms and Inspector. Replace example domain behavior with your own while retaining server authorization. See Build an App screen and Test an App.

Included files

Frontend discovery

docs/developers/examples/generated-frontend/index.ts
Code example
TypeScript
import {
    autoRegisterPackageResourceInspectors,
    autoRegisterPackageSurfaces,
} from '@nexia/sdk/host';

const resourceContractModules = import.meta.glob('./resources/*/*-resource-contract.ts', { eager: true });

autoRegisterPackageResourceInspectors(
    import.meta.glob('./resources/*/inspector/register-*-inspector.ts', { eager: true }),
    resourceContractModules,
);

autoRegisterPackageSurfaces({
    appPrefix: 'ReferenceExample',
    appKey: 'reference-example',
    overview: () => import('./overview/ReferenceExampleOverviewSurface'),
    surfaces: import.meta.glob('./resources/*/surface/*Surface.tsx'),
    resourceContracts: Object.fromEntries(
        Object.entries(resourceContractModules).map(([path, module]) => [path, async () => module]),
    ),
    overrides: {
        'ReferenceExampleWorkSummarySurface': () => import('./pages/WorkSummarySurface'),
            'ReferenceExampleWorkSummaryReadSurface': { load: () => import('./pages/WorkSummaryRecordSurface'), mode: 'read' },
            'ReferenceExampleWorkSummaryEditSurface': { load: () => import('./pages/WorkSummaryRecordSurface'), mode: 'edit' },
            // nexia:pages:end
    },
});

Resource contract

docs/developers/examples/generated-frontend/note-resource-contract.ts
Code example
TypeScript
import type { useTranslation } from 'react-i18next';
import type {
    ResourceActionDescriptor,
    ResourceRef,
} from '@nexia/sdk';

export interface NoteRecord {
    id: string;
    public_id: string;
    /** Present for Legal Entity-owned records; derived from the stored owner. */
    legal_entity_public_id?: string | null;
    legal_entity_label?: string | null;
    name: string;
    created_at: string | null;
    updated_at: string | null;
    actions: ResourceActionDecisions;
}

/** Editable business fields shared by the form and mutation. */
export interface NoteInput {
    name: string;
}

export interface ResourceActionDecisions {
    view: boolean;
    update: boolean;
    delete: boolean;
}

export const noteResourceType = 'reference-example.note';

export const notePermissions = {
    read: 'reference-example.note.read',
    create: 'reference-example.note.create',
    update: 'reference-example.note.update',
    delete: 'reference-example.note.delete',
} as const;

interface NoteActionCallbacks {
    /** Deprecated route callbacks; generated actions use canonical hrefs. */
    onView?: () => void;
    onEdit?: () => void;
    onDelete?: () => void;
    deleteDisabled?: boolean;
    testIdPrefix?: string;
}

type NoteActionTranslator = ReturnType<
    typeof useTranslation
>['t'];

/** One action contract shared by row menus and the Inspector. */
export function noteResourceActions(
    note: NoteRecord,
    t: NoteActionTranslator,
    callbacks: NoteActionCallbacks,
): ResourceActionDescriptor[] {
    const testId = (id: string) =>
        callbacks.testIdPrefix
            ? `${callbacks.testIdPrefix}-${id}`
            : undefined;

    return [
        ...(note.actions.view
            ? [{
                  id: 'show',
                  label: t('common.actions.view'),
                  permissions: [notePermissions.read],
                  testId: testId('show'),
                  href: noteShowRoute(noteResourceId(note)),
              }]
            : []),
        ...(note.actions.update
            ? [{
                  id: 'edit',
                  label: t('common.actions.edit'),
                  permissions: [notePermissions.update],
                  testId: testId('edit'),
                  href: noteEditRoute(noteResourceId(note)),
              }]
            : []),
        ...(note.actions.delete
            ? [{
                  id: 'delete',
                  label: t('common.actions.delete'),
                  permissions: [notePermissions.delete],
                  destructive: true,
                  disabled: callbacks.deleteDisabled,
                  testId: testId('delete'),
                  onSelect: callbacks.onDelete,
              }]
            : []),
    ];
}

export function noteApiRoute(
    id?: string | number | null,
    legalEntityId?: string | null,
) {
    // Canonical resource endpoints carry no Shell Legal Entity state. List and
    // create targets are request-owned; record endpoints derive the owner.
    void legalEntityId;
    const base = '/reference-example/notes';

    return id ? `${base}/${id}` : base;
}

export function noteListRoute() {
    return '/apps/reference-example/notes';
}

export function noteShowRoute(id: string | number) {
    return `/apps/reference-example/notes/${id}`;
}

export function noteCreateRoute() {
    return '/apps/reference-example/notes/new';
}

export function noteEditRoute(id: string | number) {
    return `/apps/reference-example/notes/${id}/edit`;
}

export function noteRoute(id?: string | number | null) {
    return id ? noteShowRoute(id) : noteListRoute();
}

export function noteResourceId(
    note: Pick<NoteRecord, 'id' | 'public_id'>,
) {
    return String(note.public_id ?? note.id);
}

export function noteResourceRef(
    note: NoteRecord,
): ResourceRef<NoteRecord> {
    const id = noteResourceId(note);

    return {
        type: noteResourceType,
        id,
        label: note.name,
        ...(note.actions.view
            ? { route: noteShowRoute(id) }
            : {}),
        data: note,
    };
}

/** Metadata loads with the App; the Inspector implementation stays lazy. */
export const resourceInspector = {
    type: noteResourceType,
    load: () => import('./surface/NoteRecordSurface').then(module => ({
        default: module.NoteInspector,
    })),
};

Requests and cache keys

docs/developers/examples/generated-frontend/note-queries.ts
Code example
TypeScript
import { queryOptions, useMutation, useQueryClient } from '@tanstack/react-query';
import type { ResourceListParams, ResourceListSchema, ResourceTransferMeta } from '@nexia/sdk';
import { api, serializeResourceTableSort } from '@nexia/sdk/host';
import { noteApiRoute, type NoteRecord } from './note-resource-contract.ts';

export interface NoteDetailResponse {
    note: NoteRecord;
}

export function noteDetailQueryOptions(
    tenantId: string,
    id: string,
) {
    const resourceContextId = tenantId;

    return queryOptions({
        queryKey: [
            'reference-example-note',
            tenantId,
            resourceContextId,
            id,
        ],
        queryFn: async ({ signal }) => {
            const { data } = await api.get<NoteDetailResponse>(
                noteApiRoute(id),
                { signal },
            );
            return data;
        },
    });
}

interface NoteListResponse {
    data: NoteRecord[];
    meta: {
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        list_schema: ResourceListSchema;
        actions: {
            create: boolean;
        };
        resource_transfer?: ResourceTransferMeta | null;
    };
}

export function noteListQueryScope(
    tenantId: string,
    resourceContextId: string | number | null,
) {
    return [
        'reference-example-notes',
        tenantId,
        resourceContextId,
    ] as const;
}

export async function fetchNoteList(
    legalEntityPublicIds: readonly string[],
    listParams: ResourceListParams,
    signal?: AbortSignal,
): Promise<NoteListResponse> {
    const params: Record<string, string | number | string[]> = {};
    if (listParams.search) params.search = listParams.search;
    if (listParams.sort)
        params.sort = serializeResourceTableSort(listParams.sort);
    if (listParams.page && listParams.page > 1)
        params.page = listParams.page;
    if (listParams.perPage) params.per_page = listParams.perPage;
    for (const [key, value] of Object.entries(listParams.filters)) {
        if (Array.isArray(value)) {
            if (value.length > 0) params[`filter[${key}]`] = value;
        } else if (value !== '' && value !== undefined) {
            params[`filter[${key}]`] = value;
        }
    }
    if (legalEntityPublicIds.length > 0) {
        params['legal_entity_public_ids[]'] = [...legalEntityPublicIds];
    }
    const { data } = await api.get<NoteListResponse>(
        noteApiRoute(),
        { params, signal },
    );
    return data;
}

export function noteListQueryOptions(
    tenantId: string,
    legalEntityPublicIds: readonly string[],
    listParams: ResourceListParams,
) {
    const resourceContextId = true ? legalEntityPublicIds.join(',') : tenantId;

    return queryOptions({
        queryKey: [
            ...noteListQueryScope(tenantId, resourceContextId),
            listParams,
        ],
        queryFn: ({ signal }) =>
            fetchNoteList(
                legalEntityPublicIds,
                listParams,
                signal,
            ),
    });
}


/** Shared deletion and cache ownership for list and record Inspectors. */
export function useNoteDelete(tenantId: string) {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (id: string) => {
            await api.delete(noteApiRoute(id));
        },
        onSuccess: (_data, deletedId) => {
            queryClient.removeQueries({
                queryKey: noteDetailQueryOptions(tenantId, deletedId).queryKey,
                exact: true,
            });
            void queryClient.invalidateQueries({ queryKey: ['reference-example-notes', tenantId] });
        },
    });
}

List surface

docs/developers/examples/generated-frontend/NoteListSurface.tsx
Code example
TSX
import { useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
    isHttpError,
    type ResourceRef,
    type ResourceListParams,
    type AppRoutePrefetchContext,
    type ResourceTableColumn,
} from '@nexia/sdk';
import {
    ResourceTable,
    ResourcePrimaryCell,
    ResourceRowActionsMenu,
    ResourceTextCell,
    ResourceInspectorStackHost,
    ResourceInspectorStackProvider,
    keepPreviousResourceListData,
    useResourceListParams,
    WorkSurface,
    WorkSection,
    useContextQuery,
    usePermissionsQuery,
    api,
    can,
    useMessage,
    useWorkSurfaceLabels,
    useOpenResourceWorkTab,
    useRegisterListLocateAction,
    NxButton,
    NxPageFrame,
    NxEmptyView,
    NxActionButton,
    NxSearchField,
} from '@nexia/sdk/host';
import { NxOrganizationTargetSelector, useOrganizationTargetsQuery, useOrganizationListScope } from '@nexia/sdk/host';
import {
    type NoteRecord,
    noteApiRoute,
    noteCreateRoute,
    noteShowRoute,
    noteEditRoute,
    notePermissions,
    noteResourceActions,
    noteResourceId,
    noteResourceRef,
} from '#app/resources/notes/note-resource-contract.ts';
import { useNoteDelete, noteDetailQueryOptions, fetchNoteList, noteListQueryScope, noteListQueryOptions } from '#app/resources/notes/note-queries.ts';

export function prefetch(context: AppRoutePrefetchContext): void {
    // Target availability is page-owned, never inferred from Shell state.
    void context;
}

export default function NoteListSurface() {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const [selectedId, setSelectedId] = useState<string | null>(null);
    const queryClient = useQueryClient();

    const { data: context, isPending: contextPending, isError: contextError, error: contextFailure, refetch: refetchContext } = useContextQuery();
    const tenantId = context?.tenant?.id;
    const organizationScope = useOrganizationListScope(
        tenantId,
        notePermissions.read,
        'legal-entity-list',
        true,
    );
    const { data: permissionData, isPending: permissionsPending, isError: permissionsError, error: permissionsFailure, refetch: refetchPermissions } = usePermissionsQuery(
        tenantId,
        null,
    );
    const permissions = permissionData?.permissions ?? [];
    const createTargets = useOrganizationTargetsQuery(
        tenantId,
        notePermissions.create,
        {},
        true && !!tenantId,
    );
    const creatableLegalEntityPublicIds = useMemo(() => (createTargets.data?.data ?? [])
        .filter((target) => target.operating_unit === null)
        .map((target) => target.legal_entity.public_id), [createTargets.data]);
    const legalEntityPublicIds = organizationScope.query.legalEntityPublicIds ?? [];
    const canRead = true
        ? organizationScope.canRead
        : can(permissions, notePermissions.read);
    const canCreateFallback = true
        ? !createTargets.isPending && !createTargets.isError && creatableLegalEntityPublicIds.length > 0
        : can(permissions, notePermissions.create);
    const resourceContextId = true ? legalEntityPublicIds.join(',') : tenantId ?? null;
    const { confirm } = useMessage();

    const {
        search,
        setSearch,
        sort,
        setSort,
        filters,
        setFilters,
        setParams,
        page,
        setPage,
        perPage,
        setPerPage,
    } = useResourceListParams();

    const listQueryScope = noteListQueryScope(
        tenantId ?? '',
        resourceContextId,
    );
    const listParams = { search, sort, filters, page, perPage };

    const fetchList = useCallback(
        (params: ResourceListParams, signal?: AbortSignal) => {
            if (!canRead || (true && organizationScope.requestParams === undefined)) {
                throw new Error('Organization scope is not readable.');
            }
            return fetchNoteList(legalEntityPublicIds, params, signal);
        },
        [canRead, legalEntityPublicIds, organizationScope.requestParams],
    );

    const {
        data: list,
        isLoading,
        isFetching,
        isError,
        error: listFailure,
        refetch,
    } = useQuery({
        ...noteListQueryOptions(
            tenantId ?? '',
            legalEntityPublicIds,
            listParams,
        ),
        placeholderData: keepPreviousResourceListData(listQueryScope),
        queryFn: ({ signal }) => fetchList(listParams, signal),
        enabled: !!tenantId && canRead && (!true || organizationScope.requestParams !== undefined),
    });
    const deleteResource = useNoteDelete(tenantId ?? '');

    const accessPending = !contextError && (contextPending || (!!tenantId && (true ? organizationScope.isLoading : permissionsPending)));
    const listError = contextError || (true ? organizationScope.isError : permissionsError) || isError;
    const failure = contextError ? contextFailure
        : true && organizationScope.isError ? organizationScope.targets.error
        : !true && permissionsError ? permissionsFailure : listFailure;
    const failureStatus = isHttpError(failure) ? failure.response?.status : undefined;
    const listReadable = !!tenantId && canRead && !accessPending && !listError;
    const rows = listReadable ? list?.data ?? [] : [];
    const meta = listReadable ? list?.meta : undefined;
    const canCreate = (listReadable || (!!tenantId && !canRead && !accessPending && !listError))
        && (meta?.actions.create ?? canCreateFallback);
    const labels = useWorkSurfaceLabels({
        action: 'list',
        resourceLabel: t('reference-example.note.list.title'),
    });

    useRegisterListLocateAction<NoteRecord>({
        actionType: 'reference-example.note.locate',
        label: t('reference-example.note.agent.locate.label'),
        description: t('reference-example.note.agent.locate.description'),
        enabled: listReadable,
        schema: meta?.list_schema,
        params: { setParams, perPage },
        fetchPage: async (listParams) => {
            if (!canRead || (true && organizationScope.requestParams === undefined)) {
                throw new Error('Organization scope is not readable.');
            }
            const result = await queryClient.fetchQuery({
                queryKey: [
                    ...listQueryScope,
                    {
                        search: listParams.search,
                        sort: listParams.sort,
                        filters: listParams.filters,
                        page: listParams.page,
                        perPage: listParams.perPage,
                    },
                ],
                queryFn: ({ signal }) => fetchList(listParams, signal),
            });
            return { rows: result.data ?? [], total: result.meta?.total ?? null };
        },
        resolveRow: (row) => {
            const id = noteResourceId(row);
            return {
                id,
                label: row.name,
                ...(row.actions.view
                    ? { showUrl: noteShowRoute(id) }
                    : {}),
                ...(row.actions.update
                    ? { editUrl: noteEditRoute(id) }
                    : {}),
            };
        },
        onMatch: (row) => {
            if (row.actions.view) {
                setSelectedId(noteResourceId(row));
            }
        },
    });

    const selected = useMemo(
        () =>
            selectedId
                ? rows.find((row) => noteResourceId(row) === selectedId) ??
                  null
                : null,
        [rows, selectedId],
    );
    const rootResource = selected?.actions.view
        ? noteResourceRef(selected)
        : null;
    const openOrFocusResourceTab = useOpenResourceWorkTab('document');

    function openResourceDetail(resource: ResourceRef) {
        openOrFocusResourceTab(resource, {
            route: resource.route ?? noteShowRoute(resource.id),
        });
    }

    async function handleDelete(row: NoteRecord) {
        if (!row.actions.delete) return;

        const id = noteResourceId(row);
        const ok = await confirm(
            t('reference-example.note.confirm_delete'),
            {
                confirmLabel: t('common.actions.delete'),
                variant: 'destructive',
            },
        );
        if (!ok) return;

        deleteResource.mutate(id, {
            onSuccess: () => {
                if (selectedId === id) {
                    setSelectedId(null);
                }
            },
        });
    }

    const createRecord = () => navigate(creatableLegalEntityPublicIds.length === 1
        ? noteCreateRoute() + `?legal_entity_public_id=${encodeURIComponent(creatableLegalEntityPublicIds[0]!)}`
        : noteCreateRoute());
    const selectRow = (row: NoteRecord) => {
        if (row.actions.view) setSelectedId(noteResourceId(row));
    };
    const columns: ResourceTableColumn<NoteRecord>[] = [
        // `sortable` is a visual candidate. ResourceTable intersects it with
        // the backend `meta.list_schema.sortable` catalog before activation.
        {
            key: 'name',
            header: t('reference-example.note.name.label'),
            size: 'primary',
            // This resource's own primary cell selects the row. Cross-resource
            // reference cells must use ResourceLink without onActivate so they
            // push that reference onto the Inspector stack instead.
            cell: (row) =>
                row.actions.view ? (
                    <ResourcePrimaryCell
                        resource={ noteResourceRef(row) }
                        label={row.name}
                        onActivate={() => selectRow(row)}
                        testId={`note-link-${noteResourceId(row)}`}
                    />
                ) : (
                    <ResourceTextCell primary={row.name} />
                ),
        },
        {
            key: 'actions',
            header: t('common.actions.label'),
            size: 'actions',
            align: 'right',
            cell: (row) => {
                const items = noteResourceActions(row, t, {
                    onDelete: () => void handleDelete(row),
                    deleteDisabled: deleteResource.isPending,
                    testIdPrefix: `note-actions-${noteResourceId(row)}`,
                });

                return items.length > 0 ? (
                    <ResourceRowActionsMenu
                        label={t('common.actions.label')}
                        items={items}
                        testId={`note-actions-${noteResourceId(row)}`}
                    />
                ) : null;
            },
        },
    ];

    return (
        <NxPageFrame showHeader={false}
            maxWidth="none"
            organizationScope={true ? <NxOrganizationTargetSelector {...organizationScope.selectorProps} /> : null}
            actions={
                <>
                    {canCreate ? (
                        <NxActionButton
                            kind="create"
                            label={labels.createButtonLabel}
                            onClick={createRecord}
                            data-testid="note-create"
                        />
                    ) : null}
                </>
            }
        >
            {deleteResource.isError ? <NxEmptyView kind="error" /> : null}
            <ResourceInspectorStackProvider
                root={rootResource}
                onOpenInTab={openResourceDetail}
            >
                <WorkSurface
                    primaryLabel={t('reference-example.note.list.title')}
                    inspectorLabel={t('reference-example.note.inspector.title')}
                    resizeLabel={t('reference-example.note.inspector.resize')}
                    primary={
                        <WorkSection
                            layout="fullBleed"
                            bodyClassName="overflow-hidden"
                        >
                            <ResourceTable
                                tableId="reference-example.note.list"
                                label={t('reference-example.note.list.title')}
                                rows={rows}
                                columns={columns}
                                getKey={ noteResourceId }
                                loading={isLoading}
                                access={listError ? undefined : accessPending ? { state: 'pending' } : !canRead ? {
                                    state: 'denied',
                                    deniedTestId: 'note-no-access',
                                    deniedAction: <NxButton type="button" variant="primary" onClick={() => window.alert(t('common.actions.access_request_pending'))}>{t('common.actions.request_access')}</NxButton>,
                                } : undefined}
                                error={listError}
                                errorDescription={failureStatus === 401 ? t('common.errors.unauthenticated')
                                    : failureStatus === 403 ? t('common.status.no_access_description')
                                    : failureStatus === 404 ? t('common.status.not_found_description') : undefined}
                                onRetry={() => {
                                    if (contextError) void refetchContext();
                                    else if (true && organizationScope.isError) void organizationScope.targets.refetch();
                                    else if (!true && permissionsError) void refetchPermissions();
                                    else if (canRead) void refetch();
                                }}
                                hasActiveQuery={Boolean(search.trim())}
                                emptyState={{
                                    title: t('reference-example.note.list.empty'),
                                    action: canCreate ? <NxActionButton kind="create" label={labels.createButtonLabel} onClick={createRecord} /> : null,
                                    testId: 'note-empty',
                                }}
                                rowTestId={(row) => `note-row-${noteResourceId(row)}`}
                                rowSelected={(row) => selectedId === noteResourceId(row)}
                                onRowClick={selectRow}
                                sort={sort}
                                onSortChange={setSort}
                                schema={meta?.list_schema}
                                filters={filters}
                                onFiltersChange={setFilters}
                                transferMeta={meta?.resource_transfer}
                                onTransferImported={() =>
                                    queryClient.invalidateQueries({
                                        queryKey: listQueryScope,
                                    })
                                }
                                pagination={meta}
                                onPageChange={setPage}
                                onPerPageChange={setPerPage}
                                paginationDisabled={isFetching}
                                footer
                                toolbar={{
                                    leading: (
                                        <NxSearchField
                                            value={search}
                                            onChange={setSearch}
                                            placeholder={t('reference-example.note.list.search.placeholder',
                                            )}
                                            aria-label={t('reference-example.note.list.search.label',
                                            )}
                                            data-testid="note-search"
                                        />
                                    ),
                                }}
                            />
                        </WorkSection>
                    }
                    inspector={
                        <ResourceInspectorStackHost
                            emptyState={
                                <p className="text-xs text-text-tertiary">
                                    {t('reference-example.note.inspector.empty')}
                                </p>
                            }
                            onClose={() => setSelectedId(null)}
                        />
                    }
                />
            </ResourceInspectorStackProvider>
        </NxPageFrame>
    );
}

Record and Inspector surface

docs/developers/examples/generated-frontend/NoteRecordSurface.tsx
Code example
TSX
import {
    isHttpError,
    type FormFieldErrors,
    type ResourceInspectorAdapter,
    type ResourceFormSaved,
    type ResourceFormLegalEntity,
    parseLegalEntityCreateTargetSearchParams,
} from '@nexia/sdk';
import {
    useNavigate,
    useLocation,
    useParams,
    useSearchParams,
} from 'react-router-dom';
import {
    useTranslation,
} from 'react-i18next';
import {
    queryOptions,
    useQuery,
    useMutation,
    useQueryClient,
} from '@tanstack/react-query';
import {
    api,
    NxFormSection,
    NxFormField,
    NxTextInput,
    NxDetailRow,
    NxSectionCard,
    NxResourceFormLegalEntityField,
    ResourceInspectorQuery,
    InspectorResourceActions,
    useMessage,
    useDateTimeFormatter,
    useMarkTabDirty,
    NxButton,
    NxEmptyView,
    NxLoadingBlock,
    NxPageFrame,
    NxActionButton,
    NxActions,
    useContextQuery,
    useWorkSurfaceLabels,
    useWorkTabLabel,
    firstFieldError,
    NxSelect,
    useClearTabDirty,
    parseMutationFormError,
    useResourceCreateCompletion,
    withoutFieldError,
    useOrganizationTargetsQuery,
} from '@nexia/sdk/host';
import {
    type NoteRecord,
    type NoteInput,
    noteApiRoute,
    noteEditRoute,
    noteResourceId,
    noteShowRoute,
    noteListRoute,
    notePermissions,
    noteResourceActions,
} from '#app/resources/notes/note-resource-contract.ts';

import {
    type FormEvent,
    useCallback,
    useEffect,
    useMemo,
    useState,
} from 'react';
import { useNoteDelete, noteDetailQueryOptions, type NoteDetailResponse } from '#app/resources/notes/note-queries.ts';

interface NoteRecordSurfaceProps {
    mode: 'read' | 'create' | 'edit';
}

interface NoteCollectionActionsResponse {
    meta: {
        actions: {
            create: boolean;
        };
    };
}

function noteCollectionActionsQueryOptions(
    tenantId: string,
) {
    const resourceContextId = tenantId;

    return queryOptions({
        queryKey: [
            'reference-example-notes',
            tenantId,
            resourceContextId,
            'collection-actions',
        ],
        queryFn: async ({ signal }) => {
            const { data } = await api.get<NoteCollectionActionsResponse>(
                noteApiRoute() + '/actions',
                { signal },
            );
            return data;
        },
    });
}

function RecordContent({
    mode: explicitMode,
}: NoteRecordSurfaceProps) {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const location = useLocation();
    const { id } = useParams<{ id: string }>();
    const mode = explicitMode;
    const { data: context } = useContextQuery();
    const tenantId = context?.tenant?.id;
    const [searchParams, setSearchParams] = useSearchParams();
    const createTarget = useMemo(() => {
        if (mode !== 'create') {
            return { legalEntityPublicId: null, invalid: false };
        }

        try {
            return {
                legalEntityPublicId: parseLegalEntityCreateTargetSearchParams(searchParams).legalEntityPublicId ?? null,
                invalid: false,
            };
        } catch {
            return { legalEntityPublicId: null, invalid: true };
        }
    }, [mode, searchParams]);
    const targetQuery = useOrganizationTargetsQuery(
        tenantId,
        notePermissions.create,
        {},
        true && mode === 'create' && !!tenantId,
    );
    const legalEntityOptions = useMemo(() => (targetQuery.data?.data ?? [])
        .filter((target) => target.operating_unit === null)
        .map((target) => ({
            value: target.legal_entity.public_id,
            label: `${target.legal_entity.code} · ${target.legal_entity.name}`,
        })), [targetQuery.data]);
    const [legalEntityId, setLegalEntityId] = useState<string | null>(createTarget.legalEntityPublicId);
    const selectCreateLegalEntity = useCallback((nextLegalEntityId: string | null) => {
        setLegalEntityId(nextLegalEntityId);
        if (!createTarget.invalid) return;

        const next = new URLSearchParams(searchParams);
        for (const key of [
            'legal_entity_public_id',
            'legal_entity_public_id[]',
            'legal_entity_public_ids',
            'legal_entity_public_ids[]',
            'operating_unit_public_id',
            'operating_unit_public_id[]',
            'operating_unit_public_ids',
            'operating_unit_public_ids[]',
        ]) next.delete(key);
        if (nextLegalEntityId) {
            next.set('legal_entity_public_id', nextLegalEntityId);
        }
        setSearchParams(next, { replace: true });
    }, [createTarget.invalid, searchParams, setSearchParams]);
    useEffect(() => {
        if (!true || mode !== 'create') return;
        setLegalEntityId(createTarget.legalEntityPublicId);
    }, [mode, createTarget.legalEntityPublicId, createTarget.invalid]);
    useEffect(() => {
        if (
            !true
            || mode !== 'create'
            || createTarget.invalid
            || createTarget.legalEntityPublicId
        ) return;
        if (legalEntityOptions.length !== 1) return;

        setLegalEntityId((current) => current ?? legalEntityOptions[0]!.value);
    }, [mode, createTarget.legalEntityPublicId, legalEntityOptions]);
    const resourceContextId = mode === 'create' ? legalEntityId ?? tenantId ?? null : tenantId ?? null;
    const hasSelectedLegalEntity = !true || legalEntityOptions.some(
        (option) => option.value.toLowerCase() === legalEntityId?.toLowerCase(),
    );
    const queryClient = useQueryClient();
    const resourceCreateCompletion = useResourceCreateCompletion();
    const clearTabDirty = useClearTabDirty();
    const [error, setError] = useState<string | null>(null);
    const [savedWithoutRead, setSavedWithoutRead] = useState(false);
    const [fieldErrors, setFieldErrors] = useState<FormFieldErrors>({});
    const clearFieldError = useCallback((field: string) => {
        setFieldErrors((current) => withoutFieldError(current, field));
    }, []);

    const collectionQuery = useQuery({
        ...noteCollectionActionsQueryOptions(
            tenantId ?? '',
        ),
        // Legal Entity-owned creation gets its authority from exact CREATE
        // targets. Do not probe the READ collection endpoint in that flow.
        enabled: mode === 'create' && !!tenantId && !true,
    });
    const canOpenCreate = true
        ? legalEntityOptions.length > 0
        : collectionQuery.data?.meta.actions.create ?? false;

    const { data: detail, isLoading, error: detailError, isError: detailFailed, refetch: retryDetail } = useQuery({
        ...noteDetailQueryOptions(
            tenantId ?? '',
            id ?? '',
        ),
        enabled: mode !== 'create' && !!tenantId && !!id,
    });

    const item = detail?.note ?? null;
    const canCreate = canOpenCreate
        && (!createTarget.invalid || legalEntityId !== null)
        && hasSelectedLegalEntity;
    const canUpdate = item?.actions.update ?? false;
    const canSubmit = mode === 'create' ? canCreate : mode === 'edit' && canUpdate;

    const cacheSavedRecord = (response: NoteDetailResponse) => {
        const record = response.note;
        queryClient.invalidateQueries({ queryKey: ['reference-example-notes', tenantId ?? ''] });
        queryClient.setQueryData(
            noteDetailQueryOptions(tenantId ?? '', noteResourceId(record)).queryKey,
            response,
        );
        return record;
    };
    const onAgentSaved = (saved: ResourceFormSaved): NoteRecord | null => {
        const response = saved.response as unknown as NoteDetailResponse;
        const record = response?.note;
        // Decode this App's response, never guess a record identifier in Core.
        if (!record || typeof record.name !== 'string' || !record.actions
            || typeof record.public_id !== 'string' || !record.public_id.trim()
            || typeof record.actions.update !== 'boolean' || typeof record.actions.view !== 'boolean') {
            setError(t('common.status.error'));
            return null;
        }
        if (mode === 'edit' && noteResourceId(record) !== id) return null;
        // Agent delegation has narrower action permissions than the human.
        // Refresh the human-owned cache; never seed it with delegated actions.
        queryClient.invalidateQueries({ queryKey: ['reference-example-notes', tenantId ?? ''] });
        queryClient.invalidateQueries({
            queryKey: noteDetailQueryOptions(tenantId ?? '', noteResourceId(record)).queryKey,
            exact: true,
        });
        setError(null);
        setFieldErrors({});
        if (mode === 'create') {
            // A completed create becomes an edit before another save is possible.
            // Route state carries only this App's newer input; permissions still
            // come from the authoritative detail response in the destination.
            clearTabDirty();
            navigate(noteEditRoute(noteResourceId(record)), {
                replace: true,
                state: { savedForm: { tenantId, resourceId: noteResourceId(record),
                    name: typeof saved.currentValues.name === 'string' && saved.currentValues.name !== saved.submittedValues.name
                        ? saved.currentValues.name : record.name } },
            });
        }
        return record;
    };
    const carriedDraft = location.state?.savedForm;

    const mutation = useMutation({
        mutationFn: async (payload: NoteInput) => {
            if (mode === 'read' || !canSubmit) throw new Error('Record is not editable.');
            const url =
                mode === 'edit' && id
                    ? noteApiRoute(id)
                    : noteApiRoute();
            const request =
                mode === 'edit'
                    ? api.put(url, payload)
                    : api.post(url, {
                        ...payload,
                        ...(true ? { legal_entity_public_id: legalEntityId } : {}),
                    });
            const { data } = await request;
            return data;
        },
        onError: (mutationError: unknown) => {
            const parsed = parseMutationFormError({
                error: mutationError,
                t,
                fallback: t('common.status.error'),
                fieldLabel: (field) =>
                    t(`reference-example.note.${field}.label`, {
                        defaultValue: field.replace(/_/g, ' '),
                    }),
            });
            setError(parsed.formError);
            setFieldErrors(parsed.fieldErrors);
        },
        onSuccess: async (response: NoteDetailResponse) => {
            clearTabDirty();
            const record = cacheSavedRecord(response);
            if (
                mode === 'create' &&
                await resourceCreateCompletion.complete({
                    resourceId: noteResourceId(record),
                    display: record.name,
                })
            ) {
                return;
            }
            if (!record.actions.view) {
                setSavedWithoutRead(true);
                return;
            }
            navigate(noteShowRoute(noteResourceId(record)));
        },
    });
    const labels = useWorkSurfaceLabels({
        action: mode === 'read' ? 'show' : mode,
        resourceLabel: t('reference-example.note.list.title'),
        recordLabel: item?.name,
    });
    useWorkTabLabel(labels.tabLabel);

    if (savedWithoutRead) {
        return (
            <NxPageFrame showHeader={false} currentLabel={labels.breadcrumbLabel}>
                <NxEmptyView kind="empty" title={t('reference-example.note.saved_without_read')} description="">
                    {mode === 'create' ? (
                        <NxButton onClick={() => setSavedWithoutRead(false)}>
                            {t('common.actions.create')}
                        </NxButton>
                    ) : null}
                </NxEmptyView>
            </NxPageFrame>
        );
    }

    if (mode !== 'create' && isLoading) {
        return (
            <NxPageFrame showHeader={false}
                currentLabel={labels.breadcrumbLabel}
            >
                <NxLoadingBlock
                    shape="text"
                    label={t('common.status.loading')}
                />
            </NxPageFrame>
        );
    }

    const detailStatus = isHttpError(detailError) ? detailError.response?.status : undefined;
    const detailAuthorityLost = detailStatus === 401 || detailStatus === 403 || detailStatus === 404;
    if (mode !== 'create' && detailFailed && (!item || detailAuthorityLost)) {
        const kind = detailStatus === 403 ? 'permission' : detailStatus === 404 ? 'notFound' : 'error';
        return (
            <NxPageFrame currentLabel={labels.breadcrumbLabel}>
                <NxEmptyView kind={kind} description={detailStatus === 401 ? t('common.errors.unauthenticated') : undefined}>
                    {kind === 'error' ? (
                        <NxButton type="button" variant="secondary" onClick={() => void retryDetail()}>
                            {t('common.actions.retry')}
                        </NxButton>
                    ) : null}
                </NxEmptyView>
            </NxPageFrame>
        );
    }

    if (mode !== 'create' && !item) {
        return (
            <NxPageFrame showHeader={false}
                testId="note-form-not-found"
            >
                <NxEmptyView
                    kind="notFound"
                    title={t('reference-example.note.detail.not_found_title')}
                    description={t('reference-example.note.detail.not_found')}
                />
            </NxPageFrame>
        );
    }

    if (mode === 'read') {
        if (!item?.actions.view) return <NxPageFrame currentLabel={labels.breadcrumbLabel}><NxEmptyView kind="permission" /></NxPageFrame>;
        const resourceId = noteResourceId(item);

        return (
            <NxPageFrame
                currentLabel={labels.breadcrumbLabel}

                testId="note-detail"
                actions={<>
                    <NxActions resourceKey="reference-example.note" placement="resource" currentTargets={[{ id: resourceId, label: item.name }]} legalEntityPublicId={item.legal_entity_public_id} onSuccess={() => { void retryDetail(); void queryClient.invalidateQueries({ queryKey: ['reference-example-notes', tenantId ?? ''] }); }} />
                    {
                    item.actions.update ? (
                        <NxActionButton
                            kind="edit"
                            label={t('common.actions.edit')}
                            type="button"
                            onClick={() => navigate(noteEditRoute(resourceId))}
                            data-testid="note-edit"
                        />
                    ) : null
                    }
                </>}
            >
                {detailFailed ? (
                    <NxEmptyView kind="error">
                        <NxButton type="button" variant="secondary" onClick={() => void retryDetail()}>
                            {t('common.actions.retry')}
                        </NxButton>
                    </NxEmptyView>
                ) : null}
                <RecordDetails item={item} />
            </NxPageFrame>
        );
    }

    if (mode === 'create' && true && targetQuery.isLoading) {
        return (
            <NxPageFrame showHeader={false}
                currentLabel={labels.breadcrumbLabel}
            >
                <NxLoadingBlock
                    shape="text"
                    label={t('common.status.loading')}
                />
            </NxPageFrame>
        );
    }

    if (mode === 'create' && true && targetQuery.isError) {
        return (
            <NxPageFrame showHeader={false}
                currentLabel={labels.breadcrumbLabel}
            >
                <NxEmptyView kind="error">
                    <NxButton
                        type="button"
                        variant="secondary"
                        onClick={() => void targetQuery.refetch()}
                    >
                        {t('common.actions.retry')}
                    </NxButton>
                </NxEmptyView>
            </NxPageFrame>
        );
    }

    if (mode === 'create' && true && createTarget.invalid) {
        return (
            <NxPageFrame showHeader={false}
                currentLabel={labels.breadcrumbLabel}
            >
                <NxSelect<string>
                    ariaLabel={t('common.fields.legal_entity')}
                    value={null}
                    options={legalEntityOptions}
                    onChange={selectCreateLegalEntity}
                    placeholder={t('common.fields.legal_entity')}
                    fullWidth
                />
                <NxEmptyView kind="error" />
            </NxPageFrame>
        );
    }

    if (mode === 'create' && !true && collectionQuery.isLoading) {
        return <NxPageFrame currentLabel={labels.breadcrumbLabel}><NxLoadingBlock shape="text" label={t('common.status.loading')} /></NxPageFrame>;
    }
    if (mode === 'create' && !true && collectionQuery.isError) {
        return <NxPageFrame currentLabel={labels.breadcrumbLabel}><NxEmptyView kind="error">
            <NxButton type="button" variant="secondary" onClick={() => void collectionQuery.refetch()}>{t('common.actions.retry')}</NxButton>
        </NxEmptyView></NxPageFrame>;
    }

    if ((mode === 'create' && !canOpenCreate) || (mode === 'edit' && !canSubmit)) {
        return (
            <NxPageFrame showHeader={false}
                currentLabel={labels.breadcrumbLabel}
                testId="note-form-no-access"
            >
                <NxEmptyView kind="permission">
                    <NxButton
                        type="button"
                        variant="primary"
                        onClick={() =>
                            window.alert(t('common.actions.access_request_pending'))
                        }
                    >
                        {t('common.actions.request_access')}
                    </NxButton>
                </NxEmptyView>
            </NxPageFrame>
        );
    }

    return (
        <NxPageFrame showHeader={false}
            currentLabel={labels.breadcrumbLabel}

            testId="note-form-surface"
        >
            {mode === 'edit' && detailFailed ? (
                <NxEmptyView kind="error">
                    <NxButton type="button" variant="secondary" onClick={() => void retryDetail()}>
                        {t('common.actions.retry')}
                    </NxButton>
                </NxEmptyView>
            ) : null}
            <RecordForm
                key={`${tenantId}:${mode}:${id ?? 'new'}`}
                legalEntity={!true ? undefined : mode === 'create' ? {
                    kind: 'select',
                    value: legalEntityId,
                    options: legalEntityOptions,
                    onChange: (value) => {
                        selectCreateLegalEntity(value);
                        clearFieldError('legal_entity_public_id');
                    },
                    disabled: mutation.isPending,
                    error: firstFieldError(fieldErrors, 'legal_entity_public_id'),
                } : {
                    kind: 'stored',
                    label: item?.legal_entity_label,
                }}
                mode={mode}
                initialItem={item}
                initialName={item?.name ?? ''}
                initialDraftName={carriedDraft?.tenantId === tenantId && carriedDraft?.resourceId === id
                    && typeof carriedDraft?.name === 'string' ? carriedDraft.name : undefined}
                onSaved={onAgentSaved}
                pending={mutation.isPending}
                submitDisabled={!canSubmit}
                error={error}
                fieldErrors={fieldErrors}
                onFieldChange={clearFieldError}
                onCancel={() => {
                    if (mode === 'create' && resourceCreateCompletion.cancel()) {
                        return;
                    }
                    navigate(mode === 'edit' && id ? noteShowRoute(id) : noteListRoute());
                }}
                onSubmit={(payload) => {
                    if (!canSubmit) return;
                    setError(null);
                    setFieldErrors({});
                    mutation.mutate(payload);
                }}
            />
        </NxPageFrame>
    );
}

/** Mode is supplied by the SDK route owner, never inferred from URL or permissions. */
export default function NoteRecordSurface({ mode }: NoteRecordSurfaceProps) {
    if (mode === 'read' || mode === 'create' || mode === 'edit') return <RecordContent mode={mode} />;
    throw new Error('Record screen requires an explicit SDK route mode.');
}

interface RecordFormProps {
    mode: 'create' | 'edit';
    legalEntity?: ResourceFormLegalEntity;
    initialItem?: NoteRecord | null;
    initialName?: string;
    initialDraftName?: string;
    onSaved: (saved: ResourceFormSaved) => NoteRecord | null;
    pending?: boolean;
    submitDisabled?: boolean;
    error?: string | null;
    fieldErrors?: FormFieldErrors;
    onFieldChange?: (field: string) => void;
    onSubmit: (payload: NoteInput) => void;
    onCancel: () => void;
}

/** Ordinary composed inputs use the shared form/Agent binding. */
function RecordForm({
    mode,
    legalEntity,
    initialItem = null,
    initialName = '',
    initialDraftName,
    onSaved,
    pending = false,
    submitDisabled = false,
    error = null,
    fieldErrors,
    onFieldChange,
    onSubmit,
    onCancel,
}: RecordFormProps) {
    const { t } = useTranslation();
    const { formatDateTime } = useDateTimeFormatter();
    const [draft, setDraft] = useState({ name: initialDraftName ?? initialName, baseline: initialName });
    const name = draft.name;
    useEffect(() => {
        // A background refresh may update a clean form, never overwrite a draft.
        setDraft(current => current.name === current.baseline
            ? { name: initialName, baseline: initialName } : current);
    }, [initialName]);

    useMarkTabDirty(name !== draft.baseline);

    function handleSubmit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        if (pending || submitDisabled || name.trim() === '') return;
        onSubmit({ name });
    }

    return (
        <NxFormSection
            spacing="section"
            binding={{ effect: 'draft', disabled: pending || submitDisabled, onSaved: saved => {
                const record = onSaved(saved);
                if (!record) return;
                setDraft(current => ({ baseline: record.name,
                    name: current.name === saved.submittedValues.name ? record.name : current.name }));
            } }}
            onSubmit={handleSubmit}
            error={error}
            testId="note-form"
            actions={
                <>
                    <NxActionButton
                        kind="cancel"
                        onClick={onCancel}
                        disabled={pending}
                    />
                    <NxActionButton
                        kind={mode === 'create' ? 'create' : 'save'}
                        type="submit"
                        loading={pending}
                        disabled={pending || submitDisabled || name.trim() === ''}
                        data-testid="note-submit"
                    />
                </>
            }
        >
            <NxSectionCard title={t('reference-example.note.sections.basics')}
                description={t('reference-example.note.sections.basics_description')} layout="rows">
            {legalEntity ? <div className="p-inset"><NxResourceFormLegalEntityField target={legalEntity} mode={mode} /></div> : null}
            {initialItem ? <NxDetailRow label={t('reference-example.note.id.label')}>
                {noteResourceId(initialItem)}
            </NxDetailRow> : null}
            <NxFormField layout="row" fieldKey="name" label={t('reference-example.note.name.label')}
                required error={firstFieldError(fieldErrors, 'name')}>
                {slot => <NxTextInput id={slot.id} aria-describedby={slot.describedBy}
                    invalid={slot.invalid} value={name} required disabled={pending || submitDisabled}
                    onValueChange={value => {
                        setDraft(current => ({ ...current, name: value }));
                        onFieldChange?.('name');
                    }} data-testid="note-name-input" />}
            </NxFormField>
            {initialItem ? <>
                <NxDetailRow label={t('common.fields.created_at')}>
                    {initialItem.created_at ? formatDateTime(initialItem.created_at) : t('common.cell.empty')}
                </NxDetailRow>
                <NxDetailRow label={t('common.fields.updated_at')}>
                    {initialItem.updated_at ? formatDateTime(initialItem.updated_at) : t('common.cell.empty')}
                </NxDetailRow>
            </> : null}
            </NxSectionCard>
        </NxFormSection>
    );
}

/** Readable values, never disabled inputs; also used by the Inspector. */
export function RecordDetails({ item }: { item: NoteRecord }) {
    const { t } = useTranslation();
    const { formatDateTime } = useDateTimeFormatter();
    return <NxSectionCard title={t('reference-example.note.sections.basics')}
        description={t('reference-example.note.sections.basics_description')} layout="rows">
        {true ? <NxDetailRow label={t('common.fields.legal_entity')}>
            {item.legal_entity_label ?? t('common.cell.empty')}
        </NxDetailRow> : null}
        <NxDetailRow label={t('reference-example.note.id.label')}>
            {noteResourceId(item)}
        </NxDetailRow>
        <NxDetailRow label={t('reference-example.note.name.label')}>{item.name}</NxDetailRow>
        <NxDetailRow label={t('common.fields.created_at')}>
            {item.created_at ? formatDateTime(item.created_at) : t('common.cell.empty')}
        </NxDetailRow>
        <NxDetailRow label={t('common.fields.updated_at')}>
            {item.updated_at ? formatDateTime(item.updated_at) : t('common.cell.empty')}
        </NxDetailRow>
    </NxSectionCard>;
}

/** Inspector uses the same read content without mounting page navigation or form state. */
export const NoteInspector: ResourceInspectorAdapter<NoteRecord> = ({
    resource,
    stack,
}) => {
    const { t } = useTranslation();
    const id = resource.id;
    const queryClient = useQueryClient();
    const { data: context } = useContextQuery();
    const tenantId = context?.tenant?.id;
    const detail = useQuery({
        ...noteDetailQueryOptions(tenantId ?? '', id),
        select: (response) => response.note,
        enabled: !!tenantId && !!id,
    });
    const status = isHttpError(detail.error) ? detail.error.response?.status : undefined;
    const authorityLost = status === 401 || status === 403 || status === 404;
    const item = authorityLost ? undefined : detail.data;
    const { confirm } = useMessage();
    const deleteResource = useNoteDelete(tenantId ?? '');

    async function handleDelete() {
        if (!item?.actions.view || !item.actions.delete || deleteResource.isPending) return;

        const ok = await confirm(t('reference-example.note.confirm_delete'), {
            confirmLabel: t('common.actions.delete'),
            variant: 'destructive',
        });
        if (!ok) return;

        deleteResource.mutate(resource.id, { onSuccess: () => stack.reset() });
    }

    const actions = item?.actions.view
        ? noteResourceActions(item, t, {
              onView: () => stack.openInTab(resource),
              onEdit: () =>
                  stack.openInTab({
                      ...resource,
                      route: noteEditRoute(resource.id),
                  }),
              onDelete: () => void handleDelete(),
              deleteDisabled: deleteResource.isPending,
              testIdPrefix: 'note-inspector',
          })
        : [];

    return <>
        {deleteResource.isError ? <NxEmptyView kind="error" /> : null}
        <ResourceInspectorQuery<NoteRecord>
            testId="note-inspector"
            query={detail}
            canView={(record) => record.actions.view}
            actions={(record) => <><InspectorResourceActions actions={actions} /><NxActions resourceKey="reference-example.note" placement="inspector" currentTargets={[{ id: resource.id, label: record.name }]} legalEntityPublicId={record.legal_entity_public_id} onSuccess={() => { void detail.refetch(); void queryClient.invalidateQueries({ queryKey: ['reference-example-notes', tenantId ?? ''] }); }} /></>}
        >
            {(record) => <RecordDetails item={record} />}
        </ResourceInspectorQuery>
    </>;
};
Example source: docs/developers/examples/generated-frontend/README.md