# Variance

## Overview

Variances are inventory adjustments that correct stock levels when physical counts don't match system records. They represent the "take" or "add" transactions that reconcile actual inventory with expected inventory, creating stock history entries that adjust quantities and costs to reflect reality.

The most common scenario is cycle counting. Workers count products in a specific location or sublocation. The count reveals a discrepancy - the system shows 100 units but the physical count finds only 95. A variance transaction adjusts the system down by 5 units, creating a stock history entry for the shortage. This keeps inventory accurate without waiting for full annual physical inventories.

Variances can both remove stock (when physical counts are lower than system records) and add stock (when physical counts are higher). The transaction records the quantity adjusted, the cost impact, and the reason for the adjustment. This creates an audit trail explaining why inventory changed outside of normal shipment and build transactions.

Cost adjustments are another use case. If you discover that inventory is valued at an incorrect cost - perhaps a data entry error during receiving - a variance can adjust the average cost to the correct value. This ensures your inventory valuation and cost of goods sold calculations are accurate, supporting correct financial reporting.

Variances typically require explanation. The description field captures why the adjustment was needed - cycle count discrepancy, damage, theft, data entry correction, or other reasons. This documentation supports loss prevention analysis, process improvement, and audit review. Patterns in variance reasons might reveal operational issues that need addressing.

The system tracks who created each variance and when. This accountability helps prevent fraudulent adjustments and supports investigation when variances are questioned. Variance approval workflows in some organizations require management review before large adjustments are processed, adding an additional control layer.

From an accounting perspective, variances affect both inventory quantities and values. They create general ledger entries that adjust inventory asset accounts and typically expense accounts for losses or revenue accounts for gains. These GL impacts ensure the financial records reflect the physical reality of what's actually in the warehouse.

## GraphQL API

The `variance` collection provides access to variance data via the GraphQL API. All queries use the Relay connection specification with cursor-based pagination.

**Query Name:** `varianceViewConnection`

**Available Features:**

- Cursor-based pagination (first/last/after/before)
- 11 filter options
- 5 sortable fields
- 8 relations to other collections

## Query Examples

### Basic Query

The `variance` collection is accessed via the `varianceViewConnection` query, which returns a Relay-style connection with pagination support.

```graphql
query {
  varianceViewConnection(first: 10) {
    edges {
      node {
        cancelTransactionTimestamp
        cbm
        commitTransactionTimestamp
        cost
        lotId
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Pagination

Use cursor-based pagination to retrieve large datasets:

```graphql
# First page
query {
  varianceViewConnection(first: 50) {
    edges {
      node { lotId }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

# Subsequent pages
query {
  varianceViewConnection(first: 50, after: "cursor-from-previous-page") {
    edges {
      node { lotId }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Filtering

Apply filters to narrow results:

```graphql
query {
  varianceViewConnection(
    first: 10
    connectionRelationErrorDates: { begin: "2024-01-01", end: "2024-12-31" }
  ) {
    edges {
      node { lotId }
    }
  }
}
```

### Sorting

Sort results by one or more fields:

```graphql
query {
  varianceViewConnection(
    first: 10
    sort: [{ field: "note", mode: "desc" }]
  ) {
    edges {
      node {
        lotId
        note
      }
    }
  }
}
```

### Relations

Query related data:

```graphql
query {
  varianceViewConnection(first: 10) {
    edges {
      node {
        lotId
        cancelTransactionUser {
          name
          userLoginUrl
        }
      }
    }
  }
}
```

## Summary and Aggregation

This collection supports metrics aggregation through the `summary` field. You can calculate totals, averages, counts, and other aggregate values across filtered data.

**Note:** This collection does not support groupBy dimensions. For dimensional analysis, use collections like product, order, or invoice.

### Query Structure

```graphql
varianceViewConnection(filters...) {
  summary {
    errorCode
    errorMessage
    metrics {
      # Calculated metrics (see table below)
    }
  }
}
```

### Available Metrics

This collection provides 2 metrics that can be aggregated:

| Metric                | Parameters          | Description                                             |
|----------------------|---------------------|---------------------------------------------------------|
| `totalValuation`     | `transform`, `operator` | totalValuation for variance                           |
| `count`              | None                | Count of items in the result set                        |

### Examples

#### Example 1: Total variance Metrics

Calculate aggregate metrics across all variance records:

```graphql
query {
  varianceViewConnection(first: 1) {
    summary {
      errorCode
      errorMessage
      metrics {
        totalCount: count
      }
    }
  }
}
```

Expected result structure:

```json
{
  "data": {
    "varianceViewConnection": {
      "summary": {
        "errorCode": null,
        "errorMessage": null,
        "metrics": {
          "totalCount": [1523]
        }
      }
    }
  }
}
```

## Fields

This collection has 30 fields:

- 28 simple fields
- 2 enum fields (with predefined values)
- 0 parameterized fields (accept query options)

### Simple Fields

#### `cancelTransactionTimestamp`
The date and time when the variance record was cancelled. This field is populated when a variance transaction moves to cancelled status, recording when the stock adjustment was invalidated or reversed. This timestamp appears alongside the commit transaction timestamp and cancel transaction user fields, tracking the cancellation event for audit purposes.

**Label:** Cancel transaction timestamp

#### `cbm`
The total volume measurement for the variance record, expressed in cubic meters (CBM).

**Label:** CBM subtotal

#### `commitTransactionTimestamp`
The timestamp indicating when the variance transaction was committed to the system.

**Label:** Commit transaction timestamp

#### `cost`
The total standard accounting cost for the variance transaction.

**Label:** Std accounting cost amount

#### `lotId`
The lot identifier that specifies which batch or lot of inventory is being counted or adjusted in the variance transaction.

**Label:** Lot ID

#### `quantity`
The amount by which inventory quantities changed for a product in a variance transaction.

**Label:** Quantity

#### `reason`
The reason code explaining why the inventory variance occurred.

**Label:** Reason

#### `status`
The current state of the variance record in the workflow. Possible values include Committed, Editable, and Canceled.

**Label:** Status

## Relations

### cancelTransactionUser
- **Related Collection:**  [userLogin](https://developer.finaleinventory.com/reference/graphql-user-login)

### commitTransactionUser
- **Related Collection:**  [userLogin](https://developer.finaleinventory.com/reference/graphql-user-login)

### product
- **Related Collection:**  [product](https://developer.finaleinventory.com/reference/graphql-product)

### recordCreatedUser
- **Related Collection:**  [userLogin](https://developer.finaleinventory.com/reference/graphql-user-login)

### recordLastUpdatedUser
- **Related Collection:**  [userLogin](https://developer.finaleinventory.com/reference/graphql-user-login)

### sublocationFacility
- **Related Collection:**  [facility](https://developer.finaleinventory.com/reference/graphql-facility)
