Skip to main content

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 built sendMO. A WebDev endpoint handles only the HTTP request and response, and a project script library holds the logic. See Create Web Service 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 haveFunctionId column
A category path, such as Filterssystem.kanoa.inventory.getPartCategories({'categoryPath': ...})partCategoryId
A unit code, such as EAsystem.kanoa.inventory.getUnitOfMeasures({'uomCode': ...})uomId
A manufacturer namesystem.kanoa.inventory.getManufacturers({'manufacturerName': ...})manufacturerId
A supplier namesystem.kanoa.inventory.getSuppliers({'supplierName': ...})supplierId
A part numbersystem.kanoa.inventory.getParts({'partNumber': ...})partId
A transaction type codesystem.kanoa.inventory.getInventoryTransactionTypes({'transactionTypeCode': ...})inventoryTransactionTypeId
A storeroom pathsystem.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:

CodeName
RECEIPTReceipt to inventory
ISSUEIssue from inventory
RETURNReturn to inventory
ADJUSTMENT_POSPositive adjustment
ADJUSTMENT_NEGNegative adjustment
TRANSFER_OUTTransfer out
TRANSFER_INTransfer in
CYCLE_COUNTCycle count adjustment
RESERVEReserve inventory
UNRESERVERelease reservation
Reference Materials: getInventoryTransactionTypes

Returns a list of inventory transaction types configured in the system, optionally filtered by the criteria provided in paramsDict. Transaction types classify inventory movements (e.g. receipts, issues, adjustments) and determine whether a transaction increases or decreases on-hand quantity via the quantitySign attribute. When no filters are supplied, all inventory transaction type records are returned.


Parameters​

paramsDict Dictionary

- inventoryTransactionTypeIdInteger
- quantitySignString
- transactionTypeCodeString
- transactionTypeNameString

Returns​

data pyDataset


Example​

# Look up all inventory transaction types that decrease on-hand quantity (e.g. issues/consumption)
paramsDict = {'quantitySign': '-'}

data = system.kanoa.inventory.getInventoryTransactionTypes(paramsDict)
data = system.kanoa.utilities.convertDatasetToJSON(data)

for i, row in enumerate(data):
print 'Row %i'%i
for k,v in row.items():
print k,v

break #Just limiting to returning the columns from the first record for display purposes
>>>
Row 0
transactionTypeCode CYCLE_COUNT
quantitySign 0
transactionTypeName Cycle count adjustment
inventoryTransactionTypeId 8
>>>

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.

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.
inventoryERP code block
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)
Reference Materials: addPart

Adds a new part record to the inventory master. This is the primary function for registering a new stock-keeping unit (SKU) such as a bearing, filter, or gasket, into the system, along with its category, unit of measure, manufacturer reference, and handling flags (serialized, consumable, repairable, critical spare). On success the newly created part's id is returned so it can be used immediately in follow-up calls (e.g. updatePart, updatePartField).


Parameters​

partInfo Dictionary

- defaultUomIdInteger
- enabledBoolean
- isConsumableBoolean
- isCriticalSpareBoolean
- isRepairableBoolean
- isSerializedBoolean
- manufacturerIdInteger
- manufacturerPartNumberString
- notesString
- partCategoryIdInteger
- partDescriptionString
- partNumberString

userId Integer:Id of the user executing the function


Returns​

partId Integer
message String None if success


Example​

# Register a new sealed ball bearing as a critical spare part
partInfo = {
'partNumber': '6203-2RS',
'partDescription': '6203-2RS Sealed Ball Bearing, 17x40x12mm',
'partCategoryId': 14,
'manufacturerId': 22,
'manufacturerPartNumber': 'SKF-6203-2RS',
'defaultUomId': 1,
'enabled': True,
'isConsumable': False,
'isCriticalSpare': True,
'isRepairable': False,
'isSerialized': False,
'notes': 'Primary spare for conveyor drive motor bearings'
}
userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
newPartId, message = system.kanoa.inventory.addPart(partInfo, userId)
print newPartId, message
Reference Materials: updatePartField

Updates a single named field on a part record for the given partId, without needing to supply the full part dictionary. Useful for quick, targeted edits � such as flipping a handling flag or correcting a manufacturer part number � from a UI control bound to one column at a time.


Parameters​

partId Integer: Id of part to update
field String: Valid options are partNumber, partDescription, partCategory, manufacturerId, manufacturerPartNumber, defaultUomId, isCriticalSpare, isRepairable, isSerialized, isConsumable, isActive, notes
value String: Value to update to
userId Integer:Id of the user executing the function


Returns​

# of records modified Integer
message String None if success


Example​

# Mark an existing gasket part as a critical spare
partId = 5187
field = 'isCriticalSpare'
value = True
userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})

recordsModified, message = system.kanoa.inventory.updatePartField(partId, field, value, userId)
print recordsModified, message
Reference Materials: addInventoryTransaction

Adds a new inventory transaction record, adjusting the on-hand inventory balance for the affected part and inventory asset (bin/location) by the given quantity. Passing an inventoryTransactionId inside inventoryTransactionInfo updates the existing record instead of inserting a new one; omit it (or pass None) to insert. Typical uses include recording receipts, issues, transfers, and adjustments against a part's stock.


Parameters​

inventoryTransactionInfo Dictionary

- assetIdIntegerNot required. Physical asset the part was used on.
- costCenterIdIntegerNot required.
- inventoryAssetIdIntegerRequired for insert.
- inventoryTransactionIdIntegerNot required. Pass to update existing record.
- inventoryTransactionTypeIdIntegerRequired for insert.
- notesStringNot required.
- partIdIntegerRequired for insert.
- quantityFloatRequired for insert. Must be > 0.
- referenceNumberStringNot required. e.g. 'PO 1234'
- referenceTypeStringNot required. e.g. 'PO', 'WO'
- sourceRecordIdIntegerNot required. For automated processes only.
- sourceSchemaNameStringNot required. For automated processes only.
- sourceTableNameStringNot required. For automated processes only.
- supplierIdIntegerNot required.
- unitCostFloatNot required.

userId Integer:Id of the user executing the function


Returns​

inventoryTransactionId Integer
message String None if success


Example​

inventoryTransactionInfo = {
'inventoryAssetId': 42,
'inventoryTransactionTypeId': 1,
'partId': 1057,
'quantity': 25.0,
'unitCost': 4.35,
'referenceType': 'PO',
'referenceNumber': 'PO 1234',
'supplierId': 8,
'notes': 'Receipt against purchase order for stockroom replenishment'
}
userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
inventoryTransactionId, message = system.kanoa.inventory.addInventoryTransaction(inventoryTransactionInfo, userId)
print inventoryTransactionId, message
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​

Receive a delivery and add a part
  1. In the Script Console, run:

    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.

Connect it to the ERP​

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

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:

{
"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.

Do not edit transactions to fix stock

Corrections are new transactions, as in Adjust Stock and Find Reorders. 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.