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 ERP CSV export to respect the current saved view (#874)

Chase Foster4157b29b85e1
diff --git a/apps/erp/app/components/Table/components/Download.tsx b/apps/erp/app/components/Table/components/Download.tsx
index 3c022d605b..9658ba2f02 100644
--- a/apps/erp/app/components/Table/components/Download.tsx
+++ b/apps/erp/app/components/Table/components/Download.tsx
@@ -6,20 +6,71 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { json2csv } from "json-2-csv";
-import { useCallback } from "react";
+import { useCallback, useMemo } from "react";
import { LuDownload } from "react-icons/lu";
+import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";
type DownloadProps = {
data: object[];
+ columnAccessors: Record<string, string>;
+ columnOrder: string[];
+ columnVisibility: Record<string, boolean>;
};
-const Download = ({ data }: DownloadProps) => {
+const Download = ({
+ data,
+ columnAccessors,
+ columnOrder,
+ columnVisibility
+}: DownloadProps) => {
const { t } = useLingui();
+
+ const [items] = useItems();
+ const [suppliers] = useSuppliers();
+ const [people] = usePeople();
+ const [customers] = useCustomers();
+
+ // Maps an id column's accessor key -> a lookup of record id -> name, so the
+ // CSV can show the human-readable name instead of the raw id.
+ const idNameMaps = useMemo<Record<string, Map<string, string>>>(
+ () => ({
+ itemId: new Map(items.map((i) => [i.id, i.name])),
+ supplierId: new Map(suppliers.map((s) => [s.id, s.name])),
+ employeeId: new Map(people.map((p) => [p.id, p.name])),
+ customerId: new Map(customers.map((c) => [c.id, c.name]))
+ }),
+ [items, suppliers, people, customers]
+ );
+
+ // The visible columns, in the current view's order. The column id doubles as
+ // the data accessor key; columns absent from columnAccessors (selection,
+ // expand, actions) are dropped.
+ const exportColumns = useMemo(() => {
+ const order = columnOrder.length
+ ? columnOrder
+ : Object.keys(columnAccessors);
+ return order.filter(
+ (id) => id in columnAccessors && columnVisibility[id] !== false
+ );
+ }, [columnOrder, columnVisibility, columnAccessors]);
+
const onClick = useCallback(() => {
if (!data?.length) {
return;
}
- let csvData = json2csv(data);
+ // Build label-keyed rows so json2csv emits the view's header labels, in the
+ // view's column order, substituting names for id columns.
+ const rows = data.map((row) => {
+ const out: Record<string, unknown> = {};
+ for (const key of exportColumns) {
+ const raw = (row as Record<string, unknown>)[key];
+ const map = idNameMaps[key];
+ out[columnAccessors[key]] =
+ map && raw != null ? (map.get(String(raw)) ?? raw) : raw;
+ }
+ return out;
+ });
+ let csvData = json2csv(rows, { emptyFieldValue: "" });
// Create a CSV file and allow the user to download it
let blob = new Blob([csvData], { type: "text/csv" });
let url = window.URL.createObjectURL(blob);
@@ -28,7 +79,7 @@ const Download = ({ data }: DownloadProps) => {
a.download = "data.csv";
document.body.appendChild(a);
a.click();
- }, [data]);
+ }, [data, exportColumns, idNameMaps, columnAccessors]);
if (!data?.length) {
return null;
diff --git a/apps/erp/app/components/Table/components/TableHeader.tsx b/apps/erp/app/components/Table/components/TableHeader.tsx
index a68cba4c12..3dc9a0e532 100644
--- a/apps/erp/app/components/Table/components/TableHeader.tsx
+++ b/apps/erp/app/components/Table/components/TableHeader.tsx
@@ -332,7 +332,12 @@ const TableHeader = <T extends object>({
</Tooltip>
)}
- <Download data={data} />
+ <Download
+ data={data}
+ columnAccessors={columnAccessors}
+ columnOrder={columnOrder}
+ columnVisibility={columnVisibility}
+ />
{withPagination &&
(pagination.canNextPage || pagination.canPreviousPage) && (
diff --git a/llm/cache/table-csv-export.md b/llm/cache/table-csv-export.md
new file mode 100644
index 0000000000..f3ed9a6dbe
--- /dev/null
+++ b/llm/cache/table-csv-export.md
@@ -0,0 +1,38 @@
+# Table CSV export (ERP)
+
+The reusable data table at `apps/erp/app/components/Table/Table.tsx` renders a
+"Download CSV" button via `TableHeader` → `Download`.
+
+## Flow
+- `Table.tsx` computes/holds:
+ - `columnAccessors: Record<string,string>` — accessorKey → translated human header
+ label (`Table.tsx`, built from `columns` with `getAccessorKey`; throws if an
+ accessorKey contains `_`).
+ - `columnVisibility: Record<string,boolean>` — keyed by column id; seeded from the
+ current saved view (`useSavedViews().currentView`) or `defaultColumnVisibility`.
+ - `columnOrder: string[]` (ColumnOrderState) — column ids in view order; seeded from
+ the saved view or `defaultColumnOrder`.
+- These are passed to `TableHeader` (`apps/erp/app/components/Table/components/TableHeader.tsx`),
+ which forwards `columnAccessors`, `columnOrder`, `columnVisibility` to
+ `<Download />`.
+- TanStack column `id` defaults to `accessorKey` for data columns, so these three maps
+ share keys. Synthetic columns (selection/expand/actions) are absent from
+ `columnAccessors`.
+
+## Download.tsx behavior (respects the saved view)
+`apps/erp/app/components/Table/components/Download.tsx`:
+- Exports only the columns visible in the current view, in the view's order, using the
+ view's header labels (`columnAccessors`) as CSV headers. Order falls back to
+ `Object.keys(columnAccessors)` when `columnOrder` is empty; columns absent from
+ `columnAccessors` or with `columnVisibility[id] === false` are dropped.
+- ID columns `itemId` / `supplierId` / `employeeId` / `customerId` export the record's
+ **name** instead of the raw id, via the `useItems` / `useSuppliers` / `usePeople` /
+ `useCustomers` stores (`apps/erp/app/stores/`, re-exported from `~/stores`). Lookup is
+ by id→name with fallback to the raw value. The store hooks are called in the component
+ body; id→name Maps are memoized.
+- Uses `json2csv(rows, { emptyFieldValue: "" })` from `json-2-csv`; downloads as
+ `data.csv`.
+
+Stores return tuples consumed as `const [items] = useItems();`; each element is a
+`ListItem` (`{ id: string; name: string; email?: string }`, `apps/erp/app/types/index.ts`)
+plus extras.
diff --git a/llm/tasks/todo.md b/llm/tasks/todo.md
index 663c02bd7d..114056b890 100644
--- a/llm/tasks/todo.md
+++ b/llm/tasks/todo.md
@@ -1,61 +1,37 @@
-# Merge pick/place into item rules; remove storageUnit; rebrand item→Storage rules under Inventory
-
-## Part A — Merge pick/place, remove storageUnit target
-- [x] A1. customRules.ts: TARGET_TYPES, SURFACES_BY_TARGET_TYPE. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A2. field-registry.ts: targetType ["item","storageUnit"]→"item". Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A3. server.ts: drop storageUnit target branches, keep storageType cascade. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A4. service.ts: drop storageUnit cases. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A5. customRules.models.ts validator. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A6. Call sites: receipt/shipment/adjustment swap; transfers delete pass. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A7. Delete 3 storage-units rules routes. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A8. path.ts + RuleAssignmentsList + StorageUnitForm + getRuleAssignmentCounts + type unions. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A9. Migration file. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] A10. Tests. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-
-## Part B — Rebrand item→Storage rules, move to Inventory
-- [x] B1. Relocate 4 admin routes settings→inventory. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] B2. path.ts rename customRules*→storageRules*. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] B3. Nav: remove settings entry, add inventory entry. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] B4. CustomRulesGroups relabel. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
-- [x] B5. CustomRulesTable + CustomRuleForm label maps. Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.
+# Fix ERP CSV export to respect the current saved view
+
+## Tasks
+
+- [x] Update `Download.tsx`: extend props (columnAccessors, columnOrder, columnVisibility),
+ call store hooks in body, derive ordered+visible export columns, build label-keyed
+ rows with id→name substitution. Spawn subtasks to query the cache folder any time I
+ need to learn something about the codebase. NEVER update the cache with plans or
+ information about code that is not yet committed.
+- [x] Update `TableHeader.tsx` line 335: pass the three props through to `<Download />`.
+ Spawn subtasks to query the cache folder any time I need to learn something about the
+ codebase. NEVER update the cache with plans or information about code that is not yet
+ committed.
+- [x] Typecheck. Spawn subtasks to query the cache folder any time I need to learn something
+ about the codebase. NEVER update the cache with plans or information about code that is
+ not yet committed.
+- [ ] Commit and push. Spawn subtasks to query the cache folder any time I need to learn
+ something about the codebase. NEVER update the cache with plans or information about
+ code that is not yet committed.
## Review
-**Done.** All 15 items complete. `packages/utils`, `packages/ee`, `apps/erp`
-typecheck clean (tsgo --noEmit, exit 0). Unit tests pass: utils customRules
-(51) + ee context anti-drift (23).
-
-Key decisions:
-- pick/place merged into item rules by adding them to `SURFACES_BY_TARGET_TYPE.item`
- and swapping the storageUnit eval pass → item at receipt/shipment/adjustment
- call sites; transfer call sites just dropped the redundant storageUnit pass.
-- storageUnit target fully removed (TARGET_TYPES, field-registry, evaluator,
- service, validator, UI unions, 3 assignment routes, path helpers, nav button).
- Storage-type ancestor cascade KEPT in the evaluator — item rules referencing
- `storageUnit.storageTypeId` on place/pick still get the unioned value.
-- Migration `20260603120000_remove-storage-unit-rules.sql`: DELETEs storageUnit
- rules (cascades assignments), DROPs the assignment table, recreates the enum
- without 'storageUnit'.
-- Item rules rebranded "Storage rules"; admin library relocated settings →
- `/x/inventory/storage-rules` + Inventory > Configure nav. Pages still gated on
- `settings` permission (matches `customRule` RLS); switching to inventory perms
- would need an RLS migration (out of scope).
-
-## Part C — Full rename customRule → storageRule (incl. DB), perms → inventory
-
-Done. Migrations applied + types regenerated by user. ee/erp typecheck exit 0;
-utils/ee tests green.
-- Code: blanket rename `customRule*`/`CustomRule*`/`custom-rules`/`CUSTOM_RULES`
- → `storageRule*`/`StorageRule*`/`storage-rules`/`STORAGE_RULES` (60 files);
- `git mv` of utils `storageRules.ts(.test)`, ee `storageRules/` dir, erp
- `modules/storageRules/` + `StorageRule*` component files; EE export
- `@carbon/ee/storage-rules(.server)`.
-- DB: migration 130000 renames tables (`storageRule`, `storageRuleItemAssignment`,
- `storageRuleWorkCenterAssignment`), enum `storageRuleTargetType`, customFieldTable
- row. Migration 140000 moves `storageRule` RLS → inventory_* (SELECT any-employee).
- Admin route gates + library UI perms swapped settings → inventory.
-- Left legacy constraint/index names (`customRule_*`) — internal labels only,
- surface as `foreignKeyName` strings in generated types; never referenced by code.
-
-Manual verification still pending (create a storage rule; receipt/ship to fire
-place/pick; confirm Inventory→Storage Rules nav).
+- `Download.tsx`: added `columnAccessors` / `columnOrder` / `columnVisibility` props;
+ call `useItems/useSuppliers/usePeople/useCustomers` in the body to build id→name
+ Maps (memoized); derive the ordered, visible export columns (column id == accessor
+ key; synthetic columns dropped since they're absent from `columnAccessors`); the
+ click handler builds label-keyed rows so json2csv emits the view's labels in order,
+ substituting names for `itemId`/`supplierId`/`employeeId`/`customerId` with raw-value
+ fallback.
+- `TableHeader.tsx`: passed the three already-available props to `<Download />`. No
+ change to `Table.tsx` or any interface.
+- Types confirmed by inspection (`ListItem` has `id: string; name: string`; `~/stores`
+ import is an established pattern; `[email protected]` supports `emptyFieldValue`).
+ The full `tsgo` typecheck could NOT be run here — this environment has no installed
+ `node_modules`.
+- Browser verification (custom view in Inventory) still needs to be run against a
+ running dev server, which isn't available in this container.