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.

feat(sales): bulk CSV import for quotes

sidgaikwad7fa8fe4e420d
diff --git a/.ai/specs/2026-07-28-quote-bulk-import.md b/.ai/specs/2026-07-28-quote-bulk-import.md
new file mode 100644
index 0000000000..07374db150
--- /dev/null
+++ b/.ai/specs/2026-07-28-quote-bulk-import.md
@@ -0,0 +1,420 @@
+# PRD: Bulk CSV Import for Sales Quotes
+
+- **Status:** Phase 1 implemented (2026-07-28) on branch `feat/quote-bulk-import`. Decisions: **Option B** (app-side, reuse services), **3 modes**, **create-only idempotency**. Q4 = customer by name/readableId + part by number; Q5 = dedicated "Quote Group" column; Q6 = Quotes table only; Q7 = explicit prices only. Files: `sales.import.server.ts` (engine), `imports.models.ts` (config), `import.$tableId.tsx` (route branch), `QuotesTable.tsx` (dropdown).
+- **Date:** 2026-07-28
+- **Author:** research + PRD via Claude
+- **Module:** `sales`
+- **Analogous prior art:** Parts / BOM / BOP CSV import ([#911](https://github.com/crbnos/carbon/pull/911), [#1194](https://github.com/crbnos/carbon/pull/1194))
+
+---
+
+## 1. Summary
+
+Add a **bulk CSV import for sales quotes**, mirroring the existing Parts/BOM/BOP
+("method") import. A user uploads one CSV and Carbon creates quotes — headers,
+their lines, and quantity-break pricing — in one operation, reusing the existing
+generic import wizard (upload → column-map → results).
+
+The BOM/BOP import exposes **four modes** (`part`, `bom`, `operations`,
+`partWithMethod`). The quote analog is a small set of modes over a
+**parent → children hierarchy** (`quote` → `quoteLine` → `quoteLinePrice`),
+discriminated by a per-row **Row Type** column exactly like the method import's
+`PART / BOM / BOP / STEP / TOOL / PARAM`.
+
+---
+
+## 2. Problem & motivation
+
+Quotes today are created one at a time through the UI (`insertQuote` +
+per-line `upsertQuoteLine` + pricing). A shop migrating from another system, or
+one that prepares quotes in spreadsheets, has no way to load many quotes/lines at
+once. Parts already have this (BOM/BOP import); quotes are the natural next
+document to get the same treatment, and the import framework is fully generic —
+only quote-specific config and a row handler are missing.
+
+---
+
+## 3. Goals / non-goals
+
+### Goals
+- Import **quote headers** (customer, dates, references, sales/estimator, etc.).
+- Import **quote lines** against an item (resolved by part number), with
+ description, method type, UoM, and quantity breaks.
+- Import **explicit quantity-break pricing** (`unitPrice`, `discountPercent`,
+ `leadTime`, `shippingCost`) per line.
+- Reuse the existing import wizard UI, column mapping, enum mapping, template
+ download, and results modal **unchanged**.
+- Be **idempotent / re-runnable** via the shared `externalIntegrationMapping`
+ (`integration = "csv"`) mechanism, keyed on a user-supplied external quote id.
+- Respect quote-creation side effects (opportunity, payment, shipment, external
+ link) — do **not** write raw `quote` rows that skip them.
+
+### Non-goals (Phase 1)
+- **No automatic cost rollup / price resolution.** Make-to-Order lines will
+ *not* auto-pull the item's BOM/routing or run `resolvePrice` / `applyPriceRules`
+ / cost rollup during import. Prices come from the CSV (explicit). Rationale:
+ replicating the pricing engine in the importer is large and high-drift. (Users
+ can still open a line and recalculate afterward.)
+- No import of `quoteMaterial` / `quoteMakeMethod` / `quoteOperation` (the
+ line's BOM/routing). That is a large second effort analogous to the whole
+ method import; defer to Phase 2.
+- No quote → order conversion, no RFQ import.
+- No new export format (the generic Table "Download CSV" already exists).
+
+---
+
+## 4. Background: how the BOM/BOP import works (the template we copy)
+
+Verified against the current code. The import system has three layers, all
+**generic and table-driven** — adding a type is mostly declarative config plus a
+row handler.
+
+**Flow**
+
+```
+Quotes table "Bulk Import" dropdown (importCSV prop on <Table>)
+ → ImportCSVModal (2-step wizard)
+ UploadCSV.tsx — PapaParse client-side; upload to `private` bucket
+ at `${companyId}/imports/${nanoid()}.csv`; template download
+ FieldMappings.tsx — map CSV columns → Carbon fields (+ enum value mapping)
+ → POST /x/shared/import/$tableId (import.$tableId.tsx — action only)
+ requirePermissions({ update: importPermissions[table] })
+ validate importSchemas[table].extend({ filePath, enumMappings })
+ importCsv(getCarbonServiceRole(), { table, filePath, columnMappings, enumMappings, companyId, userId })
+ → edge fn `import-csv/index.ts` (Deno): download CSV, apply mappings, switch(table)
+ bom/operations/partWithMethod → importMethods() in method-import.ts
+ → ImportResultsModal { inserted, updated, errors[], skipped[] }
+```
+
+**Config lives in three maps** in
+`apps/erp/app/modules/shared/imports.models.ts`, all keyed by table name:
+- `fieldMappings[table]` — per-column `{ label, required, type: "string"|"number"|"boolean"|"enum", default?, enumData? }`. `enumData` may carry static `options`, a dynamic `fetcher(client, companyId)`, or `creatableLookup`/`creatableForm`.
+- `importPermissions[table]` — `table → module` (gates the route). Exhaustive over `keyof fieldMappings` (TS enforces).
+- `importSchemas[table]` — a `z.ZodObject` for validation (method schemas keep every cell an optional string; authoritative validation is in the edge fn).
+
+**The hierarchical engine** (`method-import.ts`, ~950 lines) is the real
+template for quotes:
+1. **Classify + group** rows by parent (`readableId`+`revision`) using a required
+ **Row Type** column.
+2. **Batch-resolve references** (items by readable id, UoM, processes…), with
+ ambiguity detection; same-file-created parents count as resolvable.
+3. **Validate per group.**
+4. **Write per group inside one Kysely transaction** → atomic per parent.
+ Create-only / fill-if-empty (re-running skips already-populated targets).
+
+**Discoverability** is a one-line `importCSV` prop on the table:
+```tsx
+// PartsTable.tsx
+importCSV={[
+ { table: "part", label: t`Parts` },
+ { table: "bom", label: "BOM" },
+ { table: "operations", label: "Operations" },
+ { table: "partWithMethod", label: "Parts with Methods" },
+]}
+```
+
+**Confirmed facts that shape the quote design**
+- The edge fn's `importCsvValidator.table` is a **hardcoded `z.enum`** — a new
+ table **must** be added there or the route call is rejected (this is the gate
+ that made `fixedAsset` a dead entry: it's in the models but not the enum).
+- `import-csv` is **not** in `config.toml` yet deploys/runs — **no config.toml
+ change needed** to extend it.
+- The edge fn re-checks a coarse `{ create: "resources" }` permission in addition
+ to the route's real per-table gate.
+- Row numbers in results are **0-based indices** into the parsed rows.
+- Client parses with PapaParse; edge fn parses with Deno std — separate parsers.
+
+---
+
+## 5. Quote data model (what we must produce)
+
+Reconciled to current schema (base tables in `20240715024405_quotes.sql` +
+~40 later ALTER migrations).
+
+### `quote` (header) — PK `id` (`xid()`), unique `(quoteId, companyId)`
+- **Hard-required business input:** `customerId` (FK→customer).
+- `quoteId` (human id `QUO000001`) is **auto-generated** via
+ `get_next_sequence("quote", companyId)` when not supplied.
+- Validator (`quoteValidator`) also requires **`locationId`** (form-level; the
+ column is nullable — import should default to the company's default location
+ when the CSV omits it).
+- Optional: `expirationDate`, `dueDate`, `customerReference`,
+ `customerLocationId`, `customerContactId`, `salesPersonId`, `estimatorId`,
+ `currencyCode`, `status`, `notes`.
+
+### `quoteLine` — PK `id` (`xid()`)
+Required: `quoteId`, **`itemId`** (resolved from part number), `status`,
+**`description`**, `methodType`, `unitOfMeasureCode`, `quantity NUMERIC[]`
+(each ≥ 0.00001), `taxPercent` (0–1). Denormalized `itemReadableId`.
+- `methodType` enum (current): **`Purchase to Order`, `Pull from Inventory`,
+ `Make to Order`** (legacy `Buy`/`Pick`/`Make`).
+- `quoteLineStatusType`: `Not Started, In Progress, Complete, No Quote`.
+
+### `quoteLinePrice` — PK **`(quoteLineId, quantity)`**, no `id`
+`unitPrice`, `discountPercent` (**fraction 0–1, not 0–100**), `leadTime`,
+`shippingCost`, `exchangeRate`, `categoryMarkups` (JSONB). Net/extended/converted
+prices are **generated STORED** columns. Written via `upsertQuoteLinePrices`
+(delete-then-reinsert per line; preserves discount/leadTime/categoryMarkups).
+
+### Auto-created side effects (⚠ critical)
+`insertQuote` / `upsertQuote` also create: an **`opportunity`**, **`quotePayment`**
+(from the customer's payment defaults), **`quoteShipment`** (from shipping
+defaults), and an external portal link. Make-to-Order line inserts trigger a root
+`quoteMakeMethod`. **A raw table insert skips all of this** — the import must go
+through the real creation path.
+
+### Service functions to reuse
+- `insertQuote(client, input)` — header + all side effects; auto-sequences quoteId.
+- `upsertQuoteLine(client, line)` — insert (computes `sortOrder`) / update.
+- `upsertQuoteLinePrices(client, quoteId, lineId, prices[])` — quantity-break prices.
+- `getQuoteByExternalId(client, externalId)` — idempotency lookup.
+
+---
+
+## 6. Proposed feature
+
+### 6.1 Modes (the "4 options" analog)
+
+Recommended **three** modes, mirroring the part/bom/operations/partWithMethod
+symmetry (the combined mode is the flagship):
+
+| Mode (`table`) | CSV contains | Use case |
+|---|---|---|
+| `quote` | Header rows only | Load many empty quotes (headers) |
+| `quoteLine` | Line + price rows keyed to an **existing** quote (by `quoteId`) | Add lines to quotes that already exist |
+| `quoteWithLines` | Header + Line + Price rows, one file | **Flagship:** create whole quotes end-to-end |
+
+> A fourth "prices only" mode (like `bom` for parts) is possible but low value —
+> pricing is naturally imported with its line. Recommend **not** shipping it in
+> Phase 1. (Open question Q1.)
+
+### 6.2 CSV shape — Row Type discriminator
+
+`quoteWithLines` (and `quoteLine`) use a **Row Type** column, exactly like
+`partWithMethod`:
+
+- `QUOTE` — a header row. Carries customer, dates, references.
+- `LINE` — a quote line. Carries item/part number, description, method type, UoM,
+ a single quantity, and (optionally) that quantity's price fields.
+
+Because a *new* quote has no human key until `quoteId` is generated, rows are
+tied together by a **Quote Group** column (user-authored key, e.g. a PO number or
+a temporary import id). All rows sharing a Quote Group belong to one quote; the
+first `QUOTE` row is the header, subsequent `LINE` rows are its lines. The Quote
+Group value doubles as the **external id** for idempotency (see §7).
+
+Quantity breaks: one `LINE` row = one item + one quantity + its price. Multiple
+quantity breaks for the same item = multiple `LINE` rows with the same
+item/description and different `quantity`/`unitPrice` (the handler groups them
+into one `quoteLine` with a `quantity[]` array + N `quoteLinePrice` rows). This
+matches how method import represents repeated child rows.
+
+### 6.3 Proposed columns (`fieldMappings`)
+
+**Header (`QUOTE`) columns**
+| Field | Req | Type | Notes |
+|---|---|---|---|
+| `externalId` (Quote Group) | ✓ | string | groups rows + idempotency key |
+| `rowType` | ✓ (combined/line) | enum | `QUOTE` / `LINE` |
+| `customerId` | ✓ | enum | resolve by customer **name or readableId** → `customer.id` |
+| `customerReference` | – | string | |
+| `customerLocationId` | – | enum | fetcher over customer locations |
+| `customerContactId` | – | enum | fetcher over customer contacts |
+| `locationId` | – | enum | default → company default location |
+| `salesPersonId` | – | enum | match employee by email |
+| `estimatorId` | – | enum | match employee by email |
+| `expirationDate` | – | string | ISO date |
+| `dueDate` | – | string | ISO date |
+| `currencyCode` | – | enum | default → company currency |
+| `status` | – | enum | default `Draft` |
+
+**Line (`LINE`) columns**
+| Field | Req | Type | Notes |
+|---|---|---|---|
+| `itemReadableId` (Part Number) | ✓ | string | resolve → `item.id` (reuse method-import resolver) |
+| `description` | ✓ | string | |
+| `methodType` | – | enum | default `Pull from Inventory` |
+| `unitOfMeasureCode` | – | enum | default from item / `EA` |
+| `quantity` | ✓ | number | single break |
+| `unitPrice` | ✓ | number | |
+| `discountPercent` | – | number | **fraction 0–1** (validate/convert) |
+| `leadTime` | – | number | |
+| `shippingCost` | – | number | |
+| `taxPercent` | – | number | 0–1, default 0 |
+| `lineStatus` | – | enum | default `Not Started` |
+| `customerPartId` | – | string | |
+
+`importSchemas.quoteWithLines` keeps all cells optional-string (like the method
+schemas); authoritative validation is in the handler.
+
+---
+
+## 7. Idempotency
+
+Reuse the shared `externalIntegrationMapping` table (`integration = "csv"`), the
+same mechanism the customer/supplier/item imports use:
+- The **Quote Group / externalId** column is the CSV external id for the quote.
+- On import, build `externalId → quote.id` map (via `getCsvExternalIdMap`, or
+ `getQuoteByExternalId` on the `quote.externalId` JSONB column).
+- Existing external id → **update** the header / append-or-update lines; else
+ **create**. Persist the mapping via `upsertCsvMappings`.
+- Add `"quote"` to the edge fn's `CsvEntityType` union + `fetchLiveEntityIds`
+ switch if we want live-id reconciliation.
+
+**Create-only vs update semantics** need a decision (Q3): safest Phase-1 default
+is *create-only* — if a quote with that external id already exists, **skip** it
+(report in `skipped[]`), matching the method import's "don't clobber" stance.
+
+---
+
+## 8. Architecture decision — RESOLVED: Option B (app-side, reuse services)
+
+The generic imports run entirely in the **Deno edge function** with **Kysely**
+direct writes. Quotes are different: quote creation lives in **app service code**
+(`insertQuote`, etc.) as `supabase-js` calls with substantial business logic
+(sequence, opportunity, payment/shipping defaults, external link). Two paths:
+
+### Option A — Edge function `quote-import.ts` (consistency-first)
+Add `case "quote"` delegating to a new `quote-import.ts` (like `method-import.ts`)
+that **replicates** `insertQuote` + line + price logic in Deno with Kysely/
+service-role.
+- **Pros:** identical to every other import; one code path; per-quote atomic
+ transaction is natural.
+- **Cons:** must **re-implement and keep in sync** ~250 lines of quote-creation
+ business logic (opportunity, payment/shipping defaults, external link, sequence)
+ plus line/price logic. High drift risk. Directly contradicts the sales module's
+ rule that quote writes go through services.
+
+### Option B — App-side `importQuotes` service, invoked by the route (recommended)
+Special-case the route: for `table === "quote*"`, call a new app-side
+`importQuotes()` service (in `sales.service.ts` or a `sales.import.server.ts`)
+that downloads + parses the CSV, applies column/enum mappings, and loops calling
+the **existing** `insertQuote` / `upsertQuoteLine` / `upsertQuoteLinePrices` with
+the service-role client — one quote at a time, each wrapped for partial-failure
+reporting.
+- **Pros:** **zero duplication** of quote business logic; automatically respects
+ opportunity/payment/shipment/external-link/pricing rules; honors the sales
+ safety conventions; changes to quote creation flow through automatically.
+- **Cons:** introduces a second import execution path (app-side vs edge fn);
+ must replicate the small CSV-parse + mapping-apply step app-side (~40 lines,
+ PapaParse is available); per-row atomicity is weaker than a single Kysely txn
+ (mitigated: each quote created independently, failures reported per group).
+
+**Recommendation: Option B.** The quote-creation logic is too large and too
+safety-sensitive to fork into Deno. Reusing the services is the "no laziness /
+root-cause / minimal-drift" choice and matches `sales/AGENTS.md` ("MUST use…
+services", "never compute prices ad hoc"). The entire wizard UI, upload, mapping,
+template, results modal, route shell, and permission gate are still reused — only
+the execution backend differs for quotes.
+
+> If the team values single-path consistency over drift risk, Option A is viable
+> but should budget for careful replication + tests against `insertQuote`.
+
+---
+
+## 9. Touchpoints (files to change)
+
+**Shared (both options)**
+1. `apps/erp/app/modules/shared/imports.models.ts` — add `quote` / `quoteLine` /
+ `quoteWithLines` to `fieldMappings`, `importPermissions` (→ `"sales"`),
+ `importSchemas`. Add reusable column fragments (header fields, line fields).
+2. `apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx` — add `importCSV`
+ prop with the 3 modes (gated on `permissions.can("create", "sales")`).
+3. `apps/erp/app/modules/sales/sales.models.ts` — export any new import-specific
+ types if needed (row shapes).
+
+**Option A (edge fn)**
+4. `packages/database/supabase/functions/import-csv/index.ts` — add the tables to
+ `importCsvValidator.table` enum; add `case "quote*"` → `importQuotes(db, …)`;
+ extend `CsvEntityType` + `fetchLiveEntityIds`.
+5. `packages/database/supabase/functions/import-csv/quote-import.ts` — new engine
+ (group by Quote Group, resolve customer/item/UoM, replicate insertQuote/line/
+ price, per-group transaction, create-only skip).
+
+**Option B (app-side, recommended)**
+4. `apps/erp/app/routes/x+/shared+/import.$tableId.tsx` — branch: for quote
+ tables, call the app-side `importQuotes` instead of `importCsv` (edge fn).
+5. `apps/erp/app/modules/sales/sales.import.server.ts` (new) — `importQuotes()`:
+ download from `private` bucket, PapaParse, apply `columnMappings`/`enumMappings`,
+ group by Quote Group, resolve customer/item/UoM readable ids → ids, loop
+ `insertQuote`/`upsertQuoteLine`/`upsertQuoteLinePrices`, collect
+ `{ inserted, updated, errors[], skipped[] }` in the same result shape the
+ `ImportResultsModal` expects.
+
+**No change needed:** `ImportCSVModal`, `UploadCSV`, `FieldMappings`,
+`ImportResultsModal`, `path.to.import`, `config.toml`.
+
+---
+
+## 10. Scope & phasing
+
+- **Phase 1 (this PRD):** headers + lines + explicit quantity-break pricing;
+ create-only idempotency; no cost rollup. Modes `quote`, `quoteLine`,
+ `quoteWithLines`.
+- **Phase 2 (future):** import quote-line **methods** (`quoteMaterial` /
+ `quoteMakeMethod` / `quoteOperation`) — the quote analog of the full BOM/BOP
+ import; optional auto price recalculation for Make-to-Order.
+
+---
+
+## 11. Risks & mitigations
+
+| Risk | Mitigation |
+|---|---|
+| Skipping quote side effects (opportunity/payment/shipment/link) with raw inserts | Go through `insertQuote` (Option B) or faithfully replicate (Option A) |
+| `discountPercent` entered as 0–100 not 0–1 | Validate range; document in template; consider auto-detect/convert with a warning |
+| Ambiguous customer/item resolution (dup names) | Reuse method-import's ambiguity detection; prefer readableId; error the row |
+| Partial failure mid-file | Per-quote isolation + per-group error reporting in `errors[]`; create-only avoids half-updates |
+| Pricing drift if replicated in Deno (Option A) | Prefer Option B; if A, add tests pinning parity with `insertQuote` |
+| Make-to-Order lines expecting rollup | Documented non-goal; prices are explicit in Phase 1 |
+| Models/edge-enum drift (the `fixedAsset` trap) | Keep `fieldMappings` and the execution path's accepted tables in sync; add a test |
+
+---
+
+## 12. Verification plan
+
+- **Unit:** row grouping (Quote Group → header + lines), quantity-break
+ aggregation, readable-id resolution, discountPercent validation, create-only
+ skip. (vitest, `--testPathPattern=sales`.)
+- **Type/lint:** `pnpm exec turbo run typecheck --filter=@carbon/erp`, `pnpm run lint`.
+- **Manual/e2e (`/test`):** upload a `quoteWithLines` CSV → verify quotes,
+ lines, and prices created; opportunity/payment/shipment exist; re-run same file
+ → all skipped (idempotent); malformed rows surface in the results modal.
+- **Fixtures:** sample CSVs for each mode; the wizard's template download should
+ produce a valid starting file.
+
+---
+
+## 13. Open questions
+
+**Resolved 2026-07-28:**
+- **Q1 — Modes:** ✅ **3 modes** (`quote`, `quoteLine`, `quoteWithLines`).
+- **Q2 — Architecture:** ✅ **Option B** — app-side `importQuotes`, reuse services.
+- **Q3 — Idempotency:** ✅ **Create-only skip** for Phase 1 (skip existing external ids).
+
+**Still open (low-risk; recommended defaults apply unless changed):**
+- **Q4 — Customer/item keys:** Accept **name or readableId** for customer, and
+ **part number (readableId)** for items? Any support for raw ids? *(Recommend
+ name-or-readableId, no raw ids.)*
+- **Q5 — Grouping key:** Use a dedicated **Quote Group** column as external id, or
+ reuse `customerReference`? *(Recommend a dedicated column so `customerReference`
+ stays a real business field.)*
+- **Q6 — Where does the import button live?** Quotes list table only, or also
+ Opportunities? *(Recommend Quotes table only for Phase 1.)*
+- **Q7 — Pricing scope:** Confirm Phase 1 imports **explicit** prices only (no
+ `resolvePrice`/rollup). *(Recommend yes.)*
+
+---
+
+## 14. References
+
+- Prior art: [#911 Import BOM & BOP](https://github.com/crbnos/carbon/pull/911),
+ [#1194 Parts-with-Methods](https://github.com/crbnos/carbon/pull/1194)
+- Rules: `.claude/rules/csv-import-system.md`, `.claude/rules/quote-discount-system.md`,
+ `.claude/rules/workflow-edge-function.md`
+- Code: `apps/erp/app/modules/shared/imports.models.ts`,
+ `apps/erp/app/components/ImportCSVModal/`,
+ `apps/erp/app/routes/x+/shared+/import.$tableId.tsx`,
+ `packages/database/supabase/functions/import-csv/{index,method-import}.ts`,
+ `apps/erp/app/modules/sales/{sales.models,sales.service}.ts`,
+ `apps/erp/app/modules/sales/AGENTS.md`
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index 1fbfff1bed..f3456d37ac 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -54,6 +54,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=sales
## Key Service Functions
+- `importQuotes` (`sales.import.server.ts`) — app-side bulk CSV quote importer (modes `quote` / `quoteLine` / `quoteWithLines`); reuses `insertQuote` / `upsertQuoteLine` / `upsertQuoteLinePrices` so quote side effects are preserved. Wired from `routes/x+/shared+/import.$tableId.tsx`; config in `modules/shared/imports.models.ts`. Create-only idempotency via `externalIntegrationMapping` (integration `csv`).
- `convertQuoteToOrder` / `convertSalesRfqToQuote` — lifecycle conversions via edge function
- `copyQuoteLine` / `copyQuote` — duplication via `get-method` edge function
- `applyPriceRules` — applies matched discount/markup rules to a starting price
diff --git a/apps/erp/app/modules/sales/sales.import.server.ts b/apps/erp/app/modules/sales/sales.import.server.ts
new file mode 100644
index 0000000000..2ac14dac21
--- /dev/null
+++ b/apps/erp/app/modules/sales/sales.import.server.ts
@@ -0,0 +1,701 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import Papa from "papaparse";
+import {
+ insertQuote,
+ upsertQuoteLine,
+ upsertQuoteLinePrices
+} from "./sales.service";
+
+// App-side bulk quote importer. Unlike the master-data imports (which run in the
+// `import-csv` Deno edge function with direct Kysely writes), quotes are created
+// through the real sales services so their side effects — opportunity,
+// quotePayment, quoteShipment, external portal link, sequence number — are
+// preserved (see `.ai/specs/2026-07-28-quote-bulk-import.md`, Option B).
+//
+// Three modes, discriminated by the `table` arg:
+// - `quote` header rows only (one quote per row)
+// - `quoteLine` lines + pricing appended to existing quotes (by Quote Number)
+// - `quoteWithLines` combined: header + line rows grouped by Quote Group
+//
+// Idempotency is create-only: a Quote Group whose external id was already
+// imported (recorded in `externalIntegrationMapping`, integration `csv`) is
+// skipped rather than duplicated. Within a file, a repeated (Part Number,
+// Quantity) line is skipped too.
+
+const QUOTE_IMPORT_TABLES = ["quote", "quoteLine", "quoteWithLines"] as const;
+export type QuoteImportTable = (typeof QUOTE_IMPORT_TABLES)[number];
+
+export function isQuoteImportTable(table: string): table is QuoteImportTable {
+ return (QUOTE_IMPORT_TABLES as readonly string[]).includes(table);
+}
+
+const EXTERNAL_INTEGRATION = "csv";
+const QUOTE_ENTITY_TYPE = "quote";
+
+const METHOD_TYPES = [
+ "Purchase to Order",
+ "Pull from Inventory",
+ "Make to Order"
+] as const;
+type MethodType = (typeof METHOD_TYPES)[number];
+
+const LINE_STATUSES = [
+ "Not Started",
+ "In Progress",
+ "Complete",
+ "No Quote"
+] as const;
+type LineStatus = (typeof LINE_STATUSES)[number];
+
+const QUOTE_STATUSES = [
+ "Draft",
+ "Sent",
+ "Ordered",
+ "Partial",
+ "Lost",
+ "Cancelled",
+ "Expired"
+] as const;
+type QuoteStatus = (typeof QUOTE_STATUSES)[number];
+
+// Legacy Buy/Pick/Make → current method-type names.
+const LEGACY_METHOD_TYPE: Record<string, MethodType> = {
+ buy: "Purchase to Order",
+ pick: "Pull from Inventory",
+ make: "Make to Order"
+};
+
+type Rec = Record<string, string>;
+type RowIssue = { row: number; reason: string; values: Rec };
+type Summary = {
+ inserted: number;
+ updated: number;
+ errors: RowIssue[];
+ skipped: RowIssue[];
+};
+
+type ImportQuotesArgs = {
+ table: QuoteImportTable;
+ filePath: string;
+ columnMappings: Record<string, string>;
+ enumMappings?: Record<string, Record<string, string>>;
+ companyId: string;
+ companyGroupId: string;
+ userId: string;
+};
+
+type ImportQuotesResult = {
+ data: Summary | null;
+ error: { message: string } | null;
+};
+
+// ---------------------------------------------------------------------------
+// small helpers
+// ---------------------------------------------------------------------------
+
+const text = (value: string | null | undefined): string => (value ?? "").trim();
+
+const num = (value: string | null | undefined): number | undefined => {
+ const t = text(value);
+ if (!t) return undefined;
+ const n = Number(t.replace(/,/g, ""));
+ return Number.isFinite(n) ? n : undefined;
+};
+
+function normalizeMethodType(raw: string | undefined): MethodType | null {
+ const t = text(raw);
+ if (!t) return null;
+ const lower = t.toLowerCase();
+ if (LEGACY_METHOD_TYPE[lower]) return LEGACY_METHOD_TYPE[lower];
+ const match = METHOD_TYPES.find((m) => m.toLowerCase() === lower);
+ return match ?? null;
+}
+
+function normalizeLineStatus(raw: string | undefined): LineStatus {
+ const t = text(raw).toLowerCase();
+ return LINE_STATUSES.find((s) => s.toLowerCase() === t) ?? "Not Started";
+}
+
+function normalizeQuoteStatus(
+ raw: string | undefined
+): QuoteStatus | undefined {
+ const t = text(raw).toLowerCase();
+ return QUOTE_STATUSES.find((s) => s.toLowerCase() === t);
+}
+
+// discountPercent is stored as a fraction 0..1. Accept either a fraction or a
+// whole percent (e.g. 10 → 0.10); reject anything above 100.
+function normalizeDiscount(raw: string | undefined): number | "invalid" {
+ const n = num(raw);
+ if (n === undefined) return 0;
+ if (n < 0) return "invalid";
+ if (n <= 1) return n;
+ if (n <= 100) return n / 100;
+ return "invalid";
+}
+
+type RowType = "QUOTE" | "LINE";
+
+function resolveRowType(record: Rec, table: QuoteImportTable): RowType {
+ if (table === "quote") return "QUOTE";
+ if (table === "quoteLine") return "LINE";
+ const explicit = text(record.rowType).toUpperCase();
+ if (explicit === "QUOTE") return "QUOTE";
+ if (explicit === "LINE") return "LINE";
+ // Blank Row Type: a Part Number means it's a line, otherwise a header.
+ return text(record.itemReadableId) ? "LINE" : "QUOTE";
+}
+
+// ---------------------------------------------------------------------------
+// entry point
+// ---------------------------------------------------------------------------
+
+export async function importQuotes(
+ client: SupabaseClient<Database>,
+ args: ImportQuotesArgs
+): Promise<ImportQuotesResult> {
+ const { table, filePath, columnMappings, companyId, companyGroupId, userId } =
+ args;
+
+ const summary: Summary = {
+ inserted: 0,
+ updated: 0,
+ errors: [],
+ skipped: []
+ };
+
+ // 1. download + parse ----------------------------------------------------
+ const download = await client.storage.from("private").download(filePath);
+ if (download.error || !download.data) {
+ return {
+ data: null,
+ error: { message: download.error?.message ?? "Failed to download file" }
+ };
+ }
+
+ const csvText = await download.data.text();
+ const parsed = Papa.parse<Rec>(csvText, {
+ header: true,
+ skipEmptyLines: true
+ });
+ const rawRows = parsed.data ?? [];
+
+ // 2. apply column (and any enum) mappings → per-field records ------------
+ const records: Rec[] = rawRows.map((raw) => {
+ const mapped: Rec = {};
+ for (const [field, header] of Object.entries(columnMappings)) {
+ if (!header || header === "N/A") continue;
+ const value = text(raw[header]);
+ const enumMap = args.enumMappings?.[field];
+ mapped[field] = enumMap
+ ? (enumMap[value] ?? enumMap.Default ?? value)
+ : value;
+ }
+ return mapped;
+ });
+
+ if (records.length === 0) {
+ return { data: summary, error: null };
+ }
+
+ // 3. batch-resolve references (customers, items, existing quotes) --------
+ const refs = await loadReferences(client, companyId, records, table);
+
+ // 4. process by mode -----------------------------------------------------
+ if (table === "quoteLine") {
+ await importLinesIntoExistingQuotes(client, {
+ records,
+ refs,
+ companyId,
+ userId,
+ summary
+ });
+ } else {
+ await importQuoteGroups(client, {
+ table,
+ records,
+ refs,
+ companyId,
+ companyGroupId,
+ userId,
+ summary
+ });
+ }
+
+ return { data: summary, error: null };
+}
+
+// ---------------------------------------------------------------------------
+// reference resolution
+// ---------------------------------------------------------------------------
+
+type ItemInfo = {
+ id: string;
+ readableId: string;
+ type: string;
+ defaultMethodType: string | null;
+ unitOfMeasureCode: string | null;
+};
+
+type References = {
+ customersByKey: Map<string, string>; // lowercased name|readableId → customer.id
+ ambiguousCustomers: Set<string>;
+ itemsByReadableId: Map<string, ItemInfo>;
+ quotesByNumber: Map<string, string>; // Quote Number → quote.id
+ importedExternalIds: Set<string>;
+};
+
+async function loadReferences(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ records: Rec[],
+ table: QuoteImportTable
+): Promise<References> {
+ const refs: References = {
+ customersByKey: new Map(),
+ ambiguousCustomers: new Set(),
+ itemsByReadableId: new Map(),
+ quotesByNumber: new Map(),
+ importedExternalIds: new Set()
+ };
+
+ // Customers — resolve by name or readableId (only needed for header rows).
+ const customerKeys = new Set<string>();
+ for (const r of records) {
+ const key = text(r.customerId).toLowerCase();
+ if (key) customerKeys.add(key);
+ }
+ if (customerKeys.size > 0 && table !== "quoteLine") {
+ const customers = await client
+ .from("customer")
+ .select("id, name, readableId")
+ .eq("companyId", companyId);
+ for (const c of customers.data ?? []) {
+ for (const raw of [c.name, c.readableId]) {
+ const k = text(raw ?? undefined).toLowerCase();
+ if (!k) continue;
+ if (refs.customersByKey.has(k) && refs.customersByKey.get(k) !== c.id) {
+ refs.ambiguousCustomers.add(k);
+ } else {
+ refs.customersByKey.set(k, c.id);
+ }
+ }
+ }
+ }
+
+ // Items — resolve part numbers referenced by line rows.
+ const partNumbers = new Set<string>();
+ for (const r of records) {
+ const pn = text(r.itemReadableId);
+ if (pn) partNumbers.add(pn);
+ }
+ if (partNumbers.size > 0) {
+ const items = await client
+ .from("item")
+ .select("id, readableId, type, defaultMethodType, unitOfMeasureCode")
+ .eq("companyId", companyId)
+ .in("readableId", Array.from(partNumbers));
+ for (const it of items.data ?? []) {
+ refs.itemsByReadableId.set(text(it.readableId).toLowerCase(), {
+ id: it.id,
+ readableId: it.readableId,
+ type: it.type ?? "Part",
+ defaultMethodType: it.defaultMethodType ?? null,
+ unitOfMeasureCode: it.unitOfMeasureCode ?? null
+ });
+ }
+ }
+
+ // Existing quotes — needed only when appending lines by Quote Number.
+ if (table === "quoteLine") {
+ const numbers = new Set<string>();
+ for (const r of records) {
+ const q = text(r.quoteId);
+ if (q) numbers.add(q);
+ }
+ if (numbers.size > 0) {
+ const quotes = await client
+ .from("quote")
+ .select("id, quoteId")
+ .eq("companyId", companyId)
+ .in("quoteId", Array.from(numbers));
+ for (const q of quotes.data ?? []) {
+ refs.quotesByNumber.set(text(q.quoteId), q.id);
+ }
+ }
+ }
+
+ // Already-imported Quote Groups (create-only idempotency).
+ if (table !== "quoteLine") {
+ const mappings = await client
+ .from("externalIntegrationMapping")
+ .select("externalId")
+ .eq("companyId", companyId)
+ .eq("integration", EXTERNAL_INTEGRATION)
+ .eq("entityType", QUOTE_ENTITY_TYPE);
+ for (const m of mappings.data ?? []) {
+ const k = text(m.externalId);
+ if (k) refs.importedExternalIds.add(k);
+ }
+ }
+
+ return refs;
+}
+
+// ---------------------------------------------------------------------------
+// mode: quote / quoteWithLines (grouped by Quote Group)
+// ---------------------------------------------------------------------------
+
+type Entry = { record: Rec; index: number };
+
+async function importQuoteGroups(
+ client: SupabaseClient<Database>,
+ ctx: {
+ table: QuoteImportTable;
+ records: Rec[];
+ refs: References;
+ companyId: string;
+ companyGroupId: string;
+ userId: string;
+ summary: Summary;
+ }
+): Promise<void> {
+ const { table, records, refs, companyId, companyGroupId, userId, summary } =
+ ctx;
+
+ // Group rows by Quote Group (externalId), preserving order.
+ const groups = new Map<
+ string,
+ { headers: Entry[]; lines: Entry[]; firstIndex: number }
+ >();
+ const groupOrder: string[] = [];
+
+ records.forEach((record, index) => {
+ const externalId = text(record.externalId);
+ const rowType = resolveRowType(record, table);
+
+ if (!externalId) {
+ summary.errors.push({
+ row: index,
+ reason: "Quote Group is required",
+ values: record
+ });
+ return;
+ }
+
+ if (!groups.has(externalId)) {
+ groups.set(externalId, { headers: [], lines: [], firstIndex: index });
+ groupOrder.push(externalId);
+ }
+ const group = groups.get(externalId)!;
+ if (rowType === "QUOTE") group.headers.push({ record, index });
+ else group.lines.push({ record, index });
+ });
+
+ for (const externalId of groupOrder) {
+ const group = groups.get(externalId)!;
+
+ // Create-only idempotency: skip a Quote Group already imported.
+ if (refs.importedExternalIds.has(externalId)) {
+ for (const entry of [...group.headers, ...group.lines]) {
+ summary.skipped.push({
+ row: entry.index,
+ reason: `Quote Group "${externalId}" was already imported`,
+ values: entry.record
+ });
+ }
+ continue;
+ }
+
+ const header = group.headers[0];
+ if (!header) {
+ // Lines with no header row in the file (combined mode only).
+ for (const entry of group.lines) {
+ summary.errors.push({
+ row: entry.index,
+ reason: `No header (QUOTE) row for Quote Group "${externalId}"`,
+ values: entry.record
+ });
+ }
+ continue;
+ }
+
+ // Extra header rows for the same group are duplicates.
+ for (const dup of group.headers.slice(1)) {
+ summary.skipped.push({
+ row: dup.index,
+ reason: `Duplicate header for Quote Group "${externalId}"`,
+ values: dup.record
+ });
+ }
+
+ // Resolve + create the header.
+ const customerKey = text(header.record.customerId).toLowerCase();
+ if (!customerKey) {
+ summary.errors.push({
+ row: header.index,
+ reason: "Customer is required",
+ values: header.record
+ });
+ failLines(group.lines, "Parent quote could not be created", summary);
+ continue;
+ }
+ if (refs.ambiguousCustomers.has(customerKey)) {
+ summary.errors.push({
+ row: header.index,
+ reason: `Customer "${text(header.record.customerId)}" is ambiguous`,
+ values: header.record
+ });
+ failLines(group.lines, "Parent quote could not be created", summary);
+ continue;
+ }
+ const customerId = refs.customersByKey.get(customerKey);
+ if (!customerId) {
+ summary.errors.push({
+ row: header.index,
+ reason: `Customer "${text(header.record.customerId)}" not found`,
+ values: header.record
+ });
+ failLines(group.lines, "Parent quote could not be created", summary);
+ continue;
+ }
+
+ const created = await insertQuote(client, {
+ customerId,
+ companyId,
+ companyGroupId,
+ createdBy: userId,
+ customerReference: text(header.record.customerReference) || undefined,
+ expirationDate: text(header.record.expirationDate) || undefined,
+ dueDate: text(header.record.dueDate) || undefined,
+ status: normalizeQuoteStatus(header.record.quoteStatus)
+ });
+
+ if (created.error || !created.data) {
+ summary.errors.push({
+ row: header.index,
+ reason: created.error?.message ?? "Failed to create quote",
+ values: header.record
+ });
+ failLines(group.lines, "Parent quote could not be created", summary);
+ continue;
+ }
+
+ summary.inserted += 1;
+ const quoteInternalId = created.data.id;
+
+ // Record the mapping so a re-import skips this Quote Group.
+ await client.from("externalIntegrationMapping").insert({
+ entityType: QUOTE_ENTITY_TYPE,
+ entityId: quoteInternalId,
+ integration: EXTERNAL_INTEGRATION,
+ externalId,
+ companyId,
+ createdBy: userId
+ });
+
+ await createLines(client, {
+ quoteInternalId,
+ lines: group.lines,
+ refs,
+ companyId,
+ userId,
+ summary
+ });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// mode: quoteLine (append to existing quotes by Quote Number)
+// ---------------------------------------------------------------------------
+
+async function importLinesIntoExistingQuotes(
+ client: SupabaseClient<Database>,
+ ctx: {
+ records: Rec[];
+ refs: References;
+ companyId: string;
+ userId: string;
+ summary: Summary;
+ }
+): Promise<void> {
+ const { records, refs, companyId, userId, summary } = ctx;
+
+ const byQuote = new Map<string, Entry[]>();
+ records.forEach((record, index) => {
+ const quoteNumber = text(record.quoteId);
+ if (!quoteNumber) {
+ summary.errors.push({
+ row: index,
+ reason: "Quote Number is required",
+ values: record
+ });
+ return;
+ }
+ if (!byQuote.has(quoteNumber)) byQuote.set(quoteNumber, []);
+ byQuote.get(quoteNumber)!.push({ record, index });
+ });
+
+ for (const [quoteNumber, lines] of byQuote) {
+ const quoteInternalId = refs.quotesByNumber.get(quoteNumber);
+ if (!quoteInternalId) {
+ failLines(lines, `Quote "${quoteNumber}" not found`, summary);
+ continue;
+ }
+ await createLines(client, {
+ quoteInternalId,
+ lines,
+ refs,
+ companyId,
+ userId,
+ summary
+ });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// shared line creation (+ in-file dedup + explicit pricing)
+// ---------------------------------------------------------------------------
+
+async function createLines(
+ client: SupabaseClient<Database>,
+ ctx: {
+ quoteInternalId: string;
+ lines: Entry[];
+ refs: References;
+ companyId: string;
+ userId: string;
+ summary: Summary;
+ }
+): Promise<void> {
+ const { quoteInternalId, lines, refs, companyId, userId, summary } = ctx;
+ const seen = new Set<string>(); // `${partNumber}|${quantity}` within this quote
+
+ for (const { record, index } of lines) {
+ const partNumber = text(record.itemReadableId);
+ if (!partNumber) {
+ summary.errors.push({
+ row: index,
+ reason: "Part Number is required",
+ values: record
+ });
+ continue;
+ }
+ const item = refs.itemsByReadableId.get(partNumber.toLowerCase());
+ if (!item) {
+ summary.errors.push({
+ row: index,
+ reason: `Part "${partNumber}" not found`,
+ values: record
+ });
+ continue;
+ }
+
+ const description = text(record.description) || item.readableId;
+ const quantity = num(record.quantity);
+ if (quantity === undefined || quantity < 0.00001) {
+ summary.errors.push({
+ row: index,
+ reason: "Quantity is required",
+ values: record
+ });
+ continue;
+ }
+
+ const dedupKey = `${partNumber.toLowerCase()}|${quantity}`;
+ if (seen.has(dedupKey)) {
+ summary.skipped.push({
+ row: index,
+ reason: `Duplicate line (${partNumber} @ qty ${quantity})`,
+ values: record
+ });
+ continue;
+ }
+ seen.add(dedupKey);
+
+ const discount = normalizeDiscount(record.discountPercent);
+ if (discount === "invalid") {
+ summary.errors.push({
+ row: index,
+ reason: "Discount Percent must be between 0 and 100",
+ values: record
+ });
+ continue;
+ }
+
+ const methodType =
+ normalizeMethodType(record.methodType) ??
+ normalizeMethodType(item.defaultMethodType ?? undefined) ??
+ "Pull from Inventory";
+
+ const unitOfMeasureCode =
+ text(record.unitOfMeasureCode) || item.unitOfMeasureCode || "EA";
+
+ const linePayload = {
+ quoteId: quoteInternalId,
+ itemId: item.id,
+ itemReadableId: item.readableId,
+ itemType: item.type,
+ description,
+ methodType,
+ unitOfMeasureCode,
+ status: normalizeLineStatus(record.lineStatus),
+ quantity: [quantity],
+ taxPercent: 0,
+ customerPartId: text(record.customerPartId) || undefined,
+ companyId,
+ createdBy: userId
+ };
+
+ const line = await upsertQuoteLine(
+ client,
+ linePayload as Parameters<typeof upsertQuoteLine>[1]
+ );
+
+ if (line.error || !line.data) {
+ summary.errors.push({
+ row: index,
+ reason: line.error?.message ?? "Failed to create quote line",
+ values: record
+ });
+ continue;
+ }
+
+ summary.inserted += 1;
+ const lineId = line.data.id;
+
+ const unitPrice = num(record.unitPrice);
+ if (unitPrice !== undefined) {
+ const priceResult = await upsertQuoteLinePrices(
+ client,
+ quoteInternalId,
+ lineId,
+ [
+ {
+ quoteLineId: lineId,
+ unitPrice,
+ leadTime: num(record.leadTime) ?? 0,
+ discountPercent: discount,
+ quantity,
+ createdBy: userId,
+ priceSource: "manual"
+ }
+ ]
+ );
+ if (priceResult.error) {
+ summary.errors.push({
+ row: index,
+ reason: `Line created but pricing failed: ${priceResult.error.message}`,
+ values: record
+ });
+ }
+ }
+ }
+}
+
+function failLines(lines: Entry[], reason: string, summary: Summary): void {
+ for (const { record, index } of lines) {
+ summary.errors.push({ row: index, reason, values: record });
+ }
+}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
index 533faa67d6..1ebe82f475 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
@@ -313,6 +313,18 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
updatedAt: false,
updatedBy: false
}}
+ importCSV={
+ permissions.can("create", "sales")
+ ? [
+ {
+ table: "quoteWithLines" as const,
+ label: t`Quotes with Lines`
+ },
+ { table: "quote" as const, label: t`Quotes` },
+ { table: "quoteLine" as const, label: t`Quote Lines` }
+ ]
+ : undefined
+ }
primaryAction={
permissions.can("create", "sales") && (
<New label={t`Quote`} to={path.to.newQuote} />
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index 22ad15abe1..17743045d8 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -650,6 +650,51 @@ const supplierShippingImportFields = {
}
} as const;
+// Quote import field fragments. Shared across the three quote import modes
+// (`quote`, `quoteLine`, `quoteWithLines`). Unlike the master-data imports, the
+// quote import executes app-side (`sales.import.server.ts` → insertQuote /
+// upsertQuoteLine / upsertQuoteLinePrices) so quote side effects (opportunity,
+// payment, shipment, external link) are preserved. Every cell is a plain string
+// resolved/validated server-side (customer + part number by readable id/name),
+// so the wizard needs no per-value enum-mapping step.
+const quoteHeaderImportFields = {
+ externalId: { label: "Quote Group", required: false, type: "string" },
+ customerId: { label: "Customer", required: false, type: "string" },
+ customerReference: {
+ label: "Customer Reference",
+ required: false,
+ type: "string"
+ },
+ expirationDate: { label: "Expiration Date", required: false, type: "string" },
+ dueDate: { label: "Due Date", required: false, type: "string" },
+ quoteStatus: { label: "Quote Status", required: false, type: "string" }
+} as const;
+
+const quoteLineImportFields = {
+ itemReadableId: { label: "Part Number", required: false, type: "string" },
+ description: { label: "Description", required: false, type: "string" },
+ methodType: { label: "Method Type", required: false, type: "string" },
+ unitOfMeasureCode: {
+ label: "Unit of Measure",
+ required: false,
+ type: "string"
+ },
+ quantity: { label: "Quantity", required: false, type: "string" },
+ unitPrice: { label: "Unit Price", required: false, type: "string" },
+ discountPercent: {
+ label: "Discount Percent",
+ required: false,
+ type: "string"
+ },
+ leadTime: { label: "Lead Time", required: false, type: "string" },
+ customerPartId: {
+ label: "Customer Part Number",
+ required: false,
+ type: "string"
+ },
+ lineStatus: { label: "Line Status", required: false, type: "string" }
+} as const;
+
export const fieldMappings = {
customer: {
id: {
@@ -1602,6 +1647,31 @@ export const fieldMappings = {
required: false,
type: "string"
}
+ },
+ // Quote header only — creates empty quotes.
+ quote: {
+ ...quoteHeaderImportFields,
+ externalId: { ...quoteHeaderImportFields.externalId, required: true },
+ customerId: { ...quoteHeaderImportFields.customerId, required: true }
+ },
+ // Quote lines (+ pricing) appended to an existing quote, keyed by Quote Number.
+ quoteLine: {
+ quoteId: { label: "Quote Number", required: true, type: "string" },
+ rowType: { label: "Row Type", required: false, type: "string" },
+ ...quoteLineImportFields,
+ itemReadableId: {
+ ...quoteLineImportFields.itemReadableId,
+ required: true
+ }
+ },
+ // Combined file — creates quotes with their lines + pricing. Row Type
+ // (QUOTE / LINE) discriminates header rows from line rows; blank is inferred
+ // from the presence of a Part Number. Rows are grouped by Quote Group.
+ quoteWithLines: {
+ rowType: { label: "Row Type", required: false, type: "string" },
+ ...quoteHeaderImportFields,
+ externalId: { ...quoteHeaderImportFields.externalId, required: true },
+ ...quoteLineImportFields
}
} as const;
@@ -1620,7 +1690,35 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {
consumable: "parts",
workCenter: "production",
process: "production",
- fixedAsset: "accounting"
+ fixedAsset: "accounting",
+ quote: "sales",
+ quoteLine: "sales",
+ quoteWithLines: "sales"
+};
+
+// Quote import validation is intentionally permissive at the mapping layer (every
+// cell an optional string); the app-side importer (`sales.import.server.ts`) does
+// the authoritative per-row validation (required fields, customer/part resolution,
+// duplicate detection), mirroring the method-import philosophy.
+const quoteImportSchemaFields = {
+ externalId: z.string().optional(),
+ quoteId: z.string().optional(),
+ rowType: z.string().optional(),
+ customerId: z.string().optional(),
+ customerReference: z.string().optional(),
+ expirationDate: z.string().optional(),
+ dueDate: z.string().optional(),
+ quoteStatus: z.string().optional(),
+ itemReadableId: z.string().optional(),
+ description: z.string().optional(),
+ methodType: z.string().optional(),
+ unitOfMeasureCode: z.string().optional(),
+ quantity: z.string().optional(),
+ unitPrice: z.string().optional(),
+ discountPercent: z.string().optional(),
+ leadTime: z.string().optional(),
+ customerPartId: z.string().optional(),
+ lineStatus: z.string().optional()
};
// Zod fragments for the method imports. Every method cell is an optional string at
@@ -2254,5 +2352,8 @@ export const importSchemas: Record<
.string()
.optional()
.describe("The location ID where the asset is located")
- })
+ }),
+ quote: z.object(quoteImportSchemaFields),
+ quoteLine: z.object(quoteImportSchemaFields),
+ quoteWithLines: z.object(quoteImportSchemaFields)
} as const;
diff --git a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
index 38483856db..a9c8b9e716 100644
--- a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
+++ b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
@@ -4,6 +4,10 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
+import {
+ importQuotes,
+ isQuoteImportTable
+} from "~/modules/sales/sales.import.server";
import { importCsv, importPermissions, importSchemas } from "~/modules/shared";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -17,9 +21,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
throw notFound("Table not found in the list of supported tables");
}
- const { companyId, userId } = await requirePermissions(request, {
- update: importPermissions[table]
- });
+ const { companyId, companyGroupId, userId } = await requirePermissions(
+ request,
+ {
+ update: importPermissions[table]
+ }
+ );
const schema = importSchemas[table].extend({
filePath: z.string().min(1, { message: "Path is required" }),
@@ -36,16 +43,32 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const { filePath, enumMappings, ...columnMappings } = validation.data;
+ const parsedEnumMappings = enumMappings
+ ? JSON.parse(enumMappings as string)
+ : undefined;
const serviceRole = getCarbonServiceRole();
- const importResult = await importCsv(serviceRole, {
- table,
- filePath: filePath as string,
- columnMappings,
- enumMappings: enumMappings ? JSON.parse(enumMappings as string) : undefined,
- companyId,
- userId
- });
+ // Quotes are created through the sales services (Option B) so quote side
+ // effects — opportunity, payment, shipment, external link — are preserved;
+ // all other tables run through the generic import-csv edge function.
+ const importResult = isQuoteImportTable(table)
+ ? await importQuotes(serviceRole, {
+ table,
+ filePath: filePath as string,
+ columnMappings: columnMappings as Record<string, string>,
+ enumMappings: parsedEnumMappings,
+ companyId,
+ companyGroupId,
+ userId
+ })
+ : await importCsv(serviceRole, {
+ table,
+ filePath: filePath as string,
+ columnMappings,
+ enumMappings: parsedEnumMappings,
+ companyId,
+ userId
+ });
if (importResult.error) {
return {
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 2da478ddbe..7f12594ab8 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -10038,6 +10038,9 @@ msgstr "Angebots-ID"
msgid "Quote Line"
msgstr "Angebotsposition"
+msgid "Quote Lines"
+msgstr "Angebotszeilen"
+
msgid "Quote Location"
msgstr "Angebotsort"
@@ -10065,6 +10068,9 @@ msgstr "Angebotsdatum"
msgid "Quotes"
msgstr "Angebote"
+msgid "Quotes with Lines"
+msgstr "Angebote mit Zeilen"
+
msgid "Quoting"
msgstr "Angebotserstellung"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index f76c006f54..2bf0495cbb 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -10038,6 +10038,9 @@ msgstr "Quote ID"
msgid "Quote Line"
msgstr "Quote Line"
+msgid "Quote Lines"
+msgstr "Quote Lines"
+
msgid "Quote Location"
msgstr "Quote Location"
@@ -10065,6 +10068,9 @@ msgstr "Quoted Date"
msgid "Quotes"
msgstr "Quotes"
+msgid "Quotes with Lines"
+msgstr "Quotes with Lines"
+
msgid "Quoting"
msgstr "Quoting"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 387d41c65b..80f616ce16 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -10038,6 +10038,9 @@ msgstr "ID de Cotización"
msgid "Quote Line"
msgstr "Línea de Cotización"
+msgid "Quote Lines"
+msgstr "Líneas de Cotización"
+
msgid "Quote Location"
msgstr "Ubicación de Cotización"
@@ -10065,6 +10068,9 @@ msgstr "Fecha de Cotización"
msgid "Quotes"
msgstr "Cotizaciones"
+msgid "Quotes with Lines"
+msgstr "Cotizaciones con Líneas"
+
msgid "Quoting"
msgstr "Cotización"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index a356ea9296..d2c41bf9a1 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -10038,6 +10038,9 @@ msgstr "ID de devis"
msgid "Quote Line"
msgstr "Ligne de devis"
+msgid "Quote Lines"
+msgstr "Lignes de Devis"
+
msgid "Quote Location"
msgstr "Lieu du devis"
@@ -10065,6 +10068,9 @@ msgstr "Date de devis"
msgid "Quotes"
msgstr "Devis"
+msgid "Quotes with Lines"
+msgstr "Devis avec Lignes"
+
msgid "Quoting"
msgstr "Devis"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index a0f6c8673f..f575caf4df 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -10038,6 +10038,9 @@ msgstr "उद्धरण ID"
msgid "Quote Line"
msgstr "उद्धरण पंक्ति"
+msgid "Quote Lines"
+msgstr "उद्धरण पंक्तियाँ"
+
msgid "Quote Location"
msgstr "उद्धरण स्थान"
@@ -10065,6 +10068,9 @@ msgstr "उद्धृत तारीख"
msgid "Quotes"
msgstr "उद्धरण"
+msgid "Quotes with Lines"
+msgstr "पंक्तियों के साथ उद्धरण"
+
msgid "Quoting"
msgstr "उद्धरण"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 608b347aa2..91fc00a30f 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -10038,6 +10038,9 @@ msgstr "ID Preventivo"
msgid "Quote Line"
msgstr "Riga di Preventivo"
+msgid "Quote Lines"
+msgstr "Righe Preventivo"
+
msgid "Quote Location"
msgstr "Ubicazione Preventivo"
@@ -10065,6 +10068,9 @@ msgstr "Data Quotata"
msgid "Quotes"
msgstr "Preventivi"
+msgid "Quotes with Lines"
+msgstr "Preventivi con Righe"
+
msgid "Quoting"
msgstr "Quotazione"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 6432d5f028..69b9daf218 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -10038,6 +10038,9 @@ msgstr "見積ID"
msgid "Quote Line"
msgstr "見積行"
+msgid "Quote Lines"
+msgstr "見積明細"
+
msgid "Quote Location"
msgstr "見積もりロケーション"
@@ -10065,6 +10068,9 @@ msgstr "見積日"
msgid "Quotes"
msgstr "見積"
+msgid "Quotes with Lines"
+msgstr "見積明細付き"
+
msgid "Quoting"
msgstr "見積"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 8a9c3ebd7d..b52d76bb0f 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -10038,6 +10038,9 @@ msgstr "견적 ID"
msgid "Quote Line"
msgstr "견적 라인"
+msgid "Quote Lines"
+msgstr "견적 라인"
+
msgid "Quote Location"
msgstr "견적 위치"
@@ -10065,6 +10068,9 @@ msgstr "견적일"
msgid "Quotes"
msgstr "견적"
+msgid "Quotes with Lines"
+msgstr "라인이 포함된 견적"
+
msgid "Quoting"
msgstr "견적"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 267dac08ba..742849440f 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -10038,6 +10038,9 @@ msgstr "ID Oferty"
msgid "Quote Line"
msgstr "Linia oferty"
+msgid "Quote Lines"
+msgstr "Pozycje oferty"
+
msgid "Quote Location"
msgstr "Lokalizacja oferty"
@@ -10065,6 +10068,9 @@ msgstr "Data wyceny"
msgid "Quotes"
msgstr "Oferty"
+msgid "Quotes with Lines"
+msgstr "Oferty z pozycjami"
+
msgid "Quoting"
msgstr "Wycena"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index bda9a0ded6..8b37bd8208 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -10038,6 +10038,9 @@ msgstr "ID da Cotação"
msgid "Quote Line"
msgstr "Linha de Cotação"
+msgid "Quote Lines"
+msgstr "Linhas de Cotação"
+
msgid "Quote Location"
msgstr "Localização da Cotação"
@@ -10065,6 +10068,9 @@ msgstr "Data da Cotação"
msgid "Quotes"
msgstr "Orçamentos"
+msgid "Quotes with Lines"
+msgstr "Cotações com Linhas"
+
msgid "Quoting"
msgstr "Cotação"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index bfcac3b516..57f705fe79 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -10038,6 +10038,9 @@ msgstr "ID предложения"
msgid "Quote Line"
msgstr "Строка предложения"
+msgid "Quote Lines"
+msgstr "Строки котировки"
+
msgid "Quote Location"
msgstr "Местоположение предложения"
@@ -10065,6 +10068,9 @@ msgstr "Дата предложения"
msgid "Quotes"
msgstr "Предложения"
+msgid "Quotes with Lines"
+msgstr "Котировки со строками"
+
msgid "Quoting"
msgstr "Котировка"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index fb5a204674..2bed7d76bb 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -10038,6 +10038,9 @@ msgstr "Teklif Kimliği"
msgid "Quote Line"
msgstr "Teklif Satırı"
+msgid "Quote Lines"
+msgstr "Teklif Satırları"
+
msgid "Quote Location"
msgstr "Teklif Konumu"
@@ -10065,6 +10068,9 @@ msgstr "Teklif Tarihi"
msgid "Quotes"
msgstr "Teklifler"
+msgid "Quotes with Lines"
+msgstr "Satırları Olan Teklifler"
+
msgid "Quoting"
msgstr "Teklif Verme"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 359d5f1884..8a1c948a4d 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -10038,6 +10038,9 @@ msgstr "报价单ID"
msgid "Quote Line"
msgstr "报价行"
+msgid "Quote Lines"
+msgstr "报价行"
+
msgid "Quote Location"
msgstr "报价地点"
@@ -10065,6 +10068,9 @@ msgstr "报价日期"
msgid "Quotes"
msgstr "报价"
+msgid "Quotes with Lines"
+msgstr "有行的报价单"
+
msgid "Quoting"
msgstr "报价"