# Stock queries

Audience: Developer

Which stock queries to use for current and historical stock, per item or per repository, and what the insufficient stock error looks like

## Overview

Pyck keeps stock as rows in the inventory service. Each row of an item in a repository has a `version`, and the row with the highest version is the current one. The older rows are the history. This page shows which query reads the current row, which reads the history, and what a client gets when it moves more than a repository holds.

For the model behind movements, see [Concepts](https://docs.pyck.cloud/dev/concepts/movements.md).

## The stock row

Every query below returns [`Stock`](https://docs.pyck.cloud/dev/api/types/stock.md) rows. These are the fields to know:

| Field | Meaning |
| --- | --- |
| `quantity` | The quantity in the repository. For a repository with children, this rolls up the whole subtree. |
| `ownQuantity` | The quantity the repository holds itself, without its children. |
| `incomingStock`, `outgoingStock` | Quantity that pending movements will add to or take from the repository. |
| `ownIncomingStock`, `ownOutgoingStock` | The same, for the repository itself. |
| `version` | Orders the rows of one item in one repository. The highest version is the current row. |

## Current stock

The current row of an item in a repository is the row with the highest `version`. If that row is deleted, the item has no current stock in that repository.

### `currentStocks`

[`currentStocks`](https://docs.pyck.cloud/dev/api/queries/currentstocks.md) is a paginated connection of the current row of every pair of item and repository. Use it to read stock across many items or repositories.

- Filter with `where`, for example `itemID`, `itemIDIn`, `repositoryID` or `repositoryIDIn`. These and the `createdAtLT` and `createdAtLTE` cutoffs decide which rows count as the latest. Value filters such as `quantityGT` apply to the current row afterwards, so a superseded row never hides a current row with the value zero.
- A row whose values are all zero is returned. `itemstocks` leaves such rows out.
- Page it with `first` and `after`, see [API conventions](https://docs.pyck.cloud/dev/developers/api-conventions.md).

```graphql
query CurrentStockOfItem($itemID: ID!) {
  currentStocks(first: 50, where: { itemID: $itemID }) {
    edges {
      node {
        repositoryID
        quantity
        ownQuantity
        version
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### `itemstocks`

[`InventoryItem.itemstocks`](https://docs.pyck.cloud/dev/api/types/inventoryitem.md) lists the current row of each repository where one item has stock. It is a field on the item, so you read it together with the item.

- Rows whose stock values are all zero are left out.
- It is not paginated. An item with more than 10000 such rows fails with a message that starts with `too many current stock rows` and names the item. Read those items with `currentStocks`.

### `currentStockTotals`

`InventoryItem.currentStockTotals` returns the totals over the current rows of one item, for a list view that shows one line per item. Read it instead of adding up `itemstocks` on the client. It returns [`InventoryItemStockTotals`](https://docs.pyck.cloud/dev/api/types/inventoryitemstocktotals.md):

- `quantity` is the sum of `quantity` over the current rows at repositories that are not virtual and have no parent. The `quantity` of such a repository already includes its subtree, so every unit counts once.
- `lastChangedAt` is the latest `createdAt` over all current rows, virtual repositories included. It is `null` when the item has none.

To list only items that have stock, filter `inventoryItems` with `hasCurrentStock` or `hasCurrentStockWith`. Both look at the current rows only and ignore rows whose values are all zero.

### `Repository.currentStock`

[`Repository.currentStock(itemId: ID!)`](https://docs.pyck.cloud/dev/api/types/repository.md) returns the current row of one item in the repository, or `null`. It costs one database query per repository. To read many repositories, use `currentStocks`.

## Stock history

[`stocks`](https://docs.pyck.cloud/dev/api/queries/stocks.md) is a paginated connection over all rows, superseded ones included. Use it to follow how stock changed. Filter with the generated [`StockWhereInput`](https://docs.pyck.cloud/dev/api/inputs/stockwhereinput.md), and order by a field such as `VERSION` or `CREATED_AT`.

`StockWhereInput` also has a `time` field. With it, a query returns one row per pair of item and repository: the latest row created before that time, instead of the whole history.

## Which one to use

| You want | Use | Scope | Rows |
| --- | --- | --- | --- |
| Stock now, across items or repositories | `currentStocks` | Tenant, narrowed by `where` | Current |
| Stock of one item in the repositories that hold it | `InventoryItem.itemstocks` | One item | Current, non-empty |
| One number per item for a list view | `InventoryItem.currentStockTotals` | One item | Current, non-empty |
| Stock of one item in one repository | `Repository.currentStock` | One item, one repository | Current |
| How stock changed, or stock at a past time | `stocks`, with `time` for a past time | Tenant, narrowed by `where` | All rows, or the latest per pair before `time` |

## Moving more than a repository holds

A movement out of a repository is refused when the repository does not hold enough. The check runs when you create the movement with [`createInventoryItemMovement`](https://docs.pyck.cloud/dev/api/mutations/createinventoryitemmovement.md), and it reads the current row of the source repository:

- The movement is possible when `ownQuantity + ownIncomingStock - ownOutgoingStock` of the source is at least the `quantity` of the movement. Stock held by the children of the source does not count.
- A virtual source repository is not checked.
- A source that has no stock row counts as holding zero.

The refusal is a GraphQL error with the message `insufficient stock`. It has no `extensions.code`, so match on the message, see [Error codes](https://docs.pyck.cloud/dev/developers/error-handling.md#error-codes). The mutation returns no movement.

Other errors about stock quantities come from the same mutation, from `createInventoryCollectionMovement` and from [`executeInventoryItemMovement`](https://docs.pyck.cloud/dev/api/mutations/executeinventoryitemmovement.md). None has an `extensions.code` either:

| Message starts with | Cause |
| --- | --- |
| `invalid quantity` | The `quantity` of a movement is below 1 or above 9007199254740991. |
| `stock overflow` | The movement would grow a stock figure above 9007199254740991. |
| `movements between virtual repositories are not allowed` | Source and target repository are both virtual. |
| `failed calculating stock map: stock underflow` | An execution would leave a repository with a negative quantity. Nothing is written and the movement stays pending. |
| `stock underflow` | [`createInventoryCollectionMovement`](https://docs.pyck.cloud/dev/api/mutations/createinventorycollectionmovement.md) checks the final state of the source repositories after it has created all positions, and one of them would hold less than zero. |

The bound 9007199254740991 is JavaScript's `Number.MAX_SAFE_INTEGER`. Larger values are rounded when a JavaScript client reads them.
