# Sync Parts and Receipts from an ERP

An ERP usually owns the part master and the purchase orders. Kanoa Inventory owns the storeroom: what is on the shelf now. Two flows connect them:

- **Part master.** The ERP sends new and changed parts. The script adds or updates the part in the catalog.
- **Receipts.** The ERP sends a delivery against a purchase order. The script records a receipt transaction, which raises on-hand stock.

You build both the way [Connect To ERP](../../4-training-ops/03-erp-connectivity/index.md) built `sendMO`. A WebDev endpoint handles only the HTTP request and response, and a project script library holds the logic. See [Create Web Service](../../4-training-ops/03-erp-connectivity/1-create-endpoint.md) for how to create the endpoint.

## Look up ids by name

The ERP sends names and codes. The Kanoa functions need database ids. Look the ids up on each call and never hardcode them, because ids differ between systems.

| You have | Function | Id column |
| --- | --- | --- |
| A category path, such as `Filters` | `system.kanoa.inventory.getPartCategories({'categoryPath': ...})` | `partCategoryId` |
| A unit code, such as `EA` | `system.kanoa.inventory.getUnitOfMeasures({'uomCode': ...})` | `uomId` |
| A manufacturer name | `system.kanoa.inventory.getManufacturers({'manufacturerName': ...})` | `manufacturerId` |
| A supplier name | `system.kanoa.inventory.getSuppliers({'supplierName': ...})` | `supplierId` |
| A part number | `system.kanoa.inventory.getParts({'partNumber': ...})` | `partId` |
| A transaction type code | `system.kanoa.inventory.getInventoryTransactionTypes({'transactionTypeCode': ...})` | `inventoryTransactionTypeId` |
| A storeroom path | `system.kanoa.asset.getAssets({'assetPath': ...})` | `assetId` |

`system.kanoa.utilities.getFieldValue(column, dataset)` returns the value from a one-row dataset, or `None` when nothing matches.

## Transaction types

A receipt is a transaction with the `RECEIPT` type. Look up the types with `getInventoryTransactionTypes`. The types in Kanoa Inventory 1.16 are:

| Code | Name |
| --- | --- |
| `RECEIPT` | Receipt to inventory |
| `ISSUE` | Issue from inventory |
| `RETURN` | Return to inventory |
| `ADJUSTMENT_POS` | Positive adjustment |
| `ADJUSTMENT_NEG` | Negative adjustment |
| `TRANSFER_OUT` | Transfer out |
| `TRANSFER_IN` | Transfer in |
| `CYCLE_COUNT` | Cycle count adjustment |
| `RESERVE` | Reserve inventory |
| `UNRESERVE` | Release reservation |

::embed-section{src="../../../systemFunctions/inventory/getInventoryTransactionTypes.md" collapsed="true" summary="Reference Materials: getInventoryTransactionTypes"}

## Create or update a part

`system.kanoa.inventory.addPart` adds a part and returns the new `partId`. To change one field on an existing part, use `updatePartField(partId, field, value, userId)`. To overwrite several fields at once, use `updatePart` with `partId` and the full set of fields in `partInfo`.

:::action[Create the `inventoryERP` library]

1. In the Ignition Designer, open the project that holds your ERP scripts, as in the ERP chapter.
2. Create a script library called `inventoryERP`.
3. Paste in the code below.

<details>
<summary>inventoryERP code block</summary>

```python title="inventoryERP (project library)"
def getId(column, dataset):
    return system.kanoa.utilities.getFieldValue(column, dataset)
#################################################################################
def syncPart(partData):
    """
    Add the part if its number is new, otherwise update its description.
    Returns (ok, message).
    """
    userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
    partNumber = (partData.get('partNumber') or '').strip()
    if not partNumber:
        return False, 'Missing partNumber'

    partId = getId('partId', system.kanoa.inventory.getParts({'partNumber': partNumber}))
    if partId is not None:
        system.kanoa.inventory.updatePartField(partId, 'partDescription', partData.get('description'), userId)
        return True, 'Part %s updated' % partNumber

    categoryId = getId('partCategoryId', system.kanoa.inventory.getPartCategories({'categoryPath': partData.get('categoryPath')}))
    uomId = getId('uomId', system.kanoa.inventory.getUnitOfMeasures({'uomCode': partData.get('uom')}))
    if categoryId is None or uomId is None:
        return False, 'Part %s: unknown category or unit' % partNumber

    partInfo = {
        'partNumber': partNumber,
        'partDescription': partData.get('description'),
        'partCategoryId': categoryId,
        'defaultUomId': uomId,
        'manufacturerId': getId('manufacturerId', system.kanoa.inventory.getManufacturers({'manufacturerName': partData.get('manufacturer')})),
        'manufacturerPartNumber': partData.get('manufacturerPartNumber'),
        'enabled': True,
        'isConsumable': bool(partData.get('isConsumable')),
        'isCriticalSpare': bool(partData.get('isCriticalSpare')),
        'isRepairable': False,
        'isSerialized': False,
    }
    newPartId, message = system.kanoa.inventory.addPart(partInfo, userId)
    if message:
        return False, 'Part %s: %s' % (partNumber, message)
    return True, 'Part %s added' % partNumber
#################################################################################
def receiveDelivery(receipt):
    """
    Record one delivery line as a RECEIPT transaction. Safe to resend:
    a purchase order line that was already received is skipped.
    Returns (ok, message).
    """
    userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
    poNumber = receipt.get('poNumber')
    partNumber = receipt.get('partNumber')

    partId = getId('partId', system.kanoa.inventory.getParts({'partNumber': partNumber}))
    storeroomId = getId('assetId', system.kanoa.asset.getAssets({'assetPath': receipt.get('storeroomPath')}))
    typeId = getId('inventoryTransactionTypeId', system.kanoa.inventory.getInventoryTransactionTypes({'transactionTypeCode': 'RECEIPT'}))
    if partId is None or storeroomId is None or typeId is None:
        return False, 'Receipt %s %s: unknown part, storeroom or type' % (poNumber, partNumber)

    # Skip a line that was already received
    existing = system.kanoa.inventory.getInventoryTransactions({
        'referenceType': 'PO', 'referenceNumber': poNumber,
        'partId': partId, 'inventoryTransactionTypeId': typeId})
    if existing.getRowCount() > 0:
        return True, 'Receipt %s %s already recorded' % (poNumber, partNumber)

    transactionInfo = {
        'inventoryAssetId': storeroomId,
        'inventoryTransactionTypeId': typeId,
        'partId': partId,
        'quantity': float(receipt.get('quantity')),
        'unitCost': receipt.get('unitCost'),
        'supplierId': getId('supplierId', system.kanoa.inventory.getSuppliers({'supplierName': receipt.get('supplier')})),
        'referenceType': 'PO',
        'referenceNumber': poNumber,
        'notes': 'Received from ERP',
    }
    inventoryTransactionId, message = system.kanoa.inventory.addInventoryTransaction(transactionInfo, userId)
    if message:
        return False, 'Receipt %s %s: %s' % (poNumber, partNumber, message)
    return True, 'Receipt %s %s recorded' % (poNumber, partNumber)
```

</details>

:::

{/*
TODO: confirm on a gateway three things about this library. First, that getInventoryTransactions returns a dataset with getRowCount, and that filtering on referenceType, referenceNumber, partId and inventoryTransactionTypeId finds an earlier receipt. Second, that unitCost None and supplierId None are accepted by addInventoryTransaction. Third, that a duplicate partNumber makes addPart return a message, so that syncPart reports it.
*/}

::embed-section{src="../../../systemFunctions/inventory/addPart.md" collapsed="true" summary="Reference Materials: addPart"}

::embed-section{src="../../../systemFunctions/inventory/updatePartField.md" collapsed="true" summary="Reference Materials: updatePartField"}

::embed-section{src="../../../systemFunctions/inventory/addInventoryTransaction.md" collapsed="true" summary="Reference Materials: addInventoryTransaction"}

:::note[Quantity must be above zero]
`addInventoryTransaction` requires `quantity` greater than 0. The transaction type decides whether stock goes up or down, so never send a negative quantity for an issue.
:::

## Try it from the Script Console

:::action[Receive a delivery and add a part]

1. In the Script Console, run:

   ```python
   print inventoryERP.syncPart({
       'partNumber': 'CF-GSK-250',
       'description': 'Coolant pump gasket',
       'categoryPath': 'Hoses',
       'uom': 'EA',
       'manufacturer': 'Apex Tooling',
       'isConsumable': True,
   })

   print inventoryERP.receiveDelivery({
       'poNumber': 'PO-2026-0201',
       'partNumber': 'CF-FLT-COOL10',
       'quantity': 10,
       'unitCost': 18.5,
       'storeroomPath': 'CoreForge\\Philadelphia\\Storage\\Parts Room',
   })
   ```

2. Check the output. You see `(True, 'Part CF-GSK-250 added')` and `(True, 'Receipt PO-2026-0201 CF-FLT-COOL10 recorded')`.
3. In **Inventory → Parts**, `CF-GSK-250` is in the catalog. Expand `CF-FLT-COOL10`. On hand is up by 10, with a receipt that references `PO-2026-0201`.
4. Run the second call again. The result is now `Receipt PO-2026-0201 CF-FLT-COOL10 already recorded`, and the stock does not change.

:::

{/*
TODO: confirm the CoreForge category path for the demo part. Category Hoses is used because the Parts catalog lesson creates it; change it if a gasket belongs elsewhere. Also confirm the expected on-hand value after the receipt against the course data.
*/}

## Connect it to the ERP

Add a WebDev `doPost` resource for each flow, as in the ERP chapter, and keep the handler thin:

```python title="WebDev doPost: receiveDelivery"
body = request.get("data", b"")
if isinstance(body, basestring):
    body = system.util.jsonDecode(body)

ok, msg = inventoryERP.receiveDelivery(body.get("receipt") or {})
return {
    "status": 200 if ok else 400,
    "contentType": "application/json",
    "response": system.util.jsonEncode({"ok": ok, "msg": msg})
}
```

The ERP posts a payload like this one:

```json
{
  "receipt": {
    "poNumber": "PO-2026-0201",
    "partNumber": "CF-FLT-COOL10",
    "quantity": 10,
    "unitCost": 18.5,
    "supplier": "Apex Tooling",
    "storeroomPath": "CoreForge\\Philadelphia\\Storage\\Parts Room"
  }
}
```

This payload is an example. Agree the real field names with the ERP team, and send one delivery line per call.

{/*
TODO: confirm on a gateway that the request body arrives as a dict for a JSON POST in this WebDev setup, as the ERP chapter's sendMO assumes, and test the endpoint with the ERP simulator or a REST client. Also confirm whether the endpoint needs authentication.
*/}

:::warning[Do not edit transactions to fix stock]
Corrections are new transactions, as in [Adjust Stock and Find Reorders](../02-stock-transactions/3-adjust-and-reorder.md). To correct a wrong receipt, post an `ADJUSTMENT_NEG` transaction for the same quantity.
:::

You built a script library that adds or updates parts and records receipts without double counting, and you saw how to expose it to an ERP through a WebDev endpoint.
