> For the complete documentation index, see [llms.txt](https://docs.durohub.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.durohub.com/core-concepts/sourcing.md).

# Sourcing

Sourcing describes how a component gets built: the manufacturer parts (MPNs) that source it, the distributor quotes (DPNs) that price each part, and which of those sources is currently primary. A component can carry multiple parts, and each part multiple quotes — that is what lets you multi-source a component instead of committing to a single vendor.

This page covers the sourcing operations with practical examples. For the exact field-by-field shape of every type, introspect the schema in [Apollo Explorer](https://api.durohub.com/graphql) — the schema descriptions there are the source of truth.

## Overview

### The Sourcing Model

```
Component
  └─ Part            an MPN from a manufacturer
       ├─ Quote       a distributor's DPN offer — pricing, MOQ, lead time
       │    └─ Document (via QuoteDocument)
       └─ Document (via PartDocument)

Component
  └─ PrimarySource   the ranked list of quotes — rank 1 is the current primary
```

| Entity          | Identity                 | Description                                                                                                                                                                                                                                                            |
| --------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Part`          | MPN + manufacturer       | A manufacturer part that can source the component                                                                                                                                                                                                                      |
| `Quote`         | DPN + distributor        | A distributor's offer for a part                                                                                                                                                                                                                                       |
| `Vendor`        | Name, within one library | A vendor in one library; `types` says whether it acts as `MANUFACTURER`, `DISTRIBUTOR`, or both. Carries the vendor's own profile — `hqAddress`, `dunsNumber`, `taxId`                                                                                                 |
| `LibraryVendor` | —                        | The vendor's entry on its library's list, with an `approvalStatus`, the library's account details — `accountId`, `accountManager` — and computed [component and quote counts](#component-and-quote-counts-on-libraryvendor). Its `id` and `vendorId` equal `vendor.id` |
| `PrimarySource` | —                        | One entry in a component's ranked source list                                                                                                                                                                                                                          |

### The `vendorSourcing` Namespace

All sourcing operations are namespaced: queries live under `Query.vendorSourcing` and mutations under `Mutation.vendorSourcing`. There are no root-level sourcing fields. The one operation outside `vendorSourcing` is the AI filter builder for the Vendors list, which lives under `Query.vendorSearch` — see [Building vendor filters with AI](#building-vendor-filters-with-ai).

{% hint style="warning" %}
`mutation { applySourcingChangeset(...) }` fails. Wrap every sourcing operation:

```graphql
mutation {
  vendorSourcing {
    applySourcingChangeset(...)
  }
}
```

{% endhint %}

## Required Headers

All sourcing operations require the same headers as the rest of the API:

```bash
curl 'https://api.durohub.com/graphql' \
  -H 'x-api-key: YOUR_API_KEY' \
  -H 'x-organization: @your-org' \
  -H 'x-library: @your-org/your-library' \
  -H 'Content-Type: application/json' \
  -d '{"query": "..."}'
```

Sourcing operations never take a `libraryId` argument — the library comes from the `x-library` header.

***

## Querying Sourcing Data

### Parts on a Component

```graphql
query GetPartsForComponent {
  vendorSourcing {
    parts(filter: { componentId: "comp-123" }) {
      id
      mpn
      description
      manufacturer {
        name
      }
    }
  }
}
```

`part(id)` fetches a single part; `partHistory(partId)` returns its full version history. Parts carry `mpnUrl` — a link to the manufacturer's page for the MPN — accepted on the create and update inputs as well.

Parts also expose `isLegacyImport` (`Boolean`) — see [Legacy-import parts and quotes](#legacy-import-parts-and-quotes).

### Quotes

`quotes(partId)` lists a single part's quotes. To compare offers across every part on a component in one call, use `quotesByComponent`:

```graphql
query GetQuotesForComponent {
  vendorSourcing {
    quotesByComponent(componentId: "comp-123") {
      id
      dpn
      unitPrice
      leadTimeDays
      minQuantity
      distributor {
        name
      }
      part {
        mpn
        manufacturer {
          name
        }
      }
    }
  }
}
```

Quote fields that drive sourcing decisions:

| Field                           | Type                 | Description                                                                                                                |
| ------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `unitPrice`                     | `Float`              | Price per unit. Nullable — a quote can be recorded before its price is known                                               |
| `minQuantity`                   | `Int`                | The distributor's minimum order quantity                                                                                   |
| `maxQuantity`                   | `Int`                | The distributor's cap, if any                                                                                              |
| `packageQuantity`               | `Int`                | Units per reel, tube, or tray                                                                                              |
| `leadTimeDays`                  | `Int`                | Distributor lead time (the part's `manufacturerLeadTimeDays` is separate)                                                  |
| `dpnUrl`                        | `String`             | Link to the distributor's page for this DPN                                                                                |
| `description`                   | `String`             | Free-text notes about the quote                                                                                            |
| `currency`                      | `String!`            | The currency of `unitPrice`, such as `USD`. Always set                                                                     |
| `packageType` / `packageTypeId` | `PackageType` / `ID` | How the parts are packaged, such as `Tape & Reel` or `Cut Tape`                                                            |
| `isLegacyImport`                | `Boolean`            | `true` when the quote was created by the legacy cost migration rather than entered as a real distributor offer — see below |

{% hint style="warning" %}
`Quote.unitPrice` is nullable. Handle `null` rather than assuming every quote has a price.
{% endhint %}

### Legacy-import parts and quotes

Before sourcing existed, a component's price lived in a single `Cost` attribute with no manufacturer or distributor attached. When that attribute was retired, those values were migrated onto the sourcing model. Because a quote requires a part and a distributor, the migration created placeholders: a sentinel distributor (`Unknown - Legacy Import`), a part whose MPN is the component's ID, and a quote carrying the old cost as its `unitPrice` with default package quantity and lead time.

`Part.isLegacyImport` and `Quote.isLegacyImport` mark those placeholder rows:

```graphql
query FindLegacySourcing {
  vendorSourcing {
    quotesByComponent(componentId: "comp-123") {
      id
      unitPrice
      isLegacyImport
      distributor {
        name
      }
      part {
        mpn
        isLegacyImport
      }
    }
  }
}
```

Both fields are read-only — they are set by the migration and are not accepted on `CreateQuoteInput`, `CreatePartInput`, or the update inputs. Anything you create through the API returns `false`.

{% hint style="info" %}
Treat a `true` flag as "the price is real, the rest of the row is not". The manufacturer, MPN, distributor, DPN, package quantity, and lead time on a legacy-import row are placeholders, so don't surface them as vendor data or use them to compare offers. Prompt users to replace the row with a real part and quote; once they do, the flag stays `false` on the new rows.
{% endhint %}

### Vendors

Every vendor belongs to one library: the library named by the `x-library` header. `vendors` / `vendor(id)` search and read that library's vendors; another library's vendor returns `VENDOR_NOT_FOUND`, even in the same organization. `manufacturers` narrows to the library's vendors that can act as manufacturers. Every vendor a library has is on its list, `libraryVendorList`, each entry carrying an `approvalStatus`. For a paged, sorted, filtered view of that list — with per-vendor component counts — use [`libraryVendors`](#listing-library-vendors-with-paging-and-sorting).

{% hint style="warning" %}
Every vendor operation runs in one library, including `vendors`, `vendor`, `checkVendorNameSimilarity`, `createVendor`, `updateVendor`, `saveLibraryVendor` and `archiveVendor`: the library named by the `x-library` header, which must be your API key's library. A request without `x-library` fails with `MISSING_LIBRARY_CONTEXT`. The one exception is [`vendorSearch.buildFilterWithAI`](#building-vendor-filters-with-ai), which returns `MISSING_CONTEXT`. Vendor ids changed when vendors moved into libraries; see [Vendors moved into libraries](#vendors-moved-into-libraries).
{% endhint %}

Vendor names are unique within a library, and the check is case-sensitive: `createVendor`, `updateVendor` or `saveLibraryVendor` with a name the library already has returns `VENDOR_NAME_TAKEN`. Another library can use the same name.

Before creating or renaming a vendor, check for near-duplicates:

```graphql
query CheckVendorName {
  vendorSourcing {
    checkVendorNameSimilarity(name: "Texas Instruments") {
      vendorId
      name
      similarity
      reason
    }
  }
}
```

Each `SimilarVendorMatch` carries the matched vendor's `vendorId` (`ID!`), its `name`, a `similarity` score and a `reason` (`VendorNameMatchReason!`) saying why it matched:

| Reason       | Meaning                                                                                            | `similarity`                            |
| ------------ | -------------------------------------------------------------------------------------------------- | --------------------------------------- |
| `EXACT`      | The same name ignoring case and leading or trailing spaces, e.g. `acme` against an existing `Acme` | `1`                                     |
| `STEM`       | The singular or plural form of an existing name, e.g. `Resistor` against `Resistors`               | `0.95`                                  |
| `SIMILARITY` | A similar spelling, e.g. `Digikey` against `Digi-Key`                                              | The Levenshtein score, `0.85` or higher |

Results are sorted by `similarity`, highest first, so exact matches lead; the rest are ordered by score, not by `reason`. Archived vendors are not returned. When renaming a vendor, pass its id as `excludeId` so it doesn't match itself:

```graphql
query CheckVendorRename {
  vendorSourcing {
    checkVendorNameSimilarity(name: "Digi-Key Electronics", excludeId: "vendor-digikey") {
      vendorId
      name
      similarity
      reason
    }
  }
}
```

`vendorId` is the matching vendor's id in the current library: pass it to `vendor(id)`, `libraryVendor(vendorId)` or `saveLibraryVendor` to open or update the existing vendor instead of creating a duplicate.

{% hint style="info" %}
An `EXACT` match is a suggestion, not a verdict: a name that matches ignoring case is still accepted by `createVendor`, `updateVendor` and `saveLibraryVendor`. Only a name the library already has in the same case is rejected with `VENDOR_NAME_TAKEN`. Use `vendorId` to open or link the existing vendor instead of creating another.
{% endhint %}

#### Adding, archiving and removing vendors

| Operation                                              | What it does                                                                                                                                                                                                                                                                                                                            | Errors                                                                                                                       |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `createVendor`                                         | Creates the vendor in the current library and puts it on the list as `PROPOSED`                                                                                                                                                                                                                                                         | `VENDOR_NAME_TAKEN`                                                                                                          |
| `addToVendorList(input: { vendorId, approvalStatus })` | Returns the vendor's list entry. Every vendor is already on the list, so this only applies `approvalStatus` when one is given and differs from the current status. Changing it, including a reset to `PROPOSED`, needs `sourcing.vendor.status_change` (see [Changing a vendor's approval status](#changing-a-vendors-approval-status)) | `VENDOR_NOT_FOUND` for an archived or removed vendor                                                                         |
| `archiveVendor(id)`                                    | Archives the vendor in this library. It stays on the list and keeps its parts and quotes                                                                                                                                                                                                                                                | `VENDOR_NOT_FOUND` if it's already archived                                                                                  |
| `removeFromVendorList(id)`                             | Deletes the vendor and frees its name, when no part or quote in the library uses it, archived ones included                                                                                                                                                                                                                             | `VENDOR_IN_USE` while any part or quote uses it; `VENDOR_LIST_ENTRY_NOT_FOUND` for an id that isn't a vendor in this library |

{% hint style="info" %}
A removed vendor can't be added back: `addToVendorList` returns `VENDOR_NOT_FOUND`. Create it again with `createVendor`; it gets a new id. To stop using a vendor that parts or quotes still reference, archive it instead, or move its parts and quotes to another vendor first.
{% endhint %}

#### Listing library vendors with paging and sorting

`libraryVendorList` returns the whole list in one call, unpaged; it takes the same `filter` as `libraryVendors` (all four fields below, and the same error). Three queries cover the cases where that is not enough — a long list, a sort order, or a status breakdown. All three require the `sourcing.vendor.read` permission in the library named by the `x-library` header (see [RBAC](https://docs.durohub.com/advanced-topics/rbac.md)).

| Query                                                                                                            | Returns                                                                                                                                                                                                     |
| ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `libraryVendors(filter: VendorListFilterInput, pagination: VendorListPaginationInput): LibraryVendorConnection!` | The current library's vendors, excluding archived ones                                                                                                                                                      |
| `archivedLibraryVendors(pagination: VendorListPaginationInput): LibraryVendorConnection!`                        | The vendors archived in the current library — the ones `archiveVendor` archived there. Archiving is per library, so this is not an organization-wide archive. Takes no `filter`                             |
| `libraryVendorStatusCounts: [ApprovalStatusCount!]!`                                                             | How many non-archived listed vendors are in each `approvalStatus`. Always returns all four statuses, zeros included, in the order `PROPOSED`, `IN_REVIEW`, `APPROVED`, `NOT_APPROVED`. It is never filtered |

```graphql
query VendorList($after: String) {
  vendorSourcing {
    libraryVendors(
      filter: { approvalStatus: APPROVED, searchTerm: "Texas" }
      pagination: { first: 25, after: $after, orderBy: { field: TOTAL_COMPONENTS, direction: DESC } }
    ) {
      edges {
        node {
          id
          approvalStatus
          vendor { id name }
          totalComponents
          primarySourceComponents
          prioritizedComponents
          primaryQuotes
          prioritizedQuotes
          lastEditedAt
        }
      }
      pageInfo { hasNextPage endCursor }
      totalCount
    }
    libraryVendorStatusCounts { status count }
  }
}
```

The archived list takes the same selection under `archivedLibraryVendors(pagination: { first: 25, after: $after })`, with no `filter`.

**Filtering.** `VendorListFilterInput` has four optional fields, all combined with AND:

| Field                                 | Matches                                                                                                                                                                   |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `approvalStatus: ApprovalStatus`      | Exactly one approval status. Still supported; use it or `approvalStatuses`, not both                                                                                      |
| `approvalStatuses: [ApprovalStatus!]` | Any of the listed approval statuses. `null` or an empty list means all statuses                                                                                           |
| `types: [VendorType!]`                | Any of the listed vendor types — `MANUFACTURER`, `DISTRIBUTOR`. A vendor with several types matches if any one of them is listed. `null` or an empty list means all types |
| `searchTerm: String`                  | A case-insensitive substring of the vendor's name or any of its aliases. It is a literal string, so `%` and `_` match themselves rather than acting as wildcards          |

Passing `types` together with `approvalStatuses` (or `approvalStatus`) returns only vendors that satisfy both. `totalCount`, cursor and offset paging, and the sort order all follow the filtered result.

```graphql
query ApprovedOrInReviewManufacturers {
  vendorSourcing {
    libraryVendors(
      filter: { approvalStatuses: [APPROVED, IN_REVIEW], types: [MANUFACTURER] }
      pagination: { first: 25, orderBy: { field: NAME, direction: ASC } }
    ) {
      edges {
        node {
          id
          approvalStatus
          vendor { id name types }
        }
      }
      pageInfo { hasNextPage endCursor }
      totalCount
    }
  }
}
```

{% hint style="warning" %}
`approvalStatus` and `approvalStatuses` are two forms of the same filter. Supplying both — even when the single status is also in the list, and even when `approvalStatuses` is `[]` — fails with [`VENDOR_LIST_STATUS_FILTERS_BOTH`](https://docs.durohub.com/advanced-topics/error-handling.md#sourcing-query-errors) before anything is queried. Pass `approvalStatuses` to match several statuses, or `approvalStatus` for one. A `null` counts as not sent, so `approvalStatus: null` with a list is fine.
{% endhint %}

**Pagination and sorting.** `VendorListPaginationInput` has four optional fields:

| Field                           | Description                                                                                                                                                                                                                                                                                     |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `first: Int`                    | Page size. Defaults to 10 when omitted or `null`. Values outside 1–100 are clamped to that range rather than rejected, so `0` or a negative value yields one row                                                                                                                                |
| `after: String`                 | The `endCursor` of the previous page, for cursor paging. Omit it for the first page. Cannot be combined with `offset`                                                                                                                                                                           |
| `offset: Int`                   | Number of rows to skip, for offset paging — "go to page N". Must be a non-negative integer; a negative or non-integer value is rejected as a validation error. Omitting it, passing `null`, or passing `0` without `after` all return the first page as before. Cannot be combined with `after` |
| `orderBy: VendorListOrderInput` | Sort order. Defaults to `NAME` `ASC`. When supplied, both `field` and `direction` are required                                                                                                                                                                                                  |

`VendorListOrderField` is one of `NAME`, `APPROVAL_STATUS`, `TOTAL_COMPONENTS`, `PRIORITIZED_COMPONENTS`, `PRIMARY_SOURCE_COMPONENTS`, `PRIORITIZED_QUOTES`, `PRIMARY_QUOTES` or `LAST_EDITED_AT`; `OrderDirection` is `ASC` or `DESC`. `NAME` sorts case-insensitively, and `APPROVAL_STATUS` follows the workflow order `PROPOSED`, `IN_REVIEW`, `APPROVED`, `NOT_APPROVED` (reversed for `DESC`). Ties are always broken by lowercase vendor name ascending, then vendor id ascending — in both directions — so every sort is a total order and paging never skips or repeats a vendor.

`LibraryVendorConnection` carries `edges { node }`, `pageInfo { hasNextPage endCursor }` and `totalCount`. Edges have no cursor of their own; cursor paging is forward-only, so pass `pageInfo.endCursor` back as `pagination.after` while `hasNextPage` is `true`. `totalCount` is the number of vendors matching the filter, not the page size, and is still returned on an empty page (`edges: []`, `hasNextPage: false`, `endCursor: null`).

**Cursor or offset, not both.** Both `libraryVendors` and `archivedLibraryVendors` accept either style of paging in the same `pagination` argument:

* **Cursor paging** (`after`) walks the list forward one page at a time, as above. Leave `offset` out or `null`.
* **Offset paging** (`offset`) jumps straight to a page by position, which is what a numbered pager needs. `offset` skips that many rows after the filter and sort have been applied, so for page *N* send `offset = (N − 1) × the page size` (`first` after clamping to 1–100; 10 when omitted). Leave `after` out or `null`.

Passing any non-null `offset` — including `0` — together with a non-null `after` fails with [`VENDOR_LIST_OFFSET_WITH_CURSOR`](https://docs.durohub.com/advanced-topics/error-handling.md#sourcing-query-errors) before the cursor is decoded or anything is queried.

For example, with a page size of 10, page 3 is rows 21–30:

```graphql
query VendorListPage {
  vendorSourcing {
    libraryVendors(
      filter: { approvalStatus: APPROVED }
      pagination: { first: 10, offset: 20, orderBy: { field: NAME, direction: ASC } }
    ) {
      edges { node { id vendor { id name } } }
      pageInfo { hasNextPage endCursor }
      totalCount
    }
  }
}
```

An offset page returns the same `pageInfo` and `totalCount` as a cursor page: `totalCount` is still the filtered total, `hasNextPage` is `true` when rows remain after the page, and `endCursor` is the page's last row, so you can continue from an offset page with `after` alone (for example, "page 3" followed by "Next"). An `offset` past the end of the list returns `edges: []`, the correct `totalCount`, `hasNextPage: false` and `endCursor: null`.

{% hint style="info" %}
Offset pages are computed against the list as it is at the time of each request. If vendors are added to or removed from the list between requests, later pages shift, so a vendor can appear on two pages or on none. Use cursor paging when you need to walk the whole list without repeats or skips.
{% endhint %}

{% hint style="warning" %}
Cursors are opaque and are bound to the query and sort that produced them. A cursor that is malformed, empty, from the other list query, or from a different `orderBy` fails with [`VENDOR_LIST_INVALID_CURSOR`](https://docs.durohub.com/advanced-topics/error-handling.md#sourcing-query-errors). When you change the sort or switch between `libraryVendors` and `archivedLibraryVendors`, restart from the first page by omitting `after`. Cursors are not checked against the filter or library, so change those from the first page too.
{% endhint %}

#### Component and quote counts on `LibraryVendor`

Every `LibraryVendor` — from the queries above as well as from `libraryVendorList`, `libraryVendor(vendorId)` and the vendor mutations — carries six computed fields describing the vendor's footprint in the current library:

| Field                     | Type        | Description                                                                                                                                                        |
| ------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `totalComponents`         | `Int!`      | Distinct components with a live part the vendor manufactures or a live quote it distributes                                                                        |
| `primarySourceComponents` | `Int!`      | Distinct components where one of the vendor's rows is the **primary** source (rank 1)                                                                              |
| `prioritizedComponents`   | `Int!`      | Distinct components where one of the vendor's rows is a **prioritized** source (rank 2 or lower). Unlike `prioritizedQuotes`, this excludes the primary            |
| `primaryQuotes`           | `Int!`      | Live quotes the vendor distributes whose primary-source entry has rank 1 — the vendor's **PRIMARY** rows                                                           |
| `prioritizedQuotes`       | `Int!`      | Live quotes the vendor distributes with a primary-source entry at any rank, **including** the primary — the vendor's **PRIMARY** and **PRIORITIZED** rows together |
| `lastEditedAt`            | `DateTime!` | When the vendor or its list entry was last edited, to the millisecond. It does not reflect edits to the vendor's parts or quotes                                   |

The component counts use the same rule as the `sourcingTag` on [`componentSourcingByVendor`](https://docs.durohub.com/core-concepts/components.md#components-sourced-by-a-vendor): a distributor row takes its own quote's rank, and a manufacturer row inherits the best rank among its part's live quotes. Archived parts and quotes are excluded, as are archived and rollup primary-source entries. A vendor with no sourcing in the library reports zero for all of them.

`primarySourceComponents` and `prioritizedComponents` are not mutually exclusive — a component counts toward both when the vendor has both a PRIMARY and a PRIORITIZED row for it — so they do not sum to `totalComponents`.

**Quote counts versus component counts.** The two quote counts count *quotes*, not components, and only quotes the vendor itself distributes. They apply the same live and non-rollup filters as the component counts, but a manufacturer row never contributes: a vendor that only manufactures parts in the library reports `0` for both, even when its distributors' quotes are ranked. The quote counts also nest differently from the component counts — `prioritizedQuotes` includes the primary quote, whereas `prioritizedComponents` does not include rank-1 rows. For example, a vendor distributing one rank-1 quote and two lower-ranked quotes (ranks 2 and 3) on a single component reports:

| Field                     | Value |
| ------------------------- | ----- |
| `primaryQuotes`           | `1`   |
| `prioritizedQuotes`       | `3`   |
| `primarySourceComponents` | `1`   |
| `prioritizedComponents`   | `1`   |

Sort the list by either quote count with `PRIMARY_QUOTES` or `PRIORITIZED_QUOTES` in `orderBy`; ties break by vendor name and id like every other sort.

#### Building vendor filters with AI

`vendorSearch.buildFilterWithAI` turns a sentence such as "approved distributors" into the filters a Vendors list would apply. It only builds filters: it does not run a vendor search and returns no vendors. Apply the result yourself, for example as `libraryVendors` filter arguments or as editable filters a person confirms before you query. It lives under the root `Query.vendorSearch` field, not under `vendorSourcing`, and requires the `sourcing.vendor.read` permission in the library named by the `x-library` header (see [RBAC](https://docs.durohub.com/advanced-topics/rbac.md)).

```graphql
query BuildVendorFilter($query: String!) {
  vendorSearch {
    buildFilterWithAI(input: { query: $query }) {
      success
      error
      interpretation
      unsupported
      filterValues {
        field
        comparator
        value
        displayLabel
      }
    }
  }
}
```

With `{ "query": "approved distributors" }`, a response has this shape. The wording of `interpretation` comes from the model and varies.

```json
{
  "data": {
    "vendorSearch": {
      "buildFilterWithAI": {
        "success": true,
        "error": null,
        "interpretation": "Showing approved distributors",
        "unsupported": [],
        "filterValues": [
          { "field": "type", "comparator": "is", "value": "DISTRIBUTOR", "displayLabel": "Distributor" },
          { "field": "status", "comparator": "is", "value": "APPROVED", "displayLabel": "Approved" }
        ]
      }
    }
  }
}
```

**Input.** `BuildVendorAiFilterInput` has one field, `query: String!`. It is trimmed and must be 3–500 characters. The model receives only the sentence and a fixed vocabulary of fields, comparators and values — never your vendor or library records.

**Result.** `VendorAiFilterResult` has these fields:

| Field                                       | Meaning                                                                                                                                                                                              |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `success: Boolean!`                         | Whether the sentence was interpreted. `true` can come with zero filters                                                                                                                              |
| `filterValues: [VendorFilterValueOutput!]!` | The filters, at most three, one per field, in the order `name`, `type`, `status`. Combine them with AND. Empty on failure                                                                            |
| `interpretation: String`                    | The filters in plain words, starting "Showing", up to 200 characters. `null` when there are no filters, or when any filter or value was dropped                                                      |
| `unsupported: [String!]`                    | Parts of the request that cannot be expressed as a filter — distinct from failure. An empty list when there are none; `null` on failure. No repeats, at most 10 entries of up to 200 characters each |
| `error: String`                             | On failure only: a message to show the person (see below)                                                                                                                                            |

Each `VendorFilterValueOutput` carries `field: String!`, `comparator: String!`, `displayLabel: String!` and `value: JSON!`. `value` is a string when one value was chosen and an array of strings when several were.

{% hint style="warning" %}
`displayLabel` names the value only: `Distributor`, or `Proposed, In review` for several. For a `name` filter it is the text itself. It does not include the field or the comparator, so a `status` `isNot` `APPROVED` filter is labelled `Approved`. To show a filter to a person, combine `field`, `comparator` and `displayLabel` yourself.
{% endhint %}

| Field    | Comparators                          | Values                                                                                                                    |
| -------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `name`   | `contains`                           | Non-empty trimmed text, up to 200 characters                                                                              |
| `type`   | `is`, `isAnyOf`                      | `MANUFACTURER`, `DISTRIBUTOR`. A type cannot be excluded. Asking for both types filters nothing, so the filter is dropped |
| `status` | `is`, `isAnyOf`, `isNot`, `isNoneOf` | `PROPOSED`, `IN_REVIEW`, `APPROVED`, `NOT_APPROVED` (labelled Rejected)                                                   |

What is dropped, and what you are told:

* A filter on an unknown field, or with a comparator its field does not allow, is dropped.
* A value outside the vocabulary is dropped from its filter. The filter itself is dropped only when no value is left.
* A request to exclude a type is dropped and reported in `unsupported`, for example `not distributors`.
* A second `name` filter is dropped and reported in `unsupported`. The first is kept.
* For `type` and `status`, repeats that agree merge into one filter. A repeat that conflicts with an earlier one (an `is` alongside an `isNot`, say) keeps the first and reports the later one in `unsupported`.

To run the search, map the filters onto `libraryVendors`:

| Filter                       | `libraryVendors` argument                                                                                                                |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `name` `contains`            | `filter.searchTerm`. It matches a vendor's name and its other names, so it can return a vendor whose main name does not contain the text |
| `type`                       | `filter.types`, as a list. Wrap a single value in a list                                                                                 |
| `status` `is`, `isAnyOf`     | `filter.approvalStatuses`, as a list                                                                                                     |
| `status` `isNot`, `isNoneOf` | `filter.approvalStatuses` set to the statuses that were *not* named. There is no argument that excludes a status                         |

{% hint style="warning" %}
An empty `approvalStatuses` list means every status. If a negated filter names all four statuses, no vendor can match: return no results yourself rather than sending an empty list.
{% endhint %}

**Failure.** When the sentence cannot be turned into filters, the request still succeeds: the payload is `success: false`, `filterValues: []`, and an `error` string you can show as written. These four cases carry no GraphQL error and no error code.

| `error`                                                                                           | When                                                                   |
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `Describe the vendors in 3 to 500 characters.`                                                    | `query` is shorter than 3 or longer than 500 characters after trimming |
| `AI search is not available right now. Try again, or search with keys such as type:manufacturer.` | The AI service could not be reached or returned an error               |
| `That description was too long to work through. Try a shorter one.`                               | The answer was cut off before it finished                              |
| `Couldn't read an answer for that. Try describing the vendors another way.`                       | The answer could not be read as filters                                |

The second message suggests "keys such as type:manufacturer". That is the search bar's syntax in the Duro app. If your integration has no equivalent, show your own message for that case.

**Errors.** A request that is refused before it runs does return a GraphQL error. This operation uses the platform's general codes, not the sourcing codes in the [Error Codes](#error-codes) table below:

| Code                                       | Status | When                                                                                                      |
| ------------------------------------------ | ------ | --------------------------------------------------------------------------------------------------------- |
| `PERMISSION_NOT_FOUND`, `NO_ROLE_ASSIGNED` | 403    | The caller lacks `sourcing.vendor.read` in the library. Other sourcing operations return `FORBIDDEN` here |
| `MISSING_CONTEXT`                          | 400    | No `x-library` header. Other sourcing operations return `MISSING_LIBRARY_CONTEXT` here                    |
| `RATE_LIMITED`                             | 429    | The hourly `ai` budget is spent                                                                           |

See [Authorization errors](https://docs.durohub.com/advanced-topics/error-handling.md#authorization-errors) and [Handling 429s](https://docs.durohub.com/rate-limits/handling-429s.md).

{% hint style="info" %}
`vendorSearch.buildFilterWithAI` calls an AI model and draws on the hourly `ai` budget rather than `default-read`: 4 calls an hour on Free, 20 on Standard and 100 on Premium, per user or API key, unless your organization has a higher limit. Build filters when a person asks for them, not on every keystroke. See [Budget Reference](https://docs.durohub.com/rate-limits/budgets.md#ai-assisted).
{% endhint %}

#### Vendor profile fields

Facts about the vendor itself live on `Vendor`. A vendor belongs to one library, so these edits change that library only:

| Field        | Type            | Description                                                                                              |
| ------------ | --------------- | -------------------------------------------------------------------------------------------------------- |
| `hqAddress`  | `VendorAddress` | Headquarters address — `line1`, `line2`, `city`, `region`, `postalCode`, `country`, all nullable strings |
| `dunsNumber` | `String`        | The vendor's nine-digit D-U-N-S number                                                                   |
| `taxId`      | `String`        | Tax or VAT identifier                                                                                    |

All three are nullable and are accepted on `CreateVendorInput` and `UpdateVendorInput`:

```graphql
mutation UpdateVendorProfile {
  vendorSourcing {
    updateVendor(
      id: "vendor-ti"
      input: {
        hqAddress: {
          line1: "12500 TI Boulevard"
          city: "Dallas"
          region: "TX"
          postalCode: "75243"
          country: "US"
        }
        dunsNumber: "12-345-6789"
        taxId: "12-3456789"
      }
    ) {
      id
      hqAddress {
        line1
        city
        country
      }
      dunsNumber
      taxId
    }
  }
}
```

Inputs are normalized before validation. Empty strings become `null`, string values are trimmed, and nested values are trimmed too. On update, a field you leave out is unchanged and an explicit `null` clears it. A nested object replaces the stored one wholesale; one whose values are all empty is stored as `null`.

| Field                                | Normalization and limits                                                      |
| ------------------------------------ | ----------------------------------------------------------------------------- |
| `dunsNumber`                         | Spaces, dashes, and dots are stripped; the result must be exactly nine digits |
| `taxId`                              | Trimmed; at most 64 characters                                                |
| `hqAddress.line1`, `hqAddress.line2` | Trimmed; at most 255 characters each                                          |
| `hqAddress.city`, `hqAddress.region` | Trimmed; at most 128 characters each                                          |
| `hqAddress.postalCode`               | Trimmed; at most 32 characters                                                |
| `hqAddress.country`                  | Trimmed; at most 64 characters                                                |

A value that fails validation (for example a DUNS that is not nine digits after stripping) is rejected with `BAD_REQUEST` and nothing is written.

{% hint style="info" %}
`dunsNumber` is stored in its stripped form, so `"12-345-6789"` reads back as `"123456789"`. Address values are stored as entered after trimming — no address normalization is applied.
{% endhint %}

#### Vendor logo

A vendor can carry a logo, stored the same way a component stores its image: the logo is a file you upload through the file service, and the vendor keeps a reference to it. Nothing is fetched from the vendor's website.

| Field               | Type   | Description                                                                                                                                                                                    |
| ------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Vendor.logoFileId` | `ID`   | The id of the uploaded logo file, or `null` when the vendor has no logo                                                                                                                        |
| `Vendor.logoFile`   | `File` | The logo file, resolved by the file service — select `id`, `downloadUrl` and any other [`File`](https://docs.durohub.com/core-concepts/documents.md) field. `null` when the vendor has no logo |

`logoFileId` is accepted on `CreateVendorInput` and `UpdateVendorInput`, and so on `saveLibraryVendor`'s `profile` group. It is nullable everywhere.

**1. Upload the logo.** Use the file service's existing flow: `file.getUploadUrls` → `PUT` the bytes to the returned URL → `file.confirmUploads`. See [Uploading a File](https://docs.durohub.com/core-concepts/documents.md#uploading-a-file-and-linking-it-as-a-document) for the full steps. The `fileId` it returns is the value to store as `logoFileId`.

**2. Set the logo on the vendor.** On create:

```graphql
mutation CreateVendorWithLogo {
  vendorSourcing {
    createVendor(
      input: {
        name: "Example"
        types: [DISTRIBUTOR]
        logoFileId: "<uploaded-file-uuid>"
      }
    ) {
      id
      logoFileId
      logoFile {
        id
        downloadUrl
      }
    }
  }
}
```

Or set or replace it on an existing vendor with `updateVendor`:

```graphql
mutation SetVendorLogo {
  vendorSourcing {
    updateVendor(id: "vendor-example", input: { logoFileId: "<uploaded-file-uuid>" }) {
      id
      logoFileId
      logoFile {
        id
        downloadUrl
      }
    }
  }
}
```

`saveLibraryVendor` takes it in the `profile` group, alongside the other [profile fields](#saving-profile-account-and-status-in-one-call):

```graphql
mutation SaveVendorLogo {
  vendorSourcing {
    saveLibraryVendor(
      vendorId: "vendor-example"
      input: { profile: { logoFileId: "<uploaded-file-uuid>" } }
    ) {
      vendor {
        logoFileId
        logoFile {
          id
          downloadUrl
        }
      }
    }
  }
}
```

**3. Read it back.** Select `logoFileId` and `logoFile` on the vendor, from `vendor(id)` or through `libraryVendor(vendorId)`:

```graphql
query GetVendorLogo {
  vendorSourcing {
    vendor(id: "vendor-example") {
      logoFileId
      logoFile {
        id
        downloadUrl
      }
    }
    libraryVendor(vendorId: "vendor-example") {
      vendor {
        logoFileId
        logoFile {
          id
          downloadUrl
        }
      }
    }
  }
}
```

A vendor without a logo returns `null` for both fields.

How `logoFileId` behaves on `updateVendor` and `saveLibraryVendor`:

* **Omitted** leaves the stored logo unchanged.
* **Explicit `null`** clears the association, after which `logoFile` is `null`.
* **The same id that is already stored**: `saveLibraryVendor` writes nothing when the whole profile matches what's stored; `updateVendor` saves as usual.
* **Replacing or clearing** the logo does not delete the previous file. Remove it through the file service if you no longer need it.
* **A malformed or empty UUID** is rejected with the existing `BAD_REQUEST` error on `createVendor`, `updateVendor` and `saveLibraryVendor`, and nothing is written. No new error code was introduced.

Setting the logo needs the same permissions as the rest of the vendor's profile: the parent operation's permission (`sourcing.vendor.create` for `createVendor`, `sourcing.vendor.update` for `updateVendor` and `saveLibraryVendor`, see [RBAC](https://docs.durohub.com/advanced-topics/rbac.md)). No new permission was added.

{% hint style="warning" %}
The vendor write stores the id as given: it does not check that the file exists or belongs to your organization. Reading `logoFile` goes through the file service, where the usual file authorization applies, so an id for a file outside your organization resolves `logoFile` to `null` rather than exposing the file. Store the `fileId` returned by your own `confirmUploads` call.
{% endhint %}

{% hint style="info" %}
`logoFile.downloadUrl` is a presigned URL that expires (currently after about an hour). Don't persist it: query `logoFile { downloadUrl }` again when you need a fresh link.
{% endhint %}

#### Library-specific account fields

Facts about *your* relationship with a vendor — your account number and the rep who handles it — live on `LibraryVendor`. Values set in one library are not visible from another.

| Field            | Type            | Description                                                                                                        |
| ---------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ |
| `accountId`      | `String`        | Your account identifier with the vendor                                                                            |
| `accountManager` | `VendorContact` | The vendor's representative for your account — `name`, `email`, `phone`. This is a contact record, not a Duro user |

Read them from `libraryVendorList`, or for one vendor from `libraryVendor(vendorId)`:

```graphql
query GetLibraryVendorAccounts {
  vendorSourcing {
    libraryVendorList {
      approvalStatus
      accountId
      accountManager {
        name
        email
        phone
      }
      vendor {
        id
        name
      }
    }
  }
}
```

Update them with `updateLibraryVendor`. It takes the vendor's id (the same as its list entry's id) and writes to the entry in the library named by the `x-library` header. It requires the `sourcing.vendor.update` permission on that library (see [RBAC](https://docs.durohub.com/advanced-topics/rbac.md)):

```graphql
mutation UpdateVendorAccount {
  vendorSourcing {
    updateLibraryVendor(
      vendorId: "vendor-digikey"
      input: {
        accountId: "DK-00412"
        accountManager: {
          name: "Jordan Lee"
          email: "jordan.lee@example.com"
          phone: "+1 555 0100"
        }
      }
    ) {
      accountId
      accountManager {
        name
        email
        phone
      }
    }
  }
}
```

`UpdateLibraryVendorInput` normalizes the same way as the vendor profile fields — trimmed, empty strings to `null`, nested object replaced wholesale and stored as `null` when all of its values are empty:

| Field                  | Normalization and limits               |
| ---------------------- | -------------------------------------- |
| `accountId`            | Trimmed; at most 128 characters        |
| `accountManager.name`  | Trimmed; at most 255 characters        |
| `accountManager.email` | Trimmed; must be a valid email address |
| `accountManager.phone` | Trimmed; at most 64 characters         |

An invalid email or an over-length value returns `BAD_REQUEST`. If the vendor is not in the current library, or is archived, it returns `VENDOR_NOT_FOUND`.

#### Saving profile, account and status in one call

`saveLibraryVendor` writes a vendor's profile, its library account details and its approval status in one request. Use it when a form edits several of these at once, instead of calling `updateVendor`, `updateLibraryVendor` and `changeVendorApprovalStatus` in turn.

```graphql
mutation SaveVendor {
  vendorSourcing {
    saveLibraryVendor(
      vendorId: "vendor-digikey"
      input: {
        profile: {
          name: "Digi-Key Electronics"
          website: "https://www.digikey.com"
          hqAddress: { city: "Thief River Falls", region: "MN", country: "US" }
        }
        account: {
          accountId: "DK-00412"
          accountManager: { name: "Jordan Lee", email: "jordan.lee@example.com" }
        }
        approvalStatus: APPROVED
      }
    ) {
      id
      approvalStatus
      accountId
      accountManager { name email phone }
      vendor {
        id
        name
        website
        hqAddress { city region country }
      }
    }
  }
}
```

| Argument   | Type                      | Description                                                                             |
| ---------- | ------------------------- | --------------------------------------------------------------------------------------- |
| `vendorId` | `ID!`                     | The vendor's id — the same as its list entry's id — in the library named by `x-library` |
| `input`    | `SaveLibraryVendorInput!` | Up to three optional groups, described below                                            |

`SaveLibraryVendorInput` has three groups, all optional:

| Group            | Type                       | Fields                                                                                                                                                                                                                                                                                                          |
| ---------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `profile`        | `UpdateVendorInput`        | `name`, `aliases`, `types`, `website`, `description`, `hqAddress` (`line1`, `line2`, `city`, `region`, `postalCode`, `country`), `dunsNumber`, `taxId`, `logoFileId` — the same input `updateVendor` takes, with the same [normalization and limits](#vendor-profile-fields) and [logo behaviour](#vendor-logo) |
| `account`        | `UpdateLibraryVendorInput` | `accountId` and `accountManager` (`name`, `email`, `phone`) — the same input `updateLibraryVendor` takes, with the same [normalization and limits](#library-specific-account-fields)                                                                                                                            |
| `approvalStatus` | `ApprovalStatus`           | The target status: `PROPOSED`, `IN_REVIEW`, `APPROVED` or `NOT_APPROVED`                                                                                                                                                                                                                                        |

How the save behaves:

* **Atomic.** The three groups are written together. If any group fails — a `BAD_REQUEST` for an invalid value such as `dunsNumber`, a `VENDOR_NAME_TAKEN` on `profile.name`, a missing permission for the status — nothing is written, so an error in `profile` leaves `account` and the status untouched too.
* **Unchanged groups write nothing.** A group you omit is not touched. Within `profile` and `account`, a field you leave out is unchanged and an explicit `null` clears it, as on the single-purpose mutations.
* **Status is opt-in.** An omitted or `null` `approvalStatus` leaves the status as it is. Send it only when the caller intentionally changed it, so a profile edit never overwrites a status someone else set in the meantime.
* **Permissions are checked before anything is written.** Every call needs `sourcing.vendor.update`, including one that only sends `approvalStatus`. An `approvalStatus` that differs from the stored status also needs `sourcing.vendor.status_change` in the library, the same permission `changeVendorApprovalStatus` needs; no new permission was added (see [Changing a vendor's approval status](#changing-a-vendors-approval-status)). A status equal to the stored one needs no status permission. The comparison uses the status at the moment of the write, so a change someone else made in the meantime is accounted for. A caller without a needed permission gets `FORBIDDEN` and nothing is written.
* **One library.** The vendor must be a non-archived vendor in the library named by `x-library`. An archived vendor, an unknown id, or another library's vendor returns `VENDOR_NOT_FOUND`. Unlike `changeVendorApprovalStatus`, this rejects an archived vendor even for a status-only save.
* **Names.** `profile.name` is checked against every vendor in the library, archived ones included, case-sensitively; a clash returns `VENDOR_NAME_TAKEN`.

It returns the updated `LibraryVendor`, with the vendor's profile under `vendor`. The standalone `updateVendor`, `updateLibraryVendor` and `changeVendorApprovalStatus` mutations remain available; use them when a change touches one group only.

{% hint style="warning" %}
`saveLibraryVendor` is an unconditional write, like `updateVendor` and `updateLibraryVendor`: there is no version check, and the later of two concurrent saves wins for the groups it sends. Keep `approvalStatus` out of the input unless the user changed it: resending the status a form loaded earlier overwrites a change someone else made in the meantime, and, if the stored status moved, turns a profile-only edit into a status change that needs `sourcing.vendor.status_change`. Send only the groups the user edited.
{% endhint %}

#### Changing a vendor's approval status

Each list entry's `approvalStatus` is one of `PROPOSED`, `IN_REVIEW`, `APPROVED`, or `NOT_APPROVED`. A vendor added to the list starts as `PROPOSED` unless the caller says otherwise. Move it with `changeVendorApprovalStatus`, which takes the vendor's id (the same as its list entry's id), locates the entry in the library named by the `x-library` header, and returns the updated `LibraryVendor`:

```graphql
mutation ApproveVendor {
  vendorSourcing {
    changeVendorApprovalStatus(vendorId: "vendor-digikey", status: APPROVED) {
      approvalStatus
      vendor {
        id
        name
      }
    }
  }
}
```

| Argument   | Type              | Description                                         |
| ---------- | ----------------- | --------------------------------------------------- |
| `vendorId` | `ID!`             | The vendor's id — the `vendor.id` on the list entry |
| `status`   | `ApprovalStatus!` | The target status. All four values are accepted     |

Changing a status is a separate permission from editing a vendor. The mutation requires `sourcing.vendor.status_change` in the library named by the `x-library` header; `sourcing.vendor.update` is not enough (see [RBAC](https://docs.durohub.com/advanced-topics/rbac.md#sourcing)). The same check applies anywhere else a status can change:

| Operation                                                                                                                                                                                                                                                         | Permission                      |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `changeVendorApprovalStatus`                                                                                                                                                                                                                                      | `sourcing.vendor.status_change` |
| `updateVendorListEntry` (sets the status of an existing entry)                                                                                                                                                                                                    | `sourcing.vendor.status_change` |
| `saveLibraryVendor` with an `approvalStatus` that differs from the vendor's current status (sending the current status needs only `sourcing.vendor.update`; see [Saving profile, account and status in one call](#saving-profile-account-and-status-in-one-call)) | `sourcing.vendor.status_change` |
| `addToVendorList` with `approvalStatus` omitted, or `PROPOSED` on a vendor that is already `PROPOSED`                                                                                                                                                             | `sourcing.vendor.create`        |
| `addToVendorList` with any other `approvalStatus`, or `PROPOSED` on a vendor in another status (a reset)                                                                                                                                                          | `sourcing.vendor.status_change` |

A caller without the permission gets `FORBIDDEN` and nothing is written. The mutation only looks up the list entry, so its not-found error differs from `updateLibraryVendor`'s: if the id isn't a vendor in the current library, it returns `VENDOR_LIST_ENTRY_NOT_FOUND`, never `VENDOR_NOT_FOUND`. An archived vendor keeps its list entry, and that entry's status can still be changed.

{% hint style="info" %}
No non-admin system role can change a vendor's status: Editors can add vendors and edit their details, but a proposed vendor stays proposed until someone whose role in that library is an admin role (Site Admin, Admin, or the library's Admin) — or a custom role explicitly granted `sourcing.vendor.status_change` — approves it. An Editor who wants a vendor on the list adds it as `PROPOSED` and hands it off for review.
{% endhint %}

#### Vendors moved into libraries

Vendors used to be shared by every library in an organization, with a separate vendor list per library. Each vendor now belongs to one library. No operation, argument or type was added or removed; the ids, the scope and a few results changed. The sections above describe how vendors work now.

{% hint style="warning" %}
**Vendor ids change.** Every vendor id the API returns is new, `LibraryVendor.id` included. Old ids keep working until the cut-off date announced on this page; after it they return not-found errors. Look your vendors up again and store the new ids before then.
{% endhint %}

**What changed**

| Change            | Before                                                                                                                           | After                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Vendor ids        | One id per vendor across the organization, and a different `LibraryVendor.id` in each library                                    | One id per vendor in each library. `Vendor.id`, `LibraryVendor.id` and `LibraryVendor.vendorId` are the same. Until the cut-off, old vendor ids are still accepted wherever a vendor id is taken, and old `LibraryVendor.id`s by `updateVendorListEntry` and `removeFromVendorList`, in the request's library                                                                                                                                                                                                                              |
| Library header    | `vendors`, `vendor`, `checkVendorNameSimilarity`, `createVendor`, `updateVendor` and `archiveVendor` ran in organization context | They run in one library: the one named by the `x-library` header, which must be your API key's library (a request without it fails with `MISSING_LIBRARY_CONTEXT`). Permissions are checked against the user's roles in that library, and the organization role applies only when they have none there; a Site Admin always keeps the organization role (see [RBAC](https://docs.durohub.com/advanced-topics/rbac.md)). A user loses, in that library, any vendor permission their organization role grants but their library role doesn't |
| Scope and names   | Search and lookups returned the organization's vendors; names were unique across the organization                                | They return the library's vendors only, and another library's vendor id returns `VENDOR_NOT_FOUND`. Names are unique within a library, with the same case-sensitive rule                                                                                                                                                                                                                                                                                                                                                                   |
| Edits             | Editing a vendor's profile, adding a type or archiving it changed the vendor everywhere                                          | It changes the vendor in its own library only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| The vendor list   | A vendor could be used without being on a library's list. `addToVendorList` on a listed vendor returned `VENDOR_ALREADY_IN_LIST` | Every vendor a library uses is on its list: vendors that were used but not listed now appear as `PROPOSED` (archived ones on the archived list), so list totals and the `PROPOSED` count go up. `createVendor` lists the new vendor as `PROPOSED`, and `addToVendorList` on a listed vendor returns it, applying a given status                                                                                                                                                                                                            |
| Removing a vendor | `removeFromVendorList` always succeeded, and the vendor stayed usable                                                            | It deletes the vendor, and returns `VENDOR_IN_USE` while parts or quotes in the library use it, archived ones included. A removed vendor can't be added back; create it again, and it gets a new id                                                                                                                                                                                                                                                                                                                                        |

**What integrations should change**

1. **Look your vendor ids up again** in each library you use, and replace every vendor id and `LibraryVendor.id` you stored. Parts and quotes already return the new `manufacturerId` and `distributorId`.
2. **Send `x-library` on every vendor operation.**
3. **Don't match vendors across libraries by id.** The same company in two libraries is two vendors with two ids; match by name if you need to.
4. **Handle `VENDOR_IN_USE`** from `removeFromVendorList`: archive the vendor instead, or move its parts and quotes first.
5. **Stop expecting `VENDOR_ALREADY_IN_LIST`** from `addToVendorList`.

```graphql
# Each vendor's new id in the library named by x-library
query {
  vendorSourcing {
    libraryVendors(pagination: { first: 100 }) {
      edges { node { id vendor { name } } }
      pageInfo { hasNextPage endCursor }
    }
    archivedLibraryVendors(pagination: { first: 100 }) {
      edges { node { id vendor { name } } }
      pageInfo { hasNextPage endCursor }
    }
  }
}
```

### Primary Sources and Rollup State

```graphql
query GetPrimarySources {
  vendorSourcing {
    primarySources(componentId: "comp-123") {
      id
      rank
      quote {
        dpn
        unitPrice
      }
    }
    rollupPriorityState(componentId: "comp-123") {
      prioritized
      isPrimary
    }
  }
}
```

`rollupPriorityState` describes the component's own rolled-up cost row — the entry `setRollupAsPrimarySource` adds for an assembly. `prioritized` is `true` when that row is in the component's ranked list (or the component has never had one), and `isPrimary` is `true` when it holds rank 1. It does not describe the component's place in a parent assembly's rollup.

***

## Adding Sourcing

### Creating Parts

`createParts` takes an **array** — batch multiple manufacturers in one call:

```graphql
mutation AddManufacturerPart {
  vendorSourcing {
    createParts(
      inputs: [
        { componentId: "comp-123", mpn: "STM32F407VGT6", manufacturerId: "vendor-st" }
      ]
    ) {
      id
      mpn
    }
  }
}
```

### Creating Quotes

`createQuotes` is also batch. On `CreateQuoteInput`, every field except `partId` is optional:

```graphql
mutation AddDistributorOffers {
  vendorSourcing {
    createQuotes(
      inputs: [
        {
          partId: "part-123"
          distributorId: "vendor-digikey"
          dpn: "497-STM32F407VGT6-ND"
          unitPrice: 8.42
          currency: "USD"
          minQuantity: 1
          leadTimeDays: 14
        }
        {
          partId: "part-123"
          distributorId: "vendor-mouser"
          dpn: "511-STM32F407VGT6"
          unitPrice: 8.15
          currency: "USD"
          minQuantity: 10
          leadTimeDays: 21
        }
      ]
    ) {
      id
      dpn
      unitPrice
    }
  }
}
```

`updatePart` / `updateQuote` edit a single row; `archivePart` / `archiveQuote` remove a row as an active source while `partHistory` / `quoteHistory` retain its record.

{% hint style="info" %}
`updatePart` and `updateQuote` are unconditional writes — no version check, no conflict error. If two callers edit the same row concurrently, the later write silently wins. When overwrite detection matters, use `applySourcingChangeset` with `expectedVersion` instead.
{% endhint %}

***

## Ranking Primary Sources

`createParts`, `createQuotes`, and `setPrimarySource` are independent calls with no cross-call atomicity — if a later step fails (for example `MAX_PRIMARY_SOURCES_REACHED`), earlier steps are not rolled back. When the group needs to succeed or fail together, use [`applySourcingChangeset`](#applying-a-sourcing-changeset).

`setPrimarySource` places a quote in the component's ranked source list; rank 1 is the primary:

```graphql
mutation RankSources {
  vendorSourcing {
    setPrimarySource(input: { componentId: "comp-123", quoteId: "quote-456", rank: 1 }) {
      id
      rank
    }
  }
}
```

* The ranked list has a per-library maximum, 20 by default and configurable in the library's sourcing settings. At the cap, `setPrimarySource` returns `MAX_PRIMARY_SOURCES_REACHED` — un-rank an existing source first.
* `removePrimarySource(id)` takes the `PrimarySource` entry's own `id` (from `primarySources`), not the quote id.
* `reorderPrimarySources` re-ranks the existing list.
* `setRollupAsPrimarySource` adds the assembly rollup at the end of the ranked list, so it becomes the primary only when the list is empty. To add it without making it the primary, pass `belowPrimary: true` in its input; use this for an assembly with no children, whose rollup has no cost. On an empty list the rollup then takes rank 2:
  * Rank 1 stays empty until a quote is set there with `setPrimarySource` and `rank: 1`. Without a rank, the quote is appended after the rollup.
  * While rank 1 is empty, removing a ranked source (`removePrimarySource`) or archiving its quote or part renumbers the list from 1 and moves the rollup to rank 1.
* A spreadsheet import can rank sources too, through its optional Priority column — see [Priority from a spreadsheet import](#priority-from-a-spreadsheet-import).

### Priority from a spreadsheet import

A [component import](https://docs.durohub.com/core-concepts/importing-components.md#sourcing-columns-src-targets) can say which of a component's sources is the primary, which are prioritized, and which should stop being prioritized, instead of leaving that to be set by hand afterwards. The sheet's optional **Priority** column takes one of four values per row. Values are whitespace-trimmed and case-insensitive:

| Cell      | Requests                                                                         |
| --------- | -------------------------------------------------------------------------------- |
| `Primary` | Rank 1 — the component's primary source                                          |
| `Yes`     | A prioritized source below the primary (rank 2 or lower)                         |
| `No`      | No priority. The quote is removed from the ranked list; the quote itself is kept |
| blank     | No change. The import neither ranks nor un-ranks the quote                       |

The column writes to the same ranked list as `setPrimarySource`, so the per-library maximum above (20 by default) applies to what a sheet requests as well. It differs from the single-call mutations in how it handles an occupied rank 1 and how it counts the cap:

* **`Primary` replaces the current primary.** A quote marked `Primary` takes rank 1 even when another quote — or the assembly rollup — already holds it. The displaced holder is not un-ranked: it stays prioritized at rank 2 unless the same sheet marks it `No`. You do not have to clear the old primary first.
* **`Yes` never demotes.** It appends a quote that is not yet prioritized to the end of the list, in sheet order. A quote that is already ranked, the primary included, is left where it is.
* **`No` removes a priority, not a quote.** It takes an existing quote out of the ranked list and nothing else; the quote remains on the part. A quote that is not prioritized is unchanged. `No` on a quote the same import creates is rejected at `prepare` with `PRIORITY_NO_ON_NEW_QUOTE` — a new quote has no priority to remove.
* **Removing the primary does not promote anything.** After `No` on the rank-1 quote, rank 1 stays empty unless a row in the same sheet sets it with `Primary`. Only an explicit `Primary` fills it.
* **Processing order is removals, then `Primary`, then `Yes`**, per component, regardless of row order. The cap is checked against the list that results — existing prioritized quotes, minus the `No` rows, plus the new ones. The assembly rollup does not consume a slot.
* **Surviving ranks are compacted.** When the sheet actually changes the list, the remaining non-primary entries are renumbered from 2 in their existing order. A sheet that changes nothing writes no ranks at all, so a re-import of an unedited [export](https://docs.durohub.com/core-concepts/importing-components.md#exporting-and-re-importing-sourcing) leaves existing gaps as they are.

Priority is applied last. It runs after every sourcing row of the job has landed and after the single-quote auto-assignment has run, and it rechecks the live list at that point: a quote that has disappeared, or that is no longer prioritized, is left unchanged. A row whose sourcing failed and produced no quote is excluded from priority processing altogether.

#### Priority on the import result

Each sourcing result row (`ImportSourcingResultOutput`) carries two nullable fields for this. They are fields of the import result itself, separate from its part and quote fields:

| Field             | Type                      | Meaning                                                                                   |
| ----------------- | ------------------------- | ----------------------------------------------------------------------------------------- |
| `priority`        | `String`                  | The cell as stated — `Primary`, `Yes` or `No` — or `null` when the row stated no priority |
| `priorityOutcome` | `SourcingPriorityOutcome` | What priority processing did with the row, or `null`                                      |

`SourcingPriorityOutcome` has five values:

| Outcome     | Meaning                                                                                                                |
| ----------- | ---------------------------------------------------------------------------------------------------------------------- |
| `PRIMARY`   | The quote was set as the primary source (rank 1)                                                                       |
| `PRIORITY`  | The quote was added as a prioritized source                                                                            |
| `REMOVED`   | The quote was taken out of the ranked list (`No`). The quote itself still exists                                       |
| `UNCHANGED` | Nothing moved: a `Primary` or `Yes` quote was already prioritized where requested, or a `No` quote was not prioritized |
| `REFUSED`   | The priority was not applied                                                                                           |

`REFUSED` means the request could not be honored at apply time — the component had reached its maximum number of prioritized sources, or the row produced no quote. An existing, different primary is no longer a reason for refusal: `Primary` replaces it, as described above. The outcome contract also describes refusal for a row with no quote, but such rows are excluded from priority processing, so do not rely on a non-null outcome for a failed row.

{% hint style="info" %}
**`priorityOutcome` is null in two situations.** Either the row stated no priority, or a priority was stated but priority processing did not run, failed, or its reply was lost. Use `priority` to tell them apart: when `priority` is set and `priorityOutcome` is `null`, the outcome is unrecorded, not refused — priority may still have been applied. Treat the component's current [prioritized sources](#primary-sources-and-rollup-state) as authoritative rather than assuming nothing happened.
{% endhint %}

***

## Applying a Sourcing Changeset

`applySourcingChangeset` stages a whole set of part/quote adds, edits, deletes, and re-ranks as a single **atomic** operation — the same mechanism the Duro app uses for its sourcing edit sessions. It returns `Boolean!` — `true` on success — and a changeset that fails validation leaves the component's sourcing unchanged.

```graphql
mutation MultiSourceComponent {
  vendorSourcing {
    applySourcingChangeset(
      componentId: "comp-123"
      changeset: {
        newParts: [
          { tempId: "p1", mpn: "STM32F407VGT6", manufacturerId: "vendor-st" }
        ]
        newQuotes: [
          {
            tempId: "q1"
            partRef: "p1"
            distributorId: "vendor-digikey"
            dpn: "497-STM32F407VGT6-ND"
            unitPrice: 8.42
            currency: "USD"
          }
        ]
        editedParts: []
        editedQuotes: []
        deletedPartIds: []
        deletedQuoteIds: []
        prioritizedOrder: ["q1"]
        primary: { kind: QUOTE, quoteRef: "q1" }
      }
    )
  }
}
```

Two patterns to know:

* **`tempId` / `Ref`** — reference a row created in the *same* call before it has a real id: `newQuotes[0].partRef` points at `newParts[0].tempId`, and `prioritizedOrder` can reference new quotes' `tempId`s.
* **`primary.kind`** — `QUOTE` makes the quote named by `quoteRef` (a quote id or a new quote's `tempId`) the primary, and `quoteRef` is required. `NONE` sets no primary: rank 1 is left vacant and `prioritizedOrder` fills ranks 2 onward. `ROLLUP` is reserved and is currently treated the same as `NONE`.
* **`expectedVersion`** — required on every entry in `editedParts` and `editedQuotes`: pass the `version` you last read. If it no longer matches at flush time, the whole changeset is rejected (`PART_VERSION_CONFLICT` / `QUOTE_VERSION_CONFLICT`) instead of silently overwriting a concurrent change.

### Save IDs and sourcing snapshots

Applying a changeset photographs the component's sourcing — its parts, quotes, and primary-source ranking — into the component's history as a **`sourcingSnapshot`**. Read it back through `Component.history`; each row also exposes `effectiveSourcingSnapshot`, the sourcing in effect at that row even when the row itself did not touch sourcing. See [Component History](https://docs.durohub.com/core-concepts/components.md#component-history).

When a sourcing changeset is one part of a larger save — the Duro app's component page save, or a connector publishing a part and its MPNs together — pass the same optional **`saveId`** on the changeset and on the `component.update` / `item.update` that belongs to it. The writes are then recorded as one save: a single history row carrying both the component's field changes and the sourcing photo, rather than one row per call.

```graphql
mutation SaveSourcing($saveId: ID!) {
  vendorSourcing {
    applySourcingChangeset(
      componentId: "comp-123"
      changeset: {
        newParts: [{ tempId: "p1", mpn: "STM32F407VGT6", manufacturerId: "vendor-st" }]
        newQuotes: []
        editedParts: []
        editedQuotes: []
        deletedPartIds: []
        deletedQuoteIds: []
        prioritizedOrder: []
        primary: { kind: NONE }
        saveId: $saveId
      }
    )
  }
}
```

Use a fresh UUID per save. Omit `saveId` when the changeset stands alone — it is then its own save and writes its own row. `saveId` groups history only; it does not make the changeset and the component update a single transaction, so a rejected changeset does not roll back a component update that shared its `saveId`.

***

## Documents on Sourcing

Documents attach at either level: to a part (e.g. a manufacturer datasheet) via `linkDocumentToPart`, or to a quote (e.g. a distributor-specific document) via `linkDocumentToQuote`.

```graphql
mutation AttachDatasheet {
  vendorSourcing {
    linkDocumentToPart(input: { documentId: "doc-789", partId: "part-123" }) {
      id
    }
  }
}
```

`documentsByComponent(componentId)` returns every sourcing document on a component regardless of level — each result carries `linkType` (`PART` or `QUOTE`).

***

## Sourcing Configuration

Each library has a sourcing configuration. Reading it needs `sourcing.read`; updating it needs `sourcing.update`. The update is partial: a field you leave out is unchanged.

| Field                    | Type                        | Default | What it controls                                                                                                                                                                                                                                    |
| ------------------------ | --------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `maxPrimarySources`      | `Int!` (1 to 20)            | `20`    | The per-library maximum for a component's [ranked list](#ranking-primary-sources)                                                                                                                                                                   |
| `coValidationMode`       | `SourcingCoValidationMode!` | `OFF`   | The existing [`Components must have a valid primary source`](https://docs.durohub.com/library-configuration/change-order-validations.md#primary-source-required) check: whether a change order needs a priced primary source on every promoted item |
| `vendorCoValidationMode` | `SourcingCoValidationMode!` | `OFF`   | Whether the **vendors** behind each primary source — the primary quote's distributor and the manufacturer of its part — must be [approved](#changing-a-vendors-approval-status) before release                                                      |

`SourcingCoValidationMode` is `OFF`, `WARNING`, or `ERROR`. The two modes are independent: changing one never changes the other, and each can be set to any mode regardless of the other's value.

```graphql
query GetSourcingConfig {
  vendorSourcing {
    sourcingConfig {
      maxPrimarySources
      coValidationMode
      vendorCoValidationMode
    }
  }
}
```

```graphql
mutation SetVendorCoValidationMode {
  vendorSourcing {
    updateSourcingConfig(input: { vendorCoValidationMode: WARNING }) {
      maxPrimarySources
      coValidationMode
      vendorCoValidationMode
    }
  }
}
```

Every field of `UpdateSourcingConfigInput` is optional. Writing `vendorCoValidationMode` requires the `library.settings.update` permission in addition to `sourcing.update`. No non-admin system role holds it, so the setting can be changed by someone whose role in that library is an admin role (Site Admin, Admin, or the library's Admin) or a custom role explicitly granted `library.settings.update`. The check applies whenever the field is present in the input — sending the current value again is still refused for a caller who holds only `sourcing.update`. That caller gets `FORBIDDEN` and nothing in the request is written, including other fields sent with it. Leave the field out of the input to update the other sourcing settings with `sourcing.update` alone. An explicit `vendorCoValidationMode: null` is rejected with `BAD_REQUEST`; send one of the enum values or omit the field.

{% hint style="warning" %}
**Not yet enforced on change orders.** `vendorCoValidationMode` is stored and returned today, but no change-order validation reads it yet: setting it to `WARNING` or `ERROR` does not surface a warning or block a change order whose primary-source vendors are unapproved. The validation rule that uses it is being added separately. Until then, treat the field as configuration only.
{% endhint %}

***

## Error Codes

Sourcing errors are `GraphQLError`s with a stable `code` in `extensions` (see [Error Handling](https://docs.durohub.com/advanced-topics/error-handling.md)):

| Code                                               | Meaning                                                                                                                                                                                                                                                                                                           |
| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DUPLICATE_PART`                                   | A part already exists for that manufacturer + MPN                                                                                                                                                                                                                                                                 |
| `DUPLICATE_QUOTE`                                  | A quote already exists for that part + distributor + DPN + `minQuantity`                                                                                                                                                                                                                                          |
| `PART_VERSION_CONFLICT` / `QUOTE_VERSION_CONFLICT` | `expectedVersion` mismatch — re-read and retry                                                                                                                                                                                                                                                                    |
| `MAX_PRIMARY_SOURCES_REACHED`                      | The ranked-source list is at its per-library cap                                                                                                                                                                                                                                                                  |
| `INVALID_QUANTITY_RANGE`                           | A quote's `minQuantity` exceeds its `maxQuantity`                                                                                                                                                                                                                                                                 |
| `VENDOR_NOT_FOUND`                                 | The vendor is not in the current library, or is archived. `saveLibraryVendor`, `updateVendor`, `updateLibraryVendor` and `addToVendorList` return it for an archived vendor, an unknown id or another library's vendor                                                                                            |
| `VENDOR_LIST_ENTRY_NOT_FOUND`                      | `changeVendorApprovalStatus`, `updateVendorListEntry` or `removeFromVendorList` was given an id that isn't a vendor in the current library                                                                                                                                                                        |
| `VENDOR_NAME_TAKEN`                                | The library already has a vendor with that name (case-sensitive). Returned by `createVendor`, `updateVendor` and `saveLibraryVendor` with `profile.name`                                                                                                                                                          |
| `VENDOR_IN_USE`                                    | `removeFromVendorList` on a vendor that any part or quote in the library references, archived parts and quotes included. Status `409`. Archive the vendor instead, or move its parts and quotes first — see [Vendor Write Errors](https://docs.durohub.com/advanced-topics/error-handling.md#vendor-write-errors) |
| `MISSING_LIBRARY_CONTEXT`                          | A vendor operation was sent without the `x-library` header. Send it on every library-scoped call. `vendorSearch.buildFilterWithAI` returns `MISSING_CONTEXT` instead; see [Building vendor filters with AI](#building-vendor-filters-with-ai)                                                                     |
| `COMPONENT_NOT_FOUND`                              | `createParts`, or an `applySourcingChangeset` that adds new parts, named a component that does not exist in the library, or that the caller cannot access. Status `404`                                                                                                                                           |
| `COMPONENT_VALIDATION_UNAVAILABLE`                 | `createParts`, or an `applySourcingChangeset` that adds new parts, could not confirm the component exists because the component service did not answer. Nothing was written, and this does not mean the component is missing. Status `503`; retry after a short wait                                              |
| `BAD_REQUEST`                                      | An input failed validation — for example a DUNS that is not nine digits, an invalid `accountManager.email` or a `logoFileId` that is not a UUID                                                                                                                                                                   |
| `VENDOR_LIST_INVALID_CURSOR`                       | The `pagination.after` passed to `libraryVendors` or `archivedLibraryVendors` is not a valid cursor for that query and sort — see [Sourcing Query Errors](https://docs.durohub.com/advanced-topics/error-handling.md#sourcing-query-errors)                                                                       |
| `VENDOR_LIST_OFFSET_WITH_CURSOR`                   | `libraryVendors` or `archivedLibraryVendors` was given both `pagination.offset` (including `0`) and `pagination.after`. Pass one or the other — see [Sourcing Query Errors](https://docs.durohub.com/advanced-topics/error-handling.md#sourcing-query-errors)                                                     |
| `VENDOR_LIST_STATUS_FILTERS_BOTH`                  | `libraryVendors` or `libraryVendorList` was given both `filter.approvalStatus` and `filter.approvalStatuses` (`[]` counts). Pass one or the other — see [Sourcing Query Errors](https://docs.durohub.com/advanced-topics/error-handling.md#sourcing-query-errors)                                                 |

## Next Steps

* Evaluate sourcing changes as part of a formal review with [Change Orders](https://docs.durohub.com/core-concepts/change-orders.md)
* Attach datasheets and certifications with [Documents](https://docs.durohub.com/core-concepts/documents.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.durohub.com/core-concepts/sourcing.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
