Skip to content

SAP Models

Pydantic models of the SAP business objects that the SAP class reads and changes - see Models for their naming and usage.

sap_models

Pydantic models for the SAP S/4HANA OData APIs used by the SAP class (see sap.py).

The module contains: * Field types and helpers for SAP / OData formats (e.g. OData V2 "/Date(...)/" dates, SAP flags "X" / "", fixed-length item numbers). * Base classes: SAPODataModel (all SAP entity models) and SAPODataCreateModel (models that are converted into the payload of a deep insert / deep create). * Models describing OData services, their availability and SAP error responses. * Create models (e.g. SAPMaintenanceOrderModel) - validated input data that is converted into the OData payload with to_odata(). * Response models (e.g. SAPMaintenanceOrderResponseModel) - typed results of read requests. * Query models (e.g. SAPMaintenanceOrderQueryModel) - search criteria of the list methods.

Class hierarchy - the subclasses mostly declare fields, the behavior comes from the base classes:

SAPODataModel                     parse SAP responses, str() = compact JSON
├── *ResponseModel                results of SAP.get_*() / iter_*()
└── SAPODataCreateModel           to_odata() / to_odata_update()
    ├── *Model                    data of SAP.create_*(), changes of SAP.update_*()
    ├── SAPPurchasingItemModel    common fields of purchasing document items
    ├── SAPSourcingItemModel      common fields of RFQ and quotation items
    └── SAPSourcingDocumentModel  common fields of RFQ and quotation headers
SAPODataQueryModel                to_odata() = $filter / $orderby / $expand
└── *QueryModel                   search criteria of SAP.get_*s() / iter_*s()

A comment above each subclass names what it inherits and which SAP methods use it. These notes are comments on purpose: pydantic puts the class docstring into the JSON schema ("description"), and LLM tools that take or return the models show it to the LLM - so docstrings describe the data for API users and LLMs, comments explain the code to developers.

The Python attribute names of the models are snake case, the aliases are the OData property names of the SAP APIs. Both can be used to initialize the models.

See sap.py for the documentation of the SAP APIs and how to activate them.

Classes:

Name Description
SAPBusinessObjectType

An SAP business object type (BOR object type, transaction SWO1) with the structure of its key.

SAPODataModel

Base class of all models for SAP OData entities.

SAPODataCreateModel

Base class of the models used to create SAP documents (deep insert / deep create).

SAPPurchasingItemModel

Base class of the items of purchasing documents (purchase order, contract and requisition).

ODataCondition

Describes how a field of a query model becomes a condition of the OData $filter.

ODataDeletionCondition

Describes the condition of a deletion filter (is_marked_for_deletion of the query models).

ODataTextSearch

Describes how the name / description criterion of a query model is resolved via a text entity set.

SAPODataQueryModel

Base class of the search criteria for SAP OData collections (list and iterator methods).

SAPODataTextResponseModel

An entity of a text entity set as returned by SAP - all properties are kept (see ODataTextSearch).

SAPODataTextQueryModel

Query of the keys of a text or item entity set (see SAP._resolve_text_search() and SAP._find_keys_via_items()).

SAPODataServiceModel

Definition of an SAP OData service (API) used by this module.

SAPODataServiceState

Possible results of an OData service availability check.

SAPODataServiceStatusModel

Result of the availability check for one SAP OData service.

SAPAuthCheckState

Possible results of an authentication / principal propagation health check.

SAPAuthCheckStatusModel

Result of a single step of an authentication / principal propagation health check.

SAPODataErrorDetailModel

A single detail message of an SAP OData error response.

SAPODataErrorModel

An error returned by an SAP OData service.

SAPMaintenanceOrderComponentModel

A component (material, e.g. a spare part) of an operation of a maintenance order (API_MAINTENANCEORDER).

SAPTaskListReferenceModel

A maintenance task list whose operations and materials are taken over into a new maintenance order.

SAPMaintenanceOrderOperationModel

An operation of an SAP Plant Maintenance order (API_MAINTENANCEORDER).

SAPMaintenanceOrderModel

Data to create an SAP Plant Maintenance order (API_MAINTENANCEORDER).

SAPMaintenanceOrderComponentResponseModel

A component (material) of a maintenance order operation as returned by SAP (API_MAINTENANCEORDER).

SAPMaintenanceOrderOperationResponseModel

An operation of an SAP Plant Maintenance order as returned by SAP (API_MAINTENANCEORDER).

SAPMaintenanceOrderObjectListItemResponseModel

An entry of the object list of a maintenance order as returned by SAP (API_MAINTENANCEORDER).

SAPMaintenanceOrderResponseModel

An SAP Plant Maintenance order as returned by SAP (API_MAINTENANCEORDER).

SAPMaintenanceOrderQueryModel

Search criteria for SAP maintenance orders (API_MAINTENANCEORDER).

SAPMaintenanceNotificationItemModel

An item (damage / object part) of an SAP maintenance notification (API_MAINTNOTIFICATION).

SAPMaintenanceNotificationModel

Data to create an SAP maintenance notification (API_MAINTNOTIFICATION, OData V2).

SAPMaintenanceNotificationItemResponseModel

An item of an SAP maintenance notification as returned by SAP (API_MAINTNOTIFICATION).

SAPMaintenanceNotificationResponseModel

An SAP maintenance notification as returned by SAP (API_MAINTNOTIFICATION).

SAPMaintenanceNotificationQueryModel

Search criteria for SAP maintenance notifications (API_MAINTNOTIFICATION).

SAPPurchaseOrderScheduleLineModel

A schedule line (delivery date and quantity) of a purchase order item (API_PURCHASEORDER_2).

SAPPurchaseOrderAccountAssignmentModel

An account assignment of a purchase order item (API_PURCHASEORDER_2).

SAPPurchaseOrderItemModel

An item of a purchase order (API_PURCHASEORDER_2).

SAPPurchaseOrderModel

Data to create an SAP purchase order (API_PURCHASEORDER_2, OData V4).

SAPPurchaseOrderScheduleLineResponseModel

A schedule line of a purchase order item as returned by SAP (API_PURCHASEORDER_2).

SAPPurchaseOrderAccountAssignmentResponseModel

An account assignment of a purchase order item as returned by SAP (API_PURCHASEORDER_2).

SAPPurchaseOrderItemResponseModel

An item of a purchase order as returned by SAP (API_PURCHASEORDER_2).

SAPPurchaseOrderResponseModel

A purchase order as returned by SAP (API_PURCHASEORDER_2, OData V4).

SAPPurchaseOrderQueryModel

Search criteria for SAP purchase orders (API_PURCHASEORDER_2, OData V4).

SAPSalesOrderItemModel

An item of an SAP sales order (API_SALES_ORDER_SRV).

SAPSalesOrderModel

Data to create an SAP sales order (API_SALES_ORDER_SRV, OData V2).

SAPSalesOrderItemResponseModel

An item of an SAP sales order as returned by SAP (API_SALES_ORDER_SRV).

SAPSalesOrderResponseModel

An SAP sales order as returned by SAP (API_SALES_ORDER_SRV, OData V2).

SAPSalesOrderQueryModel

Search criteria for SAP sales orders (API_SALES_ORDER_SRV).

SAPSalesContractItemModel

An item of an SAP sales contract (API_SALES_CONTRACT_SRV).

SAPSalesContractModel

Data to create an SAP sales contract (API_SALES_CONTRACT_SRV, OData V2).

SAPSalesContractItemResponseModel

An item of an SAP sales contract as returned by SAP (API_SALES_CONTRACT_SRV).

SAPSalesContractResponseModel

An SAP sales contract as returned by SAP (API_SALES_CONTRACT_SRV, OData V2).

SAPSalesContractQueryModel

Search criteria for SAP sales contracts (API_SALES_CONTRACT_SRV).

SAPPurchaseContractItemModel

An item of an SAP purchase contract (API_PURCHASECONTRACT_PROCESS_SRV).

SAPPurchaseContractModel

Data to create an SAP purchase contract (API_PURCHASECONTRACT_PROCESS_SRV, OData V2).

SAPPurchaseContractItemResponseModel

An item of an SAP purchase contract as returned by SAP (API_PURCHASECONTRACT_PROCESS_SRV).

SAPPurchaseContractResponseModel

An SAP purchase contract as returned by SAP (API_PURCHASECONTRACT_PROCESS_SRV, OData V2).

SAPPurchaseContractQueryModel

Search criteria for SAP purchase contracts (API_PURCHASECONTRACT_PROCESS_SRV).

SAPPurchaseRequisitionAccountAssignmentModel

An account assignment of a purchase requisition item (API_PURCHASEREQUISITION_2).

SAPPurchaseRequisitionItemModel

An item of an SAP purchase requisition (API_PURCHASEREQUISITION_2, OData V4).

SAPPurchaseRequisitionModel

Data to create an SAP purchase requisition (API_PURCHASEREQUISITION_2, OData V4).

SAPPurchaseRequisitionAccountAssignmentResponseModel

An account assignment of a purchase requisition item as returned by SAP (API_PURCHASEREQUISITION_2).

SAPPurchaseRequisitionItemResponseModel

An item of an SAP purchase requisition as returned by SAP (API_PURCHASEREQUISITION_2).

SAPPurchaseRequisitionResponseModel

An SAP purchase requisition as returned by SAP (API_PURCHASEREQUISITION_2, OData V4).

SAPPurchaseRequisitionQueryModel

Search criteria for SAP purchase requisitions (API_PURCHASEREQUISITION_2, OData V4).

SAPRequestForQuotationAction

Status actions for requests for quotation (function imports of API_RFQ_PROCESS_SRV).

SAPSupplierQuotationAction

Status actions for supplier quotations (function imports of API_QTN_PROCESS_SRV).

SAPSourcingItemModel

Base class of the items of requests for quotation and supplier quotations.

SAPSourcingDocumentModel

Base class of the headers of requests for quotation and supplier quotations.

SAPRequestForQuotationItemModel

An item of an SAP request for quotation (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationBidderModel

A bidder (supplier asked for a quotation) of an SAP request for quotation (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationModel

Data to create an SAP request for quotation (API_RFQ_PROCESS_SRV, OData V2).

SAPRequestForQuotationItemResponseModel

An item of an SAP request for quotation as returned by SAP (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationBidderResponseModel

A bidder of an SAP request for quotation as returned by SAP (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationResponseModel

An SAP request for quotation as returned by SAP (API_RFQ_PROCESS_SRV, OData V2).

SAPRequestForQuotationQueryModel

Search criteria for SAP requests for quotation (API_RFQ_PROCESS_SRV).

SAPSupplierQuotationItemModel

The fields of an item of an SAP supplier quotation that can be changed (API_QTN_PROCESS_SRV).

SAPSupplierQuotationModel

The fields of an SAP supplier quotation that can be changed (API_QTN_PROCESS_SRV, OData V2).

SAPSupplierQuotationItemResponseModel

An item of an SAP supplier quotation as returned by SAP (API_QTN_PROCESS_SRV).

SAPSupplierQuotationResponseModel

An SAP supplier quotation as returned by SAP (API_QTN_PROCESS_SRV, OData V2).

SAPSupplierQuotationQueryModel

Search criteria for SAP supplier quotations (API_QTN_PROCESS_SRV).

SAPPurchasingInfoRecordDataModel

The purchasing organization / plant data of an SAP purchasing info record (API_INFORECORD_PROCESS_SRV).

SAPPurchasingInfoRecordModel

Data to create an SAP purchasing info record (API_INFORECORD_PROCESS_SRV, OData V2).

SAPPurchasingInfoRecordDataResponseModel

The purchasing organization / plant data of an SAP purchasing info record as returned by SAP.

SAPPurchasingInfoRecordResponseModel

An SAP purchasing info record as returned by SAP (API_INFORECORD_PROCESS_SRV, OData V2).

SAPPurchasingInfoRecordQueryModel

Search criteria for SAP purchasing info records (API_INFORECORD_PROCESS_SRV).

SAPSourceListRecordModel

Data to create an SAP source list record (API_PURCHASING_SOURCE_SRV, OData V2).

SAPSourceListRecordResponseModel

An SAP source list record as returned by SAP (API_PURCHASING_SOURCE_SRV, OData V2).

SAPSourceListRecordQueryModel

Search criteria for SAP source list records (API_PURCHASING_SOURCE_SRV).

SAPWarrantyClaimItemModel

An item of an SAP warranty claim version (API_WARRANTYCLAIM, OData V4).

SAPWarrantyClaimVersionModel

A version of an SAP warranty claim (API_WARRANTYCLAIM, OData V4).

SAPWarrantyClaimModel

Data to create an SAP warranty claim (API_WARRANTYCLAIM, OData V4).

SAPWarrantyClaimItemResponseModel

An item of an SAP warranty claim version as returned by SAP (API_WARRANTYCLAIM).

SAPWarrantyClaimVersionResponseModel

A version of an SAP warranty claim as returned by SAP (API_WARRANTYCLAIM).

SAPWarrantyClaimResponseModel

An SAP warranty claim as returned by SAP (API_WARRANTYCLAIM, OData V4).

SAPWarrantyClaimQueryModel

Search criteria for SAP warranty claims (API_WARRANTYCLAIM, OData V4).

SAPCreditMemoRequestItemModel

An item of an SAP credit memo request (API_CREDIT_MEMO_REQUEST_SRV).

SAPCreditMemoRequestModel

Data to create an SAP credit memo request (API_CREDIT_MEMO_REQUEST_SRV, OData V2).

SAPCreditMemoRequestItemResponseModel

An item of an SAP credit memo request as returned by SAP (API_CREDIT_MEMO_REQUEST_SRV).

SAPCreditMemoRequestResponseModel

An SAP credit memo request as returned by SAP (API_CREDIT_MEMO_REQUEST_SRV, OData V2).

SAPCreditMemoRequestQueryModel

Search criteria for SAP credit memo requests (API_CREDIT_MEMO_REQUEST_SRV).

SAPDebitMemoRequestItemModel

An item of an SAP debit memo request (API_DEBIT_MEMO_REQUEST_SRV).

SAPDebitMemoRequestModel

Data to create an SAP debit memo request (API_DEBIT_MEMO_REQUEST_SRV, OData V2).

SAPDebitMemoRequestItemResponseModel

An item of an SAP debit memo request as returned by SAP (API_DEBIT_MEMO_REQUEST_SRV).

SAPDebitMemoRequestResponseModel

An SAP debit memo request as returned by SAP (API_DEBIT_MEMO_REQUEST_SRV, OData V2).

SAPDebitMemoRequestQueryModel

Search criteria for SAP debit memo requests (API_DEBIT_MEMO_REQUEST_SRV).

SAPBillingDocumentRequestItemResponseModel

An item of an SAP billing document request as returned by SAP (API_BILLING_DOCUMENT_REQUEST_SRV).

SAPBillingDocumentRequestResponseModel

An SAP billing document request as returned by SAP (API_BILLING_DOCUMENT_REQUEST_SRV, OData V2).

SAPBillingDocumentRequestQueryModel

Search criteria for SAP billing document requests (API_BILLING_DOCUMENT_REQUEST_SRV).

SAPBillingDocumentItemResponseModel

An item of an SAP billing document as returned by SAP (API_BILLING_DOCUMENT_SRV).

SAPBillingDocumentResponseModel

An SAP billing document as returned by SAP (API_BILLING_DOCUMENT_SRV, OData V2).

SAPBillingDocumentQueryModel

Search criteria for SAP billing documents (API_BILLING_DOCUMENT_SRV).

SAPBillingDocumentItemQueryModel

Search criteria for SAP billing document items (API_BILLING_DOCUMENT_SRV, A_BillingDocumentItem).

SAPOutboundDeliveryItemModel

An item of an SAP outbound delivery - a reference to the sales order item to deliver (API_OUTBOUND_DELIVERY_SRV).

SAPOutboundDeliveryModel

Data to create an SAP outbound delivery for sales order items (API_OUTBOUND_DELIVERY_SRV, OData V2).

SAPOutboundDeliveryItemResponseModel

An item of an SAP outbound delivery as returned by SAP (API_OUTBOUND_DELIVERY_SRV).

SAPOutboundDeliveryResponseModel

An SAP outbound delivery as returned by SAP (API_OUTBOUND_DELIVERY_SRV, OData V2).

SAPOutboundDeliveryQueryModel

Search criteria for SAP outbound deliveries (API_OUTBOUND_DELIVERY_SRV).

SAPOutboundDeliveryItemQueryModel

Search criteria for SAP outbound delivery items (API_OUTBOUND_DELIVERY_SRV, A_OutbDeliveryItem).

SAPInboundDeliveryItemModel

An item of an SAP inbound delivery - the delivered quantity of a purchase order item (API_INBOUND_DELIVERY_SRV).

SAPInboundDeliveryModel

Data to create an SAP inbound delivery for purchase order items (API_INBOUND_DELIVERY_SRV, OData V2).

SAPInboundDeliveryItemResponseModel

An item of an SAP inbound delivery as returned by SAP (API_INBOUND_DELIVERY_SRV).

SAPInboundDeliveryResponseModel

An SAP inbound delivery as returned by SAP (API_INBOUND_DELIVERY_SRV, OData V2).

SAPInboundDeliveryQueryModel

Search criteria for SAP inbound deliveries (API_INBOUND_DELIVERY_SRV).

SAPInboundDeliveryItemQueryModel

Search criteria for SAP inbound delivery items (API_INBOUND_DELIVERY_SRV, A_InbDeliveryItem).

SAPSupplierInvoiceAccountAssignmentModel

An account assignment of a purchase order item of a new SAP supplier invoice (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceMaterialItemModel

An item of a new SAP supplier invoice posted directly to a material - without purchase order (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceAssetItemModel

An item of a new SAP supplier invoice posted directly to a fixed asset (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceWithholdingTaxModel

A withholding tax of a new SAP supplier invoice (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceSelectedPurchaseOrderModel

A purchase order (item) whose open items SAP proposes as invoice items (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceSelectedDeliveryNoteModel

A delivery note whose goods receipts SAP proposes as invoice items (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceSelectedServiceEntrySheetModel

A service entry sheet (item) whose services SAP proposes as invoice items (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceAdditionalDataModel

Name, address and bank details of a one-time supplier (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoicePurchaseOrderItemModel

An item of an SAP supplier invoice that refers to a purchase order item (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceGLAccountItemModel

An item of an SAP supplier invoice posted directly to a G/L account (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceTaxModel

A tax line of an SAP supplier invoice - needed if the tax is not calculated automatically (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceModel

Data to create (post) an SAP supplier invoice (API_SUPPLIERINVOICE_PROCESS_SRV, OData V2).

SAPSupplierInvoiceAccountAssignmentResponseModel

An account assignment of a purchase order item of an SAP supplier invoice as returned by SAP.

SAPSupplierInvoiceMaterialItemResponseModel

A material item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceAssetItemResponseModel

A fixed asset item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceTaxResponseModel

A tax line of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceWithholdingTaxResponseModel

A withholding tax of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoicePurchaseOrderItemResponseModel

A purchase order item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceGLAccountItemResponseModel

A G/L account item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceResponseModel

An SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV, OData V2).

SAPSupplierInvoiceQueryModel

Search criteria for SAP supplier invoices (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceItemQueryModel

Search criteria for purchase order items of SAP supplier invoices (A_SuplrInvcItemPurOrdRef).

SAPSupplierInvoiceGLAccountItemQueryModel

Search criteria for G/L account items of SAP supplier invoices (A_SupplierInvoiceItemGLAcct).

SAPMaintenanceOrderAction

Status actions for maintenance orders (function imports of API_MAINTENANCEORDER).

SAPMaintenanceOrderOperationAction

Status actions for maintenance order operations (function imports of API_MAINTENANCEORDER).

SAPMaintenanceNotificationAction

Status actions for maintenance notifications (actions of API_MAINTNOTIFICATION).

SAPMaintenancePlanAction

Status / scheduling actions for maintenance plans (actions of API_MAINTENANCEPLAN).

SAPProductionOrderAction

Status actions for production orders (function imports of API_PRODUCTION_ORDER_2_SRV).

SAPCreditMemoRequestAction

Approval actions for credit memo requests (function imports of API_CREDIT_MEMO_REQUEST_SRV).

SAPOutboundDeliveryAction

Status actions for outbound deliveries (function imports of API_OUTBOUND_DELIVERY_SRV).

SAPInboundDeliveryAction

Status actions for inbound deliveries (function imports of API_INBOUND_DELIVERY_SRV).

SAPGoodsMovementItemModel

An item of a goods movement (material document item, API_MATERIAL_DOCUMENT_SRV).

SAPGoodsMovementModel

Data to post a goods movement (material document, API_MATERIAL_DOCUMENT_SRV, OData V2).

SAPGoodsMovementItemResponseModel

An item of a material document as returned by SAP (API_MATERIAL_DOCUMENT_SRV).

SAPGoodsMovementResponseModel

A material document (goods movement) as returned by SAP (API_MATERIAL_DOCUMENT_SRV, OData V2).

SAPGoodsMovementQueryModel

Search criteria for SAP goods movements / material documents (API_MATERIAL_DOCUMENT_SRV).

SAPGoodsMovementItemQueryModel

Search criteria for SAP material document items (API_MATERIAL_DOCUMENT_SRV, A_MaterialDocumentItem).

SAPOutboundDeliveryStorageLocationModel

The storage location to set for an item of an outbound delivery.

SAPOutboundDeliveryStorageLocationProblemModel

An item of an outbound delivery whose storage location can't be determined.

SAPOutboundDeliveryStorageLocationsModel

The storage locations to set for the delivery items without one - and the items where that is not possible.

SAPWarrantyClaimCheckModel

What SAP would reject in a new warranty claim - found before the claim is created.

SAPInvoiceReferenceCheckModel

The invoices of a supplier with a given supplier invoice number, sorted by what they mean for a duplicate.

SAPPurchaseOrderHistoryModel

The goods receipts and supplier invoices of a purchase order (purchase order history).

SAPSupplierInvoiceCompletionModel

What SAP.complete_supplier_invoice() found out while filling in an invoice.

SAPMaterialStockResponseModel

The stock of a material in one stock segment as returned by SAP (API_MATERIAL_STOCK_SRV, A_MatlStkInAcctMod).

SAPMaterialStockQueryModel

Search criteria for the SAP material stock (API_MATERIAL_STOCK_SRV, A_MatlStkInAcctMod).

SAPMaintenanceOrderConfirmationModel

Data to confirm work on a maintenance order operation (API_MAINTORDERCONFIRMATION, OData V2).

SAPMaintenanceOrderConfirmationResponseModel

A maintenance order confirmation as returned by SAP (API_MAINTORDERCONFIRMATION, OData V2).

SAPMaintenanceOrderConfirmationQueryModel

Search criteria for SAP maintenance order confirmations (API_MAINTORDERCONFIRMATION).

SAPMaintenancePlanCycleModel

A cycle of a maintenance plan, e.g. every 3 months or every 500 operating hours.

SAPMaintenancePlanItemModel

A maintenance item of a maintenance plan - the object to maintain and how (task list, order type).

SAPMaintenancePlanModel

Data to create an SAP maintenance plan (API_MAINTENANCEPLAN, OData V2).

SAPMaintenancePlanCycleResponseModel

A cycle of a maintenance plan as returned by SAP (API_MAINTENANCEPLAN).

SAPMaintenancePlanItemResponseModel

A maintenance item of a maintenance plan as returned by SAP (API_MAINTENANCEPLAN).

SAPMaintenancePlanResponseModel

A maintenance plan as returned by SAP (API_MAINTENANCEPLAN, OData V2).

SAPMaintenancePlanQueryModel

Search criteria for SAP maintenance plans (API_MAINTENANCEPLAN).

SAPMaintenancePlanItemQueryModel

Search criteria for SAP maintenance items (API_MAINTENANCEPLAN, MaintenanceItem).

SAPTaskListOperationMaterialModel

A material (component) needed by an operation of a new task list - e.g. a spare part.

SAPTaskListOperationModel

An operation of an SAP maintenance task list (API_MAINTENANCETASKLIST, OData V4).

SAPTaskListModel

Data to create an SAP maintenance task list (API_MAINTENANCETASKLIST, OData V4).

SAPTaskListOperationMaterialResponseModel

A material (component) of a task list operation as returned by SAP (API_MAINTENANCETASKLIST, OData V4).

SAPTaskListOperationResponseModel

An operation of a maintenance task list as returned by SAP (API_MAINTENANCETASKLIST).

SAPTaskListResponseModel

A maintenance task list as returned by SAP (API_MAINTENANCETASKLIST, OData V4).

SAPTaskListQueryModel

Search criteria for SAP maintenance task lists (API_MAINTENANCETASKLIST, OData V4).

SAPPlannedOrderModel

Data to create an SAP planned order (API_PLANNEDORDER, OData V4).

SAPPlannedOrderComponentModel

The changeable fields of a component of an SAP planned order (API_PLANNEDORDER, PlannedOrderComponent).

SAPPlannedOrderResponseModel

A planned order as returned by SAP (API_PLANNEDORDER, OData V4).

SAPPlannedOrderQueryModel

Search criteria for SAP planned orders (API_PLANNEDORDER, OData V4).

SAPProductionOrderModel

Data to create an SAP production order (API_PRODUCTION_ORDER_2_SRV, OData V2).

SAPProductionOrderOperationModel

The changeable fields of an operation of an SAP production order (API_PRODUCTION_ORDER_2_SRV).

SAPProductionOrderOperationResponseModel

An operation of a production order as returned by SAP (API_PRODUCTION_ORDER_2_SRV).

SAPProductionOrderStatusResponseModel

An active status of a production order as returned by SAP (API_PRODUCTION_ORDER_2_SRV).

SAPProductionOrderResponseModel

A production order as returned by SAP (API_PRODUCTION_ORDER_2_SRV, OData V2).

SAPProductionOrderQueryModel

Search criteria for SAP production orders (API_PRODUCTION_ORDER_2_SRV).

SAPPlantResponseModel

A plant as returned by SAP (API_PLANT_2, OData V4).

SAPPlantQueryModel

Search criteria for SAP plants (API_PLANT_2, OData V4).

SAPStorageLocationResponseModel

A storage location of a plant as returned by SAP (API_STORAGELOCATION_SRV, OData V2).

SAPStorageLocationQueryModel

Search criteria for SAP storage locations (API_STORAGELOCATION_SRV).

SAPProductDescriptionModel

A (language dependent) description of a new product.

SAPProductStorageLocationModel

The storage location data of a product in a plant (extends the product to a storage location).

SAPProductPlantModel

The plant specific data of a product (extends the product to a plant) - with its storage locations.

SAPProductValuationModel

The valuation data of a product in a valuation area (usually a plant) - needed for stock postings.

SAPProductExtensionModel

What is missing to extend an SAP product to a plant, storage locations and valuation area.

SAPProductModel

Data to create an SAP product / material (API_PRODUCT_SRV, OData V2).

SAPProductDescriptionResponseModel

A (language dependent) description of a product as returned by SAP (API_PRODUCT_SRV).

SAPProductStorageLocationResponseModel

The storage location data of a product as returned by SAP (API_PRODUCT_SRV).

SAPProductValuationResponseModel

The valuation data of a product in a valuation area as returned by SAP (API_PRODUCT_SRV).

SAPProductPlantResponseModel

The plant specific data of a product as returned by SAP (API_PRODUCT_SRV).

SAPProductResponseModel

A product (material) as returned by SAP (API_PRODUCT_SRV, OData V2).

SAPProductQueryModel

Search criteria for SAP products / materials (API_PRODUCT_SRV).

SAPMaterialBOMItemModel

An item (component) of a new material BOM.

SAPMaterialBOMModel

Data to create a material BOM (bill of material) of a product in a plant (API_BILL_OF_MATERIAL_SRV, V2).

SAPMaterialBOMItemResponseModel

An item (component) of a material BOM as returned by SAP (API_BILL_OF_MATERIAL_SRV).

SAPMaterialBOMResponseModel

A material BOM as returned by SAP (API_BILL_OF_MATERIAL_SRV, OData V2).

SAPMaterialBOMQueryModel

Search criteria for material BOMs (API_BILL_OF_MATERIAL_SRV).

SAPProductionVersionResponseModel

A production version (BOM + routing for a material in a plant) as returned by SAP (API_PRODUCTION_VERSION, OData V4).

SAPProductionVersionQueryModel

Search criteria for SAP production versions (API_PRODUCTION_VERSION, OData V4).

SAPWorkCenterResponseModel

A work center as returned by SAP (API_WORK_CENTERS, OData V2).

SAPWorkCenterQueryModel

Search criteria for SAP work centers (API_WORK_CENTERS).

SAPEquipmentModel

Data to create an SAP equipment (API_EQUIPMENT, OData V2).

SAPEquipmentResponseModel

An equipment (technical object) as returned by SAP (API_EQUIPMENT, OData V2).

SAPEquipmentQueryModel

Search criteria for SAP equipment (API_EQUIPMENT).

SAPFunctionalLocationModel

Data to create an SAP functional location (API_FUNCTIONALLOCATION, OData V2).

SAPFunctionalLocationResponseModel

A functional location (technical object) as returned by SAP (API_FUNCTIONALLOCATION, OData V2).

SAPFunctionalLocationQueryModel

Search criteria for SAP functional locations (API_FUNCTIONALLOCATION).

SAPBusinessPartnerAddressModel

An address of a new business partner.

SAPBusinessPartnerRoleModel

A role of a new business partner.

SAPSupplierPurchasingOrgModel

The purchasing organization data of a new supplier - needed to order from the supplier (role FLVN01).

SAPSupplierCompanyModel

The company code data of a new supplier - needed to post its invoices and pay it (role FLVN00).

SAPSupplierModel

The supplier data of a new business partner - created together with the business partner.

SAPCustomerSalesAreaTaxModel

The tax classification of a new customer in a sales area - used to determine the output tax in sales.

SAPCustomerSalesAreaModel

The sales area data of a new customer - needed to sell to the customer (role FLCU01).

SAPCustomerCompanyModel

The company code data of a new customer - needed to post its invoices and payments (role FLCU00).

SAPCustomerModel

The customer data of a new business partner - created together with the business partner.

SAPBusinessPartnerModel

Data to create an SAP business partner - an organization (API_BUSINESS_PARTNER, OData V2).

SAPBusinessPartnerAddressResponseModel

An address of a business partner as returned by SAP (API_BUSINESS_PARTNER).

SAPSupplierPurchasingOrgResponseModel

The purchasing organization data of a supplier as returned by SAP (API_BUSINESS_PARTNER).

SAPSupplierCompanyResponseModel

The company code data of a supplier as returned by SAP (API_BUSINESS_PARTNER).

SAPSupplierResponseModel

The supplier data of a business partner as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerSalesAreaTaxResponseModel

The tax classification of a customer in a sales area as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerPartnerFunctionResponseModel

A partner function of a customer in a sales area as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerSalesAreaResponseModel

The sales area data of a customer as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerCompanyResponseModel

The company code data of a customer as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerResponseModel

The customer data of a business partner as returned by SAP (API_BUSINESS_PARTNER).

SAPBusinessPartnerRoleResponseModel

A role of a business partner (e.g. FLVN00 supplier, FLCU00 customer) as returned by SAP (API_BUSINESS_PARTNER).

SAPBusinessPartnerResponseModel

A business partner (person or organization) as returned by SAP (API_BUSINESS_PARTNER, OData V2).

SAPBusinessPartnerQueryModel

Search criteria for SAP business partners (API_BUSINESS_PARTNER).

SAPBusinessPartnerIdentificationResponseModel

An identification of a business partner (e.g. type HCM001 = personnel number) as returned by SAP.

SAPPersonEmailAddressResponseModel

An e-mail address of a person as returned by SAP (API_BUSINESS_PARTNER).

SAPPersonPhoneNumberResponseModel

A phone number of a person as returned by SAP (API_BUSINESS_PARTNER).

SAPPersonAddressResponseModel

An address of a person as returned by SAP (API_BUSINESS_PARTNER) - with e-mail addresses and phone numbers.

SAPPersonResponseModel

A person with a personnel number as returned by SAP (API_BUSINESS_PARTNER, OData V2).

SAPPersonQueryModel

Search criteria for persons with a personnel number (API_BUSINESS_PARTNER).

SAPCustomerQueryModel

Search criteria for SAP customers - business partners with the customer role (API_BUSINESS_PARTNER).

SAPSupplierQueryModel

Search criteria for SAP suppliers (vendors) - business partners with the supplier role (API_BUSINESS_PARTNER).

SAPCompanyCodeResponseModel

A company code as returned by SAP (API_COMPANYCODE_SRV, OData V2).

SAPCompanyCodeQueryModel

Search criteria for SAP company codes (API_COMPANYCODE_SRV).

SAPSalesOrganizationTextResponseModel

The (language dependent) name of a sales organization (API_SALESORGANIZATION_SRV).

SAPSalesOrganizationResponseModel

A sales organization as returned by SAP (API_SALESORGANIZATION_SRV, OData V2).

SAPSalesOrganizationQueryModel

Search criteria for SAP sales organizations (API_SALESORGANIZATION_SRV).

SAPPurchasingOrganizationResponseModel

A purchasing organization as returned by SAP (API_PURCHASINGORGANIZATION, OData V4).

SAPPurchasingOrganizationQueryModel

Search criteria for SAP purchasing organizations (API_PURCHASINGORGANIZATION, OData V4).

SAPCostCenterTextResponseModel

The (language dependent) name of a cost center (API_COSTCENTER_SRV).

SAPCostCenterResponseModel

A cost center as returned by SAP (API_COSTCENTER_SRV, OData V2).

SAPCostCenterQueryModel

Search criteria for SAP cost centers (API_COSTCENTER_SRV). Cost centers have validity periods - use valid_on for the current ones.

SAPProfitCenterTextResponseModel

The (language dependent) name of a profit center (API_PROFITCENTER_SRV).

SAPProfitCenterResponseModel

A profit center as returned by SAP (API_PROFITCENTER_SRV, OData V2).

SAPProfitCenterQueryModel

Search criteria for SAP profit centers (API_PROFITCENTER_SRV). Profit centers have validity periods - use valid_on for the current ones.

SAPGLAccountTextResponseModel

The (language dependent) name of a G/L account (API_GLACCOUNTINCHARTOFACCOUNTS_SRV).

SAPGLAccountResponseModel

A G/L account of a chart of accounts as returned by SAP (API_GLACCOUNTINCHARTOFACCOUNTS_SRV, OData V2).

SAPGLAccountQueryModel

Search criteria for SAP G/L accounts of a chart of accounts (API_GLACCOUNTINCHARTOFACCOUNTS_SRV).

Functions:

Name Description
parse_odata_datetime

Convert an OData V2 JSON date ("/Date([+|-])/") into a timezone-aware datetime.

serialize_odata_datetime

Serialize a datetime in the OData V2 JSON format for Edm.DateTimeOffset ("/Date(+0000)/").

parse_odata_date

Convert an OData V2 JSON date ("/Date()/") into a date.

serialize_odata_date

Serialize a date in the OData V2 JSON format for Edm.DateTime ("/Date()/").

parse_odata_time

Convert an OData V2 JSON time (Edm.Time, e.g. "PT08H30M00S") into a time.

serialize_odata_time

Serialize a time in the OData V2 JSON format for Edm.Time (ISO 8601 duration, e.g. "PT08H30M00S").

parse_sap_flag

Convert an SAP flag ("X" = true, "" = false) into a boolean.

serialize_sap_flag

Serialize a boolean as SAP flag ("X" = true, "" = false).

unwrap_odata_navigation

Unwrap the OData V2 representation of a to-many navigation property.

unwrap_odata_single_navigation

Unwrap the OData V2 representation of a to-one navigation property.

pad_number

Normalize an SAP item / sequence number (NUMC) to its fixed length (e.g. 10 -> '00010').

is_empty

Return True if a list of child entities is empty (used with Field(exclude_if=...)).

unique_numbers

Return a validator that checks that the given (item) number is unique within a list of child entities.

unit_iso_code

Return the ISO code of an SAP unit code, e.g. 'PC' -> 'PCE' (see SAP_UNIT_ISO_CODES).

send_purchase_requisition_units_as_iso

Remove BaseUnit from the payload of a purchase requisition item and its account assignments.

odata_literal

Format a value as OData URI literal (for $filter conditions and function import parameters).

text_search_variants

Get the spellings of a search term for a case-insensitive text search.

SAPBusinessObjectType dataclass

SAPBusinessObjectType(
    label: str,
    key_lengths: tuple[int, ...] = (),
    bo_type: str = "",
)

An SAP business object type (BOR object type, transaction SWO1) with the structure of its key.

Use SAPBusinessObjectType.get() to look up a type by its code (see SAP_BUSINESS_OBJECT_TYPES).

Attributes:

Name Type Description
label str

Name of the business object, e.g. "maintenance order".

key_lengths tuple[int, ...]

Lengths of the key fields in SAP's internal format, e.g. (10, 4) for a material document (document number and year). Empty if the key structure is unknown.

bo_type str

The code of the type, e.g. "BUS2017" - set by get().

Methods:

Name Description
get

Get an SAP business object type by its code.

get_key_fields

Convert the business object ID of a reference (e.g. a business workspace) into the key fields of the SAP object.

get_business_object_id

Convert the key fields of an SAP object into the business object ID of a reference (e.g. a business workspace).

get classmethod

get(bo_type: str) -> SAPBusinessObjectType

Get an SAP business object type by its code.

Parameters:

Name Type Description Default
bo_type str

The SAP business object type, e.g. "BUS2017" (see SAP_BUSINESS_OBJECT_TYPES).

required

Returns:

Name Type Description
SAPBusinessObjectType SAPBusinessObjectType

The type or - for types that are not in SAP_BUSINESS_OBJECT_TYPES - a generic "object" type with unknown key structure.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@classmethod
def get(cls, bo_type: str) -> "SAPBusinessObjectType":
    """Get an SAP business object type by its code.

    Args:
        bo_type (str):
            The SAP business object type, e.g. "BUS2017" (see SAP_BUSINESS_OBJECT_TYPES).

    Returns:
        SAPBusinessObjectType:
            The type or - for types that are not in SAP_BUSINESS_OBJECT_TYPES - a generic
            "object" type with unknown key structure.

    """

    return replace(SAP_BUSINESS_OBJECT_TYPES.get(bo_type) or cls(label="object"), bo_type=bo_type)

get_key_fields

get_key_fields(bo_id: str) -> tuple[str, ...]

Convert the business object ID of a reference (e.g. a business workspace) into the key fields of the SAP object.

Business object references store the key in SAP's internal format: key fields with leading zeros, concatenated for composite keys (e.g. "49000001232026" for material document 4900000123 of 2026). The OData APIs expect the key fields in the external format.

Parameters:

Name Type Description Default
bo_id str

The business object ID, e.g. "49000001232026".

required

Returns:

Type Description
tuple[str, ...]

tuple[str, ...]: The key fields in SAP's external format (ALPHA conversion: numeric keys without leading zeros), e.g. ("4000340",) or ("4900000123", "2026"). IDs of types with unknown key structure are not split.

Raises:

Type Description
ValueError

If the ID does not have the length of the composite key of the type.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def get_key_fields(self, bo_id: str) -> tuple[str, ...]:
    """Convert the business object ID of a reference (e.g. a business workspace) into the key fields of the SAP object.

    Business object references store the key in SAP's internal format: key fields with leading
    zeros, concatenated for composite keys (e.g. "49000001232026" for material document 4900000123
    of 2026). The OData APIs expect the key fields in the external format.

    Args:
        bo_id (str):
            The business object ID, e.g. "49000001232026".

    Returns:
        tuple[str, ...]:
            The key fields in SAP's external format (ALPHA conversion: numeric keys without leading
            zeros), e.g. ("4000340",) or ("4900000123", "2026"). IDs of types with unknown key
            structure are not split.

    Raises:
        ValueError:
            If the ID does not have the length of the composite key of the type.

    """

    bo_id = bo_id.strip()
    lengths = self.key_lengths or (len(bo_id),)
    if len(lengths) == 1:
        parts = [bo_id]
    elif len(bo_id) == sum(lengths):
        offsets = [sum(lengths[:index]) for index in range(len(lengths))]
        parts = [bo_id[offset : offset + length].strip() for offset, length in zip(offsets, lengths, strict=True)]
    else:
        message = "Unexpected ID -> '{}' of SAP business object type -> '{}'.".format(bo_id, self.bo_type)
        raise ValueError(message)

    return tuple((part.lstrip("0") or "0") if part.isdigit() else part for part in parts)

get_business_object_id

get_business_object_id(key_fields: tuple[str, ...]) -> str

Convert the key fields of an SAP object into the business object ID of a reference (e.g. a business workspace).

The reverse of get_key_fields(): numeric key fields get their leading zeros, composite keys are concatenated, e.g. ("4900000123", "2026") -> "49000001232026" for a material document.

Parameters:

Name Type Description Default
key_fields tuple[str, ...]

The key fields in SAP's external format, e.g. ("413",).

required

Returns:

Name Type Description
str str

The business object ID in SAP's internal format, e.g. "0000000413".

Raises:

Type Description
ValueError

If the key structure of the type is unknown or the key fields don't match it.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def get_business_object_id(self, key_fields: tuple[str, ...]) -> str:
    """Convert the key fields of an SAP object into the business object ID of a reference (e.g. a business workspace).

    The reverse of get_key_fields(): numeric key fields get their leading zeros, composite
    keys are concatenated, e.g. ("4900000123", "2026") -> "49000001232026" for a material document.

    Args:
        key_fields (tuple[str, ...]):
            The key fields in SAP's external format, e.g. ("413",).

    Returns:
        str:
            The business object ID in SAP's internal format, e.g. "0000000413".

    Raises:
        ValueError:
            If the key structure of the type is unknown or the key fields don't match it.

    """

    if len(key_fields) != len(self.key_lengths):
        message = "Key fields -> {} don't match SAP business object type -> '{}'.".format(key_fields, self.bo_type)
        raise ValueError(message)

    parts = []
    for field, length in zip(key_fields, self.key_lengths, strict=True):
        field = str(field).strip()
        if len(field) > length:
            message = "Key field -> '{}' is longer than {} characters.".format(field, length)
            raise ValueError(message)
        # Numeric fields with leading zeros (ALPHA conversion), others filled up with blanks:
        parts.append(field.zfill(length) if field.isdigit() else field.ljust(length))

    # References store the ID without trailing blanks (e.g. equipment 'P-3000-N001'):
    return "".join(parts).rstrip()

SAPODataModel

Bases: BaseModel

Base class of all models for SAP OData entities.

The Python attribute names are snake case. The aliases are the OData property names of the SAP API. Both can be used to initialize the models. Default values are validated as well (e.g. item numbers are padded to their SAP length).

OData properties that are not modelled are ignored in the response models: SAP returns many technical properties (often in raw OData formats like "/Date(...)/") that would only be noise for users or LLMs. Model a property to return it. The create models reject them instead (see SAPODataCreateModel).

Direct subclasses are the response models (*ResponseModel) that the SAP read methods validate the OData results with (model_validate()), e.g. SAP.get_sales_order().

Methods:

Name Description
drop_odata_annotations

Drop OData protocol annotations that carry no business data.

drop_empty_text_lists

Treat an empty text sent for a list field as omitted.

drop_odata_annotations classmethod

drop_odata_annotations(data: object) -> object

Drop OData protocol annotations that carry no business data.

These are "__metadata" (OData V2), "@odata.context" / "@odata.etag" (OData V4) and navigation properties that have not been expanded ({"__deferred": ...}). Otherwise the create models would reject them as unknown fields - e.g. in an entity read from SAP and passed to a create or update.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="before")
@classmethod
def drop_odata_annotations(cls, data: object) -> object:
    """Drop OData protocol annotations that carry no business data.

    These are "__metadata" (OData V2), "@odata.context" / "@odata.etag" (OData V4)
    and navigation properties that have not been expanded ({"__deferred": ...}).
    Otherwise the create models would reject them as unknown fields - e.g. in an
    entity read from SAP and passed to a create or update.

    """

    if not isinstance(data, dict):
        return data

    return {
        key: value
        for key, value in data.items()
        if not key.startswith(("__", "@")) and not (isinstance(value, dict) and "__deferred" in value)
    }

drop_empty_text_lists classmethod

drop_empty_text_lists(data: object) -> object

Treat an empty text sent for a list field as omitted.

LLMs sometimes send "" instead of [] for lists they don't need - e.g. "to_SuplrInvcItemMaterial": "" for a supplier invoice with purchase order items only. The validation would fail and the tool call would have to be repeated.

Parameters:

Name Type Description Default
data object

The input data of the model (a dict with OData or field names).

required

Returns:

Name Type Description
object object

The data without the list fields that are "" - other values are unchanged.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="before")
@classmethod
def drop_empty_text_lists(cls, data: object) -> object:
    """Treat an empty text sent for a list field as omitted.

    LLMs sometimes send "" instead of [] for lists they don't need - e.g.
    "to_SuplrInvcItemMaterial": "" for a supplier invoice with purchase order items
    only. The validation would fail and the tool call would have to be repeated.

    Args:
        data (object):
            The input data of the model (a dict with OData or field names).

    Returns:
        object:
            The data without the list fields that are "" - other values are unchanged.

    """

    if not isinstance(data, dict):
        return data

    list_keys = {
        key
        for name, field in cls.model_fields.items()
        if get_origin(field.annotation) is list
        or any(get_origin(arg) is list for arg in get_args(field.annotation))
        for key in (name, field.alias)
        if key
    }

    return {key: value for key, value in data.items() if not (value == "" and key in list_keys)}

SAPODataCreateModel

Bases: SAPODataModel

Base class of the models used to create SAP documents (deep insert / deep create).

Serialization uses the OData property names (aliases), so to_odata() returns the payload as expected by the SAP API. Only the modelled fields can be set - unknown fields are rejected, so an LLM can't invent OData properties that SAP rejects only after the user has confirmed the create or update. Model a property to make it settable.

The subclasses (e.g. SAPSalesOrderModel and its SAPSalesOrderItemModel) only declare the fields with their validations and inherit: * to_odata(): the payload of the SAP create methods, e.g. SAP.create_sales_order(). * to_odata_update(): validates the changes of the SAP update methods, e.g. SAP.update_sales_order(), with the same field definitions as a create. * check_unknown_fields(): rejects unknown field names (e.g. invented by an LLM).

Methods:

Name Description
check_unknown_fields

Reject all fields that are not modelled - with their attribute or OData name.

to_odata

Return the OData payload (deep insert / deep create) of the document.

to_odata_update

Return the OData payload to update (PATCH) individual fields of an existing document.

check_unknown_fields classmethod

check_unknown_fields(data: object) -> object

Reject all fields that are not modelled - with their attribute or OData name.

Unknown fields are misspelled or invented names (e.g. "WrntyRepairDate" instead of "WrntyClaimRepairDate") or navigation properties ("_...") copied from a read. SAP would reject them - only after the user confirmed the create.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="before")
@classmethod
def check_unknown_fields(cls, data: object) -> object:
    """Reject all fields that are not modelled - with their attribute or OData name.

    Unknown fields are misspelled or invented names (e.g. "WrntyRepairDate" instead of
    "WrntyClaimRepairDate") or navigation properties ("_...") copied from a read. SAP would
    reject them - only after the user confirmed the create.

    """

    if not isinstance(data, dict):
        return data

    known = set(cls.model_fields) | {field.alias for field in cls.model_fields.values() if field.alias}
    unknown = sorted(key for key in data if key not in known)
    if unknown:
        message = "Unknown field(s) -> {} for {} - only its modelled fields can be set".format(
            unknown, cls.__name__
        )
        raise ValueError(message)

    return data

to_odata

to_odata() -> dict

Return the OData payload (deep insert / deep create) of the document.

Returns:

Name Type Description
dict dict

The payload with OData property names. Unset (None) values and empty child lists are omitted so SAP can apply its defaults. Decimals are serialized as strings (OData V4 APIs require the IEEE754Compatible=true content type for this).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self) -> dict:
    """Return the OData payload (deep insert / deep create) of the document.

    Returns:
        dict:
            The payload with OData property names. Unset (None) values and empty
            child lists are omitted so SAP can apply its defaults. Decimals are
            serialized as strings (OData V4 APIs require the IEEE754Compatible=true
            content type for this).

    """

    return self.model_dump(exclude_none=True, mode="json")

to_odata_update classmethod

to_odata_update(changes: dict) -> dict

Return the OData payload to update (PATCH) individual fields of an existing document.

Each changed value is validated and serialized with the definition of the corresponding field of this model (type, length, upper case, SAP / OData formats) - so updates get the same treatment as creates. Validations that span several fields (e.g. "end date after start date") are not applied, as the other fields of the document are not known.

Parameters:

Name Type Description Default
changes dict

The fields to change - with snake case attribute names or OData property names, e.g. {"description": "New text"} or {"MaintenanceOrderDesc": "New text"}. Fields that are not modelled are rejected.

required

Returns:

Name Type Description
dict dict

The payload with OData property names.

Raises:

Type Description
ValueError

If a field is unknown, cannot be changed (READ_ONLY_PROPERTIES), refers to child entities (e.g. items) or has an invalid value (pydantic.ValidationError is a ValueError).

Example

SAPSalesOrderModel.to_odata_update({"requested_delivery_date": "2026-12-01"}) {'RequestedDeliveryDate': '/Date(1796083200000)/'}

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@classmethod
def to_odata_update(cls, changes: dict) -> dict:
    """Return the OData payload to update (PATCH) individual fields of an existing document.

    Each changed value is validated and serialized with the definition of the
    corresponding field of this model (type, length, upper case, SAP / OData
    formats) - so updates get the same treatment as creates. Validations that
    span several fields (e.g. "end date after start date") are not applied, as
    the other fields of the document are not known.

    Args:
        changes (dict):
            The fields to change - with snake case attribute names or OData
            property names, e.g. {"description": "New text"} or
            {"MaintenanceOrderDesc": "New text"}. Fields that are not modelled
            are rejected.

    Returns:
        dict:
            The payload with OData property names.

    Raises:
        ValueError:
            If a field is unknown, cannot be changed (READ_ONLY_PROPERTIES), refers to
            child entities (e.g. items) or has an invalid value (pydantic.ValidationError
            is a ValueError).

    Example:
        >>> SAPSalesOrderModel.to_odata_update({"requested_delivery_date": "2026-12-01"})
        {'RequestedDeliveryDate': '/Date(1796083200000)/'}

    """

    fields = {}
    for name, field in cls.model_fields.items():
        fields[name] = field
        if field.alias:
            fields[field.alias] = field

    payload = {}
    for key, value in changes.items():
        field = fields.get(key)
        odata_name = field.alias or key if field else key
        if odata_name in cls.READ_ONLY_PROPERTIES:
            message = "Field -> '{}' cannot be changed - {}".format(key, cls.READ_ONLY_PROPERTIES[odata_name])
            raise ValueError(message)
        if field is None:
            message = "Unknown field -> '{}' for {} - only its modelled fields can be changed".format(
                key, cls.__name__
            )
            raise ValueError(message)
        if get_origin(field.annotation) is list or any(
            get_origin(argument) is list for argument in get_args(field.annotation)
        ):
            message = "Field -> '{}' refers to child entities which cannot be changed with an update".format(key)
            raise ValueError(message)
        adapter = TypeAdapter(field.rebuild_annotation())
        try:
            validated = adapter.validate_python(value)
        except ValidationError:
            # Agents often send numbers for texts (e.g. a year or a code) - accept them as text:
            if not isinstance(value, int | float | Decimal) or isinstance(value, bool):
                raise
            validated = adapter.validate_python(format(value, "f") if isinstance(value, Decimal) else str(value))
        payload[field.alias or key] = adapter.dump_python(validated, mode="json")

    return payload

SAPPurchasingItemModel

Bases: SAPODataCreateModel

Base class of the items of purchasing documents (purchase order, contract and requisition).

Provides the fields and validations common to all purchasing document items. The subclasses (SAPPurchaseOrderItemModel, SAPPurchaseContractItemModel and SAPPurchaseRequisitionItemModel) add the item specific fields (e.g. the short text, whose OData name differs per document type).

Contract with the subclasses (the validations access these fields by name): * item (required): the item number - used in error messages. * text (required): the short text - without it, a material is always required. * account_assignments (optional): the account assignments - items without this field (e.g. purchase contract items) skip the account assignment check. * purchase_contract / purchase_contract_item and purchase_requisition / purchase_requisition_item (optional): the item of another document the item refers to - SAP copies material, text, material group and plant from it, so such an item needs neither a material nor a text.

Methods:

Name Description
check_material_or_text

Validate that the item has a material, a short text plus a material group or a reference item.

check_account_assignments

Validate that items with account assignments have an account assignment category.

check_material_or_text

check_material_or_text() -> Self

Validate that the item has a material, a short text plus a material group or a reference item.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_material_or_text(self) -> Self:
    """Validate that the item has a material, a short text plus a material group or a reference item."""

    # SAP copies material, text and material group from the contract or requisition item the item refers to
    # (verified in S/4HANA 2023 for purchase orders):
    refers_to_item = (
        getattr(self, "purchase_contract", None) and getattr(self, "purchase_contract_item", None)
    ) or (getattr(self, "purchase_requisition", None) and getattr(self, "purchase_requisition_item", None))
    if not self.material and not (getattr(self, "text", None) and self.material_group) and not refers_to_item:
        message = (
            "Item -> {} needs a material, a text plus a material group, or the purchase contract or requisition "
            "item it refers to".format(getattr(self, "item", "?"))
        )
        raise ValueError(message)

    return self

check_account_assignments

check_account_assignments() -> Self

Validate that items with account assignments have an account assignment category.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_account_assignments(self) -> Self:
    """Validate that items with account assignments have an account assignment category."""

    if getattr(self, "account_assignments", None) and not self.account_assignment_category:
        message = "Item -> {} has account assignments but no account assignment category".format(
            getattr(self, "item", "?"),
        )
        raise ValueError(message)

    return self

ODataCondition dataclass

ODataCondition(
    property: str | tuple[str, str],
    operator: Literal[
        "eq", "ge", "le", "contains", "valid_on"
    ] = "eq",
    kind: Literal["timestamp", "flag"] | None = None,
    path: str | None = None,
    values: dict | None = None,
)

Describes how a field of a query model becomes a condition of the OData $filter.

Used as metadata of the query model fields, e.g. Annotated[SAPCode | None, ODataCondition("MaintenancePlanningPlant")]. Fields that are None (or empty lists) are not part of the filter.

Attributes:

Name Type Description
property str | tuple[str, str]

The OData property, e.g. "MaintenancePlanningPlant". For the operator "valid_on" the properties of the start and the end of the validity period.

operator Literal['eq', 'ge', 'le', 'contains', 'valid_on']

"eq" (default - a list of values matches any of them), "ge" / "le" (ranges, a date as upper limit of a timestamp property includes the whole day), "contains" (text search, case-sensitive in most SAP services) or "valid_on" (start <= date <= end).

kind Literal['timestamp', 'flag'] | None

"timestamp" for Edm.DateTimeOffset properties, "flag" for SAP flags ("X" / "").

path str | None

Navigation property of a to-many relationship (e.g. "_PurchaseRequisitionItem") for conditions on child entities: matches if any child matches. OData V4 only.

values dict | None

Maps the field values to the OData values, e.g. {"person": "1", "organization": "2"}.

Methods:

Name Description
to_filter

Return the $filter condition for a field value.

to_filter

to_filter(value: object, odata_version: int) -> str

Return the $filter condition for a field value.

Parameters:

Name Type Description Default
value object

The (not empty) value of the query model field.

required
odata_version int

The OData version of the service (2 or 4).

required

Returns:

Name Type Description
str str

The condition, e.g. "(MaintenanceOrderType eq 'YA01' or MaintenanceOrderType eq 'YA02')".

Raises:

Type Description
ValueError

If a condition on child entities is used with an OData V2 service.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_filter(self, value: object, odata_version: int) -> str:
    """Return the $filter condition for a field value.

    Args:
        value (object):
            The (not empty) value of the query model field.
        odata_version (int):
            The OData version of the service (2 or 4).

    Returns:
        str:
            The condition, e.g. "(MaintenanceOrderType eq 'YA01' or MaintenanceOrderType eq 'YA02')".

    Raises:
        ValueError:
            If a condition on child entities is used with an OData V2 service.

    """

    prefix = "i/" if self.path else ""

    def literal(single_value: object) -> str:
        return odata_literal(
            self.values.get(single_value, single_value) if self.values else single_value,
            odata_version=odata_version,
            kind=self.kind,
        )

    def condition(single_value: object) -> str:
        name = prefix + self.property if isinstance(self.property, str) else ""
        match self.operator:
            case "contains":
                if odata_version == 2:
                    return "substringof({}, {})".format(literal(single_value), name)
                return "contains({}, {})".format(name, literal(single_value))
            case "valid_on":
                start, end = (prefix + name for name in self.property)
                return "{} le {} and {} ge {}".format(start, literal(single_value), end, literal(single_value))
            case "le" if self.kind == "timestamp" and not isinstance(single_value, datetime):
                # A date as upper limit of a timestamp includes the whole day:
                return "{} lt {}".format(name, literal(single_value + timedelta(days=1)))
            case _:
                return "{} {} {}".format(name, self.operator, literal(single_value))

    values = value if isinstance(value, list) else [value]
    result = " or ".join(condition(single_value) for single_value in values)
    if len(values) > 1:
        result = "({})".format(result)

    if self.path:
        if odata_version != 4:
            message = "Conditions on child entities ('{}') are only supported by OData V4 services".format(
                self.path
            )
            raise ValueError(message)
        result = "{}/any(i:{})".format(self.path, result)

    return result

ODataDeletionCondition dataclass

ODataDeletionCondition(
    property: str | tuple[str, str],
    operator: Literal[
        "eq", "ge", "le", "contains", "valid_on"
    ] = "eq",
    kind: Literal["timestamp", "flag"] | None = None,
    path: str | None = None,
    values: dict | None = None,
    deleted_value: str | bool = True,
)

Bases: ODataCondition

Describes the condition of a deletion filter (is_marked_for_deletion of the query models).

The field value True selects the deleted objects (property eq deleted_value), False the objects that are not deleted (property ne deleted_value). With a path, the deletion indicator is on the items: a document is deleted if all its items are deleted (e.g. purchase orders - SAP doesn't set the header indicator when all items are deleted).

Attributes:

Name Type Description
deleted_value str | bool

The value of the property for deleted objects, e.g. True, "X", "L" (purchasing documents) or "5" (processing phase of maintenance notifications).

Methods:

Name Description
to_filter

Return the $filter condition for the value of the deletion filter.

to_filter

to_filter(value: object, odata_version: int) -> str

Return the $filter condition for the value of the deletion filter.

Parameters:

Name Type Description Default
value object

True for the deleted objects, False for the objects that are not deleted.

required
odata_version int

The OData version of the service (2 or 4).

required

Returns:

Name Type Description
str str

The condition, e.g. "EquipmentIsMarkedForDeletion ne true" or "_PurchaseOrderItem/any(i:i/PurchasingDocumentDeletionCode ne 'L')".

Raises:

Type Description
ValueError

If a condition on child entities is used with an OData V2 service.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_filter(self, value: object, odata_version: int) -> str:
    """Return the $filter condition for the value of the deletion filter.

    Args:
        value (object):
            True for the deleted objects, False for the objects that are not deleted.
        odata_version (int):
            The OData version of the service (2 or 4).

    Returns:
        str:
            The condition, e.g. "EquipmentIsMarkedForDeletion ne true" or
            "_PurchaseOrderItem/any(i:i/PurchasingDocumentDeletionCode ne 'L')".

    Raises:
        ValueError:
            If a condition on child entities is used with an OData V2 service.

    """

    literal = odata_literal(self.deleted_value, odata_version=odata_version, kind=self.kind)
    if not self.path:
        return "{} {} {}".format(self.property, "eq" if value else "ne", literal)

    if odata_version != 4:
        message = "Conditions on child entities ('{}') are only supported by OData V4 services".format(self.path)
        raise ValueError(message)
    if value:
        return "{}/all(i:i/{} eq {})".format(self.path, self.property, literal)
    return "{}/any(i:i/{} ne {})".format(self.path, self.property, literal)

ODataTextSearch dataclass

ODataTextSearch(
    field: str,
    entity_set: str,
    properties: tuple[str, ...],
    key: str,
    ids_field: str,
    scope: tuple[tuple[str, str], ...] = (),
    navigation: str = "",
)

Describes how the name / description criterion of a query model is resolved via a text entity set.

Many SAP APIs keep names and descriptions in separate text entities (e.g. A_ProductDescription) that the main entity set cannot be filtered by (OData V2 has no any()). The texts are searched first and the main query is restricted to the IDs found (see SAP._resolve_text_search()).

Attributes:

Name Type Description
field str

The field of the query model with the search term, e.g. "description_contains".

entity_set str

The text entity set, e.g. "A_ProductDescription".

properties tuple[str, ...]

The text properties to search, e.g. ("ProductDescription",).

key str

The key property of the object in the text entity set, e.g. "Product".

ids_field str

The field of the query model that takes the IDs found, e.g. "product_ids".

scope tuple[tuple[str, str], ...]

Fields of the query model that also restrict the texts, as (field, text property), e.g. (("controlling_area", "ControllingArea"),).

navigation str

The to-one navigation property from the texts to their object, e.g. "to_CostCenter" - all criteria of the query then also restrict the texts, so that only the objects that match the whole query are found. Empty if the text entity set has none (e.g. A_ProductDescription).

SAPODataQueryModel

Bases: BaseModel

Base class of the search criteria for SAP OData collections (list and iterator methods).

The fields of the subclasses are the search criteria. Fields with an ODataCondition in their metadata become conditions of the OData $filter (all conditions must match); fields that are None (or empty lists) are ignored. The subclasses define: * sort_by: the sort criteria, mapped to the $orderby expression with SORT_PROPERTIES. * expand_items (optional): whether to read the child entities (with EXPAND). * BASE_CONDITIONS (optional): conditions that are always part of the filter.

The subclasses (*QueryModel) inherit limit, sort_direction, page_size and to_odata(). They are the query parameter of the SAP list methods, e.g. SAP.get_sales_orders(), which pass to_odata() to SAP._iter_odata_collection(). Their JSON schema serves as the parameters of LLM tools as well - so callers give readable criteria, not OData expressions.

Methods:

Name Description
to_odata

Return the OData query options ($filter, $orderby, $expand) of the search criteria.

to_odata_conditions

Return the $filter conditions of the fields with an ODataCondition (without BASE_CONDITIONS).

accepts

Check the criteria SAP can't filter by - applied to each entity read (client-side filter).

to_odata

to_odata(odata_version: int) -> dict

Return the OData query options ($filter, $orderby, $expand) of the search criteria.

The limit and the page size are not included - they control the paging (see SAP._iter_odata_collection()).

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (2 or 4).

required

Returns:

Name Type Description
dict dict

The query options, e.g. {"$filter": "MaintenancePlanningPlant eq '1010'", "$orderby": "MaintenanceOrder desc"}.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self, odata_version: int) -> dict:
    """Return the OData query options ($filter, $orderby, $expand) of the search criteria.

    The limit and the page size are not included - they control the paging (see
    SAP._iter_odata_collection()).

    Args:
        odata_version (int):
            The OData version of the service (2 or 4).

    Returns:
        dict:
            The query options, e.g. {"$filter": "MaintenancePlanningPlant eq '1010'",
            "$orderby": "MaintenanceOrder desc"}.

    """

    conditions = list(self.BASE_CONDITIONS) + self.to_odata_conditions(odata_version=odata_version)

    sort_by = getattr(self, "sort_by", None)
    params = {"$orderby": self.SORT_PROPERTIES[sort_by].format(direction=self.sort_direction)} if sort_by else {}
    if conditions:
        params["$filter"] = " and ".join(
            "({})".format(condition) if " or " in condition and not condition.startswith("(") else condition
            for condition in conditions
        )
    if self.EXPAND and getattr(self, "expand_items", False):
        params["$expand"] = self.EXPAND

    return params

to_odata_conditions

to_odata_conditions(
    odata_version: int,
    navigation: str = "",
    exclude: tuple[str, ...] = (),
) -> list[str]

Return the $filter conditions of the fields with an ODataCondition (without BASE_CONDITIONS).

With a navigation property, the conditions refer to the entity it leads to - so another entity set can be filtered by the criteria of this query, e.g. material document items by the posting date of their header ("to_MaterialDocumentHeader/PostingDate ge ..."). OData V2 supports this for to-one navigation properties only. Conditions on child entities (ODataCondition.path) are left out then.

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (2 or 4).

required
navigation str

The to-one navigation property to the entity of this query, e.g. "to_MaterialDocumentHeader". Defaults to "" (conditions on the entity itself).

''
exclude tuple[str, ...]

Fields to leave out, e.g. criteria that the other query already has. Defaults to ().

()

Returns:

Type Description
list[str]

list[str]: The conditions, e.g. ["MaterialDocumentYear eq '2026'", "PostingDate ge datetime'...'"].

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata_conditions(self, odata_version: int, navigation: str = "", exclude: tuple[str, ...] = ()) -> list[str]:
    """Return the $filter conditions of the fields with an ODataCondition (without BASE_CONDITIONS).

    With a navigation property, the conditions refer to the entity it leads to - so another entity set
    can be filtered by the criteria of this query, e.g. material document items by the posting date of
    their header ("to_MaterialDocumentHeader/PostingDate ge ..."). OData V2 supports this for to-one
    navigation properties only. Conditions on child entities (ODataCondition.path) are left out then.

    Args:
        odata_version (int):
            The OData version of the service (2 or 4).
        navigation (str, optional):
            The to-one navigation property to the entity of this query, e.g. "to_MaterialDocumentHeader".
            Defaults to "" (conditions on the entity itself).
        exclude (tuple[str, ...], optional):
            Fields to leave out, e.g. criteria that the other query already has. Defaults to ().

    Returns:
        list[str]:
            The conditions, e.g. ["MaterialDocumentYear eq '2026'", "PostingDate ge datetime'...'"].

    """

    conditions = []
    for name, field in type(self).model_fields.items():
        marker = next((item for item in field.metadata if isinstance(item, ODataCondition)), None)
        value = getattr(self, name)
        if marker is None or value is None or value == [] or name in exclude:
            continue
        if navigation:
            if marker.path:
                continue
            prefixed = (
                "{}/{}".format(navigation, marker.property)
                if isinstance(marker.property, str)
                else tuple("{}/{}".format(navigation, part) for part in marker.property)
            )
            marker = replace(marker, property=prefixed)
        conditions.append(marker.to_filter(value=value, odata_version=odata_version))

    return conditions

accepts

accepts(entity: BaseModel) -> bool

Check the criteria SAP can't filter by - applied to each entity read (client-side filter).

SAP._iter_odata_collection() skips the entities that are not accepted; they don't count towards the limit. Overridden by the query models with such criteria, e.g. the deletion flag of maintenance orders (only part of the status text, which SAP can't filter by).

Parameters:

Name Type Description Default
entity BaseModel

The entity read, validated into the response model.

required

Returns:

Name Type Description
bool bool

True if the entity matches. Always True here.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def accepts(self, entity: BaseModel) -> bool:  # noqa: ARG002
    """Check the criteria SAP can't filter by - applied to each entity read (client-side filter).

    SAP._iter_odata_collection() skips the entities that are not accepted; they don't count
    towards the limit. Overridden by the query models with such criteria, e.g. the deletion
    flag of maintenance orders (only part of the status text, which SAP can't filter by).

    Args:
        entity (BaseModel):
            The entity read, validated into the response model.

    Returns:
        bool:
            True if the entity matches. Always True here.

    """

    return True

SAPODataTextResponseModel

Bases: SAPODataModel

An entity of a text entity set as returned by SAP - all properties are kept (see ODataTextSearch).

SAPODataTextQueryModel

Bases: SAPODataQueryModel

Query of the keys of a text or item entity set (see SAP._resolve_text_search() and SAP._find_keys_via_items()).

The conditions are given as OData filter expressions - this model is only built internally.

Methods:

Name Description
to_odata

Return the OData query options of the text query.

to_odata

to_odata(odata_version: int) -> dict

Return the OData query options of the text query.

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (not needed - the conditions are given as expressions).

required

Returns:

Name Type Description
dict dict

The query options ($filter, $orderby, $select).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self, odata_version: int) -> dict:  # noqa: ARG002
    """Return the OData query options of the text query.

    Args:
        odata_version (int):
            The OData version of the service (not needed - the conditions are given as expressions).

    Returns:
        dict:
            The query options ($filter, $orderby, $select).

    """

    params = {}
    # Joined conditions are parenthesized - each one can have a top-level 'or' (e.g. one per text property):
    if len(self.conditions) == 1:
        params["$filter"] = self.conditions[0]
    elif self.conditions:
        params["$filter"] = " and ".join("({})".format(condition) for condition in self.conditions)
    if self.order_by:
        params["$orderby"] = self.order_by
    if self.select:
        params["$select"] = self.select

    return params

SAPODataServiceModel

Bases: BaseModel

Definition of an SAP OData service (API) used by this module.

Attributes:

Name Type Description
name str

Technical name of the service, e.g. "API_MAINTENANCEORDER".

path str

Service root path relative to the SAP base URL, e.g. "/sap/opu/odata/sap/API_MAINTENANCEORDER".

odata_version int

OData protocol version of the service (2 or 4).

oauth_scope str

OAuth 2.0 scope ID of the service, e.g. "ZAPI_MAINTENANCEORDER_0002". SAP generates it when OAuth is enabled for the service - it can differ between SAP systems. Empty if the service has no scope.

entity_sets list[str]

Entity sets that must be exposed by the service. Used by check_odata_apis() to detect services that are active but do not expose what we need (e.g. because of an older S/4HANA release).

description str

Human readable description of the service.

SAPODataServiceState

Bases: StrEnum

Possible results of an OData service availability check.

SAPODataServiceStatusModel

Bases: BaseModel

Result of the availability check for one SAP OData service.

Attributes:

Name Type Description
service SAPODataServiceModel

The service that has been checked.

url str

The URL that has been called for the check.

state SAPODataServiceState

The result of the check.

http_status int | None

The HTTP status code. None if the SAP system could not be reached.

message str

The (error) message returned by SAP or the request library.

available_entity_sets list[str]

Entity sets exposed by the service (only filled if the service is active).

missing_entity_sets list[str]

Expected entity sets that are not exposed by the service.

hint str

A hint how to fix the problem (empty if the service is active).

active bool

True if the service is active and exposes all expected entity sets (computed - also included in model_dump() / model_dump_json()).

active property

active: bool

Return True if the service is active and exposes all expected entity sets.

SAPAuthCheckState

Bases: StrEnum

Possible results of an authentication / principal propagation health check.

SAPAuthCheckStatusModel

Bases: BaseModel

Result of a single step of an authentication / principal propagation health check.

Used by SAP.check_oauth_token_endpoint() and SAP.check_principal_propagation() - see there for the checks they perform.

Attributes:

Name Type Description
name str

Short name of the checked step, e.g. "OAuth 2.0 token endpoint".

state SAPAuthCheckState

The result of the check.

http_status int | None

The HTTP status code of the check request, if one was sent.

message str

The (error) message returned by SAP or the request library.

hint str

A hint how to fix the problem (empty if the check succeeded).

ok bool

True if the check succeeded (computed - also included in model_dump() / model_dump_json()).

ok property

ok: bool

Return True if the check succeeded.

SAPODataErrorDetailModel

Bases: BaseModel

A single detail message of an SAP OData error response.

SAPODataErrorModel

Bases: BaseModel

An error returned by an SAP OData service.

SAP returns errors in different formats depending on the OData version:

OData V2

{"error": {"code": "...", "message": {"lang": "en", "value": "..."}, "innererror": {"errordetails": [{"code": "...", "message": "...", "severity": "error"}]}}}

OData V4

{"error": {"code": "...", "message": "...", "details": [{"code": "...", "message": "...", "@Common.Severity": "error"}]}}

Non-OData errors (e.g. inactive ICF nodes, proxies) are often returned as HTML.

Methods:

Name Description
from_response

Build an SAPODataErrorModel from a (failed) HTTP response.

from_response classmethod

from_response(response: Response) -> Self

Build an SAPODataErrorModel from a (failed) HTTP response.

This method never raises an exception - if the response cannot be interpreted, the raw response text is preserved instead.

Parameters:

Name Type Description Default
response Response

The failed HTTP response.

required

Returns:

Name Type Description
SAPODataErrorModel Self

The parsed error.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@classmethod
def from_response(cls, response: requests.Response) -> Self:
    """Build an SAPODataErrorModel from a (failed) HTTP response.

    This method never raises an exception - if the response cannot be
    interpreted, the raw response text is preserved instead.

    Args:
        response (requests.Response):
            The failed HTTP response.

    Returns:
        SAPODataErrorModel:
            The parsed error.

    """

    error = cls(status_code=response.status_code, raw_text=response.text or "")

    try:
        error_body = response.json().get("error", {})
    except (ValueError, AttributeError):
        # Not JSON (e.g. HTML error page) - keep raw text only:
        content_type = (response.headers.get("content-type") or "").lower()
        error.message = "HTML error page returned" if "html" in content_type else (response.text or "")[:500]
        return error

    if not isinstance(error_body, dict):
        return error

    error.code = str(error_body.get("code", ""))
    message = error_body.get("message", "")
    # OData V2 wraps the message in a dict with language and value:
    error.message = message.get("value", "") if isinstance(message, dict) else str(message)

    # OData V2 provides details in "innererror.errordetails", OData V4 in "details":
    raw_details = error_body.get("details") or (error_body.get("innererror") or {}).get("errordetails") or []
    for raw_detail in raw_details:
        if not isinstance(raw_detail, dict):
            continue
        detail_message = raw_detail.get("message", "")
        error.details.append(
            SAPODataErrorDetailModel(
                code=str(raw_detail.get("code", "")),
                message=detail_message.get("value", "")
                if isinstance(detail_message, dict)
                else str(detail_message),
                severity=str(raw_detail.get("severity") or raw_detail.get("@Common.Severity") or ""),
                target=str(raw_detail.get("target") or raw_detail.get("propertyref") or ""),
            ),
        )

    return error

SAPMaintenanceOrderComponentModel

Bases: SAPODataCreateModel

A component (material, e.g. a spare part) of an operation of a maintenance order (API_MAINTENANCEORDER).

SAP reserves the material for the operation. Components cannot be part of the deep create of the order - SAP.create_maintenance_order() creates them after the order.

SAPTaskListReferenceModel

Bases: SAPODataCreateModel

A maintenance task list whose operations and materials are taken over into a new maintenance order.

The OData API cannot include a task list in an order (its task list fields are read only) - SAP.create_maintenance_order() reads the task list and creates its operations (and their materials as components) in the order.

SAPMaintenanceOrderOperationModel

Bases: SAPODataCreateModel

An operation of an SAP Plant Maintenance order (API_MAINTENANCEORDER).

The components (materials) of the operation are created after the order.

See: https://api.sap.com/api/API_MAINTENANCEORDER/overview

SAPMaintenanceOrderModel

Bases: SAPODataCreateModel

Data to create an SAP Plant Maintenance order (API_MAINTENANCEORDER).

Which fields are mandatory depends on the customizing of the order type in the S/4HANA system. Typically, at least an order type, a description, a planning plant, a main work center and a reference object (equipment or functional location) are required.

With a task list reference (task_list), the operations and materials of the task list become the first operations and components of the order - the API cannot include a task list. Components and the long text are created after the order (SAP rejects them in the deep insert), see SAP.create_maintenance_order().

See: https://api.sap.com/api/API_MAINTENANCEORDER/overview

Methods:

Name Description
check_dates

Default the basic start date and validate that the basic end date is not before it.

to_odata

Return the OData payload of the order (deep create of the order with its operations).

check_dates

check_dates() -> Self

Default the basic start date and validate that the basic end date is not before it.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Default the basic start date and validate that the basic end date is not before it."""

    # The API does not default the basic dates - without them SAP rejects the order with
    # IW/426 "Forward scheduling: Please enter start date". An end date alone is left
    # as is (backward scheduling):
    if self.basic_start_datetime is None and self.basic_end_datetime is None:
        self.basic_start_datetime = datetime.now(tz=UTC).replace(microsecond=0)

    # Compare as UTC timestamps (naive datetimes are treated as UTC, see serialize_odata_datetime()):
    start, end = (
        value.replace(tzinfo=value.tzinfo or UTC) if value else None
        for value in (self.basic_start_datetime, self.basic_end_datetime)
    )
    if start and end and end < start:
        message = "Basic end date -> {} is before basic start date -> {}".format(
            self.basic_end_datetime,
            self.basic_start_datetime,
        )
        raise ValueError(message)

    return self

to_odata

to_odata() -> dict

Return the OData payload of the order (deep create of the order with its operations).

The task list reference, the long text and the components of the operations are not part of it: SAP cannot include a task list with the API and rejects components in the deep create, nor is the long text - SAP.create_maintenance_order() handles them.

Returns:

Name Type Description
dict dict

The payload with OData property names.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self) -> dict:
    """Return the OData payload of the order (deep create of the order with its operations).

    The task list reference, the long text and the components of the operations are not part of it:
    SAP cannot include a task list with the API and rejects components in the deep
    create, nor is the long text - SAP.create_maintenance_order() handles them.

    Returns:
        dict:
            The payload with OData property names.

    """

    payload = super().to_odata()
    payload.pop("TaskListReference", None)
    payload.pop("MaintenanceOrderLongText", None)
    for operation in payload.get("to_MaintenanceOrderOperation", []):
        operation.pop("to_MaintOrderOpComponent_2", None)

    return payload

SAPMaintenanceOrderComponentResponseModel

Bases: SAPODataModel

A component (material) of a maintenance order operation as returned by SAP (API_MAINTENANCEORDER).

SAPMaintenanceOrderOperationResponseModel

Bases: SAPODataModel

An operation of an SAP Plant Maintenance order as returned by SAP (API_MAINTENANCEORDER).

In contrast to SAPMaintenanceOrderOperationModel (used to create operations) all fields except the keys are optional and dates are converted into timezone-aware datetime objects.

SAPMaintenanceOrderObjectListItemResponseModel

Bases: SAPODataModel

An entry of the object list of a maintenance order as returned by SAP (API_MAINTENANCEORDER).

The object list holds the further technical objects and maintenance notifications the order is performed for - SAP lists the notification of the order header as well (usually item 1). Notifications are added with SAP.assign_maintenance_notification_to_order().

SAPMaintenanceOrderResponseModel

Bases: SAPODataModel

An SAP Plant Maintenance order as returned by SAP (API_MAINTENANCEORDER).

In contrast to SAPMaintenanceOrderModel (used to create orders) all fields except the order number are optional and dates are converted into timezone-aware datetime objects.

Attributes:

Name Type Description
operations list[SAPMaintenanceOrderOperationResponseModel] | None

The operations of the order. None if the operations have not been requested ($expand), an empty list if the order has no operations.

SAPMaintenanceOrderQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP maintenance orders (API_MAINTENANCEORDER).

Methods:

Name Description
accepts

Check the deletion flag - the API only has it in the status text, which SAP can't filter by (HTTP 501).

accepts

accepts(entity: BaseModel) -> bool

Check the deletion flag - the API only has it in the status text, which SAP can't filter by (HTTP 501).

Parameters:

Name Type Description Default
entity BaseModel

The maintenance order read (SAPMaintenanceOrderResponseModel).

required

Returns:

Name Type Description
bool bool

True if the order matches is_marked_for_deletion (or the criterion isn't set).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def accepts(self, entity: BaseModel) -> bool:
    """Check the deletion flag - the API only has it in the status text, which SAP can't filter by (HTTP 501).

    Args:
        entity (BaseModel):
            The maintenance order read (SAPMaintenanceOrderResponseModel).

    Returns:
        bool:
            True if the order matches is_marked_for_deletion (or the criterion isn't set).

    """

    if self.is_marked_for_deletion is None:
        return True

    order = cast("SAPMaintenanceOrderResponseModel", entity)

    return ("DLFL" in (order.system_status or "").split()) == self.is_marked_for_deletion

SAPMaintenanceNotificationItemModel

Bases: SAPODataCreateModel

An item (damage / object part) of an SAP maintenance notification (API_MAINTNOTIFICATION).

SAPMaintenanceNotificationModel

Bases: SAPODataCreateModel

Data to create an SAP maintenance notification (API_MAINTNOTIFICATION, OData V2).

The affected object is given as technical object plus its type ("EAMS_EQUI" for an equipment, "EAMS_FL" for a functional location) - the API has no separate equipment field. The notification number is assigned by SAP. The notification date and the malfunction dates can be in the past (the creation date of the record is always today); SAP may determine the required dates from the priority.

See: https://api.sap.com/api/API_MAINTNOTIFICATION/overview

Methods:

Name Description
check_consistency

Validate dependencies between fields.

check_consistency

check_consistency() -> Self

Validate dependencies between fields.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_consistency(self) -> Self:
    """Validate dependencies between fields."""

    if self.technical_object and not self.technical_object_type:
        message = "Technical object -> '{}' needs a technical object type ('EAMS_EQUI' or 'EAMS_FL')".format(
            self.technical_object,
        )
        raise ValueError(message)

    if self.required_start_date and self.required_end_date and self.required_end_date < self.required_start_date:
        message = "Required end date -> {} is before required start date -> {}".format(
            self.required_end_date,
            self.required_start_date,
        )
        raise ValueError(message)

    return self

SAPMaintenanceNotificationItemResponseModel

Bases: SAPODataModel

An item of an SAP maintenance notification as returned by SAP (API_MAINTNOTIFICATION).

SAPMaintenanceNotificationResponseModel

Bases: SAPODataModel

An SAP maintenance notification as returned by SAP (API_MAINTNOTIFICATION).

All fields except the notification number are optional and timestamps are converted into timezone-aware datetime objects.

Attributes:

Name Type Description
items list[SAPMaintenanceNotificationItemResponseModel] | None

The items of the notification. None if the items have not been requested ($expand), an empty list if the notification has no items.

SAPMaintenanceNotificationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP maintenance notifications (API_MAINTNOTIFICATION).

Methods:

Name Description
add_padded_equipment_numbers

Also match numeric equipment numbers with leading zeros.

add_padded_equipment_numbers classmethod

add_padded_equipment_numbers(
    values: list[str] | None,
) -> list[str] | None

Also match numeric equipment numbers with leading zeros.

TechnicalObject is a generic field without ALPHA conversion: SAP stores a numeric equipment number with leading zeros ('000000000010000004'), so '10000004' alone finds nothing. The unpadded value is kept for numeric functional location labels.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@field_validator("technical_object_ids")
@classmethod
def add_padded_equipment_numbers(cls, values: list[str] | None) -> list[str] | None:
    """Also match numeric equipment numbers with leading zeros.

    TechnicalObject is a generic field without ALPHA conversion: SAP stores a numeric
    equipment number with leading zeros ('000000000010000004'), so '10000004' alone
    finds nothing. The unpadded value is kept for numeric functional location labels.

    """

    if not values:
        return values

    return list(
        dict.fromkeys(
            padded
            for value in values
            for padded in (value, value.zfill(18) if value.isdigit() and len(value) < 18 else value)
        )
    )

SAPPurchaseOrderScheduleLineModel

Bases: SAPODataCreateModel

A schedule line (delivery date and quantity) of a purchase order item (API_PURCHASEORDER_2).

SAPPurchaseOrderAccountAssignmentModel

Bases: SAPODataCreateModel

An account assignment of a purchase order item (API_PURCHASEORDER_2).

Required if the item has an account assignment category, e.g. "K" (cost center) requires a cost center and a G/L account.

SAPPurchaseOrderItemModel

Bases: SAPPurchasingItemModel

An item of a purchase order (API_PURCHASEORDER_2).

An item needs a material, a short text plus a material group, or the purchase contract or requisition item it refers to (SAP takes the material from it). Items can only be created together with the purchase order (SAP does not allow adding items to an existing purchase order via this API). An item that refers to a purchase contract item is a release order of the contract: SAP takes the price and conditions of the contract and updates its released quantity.

Methods:

Name Description
check_units

Fill in the order unit for the price, the schedule lines and the account assignments.

check_units

check_units() -> Self

Fill in the order unit for the price, the schedule lines and the account assignments.

OData V4 rejects quantities without their unit. The schedule lines must use the item's unit.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_units(self) -> Self:
    """Fill in the order unit for the price, the schedule lines and the account assignments.

    OData V4 rejects quantities without their unit. The schedule lines must use the item's unit.

    """

    if self.price_unit is not None:
        self.price_unit_of_measure = self.price_unit_of_measure or self.unit
    for account_assignment in self.account_assignments:
        if account_assignment.quantity is not None:
            account_assignment.unit = account_assignment.unit or self.unit
    for schedule_line in self.schedule_lines:
        schedule_line.unit = schedule_line.unit or self.unit
        if schedule_line.unit != self.unit:
            message = "Schedule line -> {} has unit -> '{}' but the item -> {} has unit -> '{}'".format(
                schedule_line.schedule_line, schedule_line.unit, self.item, self.unit
            )
            raise ValueError(message)

    return self

SAPPurchaseOrderModel

Bases: SAPODataCreateModel

Data to create an SAP purchase order (API_PURCHASEORDER_2, OData V4).

The purchase order number is assigned by SAP. Which further fields are required depends on the customizing (order type, supplier, material).

See: https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/f296651f454c4284ade361292c633d69/dbf882e32bac456eb506bc415f0d2df1.html

Methods:

Name Description
check_item_currencies

Fill in the purchase order's currency for the item prices (OData V4 needs the currency with the amount).

check_item_currencies

check_item_currencies() -> Self

Fill in the purchase order's currency for the item prices (OData V4 needs the currency with the amount).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_item_currencies(self) -> Self:
    """Fill in the purchase order's currency for the item prices (OData V4 needs the currency with the amount)."""

    for item in self.items:
        if item.net_price is not None:
            item.currency = item.currency or self.currency
            if not item.currency:
                message = (
                    "Item -> {} has a `net_price` but no currency - give the purchase order's `currency`".format(
                        item.item
                    )
                )
                raise ValueError(message)

    return self

SAPPurchaseOrderScheduleLineResponseModel

Bases: SAPODataModel

A schedule line of a purchase order item as returned by SAP (API_PURCHASEORDER_2).

SAPPurchaseOrderAccountAssignmentResponseModel

Bases: SAPODataModel

An account assignment of a purchase order item as returned by SAP (API_PURCHASEORDER_2).

SAPPurchaseOrderItemResponseModel

Bases: SAPODataModel

An item of a purchase order as returned by SAP (API_PURCHASEORDER_2).

Attributes:

Name Type Description
schedule_lines / account_assignments

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPPurchaseOrderResponseModel

Bases: SAPODataModel

A purchase order as returned by SAP (API_PURCHASEORDER_2, OData V4).

All fields except the purchase order number are optional.

Attributes:

Name Type Description
items list[SAPPurchaseOrderItemResponseModel] | None

The items of the purchase order. None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPPurchaseOrderQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP purchase orders (API_PURCHASEORDER_2, OData V4).

SAPSalesOrderItemModel

Bases: SAPODataCreateModel

An item of an SAP sales order (API_SALES_ORDER_SRV).

SAPSalesOrderModel

Bases: SAPODataCreateModel

Data to create an SAP sales order (API_SALES_ORDER_SRV, OData V2).

The sales order number is assigned by SAP. Which further fields are required depends on the customizing of the sales document type.

See: https://api.sap.com/api/API_SALES_ORDER_SRV/overview

SAPSalesOrderItemResponseModel

Bases: SAPODataModel

An item of an SAP sales order as returned by SAP (API_SALES_ORDER_SRV).

SAPSalesOrderResponseModel

Bases: SAPODataModel

An SAP sales order as returned by SAP (API_SALES_ORDER_SRV, OData V2).

All fields except the sales order number are optional.

Attributes:

Name Type Description
items list[SAPSalesOrderItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPSalesOrderQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP sales orders (API_SALES_ORDER_SRV).

SAPSalesContractItemModel

Bases: SAPODataCreateModel

An item of an SAP sales contract (API_SALES_CONTRACT_SRV).

For quantity contracts the quantity is the target quantity, for value contracts the target amount is used.

SAPSalesContractModel

Bases: SAPODataCreateModel

Data to create an SAP sales contract (API_SALES_CONTRACT_SRV, OData V2).

The sales contract number is assigned by SAP. Items are optional (e.g. for contracts that are only used as a framework).

See: https://api.sap.com/api/API_SALES_CONTRACT_SRV/overview

Methods:

Name Description
check_dates

Validate that the validity end date is not before the validity start date.

check_dates

check_dates() -> Self

Validate that the validity end date is not before the validity start date.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Validate that the validity end date is not before the validity start date."""

    if self.validity_start_date and self.validity_end_date and self.validity_end_date < self.validity_start_date:
        message = "Validity end date -> {} is before validity start date -> {}".format(
            self.validity_end_date,
            self.validity_start_date,
        )
        raise ValueError(message)

    return self

SAPSalesContractItemResponseModel

Bases: SAPODataModel

An item of an SAP sales contract as returned by SAP (API_SALES_CONTRACT_SRV).

SAPSalesContractResponseModel

Bases: SAPODataModel

An SAP sales contract as returned by SAP (API_SALES_CONTRACT_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPSalesContractItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPSalesContractQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP sales contracts (API_SALES_CONTRACT_SRV).

SAPPurchaseContractItemModel

Bases: SAPPurchasingItemModel

An item of an SAP purchase contract (API_PURCHASECONTRACT_PROCESS_SRV).

An item needs either a material or a short text plus a material group. For quantity contracts ("MK") the target quantity is required. Materials without stock management in the plant need an account assignment category ('U' if the account assignment is given in the release orders).

SAPPurchaseContractModel

Bases: SAPODataCreateModel

Data to create an SAP purchase contract (API_PURCHASECONTRACT_PROCESS_SRV, OData V2).

"MK" is a quantity contract (items need a target quantity), "WK" a value contract (the header needs a target amount). The contract number is assigned by SAP. The API has no contract name or header text - only the references (12 characters each) and the item texts.

See: https://api.sap.com/api/API_PURCHASECONTRACT_PROCESS_SRV/overview

Methods:

Name Description
check_dates

Validate that the validity dates are given and the end date is not before the start date.

check_dates

check_dates() -> Self

Validate that the validity dates are given and the end date is not before the start date.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Validate that the validity dates are given and the end date is not before the start date."""

    if not self.validity_start_date or not self.validity_end_date:
        message = "A purchase contract needs a validity start and end date"
        raise ValueError(message)
    if self.validity_end_date < self.validity_start_date:
        message = "Validity end date -> {} is before validity start date -> {}".format(
            self.validity_end_date,
            self.validity_start_date,
        )
        raise ValueError(message)

    return self

SAPPurchaseContractItemResponseModel

Bases: SAPODataModel

An item of an SAP purchase contract as returned by SAP (API_PURCHASECONTRACT_PROCESS_SRV).

SAPPurchaseContractResponseModel

Bases: SAPODataModel

An SAP purchase contract as returned by SAP (API_PURCHASECONTRACT_PROCESS_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPPurchaseContractItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPPurchaseContractQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP purchase contracts (API_PURCHASECONTRACT_PROCESS_SRV).

Methods:

Name Description
to_odata

Return the OData query options - with the items if the deletion flag is a criterion (see accepts()).

accepts

Check the deletion flag - deleting a contract sets the indicator of its items, not of the header.

to_odata

to_odata(odata_version: int) -> dict

Return the OData query options - with the items if the deletion flag is a criterion (see accepts()).

SAP.iter_purchase_contracts() drops the items again if they haven't been requested (expand_items).

Parameters:

Name Type Description Default
odata_version int

The OData version of the service.

required

Returns:

Name Type Description
dict dict

The query options ($filter, $orderby, $expand).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self, odata_version: int) -> dict:
    """Return the OData query options - with the items if the deletion flag is a criterion (see accepts()).

    SAP.iter_purchase_contracts() drops the items again if they haven't been requested (expand_items).

    Args:
        odata_version (int):
            The OData version of the service.

    Returns:
        dict:
            The query options ($filter, $orderby, $expand).

    """

    params = super().to_odata(odata_version=odata_version)
    if self.is_marked_for_deletion is not None:
        params["$expand"] = self.EXPAND

    return params

accepts

accepts(entity: BaseModel) -> bool

Check the deletion flag - deleting a contract sets the indicator of its items, not of the header.

The API (OData V2) can't filter by the items, so the contracts are checked when read.

Parameters:

Name Type Description Default
entity BaseModel

The purchase contract read with its items (SAPPurchaseContractResponseModel).

required

Returns:

Name Type Description
bool bool

True if the contract matches is_marked_for_deletion (or the criterion isn't set).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def accepts(self, entity: BaseModel) -> bool:
    """Check the deletion flag - deleting a contract sets the indicator of its items, not of the header.

    The API (OData V2) can't filter by the items, so the contracts are checked when read.

    Args:
        entity (BaseModel):
            The purchase contract read with its items (SAPPurchaseContractResponseModel).

    Returns:
        bool:
            True if the contract matches is_marked_for_deletion (or the criterion isn't set).

    """

    if self.is_marked_for_deletion is None:
        return True

    contract = cast("SAPPurchaseContractResponseModel", entity)
    items = contract.items or []
    is_deleted = contract.deletion_code == "L" or bool(items and all(item.deletion_code == "L" for item in items))

    return is_deleted == self.is_marked_for_deletion

SAPPurchaseRequisitionAccountAssignmentModel

Bases: SAPODataCreateModel

An account assignment of a purchase requisition item (API_PURCHASEREQUISITION_2).

Required if the item has an account assignment category, e.g. "K" (cost center) requires a cost center and a G/L account.

SAPPurchaseRequisitionItemModel

Bases: SAPPurchasingItemModel

An item of an SAP purchase requisition (API_PURCHASEREQUISITION_2, OData V4).

An item needs either a material or a short text plus a material group. In contrast to purchase orders, the delivery date is part of the item.

Methods:

Name Description
check_units_and_currency

Fill in the item's unit for the account assignments and check the currency of the price.

to_odata_update

Return the OData payload to update individual fields of an item - a new unit as ISO code.

to_odata

Return the OData payload of the item - its units only as ISO codes.

check_units_and_currency

check_units_and_currency() -> Self

Fill in the item's unit for the account assignments and check the currency of the price.

OData V4 rejects quantities without their unit and amounts without their currency.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_units_and_currency(self) -> Self:
    """Fill in the item's unit for the account assignments and check the currency of the price.

    OData V4 rejects quantities without their unit and amounts without their currency.

    """

    self.unit_iso_code = self.unit_iso_code or unit_iso_code(self.unit)
    if not self.unit_iso_code:
        message = (
            "Item -> {} needs a `unit_iso_code` - the ISO code of unit -> '{}' is not known".format(
                self.item, self.unit
            )
            if self.unit
            else "Item -> {} needs a `unit` or `unit_iso_code`".format(self.item)
        )
        raise ValueError(message)
    for account_assignment in self.account_assignments:
        if account_assignment.quantity is not None and not account_assignment.unit_iso_code:
            account_assignment.unit_iso_code = unit_iso_code(account_assignment.unit) or self.unit_iso_code
    if self.price is not None and not self.currency:
        message = "Item -> {} has a `price` but no `currency`".format(self.item)
        raise ValueError(message)

    return self

to_odata_update classmethod

to_odata_update(changes: dict) -> dict

Return the OData payload to update individual fields of an item - a new unit as ISO code.

Parameters:

Name Type Description Default
changes dict

The fields to change (see SAPODataCreateModel.to_odata_update()).

required

Returns:

Name Type Description
dict dict

The payload with OData property names.

Raises:

Type Description
ValueError

If a field is invalid or the ISO code of a new unit is not known.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@classmethod
def to_odata_update(cls, changes: dict) -> dict:
    """Return the OData payload to update individual fields of an item - a new unit as ISO code.

    Args:
        changes (dict):
            The fields to change (see SAPODataCreateModel.to_odata_update()).

    Returns:
        dict:
            The payload with OData property names.

    Raises:
        ValueError:
            If a field is invalid or the ISO code of a new unit is not known.

    """

    payload = super().to_odata_update(changes)
    if "BaseUnit" in payload:
        unit = payload.pop("BaseUnit")
        payload.setdefault("BaseUnitISOCode", unit_iso_code(unit))
        if not payload["BaseUnitISOCode"]:
            message = "The ISO code of unit -> '{}' is not known - change `unit_iso_code` instead".format(unit)
            raise ValueError(message)

    return payload

to_odata

to_odata() -> dict

Return the OData payload of the item - its units only as ISO codes.

API_PURCHASEREQUISITION_2 expects SAP's internal unit code in BaseUnit (e.g. 'ST' for 'PC') and rejects a BaseUnit that doesn't match the ISO code - with the ISO code alone, SAP determines the unit itself.

Returns:

Name Type Description
dict dict

The payload with OData property names.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self) -> dict:
    """Return the OData payload of the item - its units only as ISO codes.

    API_PURCHASEREQUISITION_2 expects SAP's internal unit code in BaseUnit (e.g. 'ST' for 'PC')
    and rejects a BaseUnit that doesn't match the ISO code - with the ISO code alone, SAP
    determines the unit itself.

    Returns:
        dict:
            The payload with OData property names.

    """

    return send_purchase_requisition_units_as_iso(super().to_odata())

SAPPurchaseRequisitionModel

Bases: SAPODataCreateModel

Data to create an SAP purchase requisition (API_PURCHASEREQUISITION_2, OData V4).

The purchase requisition number is assigned by SAP. Items can only be created together with the purchase requisition.

Methods:

Name Description
to_odata

Return the OData payload of the purchase requisition - the units of its items only as ISO codes.

to_odata

to_odata() -> dict

Return the OData payload of the purchase requisition - the units of its items only as ISO codes.

Returns:

Name Type Description
dict dict

The payload with OData property names.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self) -> dict:
    """Return the OData payload of the purchase requisition - the units of its items only as ISO codes.

    Returns:
        dict:
            The payload with OData property names.

    """

    payload = super().to_odata()
    for item in payload.get("_PurchaseRequisitionItem", []):
        send_purchase_requisition_units_as_iso(item)

    return payload

SAPPurchaseRequisitionAccountAssignmentResponseModel

Bases: SAPODataModel

An account assignment of a purchase requisition item as returned by SAP (API_PURCHASEREQUISITION_2).

SAPPurchaseRequisitionItemResponseModel

Bases: SAPODataModel

An item of an SAP purchase requisition as returned by SAP (API_PURCHASEREQUISITION_2).

Attributes:

Name Type Description
account_assignments list[SAPPurchaseRequisitionAccountAssignmentResponseModel] | None

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPPurchaseRequisitionResponseModel

Bases: SAPODataModel

An SAP purchase requisition as returned by SAP (API_PURCHASEREQUISITION_2, OData V4).

Attributes:

Name Type Description
items list[SAPPurchaseRequisitionItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPPurchaseRequisitionQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP purchase requisitions (API_PURCHASEREQUISITION_2, OData V4).

SAPRequestForQuotationAction

Bases: StrEnum

Status actions for requests for quotation (function imports of API_RFQ_PROCESS_SRV).

Lifecycle statuses: 01 in preparation, 06 in approval, 02 published, 05 completed, 03 cancelled, 07 rejected. The API has no separate publish action. Values (SAP function names) and their effect on the RFQ: * SubmitForApproval: only in preparation - starts SAP's approval workflow (in approval); the workflow publishes the RFQ to the bidders when it is approved or no approval is needed. Quotations need a published RFQ. * Complete: close a published RFQ (completed) - no more quotations. * Cancel: cancel the RFQ.

SAPSupplierQuotationAction

Bases: StrEnum

Status actions for supplier quotations (function imports of API_QTN_PROCESS_SRV).

Lifecycle statuses: 01 in preparation, 02 submitted, 06 in approval, 03 awarded, 05 completed, 04 cancelled, 07 rejected. Values (SAP function names) and their effect on the quotation: * Submit: submit the quotation (the supplier's answer is final). * SubmitForApproval: award a submitted quotation - set the awarded quantities of its items first; SAP's approval workflow awards it when it is approved or no approval is needed. * Complete: close a submitted quotation without awarding it. * Cancel: cancel the quotation.

SAPSourcingItemModel

Bases: SAPODataCreateModel

Base class of the items of requests for quotation and supplier quotations.

An item needs either a material or a short text plus a material group.

Contract with the subclasses: they declare the item number as field "item" (see SAP._create_document_item()).

Methods:

Name Description
check_material_or_text

Validate that the item has a material or a short text plus a material group.

check_material_or_text

check_material_or_text() -> Self

Validate that the item has a material or a short text plus a material group.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_material_or_text(self) -> Self:
    """Validate that the item has a material or a short text plus a material group."""

    if not self.material and not (self.text and self.material_group):
        message = "Item -> {} needs a material or a text plus a material group".format(getattr(self, "item", "?"))
        raise ValueError(message)

    return self

SAPSourcingDocumentModel

Bases: SAPODataCreateModel

Base class of the headers of requests for quotation and supplier quotations.

SAPRequestForQuotationItemModel

Bases: SAPSourcingItemModel

An item of an SAP request for quotation (API_RFQ_PROCESS_SRV).

An item needs either a material or a short text plus a material group.

Methods:

Name Description
check_delivery_date

Validate that the item has a delivery date (SAP: 'Please enter a valid delivery date').

check_delivery_date

check_delivery_date() -> Self

Validate that the item has a delivery date (SAP: 'Please enter a valid delivery date').

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_delivery_date(self) -> Self:
    """Validate that the item has a delivery date (SAP: 'Please enter a valid delivery date')."""

    if not self.delivery_date:
        message = "Item -> {} needs a delivery date".format(self.item)
        raise ValueError(message)

    return self

SAPRequestForQuotationBidderModel

Bases: SAPODataCreateModel

A bidder (supplier asked for a quotation) of an SAP request for quotation (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationModel

Bases: SAPSourcingDocumentModel

Data to create an SAP request for quotation (API_RFQ_PROCESS_SRV, OData V2).

The RFQ is created in preparation. It is published to the bidders by SAP's approval workflow after the action SubmitForApproval (see SAPRequestForQuotationAction). The RFQ number is assigned by SAP. SAP requires the document type, the currency, at least one item (with a delivery date) and at least one bidder.

See: https://api.sap.com/api/API_RFQ_PROCESS_SRV/overview

Methods:

Name Description
check_dates

Validate that the submission deadline is not before the earliest submission date.

check_items_and_bidders

Validate that the RFQ has at least one item and one bidder (SAP: 'Enter at least one bidder').

check_dates

check_dates() -> Self

Validate that the submission deadline is not before the earliest submission date.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Validate that the submission deadline is not before the earliest submission date."""

    if (
        self.submission_deadline
        and self.earliest_submission_date
        and self.submission_deadline < self.earliest_submission_date
    ):
        message = "Submission deadline -> {} is before the earliest submission date -> {}".format(
            self.submission_deadline,
            self.earliest_submission_date,
        )
        raise ValueError(message)

    return self

check_items_and_bidders

check_items_and_bidders() -> Self

Validate that the RFQ has at least one item and one bidder (SAP: 'Enter at least one bidder').

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_items_and_bidders(self) -> Self:
    """Validate that the RFQ has at least one item and one bidder (SAP: 'Enter at least one bidder')."""

    if not self.items or not self.bidders:
        message = "A request for quotation needs at least one item and one bidder"
        raise ValueError(message)

    return self

SAPRequestForQuotationItemResponseModel

Bases: SAPODataModel

An item of an SAP request for quotation as returned by SAP (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationBidderResponseModel

Bases: SAPODataModel

A bidder of an SAP request for quotation as returned by SAP (API_RFQ_PROCESS_SRV).

SAPRequestForQuotationResponseModel

Bases: SAPODataModel

An SAP request for quotation as returned by SAP (API_RFQ_PROCESS_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPRequestForQuotationItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

bidders list[SAPRequestForQuotationBidderResponseModel] | None

None if the bidders have not been requested ($expand), otherwise a (possibly empty) list.

SAPRequestForQuotationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP requests for quotation (API_RFQ_PROCESS_SRV).

SAPSupplierQuotationItemModel

Bases: SAPSourcingItemModel

The fields of an item of an SAP supplier quotation that can be changed (API_QTN_PROCESS_SRV).

Items cannot be added to a quotation - a quotation created from an RFQ gets the items of the RFQ, the supplier's prices are then set with an update.

SAPSupplierQuotationModel

Bases: SAPSourcingDocumentModel

The fields of an SAP supplier quotation that can be changed (API_QTN_PROCESS_SRV, OData V2).

SAP does not create quotations directly (POST is not supported by the API): a quotation is created for a request for quotation and a bidder (see SAP.create_supplier_quotation_from_rfq()) and then changed. The items are changed with SAPSupplierQuotationItemModel.

See: https://api.sap.com/api/API_QTN_PROCESS_SRV/overview

SAPSupplierQuotationItemResponseModel

Bases: SAPODataModel

An item of an SAP supplier quotation as returned by SAP (API_QTN_PROCESS_SRV).

SAPSupplierQuotationResponseModel

Bases: SAPODataModel

An SAP supplier quotation as returned by SAP (API_QTN_PROCESS_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPSupplierQuotationItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPSupplierQuotationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP supplier quotations (API_QTN_PROCESS_SRV).

SAPPurchasingInfoRecordDataModel

Bases: SAPODataCreateModel

The purchasing organization / plant data of an SAP purchasing info record (API_INFORECORD_PROCESS_SRV).

It holds the conditions the supplier delivers the material under in a purchasing organization (and optionally a plant): price, delivery time, tolerances, order quantities, taxes and Incoterms. SAP requires the standard order quantity and the planned delivery time.

SAPPurchasingInfoRecordModel

Bases: SAPODataCreateModel

Data to create an SAP purchasing info record (API_INFORECORD_PROCESS_SRV, OData V2).

An info record links a supplier with a material (or a material group and a text) and keeps the supplier's conditions per purchasing organization and plant (purchasing_data) - e.g. the price. The number is assigned by SAP.

See: https://api.sap.com/api/API_INFORECORD_PROCESS_SRV/overview

Methods:

Name Description
check_material_or_description

Validate that the info record has a material or a short text plus a material group.

check_material_or_description

check_material_or_description() -> Self

Validate that the info record has a material or a short text plus a material group.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_material_or_description(self) -> Self:
    """Validate that the info record has a material or a short text plus a material group."""

    if not self.material and not (self.description and self.material_group):
        message = "An info record needs a material or a description plus a material group"
        raise ValueError(message)

    return self

SAPPurchasingInfoRecordDataResponseModel

Bases: SAPODataModel

The purchasing organization / plant data of an SAP purchasing info record as returned by SAP.

SAPPurchasingInfoRecordResponseModel

Bases: SAPODataModel

An SAP purchasing info record as returned by SAP (API_INFORECORD_PROCESS_SRV, OData V2).

Attributes:

Name Type Description
purchasing_data list[SAPPurchasingInfoRecordDataResponseModel] | None

None if the purchasing organization / plant data have not been requested ($expand), otherwise a (possibly empty) list.

SAPPurchasingInfoRecordQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP purchasing info records (API_INFORECORD_PROCESS_SRV).

The purchasing organization / plant data cannot be searched (OData V2) - read the info records of a supplier and / or material with expand_items and pick the data of the organization / plant.

SAPSourceListRecordModel

Bases: SAPODataCreateModel

Data to create an SAP source list record (API_PURCHASING_SOURCE_SRV, OData V2).

A source list record says which supplier (and / or outline agreement) may supply a material to a plant, and when. The record number within the material and plant is assigned by SAP.

See: https://api.sap.com/api/API_PURCHASING_SOURCE_SRV/overview

Methods:

Name Description
check_dates

Validate that the validity dates are given and the end date is not before the start date.

check_dates

check_dates() -> Self

Validate that the validity dates are given and the end date is not before the start date.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Validate that the validity dates are given and the end date is not before the start date."""

    if not self.validity_start_date or not self.validity_end_date:
        message = "A source list record needs a validity start and end date"
        raise ValueError(message)
    if self.validity_end_date < self.validity_start_date:
        message = "Validity end date -> {} is before validity start date -> {}".format(
            self.validity_end_date,
            self.validity_start_date,
        )
        raise ValueError(message)

    return self

SAPSourceListRecordResponseModel

Bases: SAPODataModel

An SAP source list record as returned by SAP (API_PURCHASING_SOURCE_SRV, OData V2).

SAPSourceListRecordQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP source list records (API_PURCHASING_SOURCE_SRV).

SAPWarrantyClaimItemModel

Bases: SAPODataCreateModel

An item of an SAP warranty claim version (API_WARRANTYCLAIM, OData V4).

The item type is required by SAP. Which other fields are required depends on the item type and the warranty customizing of the system - SAP reports missing fields in its error messages.

Methods:

Name Description
check_quantity_unit

Validate that an item with a quantity has its unit (SAP rejects the quantity without it).

check_quantity_unit

check_quantity_unit() -> Self

Validate that an item with a quantity has its unit (SAP rejects the quantity without it).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_quantity_unit(self) -> Self:
    """Validate that an item with a quantity has its unit (SAP rejects the quantity without it)."""

    if self.quantity is not None and not self.unit:
        message = "Item -> {} has a quantity but no unit - give the unit, e.g. 'PC'".format(self.item or "?")
        raise ValueError(message)

    return self

SAPWarrantyClaimVersionModel

Bases: SAPODataCreateModel

A version of an SAP warranty claim (API_WARRANTYCLAIM, OData V4).

SAP creates the first version with the claim. Changes of the claim (e.g. a new decision) are made in new versions, so a version can be given with the claim - the items belong to it. SAP requires the sales area and the currency in every version, supplier claims also the purchasing organization.

SAPWarrantyClaimModel

Bases: SAPODataCreateModel

Data to create an SAP warranty claim (API_WARRANTYCLAIM, OData V4).

The claim number is assigned by SAP. The claim type and the object (plant, object type and external object number, e.g. an equipment) are the basis of the claim. A supplier claim needs the supplier, a customer claim the customer. Unlike other SAP documents, the claim is not deleted via the API.

SAPWarrantyClaimItemResponseModel

Bases: SAPODataModel

An item of an SAP warranty claim version as returned by SAP (API_WARRANTYCLAIM).

SAPWarrantyClaimVersionResponseModel

Bases: SAPODataModel

A version of an SAP warranty claim as returned by SAP (API_WARRANTYCLAIM).

SAPWarrantyClaimResponseModel

Bases: SAPODataModel

An SAP warranty claim as returned by SAP (API_WARRANTYCLAIM, OData V4).

Attributes:

Name Type Description
versions list[SAPWarrantyClaimVersionResponseModel] | None

None if the versions have not been requested ($expand), otherwise a (possibly empty) list.

SAPWarrantyClaimQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP warranty claims (API_WARRANTYCLAIM, OData V4).

SAPCreditMemoRequestItemModel

Bases: SAPODataCreateModel

An item of an SAP credit memo request (API_CREDIT_MEMO_REQUEST_SRV).

SAPCreditMemoRequestModel

Bases: SAPODataCreateModel

Data to create an SAP credit memo request (API_CREDIT_MEMO_REQUEST_SRV, OData V2).

A credit memo request is the sales document from which SAP creates the credit memo (a billing document) for the customer. The number is assigned by SAP. Which further fields are required depends on the customizing of the document type.

See: https://api.sap.com/api/API_CREDIT_MEMO_REQUEST_SRV/overview

SAPCreditMemoRequestItemResponseModel

Bases: SAPODataModel

An item of an SAP credit memo request as returned by SAP (API_CREDIT_MEMO_REQUEST_SRV).

SAPCreditMemoRequestResponseModel

Bases: SAPODataModel

An SAP credit memo request as returned by SAP (API_CREDIT_MEMO_REQUEST_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPCreditMemoRequestItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPCreditMemoRequestQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP credit memo requests (API_CREDIT_MEMO_REQUEST_SRV).

SAPDebitMemoRequestItemModel

Bases: SAPODataCreateModel

An item of an SAP debit memo request (API_DEBIT_MEMO_REQUEST_SRV).

SAPDebitMemoRequestModel

Bases: SAPODataCreateModel

Data to create an SAP debit memo request (API_DEBIT_MEMO_REQUEST_SRV, OData V2).

A debit memo request is the sales document from which SAP creates the debit memo (a billing document) - an additional charge to the customer. The number is assigned by SAP.

See: https://api.sap.com/api/API_DEBIT_MEMO_REQUEST_SRV/overview

SAPDebitMemoRequestItemResponseModel

Bases: SAPODataModel

An item of an SAP debit memo request as returned by SAP (API_DEBIT_MEMO_REQUEST_SRV).

SAPDebitMemoRequestResponseModel

Bases: SAPODataModel

An SAP debit memo request as returned by SAP (API_DEBIT_MEMO_REQUEST_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPDebitMemoRequestItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPDebitMemoRequestQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP debit memo requests (API_DEBIT_MEMO_REQUEST_SRV).

SAPBillingDocumentRequestItemResponseModel

Bases: SAPODataModel

An item of an SAP billing document request as returned by SAP (API_BILLING_DOCUMENT_REQUEST_SRV).

SAPBillingDocumentRequestResponseModel

Bases: SAPODataModel

An SAP billing document request as returned by SAP (API_BILLING_DOCUMENT_REQUEST_SRV, OData V2).

Billing document requests hold billing data of external systems (external billing). SAP creates billing documents (invoices) from them - see get_billing_documents().

Attributes:

Name Type Description
items list[SAPBillingDocumentRequestItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPBillingDocumentRequestQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP billing document requests (API_BILLING_DOCUMENT_REQUEST_SRV).

SAPBillingDocumentItemResponseModel

Bases: SAPODataModel

An item of an SAP billing document as returned by SAP (API_BILLING_DOCUMENT_SRV).

SAPBillingDocumentResponseModel

Bases: SAPODataModel

An SAP billing document as returned by SAP (API_BILLING_DOCUMENT_SRV, OData V2).

Billing documents are customer invoices, credit memos, debit memos and their cancellations. They are created by SAP (e.g. from deliveries, credit / debit memo requests or billing document requests) - the API cannot create them.

Attributes:

Name Type Description
items list[SAPBillingDocumentItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

category_name property

category_name: str | None

Return the name of the document category, e.g. "Invoice" or "Credit Memo" (see SAP_SD_DOCUMENT_CATEGORIES).

A plain property (no computed field), so it is not part of the serialized data.

Returns:

Type Description
str | None

str | None: The name of the category or None if the category is not set or unknown.

SAPBillingDocumentQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP billing documents (API_BILLING_DOCUMENT_SRV).

SAPBillingDocumentItemQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP billing document items (API_BILLING_DOCUMENT_SRV, A_BillingDocumentItem).

Used to find the billing documents of sales orders (see SAP.iter_billing_documents()).

SAPOutboundDeliveryItemModel

Bases: SAPODataCreateModel

An item of an SAP outbound delivery - a reference to the sales order item to deliver (API_OUTBOUND_DELIVERY_SRV).

SAPOutboundDeliveryModel

Bases: SAPODataCreateModel

Data to create an SAP outbound delivery for sales order items (API_OUTBOUND_DELIVERY_SRV, OData V2).

The delivery number and the item numbers are assigned by SAP; the material, plant and customer are copied from the sales order. Further steps (picking, goods issue) are done with change_outbound_delivery_status().

See: https://api.sap.com/api/OP_API_OUTBOUND_DELIVERY_SRV_0002/overview

Methods:

Name Description
check_item_storage_location

Reject a storage location on create - $metadata: StorageLocation is not creatable (SAP determines it).

check_item_storage_location

check_item_storage_location() -> Self

Reject a storage location on create - $metadata: StorageLocation is not creatable (SAP determines it).

It can only be changed on an existing delivery item (update_outbound_delivery()).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_item_storage_location(self) -> Self:
    """Reject a storage location on create - $metadata: StorageLocation is not creatable (SAP determines it).

    It can only be changed on an existing delivery item (update_outbound_delivery()).

    """

    if any(item.storage_location for item in self.items):
        message = (
            "The storage location of a delivery item can't be set on create - SAP determines it; change it "
            "with an update of the delivery afterwards"
        )
        raise ValueError(message)

    return self

SAPOutboundDeliveryItemResponseModel

Bases: SAPODataModel

An item of an SAP outbound delivery as returned by SAP (API_OUTBOUND_DELIVERY_SRV).

SAPOutboundDeliveryResponseModel

Bases: SAPODataModel

An SAP outbound delivery as returned by SAP (API_OUTBOUND_DELIVERY_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPOutboundDeliveryItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPOutboundDeliveryQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP outbound deliveries (API_OUTBOUND_DELIVERY_SRV).

Attributes:

Name Type Description
has_item_criteria bool

Whether the query has criteria of the delivery items (resolved via the items first).

has_item_criteria property

has_item_criteria: bool

Whether the query has criteria of the delivery items (resolved via the items first).

SAPOutboundDeliveryItemQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP outbound delivery items (API_OUTBOUND_DELIVERY_SRV, A_OutbDeliveryItem).

Used to find the deliveries of sales orders and materials (see SAP.iter_outbound_deliveries()).

SAPInboundDeliveryItemModel

Bases: SAPODataCreateModel

An item of an SAP inbound delivery - the delivered quantity of a purchase order item (API_INBOUND_DELIVERY_SRV).

SAPInboundDeliveryModel

Bases: SAPODataCreateModel

Data to create an SAP inbound delivery for purchase order items (API_INBOUND_DELIVERY_SRV, OData V2).

An inbound delivery announces the goods a supplier sends for purchase orders. The delivery number is assigned by SAP. Putaway and goods receipt are posted with change_inbound_delivery_status().

See: https://api.sap.com/api/OP_API_INBOUND_DELIVERY_SRV_0002/overview

SAPInboundDeliveryItemResponseModel

Bases: SAPODataModel

An item of an SAP inbound delivery as returned by SAP (API_INBOUND_DELIVERY_SRV).

SAPInboundDeliveryResponseModel

Bases: SAPODataModel

An SAP inbound delivery as returned by SAP (API_INBOUND_DELIVERY_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPInboundDeliveryItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPInboundDeliveryQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP inbound deliveries (API_INBOUND_DELIVERY_SRV).

Attributes:

Name Type Description
has_item_criteria bool

Whether the query has criteria of the delivery items (resolved via the items first).

has_item_criteria property

has_item_criteria: bool

Whether the query has criteria of the delivery items (resolved via the items first).

SAPInboundDeliveryItemQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP inbound delivery items (API_INBOUND_DELIVERY_SRV, A_InbDeliveryItem).

Used to find the inbound deliveries of purchase orders and materials (see SAP.iter_inbound_deliveries()).

SAPSupplierInvoiceAccountAssignmentModel

Bases: SAPODataCreateModel

An account assignment of a purchase order item of a new SAP supplier invoice (API_SUPPLIERINVOICE_PROCESS_SRV).

Only for purchase order items with multiple account assignment (distribution), e.g. to distribute the invoiced amount differently than in the purchase order. With a single account assignment, SAP takes it from the purchase order item and rejects one given in the invoice - also with the same values (verified in S/4HANA: M8/892 "There is different account assignment information in item ...").

SAPSupplierInvoiceMaterialItemModel

Bases: SAPODataCreateModel

An item of a new SAP supplier invoice posted directly to a material - without purchase order (API_SUPPLIERINVOICE_PROCESS_SRV).

Changes the stock value of the material (e.g. subsequent costs of a stock material).

SAPSupplierInvoiceAssetItemModel

Bases: SAPODataCreateModel

An item of a new SAP supplier invoice posted directly to a fixed asset (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceWithholdingTaxModel

Bases: SAPODataCreateModel

A withholding tax of a new SAP supplier invoice (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceSelectedPurchaseOrderModel

Bases: SAPODataCreateModel

A purchase order (item) whose open items SAP proposes as invoice items (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceSelectedDeliveryNoteModel

Bases: SAPODataCreateModel

A delivery note whose goods receipts SAP proposes as invoice items (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceSelectedServiceEntrySheetModel

Bases: SAPODataCreateModel

A service entry sheet (item) whose services SAP proposes as invoice items (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceAdditionalDataModel

Bases: SAPODataCreateModel

Name, address and bank details of a one-time supplier (API_SUPPLIERINVOICE_PROCESS_SRV).

Only for invoices of a one-time supplier account (the invoicing party has no master data of its own).

SAPSupplierInvoicePurchaseOrderItemModel

Bases: SAPODataCreateModel

An item of an SAP supplier invoice that refers to a purchase order item (API_SUPPLIERINVOICE_PROCESS_SRV).

Methods:

Name Description
check_account_assignments

Fill in the item number for the account assignments (part of their key).

check_quantity

Require the invoiced quantity - only subsequent debits / credits (price differences) have none.

check_account_assignments

check_account_assignments() -> Self

Fill in the item number for the account assignments (part of their key).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_account_assignments(self) -> Self:
    """Fill in the item number for the account assignments (part of their key)."""

    for account_assignment in self.account_assignments:
        account_assignment.item = self.item

    return self

check_quantity

check_quantity() -> Self

Require the invoiced quantity - only subsequent debits / credits (price differences) have none.

Verified in S/4HANA: SAP ignores the amount of a purchase order item without a quantity and rejects the invoice with M8/186 "Balance is not equal to zero".

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_quantity(self) -> Self:
    """Require the invoiced quantity - only subsequent debits / credits (price differences) have none.

    Verified in S/4HANA: SAP ignores the amount of a purchase order item without a quantity and
    rejects the invoice with M8/186 "Balance is not equal to zero".

    """

    if self.quantity is None and not self.is_subsequent_debit_credit:
        message = (
            "Purchase order item {} of purchase order {} needs the invoiced quantity "
            "(QuantityInPurchaseOrderUnit) - without it SAP ignores the amount".format(
                self.purchase_order_item, self.purchase_order
            )
        )
        raise ValueError(message)

    return self

SAPSupplierInvoiceGLAccountItemModel

Bases: SAPODataCreateModel

An item of an SAP supplier invoice posted directly to a G/L account (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceTaxModel

Bases: SAPODataCreateModel

A tax line of an SAP supplier invoice - needed if the tax is not calculated automatically (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceModel

Bases: SAPODataCreateModel

Data to create (post) an SAP supplier invoice (API_SUPPLIERINVOICE_PROCESS_SRV, OData V2).

Logistics invoice verification: the invoice of a supplier, usually for purchase order items (purchase_order_items) and / or posted to G/L accounts (gl_account_items), materials (material_items) or fixed assets (asset_items). Instead of giving the items, purchase orders, delivery notes or service entry sheets can be selected - SAP then proposes their open items (only when the invoice is posted directly, not together with purchase_order_items). The invoice is posted directly or parked (status 'A') and posted later (SAP.post_supplier_invoice()). The invoice number and fiscal year are assigned by SAP.

See: https://api.sap.com/api/API_SUPPLIERINVOICE_PROCESS_SRV/overview

Methods:

Name Description
fill_currency

Fill in the document currency of the items, account assignments and taxes.

fill_debit_credit_code

Fill in the debit / credit code of the G/L account, material and asset items.

check_items

Validate that the invoice has items - or selects the documents SAP proposes the items from.

check_taxes

Validate that the tax is either calculated automatically or given as tax lines - not both.

check_selected_documents

Validate the selected purchase orders, delivery notes and service entry sheets.

fill_currency

fill_currency() -> Self

Fill in the document currency of the items, account assignments and taxes.

SAP rejects items without it ("Document currency is missing in item ...") although it is the currency of the invoice.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def fill_currency(self) -> Self:
    """Fill in the document currency of the items, account assignments and taxes.

    SAP rejects items without it ("Document currency is missing in item ...") although it is
    the currency of the invoice.

    """

    children = [
        *self.purchase_order_items,
        *(
            account_assignment
            for item in self.purchase_order_items
            for account_assignment in item.account_assignments
        ),
        *self.gl_account_items,
        *self.material_items,
        *self.asset_items,
        *self.taxes,
        *self.withholding_taxes,
    ]
    for child in children:
        child.currency = child.currency or self.currency

    return self

fill_debit_credit_code

fill_debit_credit_code() -> Self

Fill in the debit / credit code of the G/L account, material and asset items.

SAP requires it (M8/375 "Fill in mandatory field 'DebitCreditCode'"): debit 'S' for an invoice, credit 'H' for a credit memo - unless the item gives its own.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def fill_debit_credit_code(self) -> Self:
    """Fill in the debit / credit code of the G/L account, material and asset items.

    SAP requires it (M8/375 "Fill in mandatory field 'DebitCreditCode'"): debit 'S' for an
    invoice, credit 'H' for a credit memo - unless the item gives its own.

    """

    for item in [*self.gl_account_items, *self.material_items, *self.asset_items]:
        item.debit_credit_code = item.debit_credit_code or ("H" if self.is_credit_memo else "S")

    return self

check_items

check_items() -> Self

Validate that the invoice has items - or selects the documents SAP proposes the items from.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_items(self) -> Self:
    """Validate that the invoice has items - or selects the documents SAP proposes the items from."""

    if not any(
        (
            self.purchase_order_items,
            self.gl_account_items,
            self.material_items,
            self.asset_items,
            self.selected_purchase_orders,
            self.selected_delivery_notes,
            self.selected_service_entry_sheets,
        )
    ):
        message = (
            "A supplier invoice needs items (purchase order, G/L account, material or asset items) or selected "
            "purchase orders, delivery notes or service entry sheets"
        )
        raise ValueError(message)

    return self

check_taxes

check_taxes() -> Self

Validate that the tax is either calculated automatically or given as tax lines - not both.

Verified in S/4HANA: SAP rejects tax lines together with automatic tax calculation (M8/738 "Enter value in either field 'TaxIsCalculatedAutomatically' or field 'TaxAmount'") - also tax lines with a tax amount of 0.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_taxes(self) -> Self:
    """Validate that the tax is either calculated automatically or given as tax lines - not both.

    Verified in S/4HANA: SAP rejects tax lines together with automatic tax calculation (M8/738
    "Enter value in either field 'TaxIsCalculatedAutomatically' or field 'TaxAmount'") - also tax
    lines with a tax amount of 0.

    """

    if self.tax_is_calculated_automatically and self.taxes:
        message = (
            "Give either TaxIsCalculatedAutomatically = true or the tax lines (to_SupplierInvoiceTax) - SAP "
            "rejects both together (M8/738). With automatic tax calculation, SAP calculates the tax from the "
            "tax codes of the items - leave out the tax lines"
        )
        raise ValueError(message)

    return self

check_selected_documents

check_selected_documents() -> Self

Validate the selected purchase orders, delivery notes and service entry sheets.

Verified in S/4HANA: SAP rejects selected documents together with purchase order items (M8/742 "Table 'to_SuplrInvcItemPurOrdRef' must not be filled"), and a parked invoice with selected documents is saved without items - it can't be posted later (M8/063).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_selected_documents(self) -> Self:
    """Validate the selected purchase orders, delivery notes and service entry sheets.

    Verified in S/4HANA: SAP rejects selected documents together with purchase order items
    (M8/742 "Table 'to_SuplrInvcItemPurOrdRef' must not be filled"), and a parked invoice with
    selected documents is saved without items - it can't be posted later (M8/063).

    """

    if not (self.selected_purchase_orders or self.selected_delivery_notes or self.selected_service_entry_sheets):
        return self

    if self.purchase_order_items:
        message = (
            "Give either purchase_order_items or selected purchase orders / delivery notes / service entry "
            "sheets - SAP rejects both together (M8/742)"
        )
        raise ValueError(message)
    if self.status == "A":
        message = (
            "A parked invoice (status 'A') gets no items from selected purchase orders / delivery notes / service "
            "entry sheets - give purchase_order_items (with the goods receipt as reference_document for "
            "goods-receipt-based invoice verification) or post the invoice directly"
        )
        raise ValueError(message)

    return self

SAPSupplierInvoiceAccountAssignmentResponseModel

Bases: SAPODataModel

An account assignment of a purchase order item of an SAP supplier invoice as returned by SAP.

SAPSupplierInvoiceMaterialItemResponseModel

Bases: SAPODataModel

A material item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceAssetItemResponseModel

Bases: SAPODataModel

A fixed asset item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceTaxResponseModel

Bases: SAPODataModel

A tax line of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceWithholdingTaxResponseModel

Bases: SAPODataModel

A withholding tax of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoicePurchaseOrderItemResponseModel

Bases: SAPODataModel

A purchase order item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceGLAccountItemResponseModel

Bases: SAPODataModel

A G/L account item of an SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceResponseModel

Bases: SAPODataModel

An SAP supplier invoice as returned by SAP (API_SUPPLIERINVOICE_PROCESS_SRV, OData V2).

A supplier invoice is identified by its number and fiscal year.

Attributes:

Name Type Description
purchase_order_items / gl_account_items / material_items / asset_items / taxes / withholding_taxes

None if they have not been requested ($expand), otherwise a (possibly empty) list.

status_name property

status_name: str | None

Return the meaning of the status, e.g. 'Posted' for '5' - the code alone is misread (e.g. as parked).

SAPSupplierInvoiceQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP supplier invoices (API_SUPPLIERINVOICE_PROCESS_SRV).

SAPSupplierInvoiceItemQueryModel

Bases: SAPODataQueryModel

Search criteria for purchase order items of SAP supplier invoices (A_SuplrInvcItemPurOrdRef).

Used to find the invoices of purchase orders (see SAP.get_supplier_invoice_items()) - the invoice header has no purchase order. The items carry no reversal status: reversed invoices and their reversal documents are found too.

SAPSupplierInvoiceGLAccountItemQueryModel

Bases: SAPODataQueryModel

Search criteria for G/L account items of SAP supplier invoices (A_SupplierInvoiceItemGLAcct).

Used to find how costs were posted before, e.g. the tax jurisdiction of a cost center - the cost center API doesn't return it. Reversed invoices and their reversal documents are found too.

SAPMaintenanceOrderAction

Bases: StrEnum

Status actions for maintenance orders (function imports of API_MAINTENANCEORDER).

Values (SAP function names) and their effect on the order: * ReleaseMaintenanceOrder: release the order for execution (status REL). * ScheduleMaintenanceOrder: schedule the order (calculate the operation dates). * SetMaintOrderToReadyForSchedg / ResetMaintOrderStsRdyForSchedg: set / reset "ready for scheduling". * SubmitMaintOrderForApproval: submit the order for approval. * ApproveMaintenanceOrder / RejectMaintenanceOrder: approve / reject a submitted order. * SetMaintOrderStatusToLocked / SetMaintOrderStatusToUnlocked: lock (LKD) / unlock the order. * SetMaintOrdToMainWorkComplete / ResetMaintOrdStsMainWorkCmplt: set / reset "main work completed". * SetMaintOrdToTechCompleted / ResetMaintOrdStsTechCompleted: complete technically (TECO) / undo it. * SetMaintOrderStatusToClosed / ResetMaintOrderStatusClosed: close (CLSD, business completion) / undo it. * SetMaintOrdStsToMrkdForDeltn / ResetMaintOrdStsMrkdForDeltn: set / reset the deletion flag (DLFL). * SetMaintOrderToDoNotExecute: mark the order as "do not execute" (it will not be carried out).

Some actions accept optional parameters (e.g. "MaintOrderReferenceDateTime" or "AssignedMaintNotifIsToBeClosed") - pass them to change_maintenance_order_status(). SetMaintOrdStsToMrkdForDeltn accepts "AssgdMaintNotifIsToBeSetDel" (True also sets the deletion flag of the assigned maintenance notification - API_MAINTNOTIFICATION itself cannot delete notifications). SAP only accepts it for closed orders - use delete_maintenance_order() which closes the order first.

SAPMaintenanceOrderOperationAction

Bases: StrEnum

Status actions for maintenance order operations (function imports of API_MAINTENANCEORDER).

Values (SAP function names) and their effect on the operation: * SetMaintOrderOpToDispatched: dispatch the operation (status DSPT) - it is planned for execution by its work center at its scheduled dates. * ResetMaintOrderOpStsDispatched: undo the dispatching.

Operations are deleted with delete_maintenance_order_operation().

SAPMaintenanceNotificationAction

Bases: StrEnum

Status actions for maintenance notifications (actions of API_MAINTNOTIFICATION).

Values (SAP function names) and their effect on the notification: * CompleteMaintNotification: complete the notification (status NOCO). * SetMaintNotifToInProcess: put the notification in process (status NOPR).

API_MAINTNOTIFICATION has no action to delete a notification (and does not allow DELETE). A notification assigned to an order can get the deletion flag together with its order - see delete_maintenance_order().

SAPMaintenancePlanAction

Bases: StrEnum

Status / scheduling actions for maintenance plans (actions of API_MAINTENANCEPLAN).

Values (SAP function names) and their effect on the plan: * StartMaintPlnSchedule: start scheduling - generates the maintenance calls from the scheduling start date. * RestartMaintPlnSchedule: restart scheduling with a new start date. * SetMaintPlanStatusToActive / SetMaintPlanStatusToInactive: activate / deactivate the plan (no calls if inactive). * SetMainPlanStsToMrkdForDeltn / ResetMaintPlanStsMrkdForDeltn: set / reset the deletion flag.

SAPProductionOrderAction

Bases: StrEnum

Status actions for production orders (function imports of API_PRODUCTION_ORDER_2_SRV).

Values (SAP function names) and their effect on the order: * ReleaseOrder: release the order for production (status REL). * TechlyCmpltOrder: complete the order technically (status TECO) - no further production. * CloseOrder: close the order (status CLSD) - no further postings. * DeletionFlagOrder: set the deletion flag (status DLFL). * DeletionIndOrder: set the deletion indicator (status DLT) - the order can be archived. * DiscardOrder: discard (cancel) the order. * DeliveryCompletedOrder: set "delivery completed" (status DLV) - no further goods receipts expected. * OrderReleasedByMES: record that the order has been released by a Manufacturing Execution System.

SAPCreditMemoRequestAction

Bases: StrEnum

Approval actions for credit memo requests (function imports of API_CREDIT_MEMO_REQUEST_SRV).

Values (SAP function names) and their effect: * releaseApprovalRequest: approve (release) a credit memo request that is in approval. * rejectApprovalRequest: reject a credit memo request that is in approval.

SAPOutboundDeliveryAction

Bases: StrEnum

Status actions for outbound deliveries (function imports of API_OUTBOUND_DELIVERY_SRV).

Values (SAP function names) and their effect on the delivery: * PickAllItems: pick all items (picking quantity = delivery quantity). * ConfirmPickingAllItems: confirm the picking of all items. * PostGoodsIssue: post the goods issue - reduces the stock, the delivery can be billed. * ReverseGoodsIssue: reverse the goods issue - needs the parameter "ActualGoodsMovementDate". * DeleteAllHandlingUnitsFromDelivery: unpack the delivery (delete all handling units).

Item actions (e.g. "PickOneItem", "ConfirmPickingOneItem") are called the same way with the parameter "DeliveryDocumentItem" - see change_outbound_delivery_status().

Attributes:

Name Type Description
needs_storage_location bool

Whether SAP rejects the action for items without a storage location ("[M7/018] Enter Location").

needs_storage_location property

needs_storage_location: bool

Whether SAP rejects the action for items without a storage location ("[M7/018] Enter Location").

SAP doesn't always determine the storage location when the delivery is created, see SAP.get_missing_outbound_delivery_storage_locations().

SAPInboundDeliveryAction

Bases: StrEnum

Status actions for inbound deliveries (function imports of API_INBOUND_DELIVERY_SRV).

Values (SAP function names) and their effect on the delivery: * PutawayAllItems: put away all items (putaway quantity = delivery quantity). * ConfirmPutawayAllItems: confirm the putaway of all items. * PostGoodsReceipt: post the goods receipt - increases the stock. * ReverseGoodsReceipt: reverse the goods receipt - needs the parameter "ActualGoodsMovementDate".

Item actions (e.g. "PutawayOneItem", "ConfirmPutawayOneItem") are called the same way with the parameter "DeliveryDocumentItem" - see change_inbound_delivery_status().

SAPGoodsMovementItemModel

Bases: SAPODataCreateModel

An item of a goods movement (material document item, API_MATERIAL_DOCUMENT_SRV).

The movement type defines the business transaction, e.g. 101 (goods receipt for a purchase order - with purchase order, item and reference document type "B"), 201 (goods issue to a cost center), 261 (goods issue to a production order), 311 (transfer posting between storage locations) or 412 with special stock "E" (transfer posting from the plant's own stock into the sales order stock of a make-to-order sales order item - 411 "E" moves it back; both need the receiving storage location, e.g. the same storage location).

The item fields SAP accepts are not in $metadata (no sap:creatable annotations) - SAP checks them at runtime per movement type, see check_allowed_fields().

Methods:

Name Description
check_sales_order_stock

Validate that sales order stock (special stock 'E') is given with its sales order item.

check_allowed_fields

Apply the item field rules of API_MATERIAL_DOCUMENT_SRV before the item is posted.

check_sales_order_stock

check_sales_order_stock() -> Self

Validate that sales order stock (special stock 'E') is given with its sales order item.

Transfer postings between own and sales order stock (411 / 412 'E') also need the receiving storage location - SAP rejects them without it ("[MM_IM_ODATA_API_MDOC/010] Property IssuingOrReceivingStorageLoc is mandatory").

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_sales_order_stock(self) -> Self:
    """Validate that sales order stock (special stock 'E') is given with its sales order item.

    Transfer postings between own and sales order stock (411 / 412 'E') also need the
    receiving storage location - SAP rejects them without it
    ("[MM_IM_ODATA_API_MDOC/010] Property IssuingOrReceivingStorageLoc is mandatory").

    """

    if (self.special_stock_type or "").upper() != "E":
        return self
    if not (self.sales_order_stock and self.sales_order_stock_item):
        message = (
            "Sales order stock (`special_stock_type` 'E') needs `sales_order_stock` and `sales_order_stock_item`"
        )
        raise ValueError(message)
    if self.movement_type in ("411", "412") and not self.receiving_storage_location:
        message = "Movement type {} 'E' needs the `receiving_storage_location`".format(self.movement_type)
        raise ValueError(message)

    return self

check_allowed_fields

check_allowed_fields() -> Self

Apply the item field rules of API_MATERIAL_DOCUMENT_SRV before the item is posted.

$metadata has no sap:creatable annotations for the item - SAP checks the fields at runtime (CL_MATERIAL_DOCUMENT_API->GET_RELEVANT_FIELDS / ITEM_CHECK_ALLOWED_FIELDS): a fixed set of always allowed fields, the field selection of the movement type (customizing MIGO_CUST_FIELDS) and fields that depend on the reference document type or on transfer movement types. The rules that do not depend on the customizing:

  • Purchase order and delivery properties need reference document type "B" - and "B" needs the purchase order and its item.
  • With a reference document ("B" purchase order, "F" production order) SAP takes the account assignment from the order and rejects the account assignment properties that are not in the field selection of the goods receipt (e.g. a cost center the LLM copied from the purchase order item) - they are dropped.
  • A goods receipt for an order is no transfer posting - receiving properties are rejected.

Errors are raised before the user is asked to confirm the posting.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_allowed_fields(self) -> Self:
    """Apply the item field rules of API_MATERIAL_DOCUMENT_SRV before the item is posted.

    $metadata has no sap:creatable annotations for the item - SAP checks the fields at
    runtime (CL_MATERIAL_DOCUMENT_API->GET_RELEVANT_FIELDS / ITEM_CHECK_ALLOWED_FIELDS):
    a fixed set of always allowed fields, the field selection of the movement type
    (customizing MIGO_CUST_FIELDS) and fields that depend on the reference document type
    or on transfer movement types. The rules that do not depend on the customizing:

    * Purchase order and delivery properties need reference document type "B" - and "B"
      needs the purchase order and its item.
    * With a reference document ("B" purchase order, "F" production order) SAP takes the
      account assignment from the order and rejects the account assignment properties
      that are not in the field selection of the goods receipt (e.g. a cost center the
      LLM copied from the purchase order item) - they are dropped.
    * A goods receipt for an order is no transfer posting - receiving properties are rejected.

    Errors are raised before the user is asked to confirm the posting.

    """

    properties = self.model_dump(by_alias=True, exclude_none=True)

    reference_document_type = (self.reference_document_type or "").upper()
    purchase_order_properties = [name for name in self.PURCHASE_ORDER_PROPERTIES if properties.get(name)]
    if purchase_order_properties and reference_document_type != "B":
        message = "{} need reference document type 'B' (GoodsMovementRefDocType)".format(purchase_order_properties)
        raise ValueError(message)
    if reference_document_type == "B" and not (self.purchase_order and self.purchase_order_item):
        message = "Reference document type 'B' needs `purchase_order` and `purchase_order_item`"
        raise ValueError(message)

    if reference_document_type not in ("B", "F"):
        return self

    receiving = [name for name in self.RECEIVING_PROPERTIES if properties.get(name)]
    if receiving:
        message = "A goods receipt for a purchase / production order is no transfer posting - remove {}".format(
            receiving
        )
        raise ValueError(message)

    # SAP derives the account assignment from the order - drop the ones the caller copied from it:
    for name in self.CUSTOMIZED_ACCOUNT_ASSIGNMENT_PROPERTIES:
        field_name = next((key for key, field in type(self).model_fields.items() if field.alias == name), None)
        if field_name:
            setattr(self, field_name, None)

    return self

SAPGoodsMovementModel

Bases: SAPODataCreateModel

Data to post a goods movement (material document, API_MATERIAL_DOCUMENT_SRV, OData V2).

The goods movement code defines the kind of posting: "01" goods receipt for a purchase order, "02" goods receipt for a production order, "03" goods issue, "04" transfer posting, "05" other goods receipts, "06" reversal of goods movements, "07" subsequent adjustment. The material document number is assigned by SAP.

See: https://api.sap.com/api/API_MATERIAL_DOCUMENT_SRV/overview

SAPGoodsMovementItemResponseModel

Bases: SAPODataModel

An item of a material document as returned by SAP (API_MATERIAL_DOCUMENT_SRV).

SAPGoodsMovementResponseModel

Bases: SAPODataModel

A material document (goods movement) as returned by SAP (API_MATERIAL_DOCUMENT_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPGoodsMovementItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPGoodsMovementQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP goods movements / material documents (API_MATERIAL_DOCUMENT_SRV).

Purchase orders, production orders, materials, plants and movement types are item properties - they are resolved via the material document items first (see SAP.iter_goods_movements()).

Methods:

Name Description
to_odata

Return the OData query options - the reference document also with leading zeros.

Attributes:

Name Type Description
has_item_criteria bool

Whether the query has criteria of the material document items (resolved via the items first).

has_item_criteria property

has_item_criteria: bool

Whether the query has criteria of the material document items (resolved via the items first).

to_odata

to_odata(odata_version: int) -> dict

Return the OData query options - the reference document also with leading zeros.

ReferenceDocument is a free text field without ALPHA conversion: the goods issue of an outbound delivery stores the delivery number with leading zeros ('0080000155'), so '80000155' alone finds nothing. The value as given is kept for delivery notes of suppliers.

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (2 or 4).

required

Returns:

Name Type Description
dict dict

The query options ($filter, $orderby, $expand).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self, odata_version: int) -> dict:
    """Return the OData query options - the reference document also with leading zeros.

    ReferenceDocument is a free text field without ALPHA conversion: the goods issue of an outbound
    delivery stores the delivery number with leading zeros ('0080000155'), so '80000155' alone finds
    nothing. The value as given is kept for delivery notes of suppliers.

    Args:
        odata_version (int):
            The OData version of the service (2 or 4).

    Returns:
        dict:
            The query options ($filter, $orderby, $expand).

    """

    params = super().to_odata(odata_version=odata_version)
    reference = (self.reference_document or "").strip()
    if reference:
        values = dict.fromkeys((reference, reference.zfill(10) if reference.isdigit() else reference))
        condition = " or ".join(
            "ReferenceDocument eq {}".format(odata_literal(value, odata_version=odata_version)) for value in values
        )
        condition = "({})".format(condition) if len(values) > 1 else condition
        params["$filter"] = "{} and {}".format(params["$filter"], condition) if "$filter" in params else condition

    return params

SAPGoodsMovementItemQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP material document items (API_MATERIAL_DOCUMENT_SRV, A_MaterialDocumentItem).

Used to find the material documents of purchase orders, production orders, materials, plants and movement types (see SAP.iter_goods_movements()).

SAPOutboundDeliveryStorageLocationModel

Bases: SAPODataModel

The storage location to set for an item of an outbound delivery.

SAPOutboundDeliveryStorageLocationProblemModel

Bases: SAPODataModel

An item of an outbound delivery whose storage location can't be determined.

SAPOutboundDeliveryStorageLocationsModel

Bases: SAPODataModel

The storage locations to set for the delivery items without one - and the items where that is not possible.

SAPWarrantyClaimCheckModel

Bases: SAPODataModel

What SAP would reject in a new warranty claim - found before the claim is created.

Attributes:

Name Type Description
errors bool

Whether the claim would be rejected.

errors property

errors: bool

Whether the claim would be rejected.

SAPInvoiceReferenceCheckModel

Bases: SAPODataModel

The invoices of a supplier with a given supplier invoice number, sorted by what they mean for a duplicate.

SAPPurchaseOrderHistoryModel

Bases: SAPODataModel

The goods receipts and supplier invoices of a purchase order (purchase order history).

Attributes:

Name Type Description
open_invoices list[SAPSupplierInvoiceResponseModel]

The invoices that have not been cancelled - in the order to cancel them (before the goods receipts).

open_goods_receipts list[SAPGoodsMovementItemResponseModel]

The goods receipt items that have not been cancelled.

open_invoices property

open_invoices: list[SAPSupplierInvoiceResponseModel]

The invoices that have not been cancelled - in the order to cancel them (before the goods receipts).

A reversed invoice has IsReversed, its reversal document has the reversed invoice in ReverseDocument.

open_goods_receipts property

open_goods_receipts: list[SAPGoodsMovementItemResponseModel]

The goods receipt items that have not been cancelled.

SAPSupplierInvoiceCompletionModel

Bases: SAPODataModel

What SAP.complete_supplier_invoice() found out while filling in an invoice.

SAPMaterialStockResponseModel

Bases: SAPODataModel

The stock of a material in one stock segment as returned by SAP (API_MATERIAL_STOCK_SRV, A_MatlStkInAcctMod).

A stock segment is the combination of plant, storage location, batch, stock type and special stock (e.g. consignment stock of a supplier or the stock of a sales order). SAP keeps segments with a quantity of 0 (e.g. after the stock has been issued) - see SAPMaterialStockQueryModel.include_zero.

Methods:

Name Description
check_initial_numbers

SAP returns '0' / '000...0' for stock without WBS element or sales order item - read it as None.

Attributes:

Name Type Description
stock_type_name str | None

Return the name of the stock type, e.g. 'Blocked Stock'.

stock_type_name property

stock_type_name: str | None

Return the name of the stock type, e.g. 'Blocked Stock'.

check_initial_numbers classmethod

check_initial_numbers(value: str | None) -> str | None

SAP returns '0' / '000...0' for stock without WBS element or sales order item - read it as None.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@field_validator("wbs_element_internal_id", "sales_order_item", mode="before")
@classmethod
def check_initial_numbers(cls, value: str | None) -> str | None:
    """SAP returns '0' / '000...0' for stock without WBS element or sales order item - read it as None."""

    return value if value and value.strip("0") else None

SAPMaterialStockQueryModel

Bases: SAPODataQueryModel

Search criteria for the SAP material stock (API_MATERIAL_STOCK_SRV, A_MatlStkInAcctMod).

Methods:

Name Description
to_odata

Return the OData query options - without the segments of quantity 0 unless include_zero is set.

to_odata

to_odata(odata_version: int) -> dict

Return the OData query options - without the segments of quantity 0 unless include_zero is set.

The segments without stock are filtered by SAP, so that the limit and the paging only count segments with stock (in S/4HANA most segments of a plant can have a quantity of 0).

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (2 or 4).

required

Returns:

Name Type Description
dict dict

The query options ($filter, $orderby).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self, odata_version: int) -> dict:
    """Return the OData query options - without the segments of quantity 0 unless include_zero is set.

    The segments without stock are filtered by SAP, so that the limit and the paging only count
    segments with stock (in S/4HANA most segments of a plant can have a quantity of 0).

    Args:
        odata_version (int):
            The OData version of the service (2 or 4).

    Returns:
        dict:
            The query options ($filter, $orderby).

    """

    params = super().to_odata(odata_version=odata_version)
    if not self.include_zero:
        condition = "MatlWrhsStkQtyInMatlBaseUnit ne {}".format("0M" if odata_version == 2 else "0")
        params["$filter"] = "{} and {}".format(params["$filter"], condition) if "$filter" in params else condition

    return params

SAPMaintenanceOrderConfirmationModel

Bases: SAPODataCreateModel

Data to confirm work on a maintenance order operation (API_MAINTORDERCONFIRMATION, OData V2).

The confirmation number is assigned by SAP. A final confirmation (is_final=True) completes the operation.

SAPMaintenanceOrderConfirmationResponseModel

Bases: SAPODataModel

A maintenance order confirmation as returned by SAP (API_MAINTORDERCONFIRMATION, OData V2).

SAPMaintenanceOrderConfirmationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP maintenance order confirmations (API_MAINTORDERCONFIRMATION).

SAPMaintenancePlanCycleModel

Bases: SAPODataCreateModel

A cycle of a maintenance plan, e.g. every 3 months or every 500 operating hours.

SAPMaintenancePlanItemModel

Bases: SAPODataCreateModel

A maintenance item of a maintenance plan - the object to maintain and how (task list, order type).

SAPMaintenancePlanModel

Bases: SAPODataCreateModel

Data to create an SAP maintenance plan (API_MAINTENANCEPLAN, OData V2).

A single cycle plan has one or more cycles; a strategy plan references a maintenance strategy instead. The plan number is assigned by SAP. After the creation, scheduling has to be started (see change_maintenance_plan_status()).

Methods:

Name Description
check_item_categories

Fill in the plan category for the items and check that plan and items have the same category.

check_scheduling_duration_unit

Validate that single cycle plans have a unit for the scheduling period (SAP rejects them with IP/131).

check_item_categories

check_item_categories() -> Self

Fill in the plan category for the items and check that plan and items have the same category.

SAP requires the category for each item and only assigns items of the plan's category.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_item_categories(self) -> Self:
    """Fill in the plan category for the items and check that plan and items have the same category.

    SAP requires the category for each item and only assigns items of the plan's category.

    """

    if not self.items:
        return self

    self.category = self.category or next((item.category for item in self.items if item.category), None)
    if not self.category:
        message = "The maintenance plan needs a category, e.g. 'PM'"
        raise ValueError(message)
    for item in self.items:
        item.category = item.category or self.category
    categories = {self.category} | {item.category for item in self.items}
    if len(categories) > 1:
        message = "Maintenance plan and items must have the same category, got -> {}".format(sorted(categories))
        raise ValueError(message)

    return self

check_scheduling_duration_unit

check_scheduling_duration_unit() -> Self

Validate that single cycle plans have a unit for the scheduling period (SAP rejects them with IP/131).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_scheduling_duration_unit(self) -> Self:
    """Validate that single cycle plans have a unit for the scheduling period (SAP rejects them with IP/131)."""

    if self.cycles and not self.scheduling_duration_unit:
        message = (
            "Single cycle plans need a `scheduling_duration_unit` (time unit of the scheduling period), e.g. 'MON'"
        )
        raise ValueError(message)

    return self

SAPMaintenancePlanCycleResponseModel

Bases: SAPODataModel

A cycle of a maintenance plan as returned by SAP (API_MAINTENANCEPLAN).

SAPMaintenancePlanItemResponseModel

Bases: SAPODataModel

A maintenance item of a maintenance plan as returned by SAP (API_MAINTENANCEPLAN).

SAPMaintenancePlanResponseModel

Bases: SAPODataModel

A maintenance plan as returned by SAP (API_MAINTENANCEPLAN, OData V2).

Attributes:

Name Type Description
cycles / items

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPMaintenancePlanQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP maintenance plans (API_MAINTENANCEPLAN).

Methods:

Name Description
accepts

Check the deletion flag (system status I0076) - SAP can't filter by the system status (HTTP 501).

Attributes:

Name Type Description
has_item_criteria bool

Whether the query has criteria of the maintenance items (resolved via the items first).

has_item_criteria property

has_item_criteria: bool

Whether the query has criteria of the maintenance items (resolved via the items first).

accepts

accepts(entity: BaseModel) -> bool

Check the deletion flag (system status I0076) - SAP can't filter by the system status (HTTP 501).

Parameters:

Name Type Description Default
entity BaseModel

The maintenance plan read (SAPMaintenancePlanResponseModel).

required

Returns:

Name Type Description
bool bool

True if the plan matches is_marked_for_deletion (or the criterion isn't set).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def accepts(self, entity: BaseModel) -> bool:
    """Check the deletion flag (system status I0076) - SAP can't filter by the system status (HTTP 501).

    Args:
        entity (BaseModel):
            The maintenance plan read (SAPMaintenancePlanResponseModel).

    Returns:
        bool:
            True if the plan matches is_marked_for_deletion (or the criterion isn't set).

    """

    if self.is_marked_for_deletion is None:
        return True

    plan = cast("SAPMaintenancePlanResponseModel", entity)

    return ("I0076" in (plan.system_status or "").split()) == self.is_marked_for_deletion

SAPMaintenancePlanItemQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP maintenance items (API_MAINTENANCEPLAN, MaintenanceItem).

Used to find the maintenance plans of planning plants, functional locations and equipments (see SAP.iter_maintenance_plans()).

SAPTaskListOperationMaterialModel

Bases: SAPODataCreateModel

A material (component) needed by an operation of a new task list - e.g. a spare part.

SAP allocates the material to the operation via an item of a plant maintenance BOM: the BOM of the assembly of a general task list or of the equipment / functional location (or its construction type). The material must be an item of this BOM.

SAPTaskListOperationModel

Bases: SAPODataCreateModel

An operation of an SAP maintenance task list (API_MAINTENANCETASKLIST, OData V4).

Methods:

Name Description
check_units

Validate that work and duration have a unit (OData V4 rejects quantities without their unit).

check_units

check_units() -> Self

Validate that work and duration have a unit (OData V4 rejects quantities without their unit).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_units(self) -> Self:
    """Validate that work and duration have a unit (OData V4 rejects quantities without their unit)."""

    if self.work is not None and not self.work_unit:
        message = "Operation -> {} has `work` but no `work_unit`, e.g. 'H'".format(self.operation)
        raise ValueError(message)
    if self.duration is not None and not self.duration_unit:
        message = "Operation -> {} has a `duration` but no `duration_unit`, e.g. 'H'".format(self.operation)
        raise ValueError(message)

    return self

SAPTaskListModel

Bases: SAPODataCreateModel

Data to create an SAP maintenance task list (API_MAINTENANCETASKLIST, OData V4).

A task list describes the work (operations) of a maintenance task. It can be referenced by maintenance plan items and maintenance orders. There are three types: general task lists ('A', not bound to an object), equipment task lists ('E', need equipment) and functional location task lists ('T', need functional_location). The task list group is assigned by SAP unless it is given.

A general task list with an assembly (a material, e.g. the construction type of equipment) applies to all equipment of this type. The materials of its operations (e.g. spare parts) are allocated via the plant maintenance BOM of the assembly - they can only be created together with the task list (not added later).

See: https://api.sap.com/api/OP_API_MAINTENANCETASKLIST_0001/overview

Methods:

Name Description
check_technical_object

Validate that equipment and functional location task lists have their technical object.

assign_operation_keys

Set the task list type and operation number in operations with materials and their materials.

check_technical_object

check_technical_object() -> Self

Validate that equipment and functional location task lists have their technical object.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_technical_object(self) -> Self:
    """Validate that equipment and functional location task lists have their technical object."""

    if self.task_list_type == "E" and not self.equipment:
        message = "Equipment task lists (type 'E') need an equipment"
        raise ValueError(message)
    if self.task_list_type == "T" and not self.functional_location:
        message = "Functional location task lists (type 'T') need a functional location"
        raise ValueError(message)
    self.assign_operation_keys()

    # The materials are allocated via the BOM of the assembly - a general task list has no other object:
    if (
        self.task_list_type == "A"
        and not self.assembly
        and any(operation.materials for operation in self.operations)
    ):
        message = (
            "General task lists (type 'A') with materials in their operations need an assembly - the material "
            "whose plant maintenance BOM contains them"
        )
        raise ValueError(message)

    return self

assign_operation_keys

assign_operation_keys() -> None

Set the task list type and operation number in operations with materials and their materials.

SAP needs them to allocate the materials in the deep create of the task list.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def assign_operation_keys(self) -> None:
    """Set the task list type and operation number in operations with materials and their materials.

    SAP needs them to allocate the materials in the deep create of the task list.

    """

    for operation in self.operations:
        if not operation.materials:
            continue
        operation.task_list_type = self.task_list_type
        for material in operation.materials:
            material.task_list_type = self.task_list_type
            material.operation = operation.operation

SAPTaskListOperationMaterialResponseModel

Bases: SAPODataModel

A material (component) of a task list operation as returned by SAP (API_MAINTENANCETASKLIST, OData V4).

SAPTaskListOperationResponseModel

Bases: SAPODataModel

An operation of a maintenance task list as returned by SAP (API_MAINTENANCETASKLIST).

SAPTaskListResponseModel

Bases: SAPODataModel

A maintenance task list as returned by SAP (API_MAINTENANCETASKLIST, OData V4).

A task list is identified by its type, group and group counter. With change numbers it can have several versions (TaskListVersionCounter).

Attributes:

Name Type Description
operations list[SAPTaskListOperationResponseModel] | None

None if the operations have not been requested ($expand), otherwise a (possibly empty) list.

SAPTaskListQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP maintenance task lists (API_MAINTENANCETASKLIST, OData V4).

SAPPlannedOrderModel

Bases: SAPODataCreateModel

Data to create an SAP planned order (API_PLANNEDORDER, OData V4).

Components and capacities are determined by SAP (bill of material and routing / production version). A planned order can be converted into a production order (see SAP.convert_planned_order()). The planned order number is assigned by SAP.

Methods:

Name Description
check_dates

Validate the dates and default the MRP area to the MRP plant.

check_dates

check_dates() -> Self

Validate the dates and default the MRP area to the MRP plant.

Without an explicit MRP area SAP rejects the procurement category ("MRP area E has not been defined").

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Validate the dates and default the MRP area to the MRP plant.

    Without an explicit MRP area SAP rejects the procurement category ("MRP area E has not
    been defined").

    """

    self.mrp_area = self.mrp_area or self.mrp_plant
    if not self.start_date and not self.end_date:
        message = "Give an `end_date` and/or a `start_date` - SAP schedules the planned order from them"
        raise ValueError(message)
    if self.start_date and self.end_date and self.end_date < self.start_date:
        message = "Planned end date -> {} is before planned start date -> {}".format(
            self.end_date,
            self.start_date,
        )
        raise ValueError(message)

    return self

SAPPlannedOrderComponentModel

Bases: SAPODataCreateModel

The changeable fields of a component of an SAP planned order (API_PLANNEDORDER, PlannedOrderComponent).

Only used to validate component changes (see SAP.update_planned_order()) - components are created by SAP from the bill of material.

SAPPlannedOrderResponseModel

Bases: SAPODataModel

A planned order as returned by SAP (API_PLANNEDORDER, OData V4).

Components and capacities are not modelled - they are available in model_extra if requested with $expand.

SAPPlannedOrderQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP planned orders (API_PLANNEDORDER, OData V4).

SAPProductionOrderModel

Bases: SAPODataCreateModel

Data to create an SAP production order (API_PRODUCTION_ORDER_2_SRV, OData V2).

Creates the header of a production order - operations and components are determined by SAP (routing / production version and bill of material). The production order number is assigned by SAP.

Methods:

Name Description
check_dates

Validate the planned dates and derive the scheduling type.

check_sales_order

Validate that a sales order is given together with its item.

check_dates

check_dates() -> Self

Validate the planned dates and derive the scheduling type.

SAP schedules forwards from the start date or backwards from the end date. Without a scheduling type it uses the default of the order type (e.g. backwards for PP01), which fails if only the start date is given ("CO/028 Backward scheduling (enter finish date)").

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_dates(self) -> Self:
    """Validate the planned dates and derive the scheduling type.

    SAP schedules forwards from the start date or backwards from the end date. Without a
    scheduling type it uses the default of the order type (e.g. backwards for PP01), which
    fails if only the start date is given ("CO/028 Backward scheduling (enter finish date)").

    """

    if not self.planned_start_date and not self.planned_end_date:
        message = "Give a `planned_end_date` (backward scheduling) or a `planned_start_date` (forward scheduling)"
        raise ValueError(message)
    if not self.scheduling_type:
        self.scheduling_type = "2" if self.planned_end_date else "1"
    if self.scheduling_type == "1" and not self.planned_start_date:
        message = "Forward scheduling (`scheduling_type` '1') needs a `planned_start_date`"
        raise ValueError(message)
    if self.scheduling_type == "2" and not self.planned_end_date:
        message = "Backward scheduling (`scheduling_type` '2') needs a `planned_end_date`"
        raise ValueError(message)
    if self.planned_start_date and self.planned_end_date and self.planned_end_date < self.planned_start_date:
        message = "Planned end date -> {} is before planned start date -> {}".format(
            self.planned_end_date,
            self.planned_start_date,
        )
        raise ValueError(message)

    return self

check_sales_order

check_sales_order() -> Self

Validate that a sales order is given together with its item.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_sales_order(self) -> Self:
    """Validate that a sales order is given together with its item."""

    if bool(self.sales_order) != bool(self.sales_order_item):
        message = "Give the `sales_order` together with its `sales_order_item` (make-to-order production)"
        raise ValueError(message)

    return self

SAPProductionOrderOperationModel

Bases: SAPODataCreateModel

The changeable fields of an operation of an SAP production order (API_PRODUCTION_ORDER_2_SRV).

Only used to validate operation changes (see SAP.update_production_order()) - operations are created by SAP from the routing.

SAPProductionOrderOperationResponseModel

Bases: SAPODataModel

An operation of a production order as returned by SAP (API_PRODUCTION_ORDER_2_SRV).

SAPProductionOrderStatusResponseModel

Bases: SAPODataModel

An active status of a production order as returned by SAP (API_PRODUCTION_ORDER_2_SRV).

SAPProductionOrderResponseModel

Bases: SAPODataModel

A production order as returned by SAP (API_PRODUCTION_ORDER_2_SRV, OData V2).

Attributes:

Name Type Description
operations / statuses

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPProductionOrderQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP production orders (API_PRODUCTION_ORDER_2_SRV).

SAPPlantResponseModel

Bases: SAPODataModel

A plant as returned by SAP (API_PLANT_2, OData V4).

SAPPlantQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP plants (API_PLANT_2, OData V4).

SAPStorageLocationResponseModel

Bases: SAPODataModel

A storage location of a plant as returned by SAP (API_STORAGELOCATION_SRV, OData V2).

SAPStorageLocationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP storage locations (API_STORAGELOCATION_SRV).

SAPProductDescriptionModel

Bases: SAPODataCreateModel

A (language dependent) description of a new product.

SAPProductStorageLocationModel

Bases: SAPODataCreateModel

The storage location data of a product in a plant (extends the product to a storage location).

SAPProductPlantModel

Bases: SAPODataCreateModel

The plant specific data of a product (extends the product to a plant) - with its storage locations.

Methods:

Name Description
check_storage_locations

Fill in the plant for the storage locations.

assign_product_id

Set the product number of the plant data and its storage locations (needed with an external number).

check_storage_locations

check_storage_locations() -> Self

Fill in the plant for the storage locations.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_storage_locations(self) -> Self:
    """Fill in the plant for the storage locations."""

    self.assign_product_id(self.product_id)

    return self

assign_product_id

assign_product_id(product_id: str | None) -> None

Set the product number of the plant data and its storage locations (needed with an external number).

Parameters:

Name Type Description Default
product_id str | None

The product number.

required
Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def assign_product_id(self, product_id: str | None) -> None:
    """Set the product number of the plant data and its storage locations (needed with an external number).

    Args:
        product_id (str | None):
            The product number.

    """

    self.product_id = self.product_id or product_id
    for storage_location in self.storage_locations:
        storage_location.product_id = storage_location.product_id or self.product_id
        storage_location.plant = storage_location.plant or self.plant

SAPProductValuationModel

Bases: SAPODataCreateModel

The valuation data of a product in a valuation area (usually a plant) - needed for stock postings.

Methods:

Name Description
check_price

Check that the price of the price control is given.

check_price

check_price() -> Self

Check that the price of the price control is given.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_price(self) -> Self:
    """Check that the price of the price control is given."""

    if self.price_control == "S" and self.standard_price is None:
        message = "Price control 'S' needs a standard price (StandardPrice)"
        raise ValueError(message)
    if self.price_control == "V" and self.moving_average_price is None:
        message = "Price control 'V' needs a moving average price (MovingAveragePrice)"
        raise ValueError(message)

    return self

SAPProductExtensionModel

Bases: SAPODataModel

What is missing to extend an SAP product to a plant, storage locations and valuation area.

Attributes:

Name Type Description
is_complete bool

Whether the product is already extended as requested - nothing to do.

is_complete property

is_complete: bool

Whether the product is already extended as requested - nothing to do.

SAPProductModel

Bases: SAPODataCreateModel

Data to create an SAP product / material (API_PRODUCT_SRV, OData V2).

The product number is assigned by SAP unless it is given (external number assignment - depends on the customizing of the product type). Descriptions, plant data (with storage locations) and valuation data are created together with the product (deep insert) - existing products are extended with SAP.create_product_plant(), create_product_storage_location() and create_product_valuation().

See: https://api.sap.com/api/API_PRODUCT_SRV/overview

Methods:

Name Description
check_product_ids

Fill in the product number for the descriptions, plants and valuations (needed with an external number).

check_batch_management

Set batch management on the product and its plants - SAP needs it on both levels.

check_product_ids

check_product_ids() -> Self

Fill in the product number for the descriptions, plants and valuations (needed with an external number).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_product_ids(self) -> Self:
    """Fill in the product number for the descriptions, plants and valuations (needed with an external number)."""

    for child in [*self.descriptions, *self.plants, *self.valuations]:
        child.product_id = child.product_id or self.product_id
        if child.product_id != self.product_id:
            message = "The descriptions, plants and valuations must belong to product -> '{}', got -> '{}'".format(
                self.product_id, child.product_id
            )
            raise ValueError(message)
    for plant in self.plants:
        plant.assign_product_id(self.product_id)

    return self

check_batch_management

check_batch_management() -> Self

Set batch management on the product and its plants - SAP needs it on both levels.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_batch_management(self) -> Self:
    """Set batch management on the product and its plants - SAP needs it on both levels."""

    if self.is_batch_managed is None and any(plant.is_batch_managed for plant in self.plants):
        self.is_batch_managed = True
    for plant in self.plants:
        if plant.is_batch_managed is None:
            plant.is_batch_managed = self.is_batch_managed

    return self

SAPProductDescriptionResponseModel

Bases: SAPODataModel

A (language dependent) description of a product as returned by SAP (API_PRODUCT_SRV).

SAPProductStorageLocationResponseModel

Bases: SAPODataModel

The storage location data of a product as returned by SAP (API_PRODUCT_SRV).

SAPProductValuationResponseModel

Bases: SAPODataModel

The valuation data of a product in a valuation area as returned by SAP (API_PRODUCT_SRV).

SAPProductPlantResponseModel

Bases: SAPODataModel

The plant specific data of a product as returned by SAP (API_PRODUCT_SRV).

Provides plant dependent defaults for documents, e.g. the MRP controller for planned / production orders or the purchasing group for purchasing documents.

SAPProductResponseModel

Bases: SAPODataModel

A product (material) as returned by SAP (API_PRODUCT_SRV, OData V2).

Attributes:

Name Type Description
descriptions / plants (with their storage locations) / valuations

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPProductQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP products / materials (API_PRODUCT_SRV).

SAPMaterialBOMItemModel

Bases: SAPODataCreateModel

An item (component) of a new material BOM.

SAPMaterialBOMModel

Bases: SAPODataCreateModel

Data to create a material BOM (bill of material) of a product in a plant (API_BILL_OF_MATERIAL_SRV, V2).

The BOM lists the components of the product. With the usage '4' (plant maintenance) it is the spare parts list of all equipment with this product as construction type (see SAPEquipmentModel.construction_material). The items are created together with the BOM (deep insert).

See: https://api.sap.com/api/API_BILL_OF_MATERIAL_SRV_0002/overview

Methods:

Name Description
number_items

Assign the item numbers 0010, 0020, ... to the items without one (after the highest given number).

number_items classmethod

number_items(data: object) -> object

Assign the item numbers 0010, 0020, ... to the items without one (after the highest given number).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="before")
@classmethod
def number_items(cls, data: object) -> object:
    """Assign the item numbers 0010, 0020, ... to the items without one (after the highest given number)."""

    if not isinstance(data, dict):
        return data

    key = "to_BillOfMaterialItem" if "to_BillOfMaterialItem" in data else "items"
    items = data.get(key)
    if not isinstance(items, list):
        return data

    def given_number(item: object) -> int | None:
        if isinstance(item, dict):
            number = item.get("BillOfMaterialItemNumber", item.get("item_number"))
        else:
            number = getattr(item, "item_number", None)
        return int(number) if number not in (None, "") and str(number).strip().isdigit() else None

    next_number = max((number for item in items if (number := given_number(item)) is not None), default=0)
    numbered = []
    for item in items:
        if isinstance(item, dict) and given_number(item) is None:
            next_number += 10
            item = {**item, "BillOfMaterialItemNumber": str(next_number)}
        numbered.append(item)

    return {**data, key: numbered}

SAPMaterialBOMItemResponseModel

Bases: SAPODataModel

An item (component) of a material BOM as returned by SAP (API_BILL_OF_MATERIAL_SRV).

SAPMaterialBOMResponseModel

Bases: SAPODataModel

A material BOM as returned by SAP (API_BILL_OF_MATERIAL_SRV, OData V2).

Attributes:

Name Type Description
items list[SAPMaterialBOMItemResponseModel] | None

None if the items have not been requested ($expand), otherwise a (possibly empty) list.

SAPMaterialBOMQueryModel

Bases: SAPODataQueryModel

Search criteria for material BOMs (API_BILL_OF_MATERIAL_SRV).

SAPProductionVersionResponseModel

Bases: SAPODataModel

A production version (BOM + routing for a material in a plant) as returned by SAP (API_PRODUCTION_VERSION, OData V4).

SAPProductionVersionQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP production versions (API_PRODUCTION_VERSION, OData V4).

SAPWorkCenterResponseModel

Bases: SAPODataModel

A work center as returned by SAP (API_WORK_CENTERS, OData V2).

The key is the internal ID plus type - the work center code (e.g. "1904") is only unique within a plant.

SAPWorkCenterQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP work centers (API_WORK_CENTERS).

SAPEquipmentModel

Bases: SAPODataCreateModel

Data to create an SAP equipment (API_EQUIPMENT, OData V2).

The equipment number is assigned by SAP unless it is given (external number assignment - depends on the customizing of the equipment category). The construction type (construction_material) connects the equipment to the material it is built from - the plant maintenance BOM of this material is the spare parts list of the equipment. Serialized equipment is an individual unit of a material (material + serial_number).

See: https://api.sap.com/api/API_EQUIPMENT/overview

Methods:

Name Description
check_serial_number

Check that a serial number comes with its material (serialized equipment).

check_serial_number

check_serial_number() -> Self

Check that a serial number comes with its material (serialized equipment).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_serial_number(self) -> Self:
    """Check that a serial number comes with its material (serialized equipment)."""

    if self.serial_number and not self.material:
        message = "A serial number needs the material of the serialized equipment (Material)"
        raise ValueError(message)

    return self

SAPEquipmentResponseModel

Bases: SAPODataModel

An equipment (technical object) as returned by SAP (API_EQUIPMENT, OData V2).

Equipment data is time dependent - the key includes the end of the validity period.

SAPEquipmentQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP equipment (API_EQUIPMENT).

SAPFunctionalLocationModel

Bases: SAPODataCreateModel

Data to create an SAP functional location (API_FUNCTIONALLOCATION, OData V2).

The functional location is identified by its label (e.g. "1010-PU-01"), which has to match the edit mask of the structure indicator. SAP derives the superior functional location from the label (the label of the superior is its prefix) unless superior_label is given.

See: https://api.sap.com/api/API_FUNCTIONALLOCATION/overview

SAPFunctionalLocationResponseModel

Bases: SAPODataModel

A functional location (technical object) as returned by SAP (API_FUNCTIONALLOCATION, OData V2).

The key is the internal ID - the label (e.g. "C1-B01-1") is the identifier shown in the UI.

SAPFunctionalLocationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP functional locations (API_FUNCTIONALLOCATION).

SAPBusinessPartnerAddressModel

Bases: SAPODataCreateModel

An address of a new business partner.

SAPBusinessPartnerRoleModel

Bases: SAPODataCreateModel

A role of a new business partner.

SAPSupplierPurchasingOrgModel

Bases: SAPODataCreateModel

The purchasing organization data of a new supplier - needed to order from the supplier (role FLVN01).

SAPSupplierCompanyModel

Bases: SAPODataCreateModel

The company code data of a new supplier - needed to post its invoices and pay it (role FLVN00).

SAPSupplierModel

Bases: SAPODataCreateModel

The supplier data of a new business partner - created together with the business partner.

SAP creates the supplier itself for the role FLVN00 - this model adds its purchasing organization and company code data. The supplier number is assigned by SAP and can differ from the business partner number (depending on the customizing of the grouping).

SAPCustomerSalesAreaTaxModel

Bases: SAPODataCreateModel

The tax classification of a new customer in a sales area - used to determine the output tax in sales.

SAPCustomerSalesAreaModel

Bases: SAPODataCreateModel

The sales area data of a new customer - needed to sell to the customer (role FLCU01).

SAPCustomerCompanyModel

Bases: SAPODataCreateModel

The company code data of a new customer - needed to post its invoices and payments (role FLCU00).

SAPCustomerModel

Bases: SAPODataCreateModel

The customer data of a new business partner - created together with the business partner.

SAP creates the customer itself for the role FLCU00 - this model adds its sales area and company code data. The customer number is assigned by SAP and can differ from the business partner number (depending on the customizing of the grouping). The partner functions of a sales area (sold-to, ship-to, bill-to, payer) are not given - SAP determines them.

SAPBusinessPartnerModel

Bases: SAPODataCreateModel

Data to create an SAP business partner - an organization (API_BUSINESS_PARTNER, OData V2).

Addresses, roles and the supplier / customer data are created together with the business partner (deep insert). With a supplier or customer role SAP also creates the supplier / customer - its number can differ from the business partner number (depending on the customizing of the grouping). Typical roles:

  • FLVN00: supplier - general and company code data (enough for the manufacturer of a product)
  • FLVN01: supplier - purchasing data (in addition to FLVN00 to order from the supplier)
  • FLCU00: customer - general and company code data
  • FLCU01: customer - sales data (in addition to FLCU00 to sell to the customer)

Business partners cannot be deleted with the API.

See: https://api.sap.com/api/API_BUSINESS_PARTNER/overview

Methods:

Name Description
check_business_partner_ids

Fill in the business partner number for the addresses and roles (needed with an external number).

check_address

Check that a supplier or customer has an address (SAP needs its country).

check_supplier_roles

Check that the supplier data comes with the supplier roles it needs (FLVN00 / FLVN01).

check_customer_roles

Check that the customer data comes with the customer roles it needs (FLCU00 / FLCU01).

check_business_partner_ids

check_business_partner_ids() -> Self

Fill in the business partner number for the addresses and roles (needed with an external number).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_business_partner_ids(self) -> Self:
    """Fill in the business partner number for the addresses and roles (needed with an external number)."""

    for child in [*self.addresses, *self.roles]:
        child.business_partner_id = child.business_partner_id or self.business_partner_id
        if child.business_partner_id != self.business_partner_id:
            message = "The addresses and roles must belong to business partner -> '{}', got -> '{}'".format(
                self.business_partner_id, child.business_partner_id
            )
            raise ValueError(message)

    return self

check_address

check_address() -> Self

Check that a supplier or customer has an address (SAP needs its country).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_address(self) -> Self:
    """Check that a supplier or customer has an address (SAP needs its country)."""

    if not self.addresses and any(role.role.startswith(("FLVN", "FLCU")) for role in self.roles):
        message = "A business partner with a supplier or customer role needs an address (at least the country)"
        raise ValueError(message)

    return self

check_supplier_roles

check_supplier_roles() -> Self

Check that the supplier data comes with the supplier roles it needs (FLVN00 / FLVN01).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_supplier_roles(self) -> Self:
    """Check that the supplier data comes with the supplier roles it needs (FLVN00 / FLVN01)."""

    if not self.supplier:
        return self

    roles = {role.role for role in self.roles}
    if "FLVN00" not in roles:
        message = "Supplier data needs the business partner role FLVN00 (supplier)"
        raise ValueError(message)
    if self.supplier.purchasing_organizations and "FLVN01" not in roles:
        message = "Purchasing organization data needs the business partner role FLVN01 (supplier - purchasing)"
        raise ValueError(message)

    return self

check_customer_roles

check_customer_roles() -> Self

Check that the customer data comes with the customer roles it needs (FLCU00 / FLCU01).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
@model_validator(mode="after")
def check_customer_roles(self) -> Self:
    """Check that the customer data comes with the customer roles it needs (FLCU00 / FLCU01)."""

    if not self.customer:
        return self

    roles = {role.role for role in self.roles}
    if "FLCU00" not in roles:
        message = "Customer data needs the business partner role FLCU00 (customer)"
        raise ValueError(message)
    if self.customer.sales_areas and "FLCU01" not in roles:
        message = "Sales area data needs the business partner role FLCU01 (customer - sales)"
        raise ValueError(message)

    return self

SAPBusinessPartnerAddressResponseModel

Bases: SAPODataModel

An address of a business partner as returned by SAP (API_BUSINESS_PARTNER).

SAPSupplierPurchasingOrgResponseModel

Bases: SAPODataModel

The purchasing organization data of a supplier as returned by SAP (API_BUSINESS_PARTNER).

SAPSupplierCompanyResponseModel

Bases: SAPODataModel

The company code data of a supplier as returned by SAP (API_BUSINESS_PARTNER).

SAPSupplierResponseModel

Bases: SAPODataModel

The supplier data of a business partner as returned by SAP (API_BUSINESS_PARTNER).

Attributes:

Name Type Description
purchasing_organizations / company_codes

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPCustomerSalesAreaTaxResponseModel

Bases: SAPODataModel

The tax classification of a customer in a sales area as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerPartnerFunctionResponseModel

Bases: SAPODataModel

A partner function of a customer in a sales area as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerSalesAreaResponseModel

Bases: SAPODataModel

The sales area data of a customer as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerCompanyResponseModel

Bases: SAPODataModel

The company code data of a customer as returned by SAP (API_BUSINESS_PARTNER).

SAPCustomerResponseModel

Bases: SAPODataModel

The customer data of a business partner as returned by SAP (API_BUSINESS_PARTNER).

Attributes:

Name Type Description
sales_areas / company_codes

None if they have not been requested ($expand), otherwise a (possibly empty) list.

SAPBusinessPartnerRoleResponseModel

Bases: SAPODataModel

A role of a business partner (e.g. FLVN00 supplier, FLCU00 customer) as returned by SAP (API_BUSINESS_PARTNER).

SAPBusinessPartnerResponseModel

Bases: SAPODataModel

A business partner (person or organization) as returned by SAP (API_BUSINESS_PARTNER, OData V2).

Suppliers and customers are business partners - 'supplier' / 'customer' contain the supplier / customer numbers used in documents.

Attributes:

Name Type Description
roles list[SAPBusinessPartnerRoleResponseModel] | None

None if the roles have not been requested ($expand), otherwise a (possibly empty) list.

SAPBusinessPartnerQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP business partners (API_BUSINESS_PARTNER).

SAPBusinessPartnerIdentificationResponseModel

Bases: SAPODataModel

An identification of a business partner (e.g. type HCM001 = personnel number) as returned by SAP.

SAPPersonEmailAddressResponseModel

Bases: SAPODataModel

An e-mail address of a person as returned by SAP (API_BUSINESS_PARTNER).

SAPPersonPhoneNumberResponseModel

Bases: SAPODataModel

A phone number of a person as returned by SAP (API_BUSINESS_PARTNER).

SAPPersonAddressResponseModel

Bases: SAPODataModel

An address of a person as returned by SAP (API_BUSINESS_PARTNER) - with e-mail addresses and phone numbers.

SAPPersonResponseModel

Bases: SAPODataModel

A person with a personnel number as returned by SAP (API_BUSINESS_PARTNER, OData V2).

The personnel number is what SAP stores as the person responsible of a maintenance order (see SAPMaintenanceOrderModel.person_responsible). The persons are HR master data - they are independent of the SAP users. The contact data (e-mail, phone, address) is only filled if requested (expand_items).

Attributes:

Name Type Description
personnel_number str | None

Get the personnel number (identification type HCM001) of the person.

email str | None

Get the default e-mail address of the person (from the first address that has one).

phone str | None

Get the default phone number of the person (from the first address that has one).

city str | None

Get the city of the first address of the person.

country str | None

Get the country of the first address of the person.

personnel_number property

personnel_number: str | None

Get the personnel number (identification type HCM001) of the person.

email property

email: str | None

Get the default e-mail address of the person (from the first address that has one).

phone property

phone: str | None

Get the default phone number of the person (from the first address that has one).

city property

city: str | None

Get the city of the first address of the person.

country property

country: str | None

Get the country of the first address of the person.

SAPPersonQueryModel

Bases: SAPODataQueryModel

Search criteria for persons with a personnel number (API_BUSINESS_PARTNER).

Methods:

Name Description
to_odata

Return the OData query options - the identifications are always expanded (they hold the personnel number).

to_odata_conditions

Return the conditions - and the name conditions: SAP searches case-sensitively, so the common spellings are searched.

accepts

Check that the business partner has a personnel number - SAP can't filter by the identifications (V2).

to_odata

to_odata(odata_version: int) -> dict

Return the OData query options - the identifications are always expanded (they hold the personnel number).

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (2 or 4).

required

Returns:

Name Type Description
dict dict

The query options ($filter, $orderby, $expand).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata(self, odata_version: int) -> dict:
    """Return the OData query options - the identifications are always expanded (they hold the personnel number).

    Args:
        odata_version (int):
            The OData version of the service (2 or 4).

    Returns:
        dict:
            The query options ($filter, $orderby, $expand).

    """

    params = super().to_odata(odata_version=odata_version)
    params["$expand"] = self.EXPAND if self.expand_items else "to_BuPaIdentification"

    return params

to_odata_conditions

to_odata_conditions(
    odata_version: int,
    navigation: str = "",
    exclude: tuple[str, ...] = (),
) -> list[str]

Return the conditions - and the name conditions: SAP searches case-sensitively, so the common spellings are searched.

Parameters:

Name Type Description Default
odata_version int

The OData version of the service (2 or 4).

required
navigation str

The to-one navigation property to the entity of this query (see the base class).

''
exclude tuple[str, ...]

Fields to leave out (see the base class).

()

Returns:

Type Description
list[str]

list[str]: The conditions of the fields and on the first and last name.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def to_odata_conditions(self, odata_version: int, navigation: str = "", exclude: tuple[str, ...] = ()) -> list[str]:
    """Return the conditions - and the name conditions: SAP searches case-sensitively, so the common spellings are searched.

    Args:
        odata_version (int):
            The OData version of the service (2 or 4).
        navigation (str, optional):
            The to-one navigation property to the entity of this query (see the base class).
        exclude (tuple[str, ...], optional):
            Fields to leave out (see the base class).

    Returns:
        list[str]:
            The conditions of the fields and on the first and last name.

    """

    conditions = super().to_odata_conditions(odata_version=odata_version, navigation=navigation, exclude=exclude)
    conditions += [
        ODataCondition(property_name, operator="contains").to_filter(
            value=text_search_variants(term), odata_version=odata_version
        )
        for property_name, term in (("LastName", self.last_name_contains), ("FirstName", self.first_name_contains))
        if term and term.strip()
    ]

    return conditions

accepts

accepts(entity: BaseModel) -> bool

Check that the business partner has a personnel number - SAP can't filter by the identifications (V2).

Parameters:

Name Type Description Default
entity BaseModel

The business partner read with its identifications (SAPPersonResponseModel).

required

Returns:

Name Type Description
bool bool

True if the person has a personnel number.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def accepts(self, entity: BaseModel) -> bool:
    """Check that the business partner has a personnel number - SAP can't filter by the identifications (V2).

    Args:
        entity (BaseModel):
            The business partner read with its identifications (SAPPersonResponseModel).

    Returns:
        bool:
            True if the person has a personnel number.

    """

    return bool(getattr(entity, "personnel_number", None))

SAPCustomerQueryModel

Bases: SAPBusinessPartnerQueryModel

Search criteria for SAP customers - business partners with the customer role (API_BUSINESS_PARTNER).

SAPSupplierQueryModel

Bases: SAPBusinessPartnerQueryModel

Search criteria for SAP suppliers (vendors) - business partners with the supplier role (API_BUSINESS_PARTNER).

SAPCompanyCodeResponseModel

Bases: SAPODataModel

A company code as returned by SAP (API_COMPANYCODE_SRV, OData V2).

SAPCompanyCodeQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP company codes (API_COMPANYCODE_SRV).

SAPSalesOrganizationTextResponseModel

Bases: SAPODataModel

The (language dependent) name of a sales organization (API_SALESORGANIZATION_SRV).

SAPSalesOrganizationResponseModel

Bases: SAPODataModel

A sales organization as returned by SAP (API_SALESORGANIZATION_SRV, OData V2).

Attributes:

Name Type Description
texts list[SAPSalesOrganizationTextResponseModel] | None

The names - None if they have not been requested ($expand).

SAPSalesOrganizationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP sales organizations (API_SALESORGANIZATION_SRV).

SAPPurchasingOrganizationResponseModel

Bases: SAPODataModel

A purchasing organization as returned by SAP (API_PURCHASINGORGANIZATION, OData V4).

SAPPurchasingOrganizationQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP purchasing organizations (API_PURCHASINGORGANIZATION, OData V4).

SAPCostCenterTextResponseModel

Bases: SAPODataModel

The (language dependent) name of a cost center (API_COSTCENTER_SRV).

SAPCostCenterResponseModel

Bases: SAPODataModel

A cost center as returned by SAP (API_COSTCENTER_SRV, OData V2).

Cost center data is time dependent - the key includes the end of the validity period.

Attributes:

Name Type Description
texts list[SAPCostCenterTextResponseModel] | None

The names - None if they have not been requested ($expand).

SAPCostCenterQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP cost centers (API_COSTCENTER_SRV). Cost centers have validity periods - use valid_on for the current ones.

SAPProfitCenterTextResponseModel

Bases: SAPODataModel

The (language dependent) name of a profit center (API_PROFITCENTER_SRV).

SAPProfitCenterResponseModel

Bases: SAPODataModel

A profit center as returned by SAP (API_PROFITCENTER_SRV, OData V2).

Profit center data is time dependent - the key includes the end of the validity period.

Attributes:

Name Type Description
texts list[SAPProfitCenterTextResponseModel] | None

The names - None if they have not been requested ($expand).

SAPProfitCenterQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP profit centers (API_PROFITCENTER_SRV). Profit centers have validity periods - use valid_on for the current ones.

SAPGLAccountTextResponseModel

Bases: SAPODataModel

The (language dependent) name of a G/L account (API_GLACCOUNTINCHARTOFACCOUNTS_SRV).

SAPGLAccountResponseModel

Bases: SAPODataModel

A G/L account of a chart of accounts as returned by SAP (API_GLACCOUNTINCHARTOFACCOUNTS_SRV, OData V2).

Attributes:

Name Type Description
texts list[SAPGLAccountTextResponseModel] | None

The names - None if they have not been requested ($expand).

SAPGLAccountQueryModel

Bases: SAPODataQueryModel

Search criteria for SAP G/L accounts of a chart of accounts (API_GLACCOUNTINCHARTOFACCOUNTS_SRV).

parse_odata_datetime

parse_odata_datetime(
    value: str | datetime | None,
) -> str | datetime | None

Convert an OData V2 JSON date ("/Date([+|-])/") into a timezone-aware datetime.

Used as a pydantic "before" validator (see ODataDateTime). Other values (datetime objects, ISO 8601 strings, None) are passed through unchanged and handled by pydantic's standard datetime parsing.

The milliseconds are always counted from 1970-01-01 UTC. The optional offset is given in minutes (e.g. "+0120" = UTC+02:00) and only determines the timezone of the result, not the point in time. Values without offset (Edm.DateTime) are returned in UTC.

Parameters:

Name Type Description Default
value str | datetime | None

The value to convert, e.g. "/Date(1724354331000+0000)/".

required

Returns:

Type Description
str | datetime | None

str | datetime | None: The timezone-aware datetime (e.g. 2024-08-22 19:18:51+00:00) for OData V2 dates, None for initial (empty) OData V2 dates, otherwise the unchanged value.

Raises:

Type Description
ValueError

If the value looks like an OData V2 date but is malformed.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def parse_odata_datetime(value: str | datetime | None) -> str | datetime | None:
    """Convert an OData V2 JSON date ("/Date(<ms>[+|-<offset>])/") into a timezone-aware datetime.

    Used as a pydantic "before" validator (see ODataDateTime). Other values
    (datetime objects, ISO 8601 strings, None) are passed through unchanged
    and handled by pydantic's standard datetime parsing.

    The milliseconds are always counted from 1970-01-01 UTC. The optional offset
    is given in minutes (e.g. "+0120" = UTC+02:00) and only determines the timezone
    of the result, not the point in time. Values without offset (Edm.DateTime) are
    returned in UTC.

    Args:
        value (str | datetime | None):
            The value to convert, e.g. "/Date(1724354331000+0000)/".

    Returns:
        str | datetime | None:
            The timezone-aware datetime (e.g. 2024-08-22 19:18:51+00:00) for OData V2
            dates, None for initial (empty) OData V2 dates, otherwise the unchanged value.

    Raises:
        ValueError:
            If the value looks like an OData V2 date but is malformed.

    """

    # Some services (e.g. API_PRODUCTION_ORDER_2_SRV) return an ABAP timestamp
    # (YYYYMMDDhhmmss in UTC, e.g. "20160412160912") - pydantic would read it as
    # milliseconds since 1970. An initial timestamp ("00000000000000") means no value:
    if isinstance(value, str) and len(value) == 14 and value.isdigit():
        return None if int(value) == 0 else datetime.strptime(value, "%Y%m%d%H%M%S").replace(tzinfo=UTC)

    if not isinstance(value, str) or not value.startswith("/Date("):
        return value

    match = ODATA_V2_DATE_PATTERN.match(value)
    if not match:
        message = "Invalid OData V2 date value -> '{}'".format(value)
        raise ValueError(message)

    milliseconds, offset_minutes = match.groups()
    if int(milliseconds) < ODATA_V2_MIN_MILLISECONDS:
        return None
    result = datetime.fromtimestamp(int(milliseconds) / 1000, tz=UTC)
    if offset_minutes:
        result = result.astimezone(timezone(timedelta(minutes=int(offset_minutes))))

    return result

serialize_odata_datetime

serialize_odata_datetime(
    value: datetime | None,
) -> str | None

Serialize a datetime in the OData V2 JSON format for Edm.DateTimeOffset ("/Date(+0000)/").

Parameters:

Name Type Description Default
value datetime | None

The datetime to serialize. Datetimes without timezone are treated as UTC.

required

Returns:

Type Description
str | None

str | None: The OData V2 JSON datetime (in UTC) or None.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def serialize_odata_datetime(value: datetime | None) -> str | None:
    """Serialize a datetime in the OData V2 JSON format for Edm.DateTimeOffset ("/Date(<ms>+0000)/").

    Args:
        value (datetime | None):
            The datetime to serialize. Datetimes without timezone are treated as UTC.

    Returns:
        str | None:
            The OData V2 JSON datetime (in UTC) or None.

    """

    if value is None:
        return None
    if value.tzinfo is None:
        value = value.replace(tzinfo=UTC)

    return "/Date({}+0000)/".format(int(value.timestamp() * 1000))

parse_odata_date

parse_odata_date(
    value: str | date | None,
) -> str | date | None

Convert an OData V2 JSON date ("/Date()/") into a date.

Used as a pydantic "before" validator (see ODataDate) for Edm.DateTime properties with date semantics. Other values (date objects, ISO 8601 strings, None) are passed through unchanged.

Parameters:

Name Type Description Default
value str | date | None

The value to convert, e.g. "/Date(1791504000000)/".

required

Returns:

Type Description
str | date | None

str | date | None: The date for OData V2 dates, otherwise the unchanged value.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def parse_odata_date(value: str | date | None) -> str | date | None:
    """Convert an OData V2 JSON date ("/Date(<ms of midnight UTC>)/") into a date.

    Used as a pydantic "before" validator (see ODataDate) for Edm.DateTime
    properties with date semantics. Other values (date objects, ISO 8601
    strings, None) are passed through unchanged.

    Args:
        value (str | date | None):
            The value to convert, e.g. "/Date(1791504000000)/".

    Returns:
        str | date | None:
            The date for OData V2 dates, otherwise the unchanged value.

    """

    parsed = parse_odata_datetime(value) if isinstance(value, str) else value

    return parsed.date() if isinstance(parsed, datetime) else parsed

serialize_odata_date

serialize_odata_date(value: date | None) -> str | None

Serialize a date in the OData V2 JSON format for Edm.DateTime ("/Date()/").

Parameters:

Name Type Description Default
value date | None

The date to serialize.

required

Returns:

Type Description
str | None

str | None: The OData V2 JSON date or None.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def serialize_odata_date(value: date | None) -> str | None:
    """Serialize a date in the OData V2 JSON format for Edm.DateTime ("/Date(<ms of midnight UTC>)/").

    Args:
        value (date | None):
            The date to serialize.

    Returns:
        str | None:
            The OData V2 JSON date or None.

    """

    if value is None:
        return None

    return "/Date({})/".format(int(datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp() * 1000))

parse_odata_time

parse_odata_time(
    value: str | time | None,
) -> str | time | None

Convert an OData V2 JSON time (Edm.Time, e.g. "PT08H30M00S") into a time.

Other values (time objects, ISO 8601 strings like "08:30", None) are passed through unchanged and handled by pydantic's standard time parsing.

Parameters:

Name Type Description Default
value str | time | None

The value to convert.

required

Returns:

Type Description
str | time | None

str | dtime | None: The time for OData V2 times, otherwise the unchanged value.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def parse_odata_time(value: str | dtime | None) -> str | dtime | None:
    """Convert an OData V2 JSON time (Edm.Time, e.g. "PT08H30M00S") into a time.

    Other values (time objects, ISO 8601 strings like "08:30", None) are passed
    through unchanged and handled by pydantic's standard time parsing.

    Args:
        value (str | dtime | None):
            The value to convert.

    Returns:
        str | dtime | None:
            The time for OData V2 times, otherwise the unchanged value.

    """

    match = ODATA_V2_TIME_PATTERN.match(value) if isinstance(value, str) else None
    if not match:
        return value
    hours, minutes, seconds = (int(part) for part in match.groups())
    # SAP uses "PT24H00M00S" for the end of the day - a time cannot hold 24:00:00:
    if (hours, minutes, seconds) == (24, 0, 0):
        return dtime(23, 59, 59)

    return dtime(hours, minutes, seconds)

serialize_odata_time

serialize_odata_time(value: time | None) -> str | None

Serialize a time in the OData V2 JSON format for Edm.Time (ISO 8601 duration, e.g. "PT08H30M00S").

Parameters:

Name Type Description Default
value time | None

The time to serialize.

required

Returns:

Type Description
str | None

str | None: The OData V2 JSON time or None.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def serialize_odata_time(value: dtime | None) -> str | None:
    """Serialize a time in the OData V2 JSON format for Edm.Time (ISO 8601 duration, e.g. "PT08H30M00S").

    Args:
        value (dtime | None):
            The time to serialize.

    Returns:
        str | None:
            The OData V2 JSON time or None.

    """

    return value.strftime("PT%HH%MM%SS") if value else None

parse_sap_flag

parse_sap_flag(value: str | bool | None) -> bool | None

Convert an SAP flag ("X" = true, "" = false) into a boolean.

Booleans (e.g. OData V4 Edm.Boolean values) and None are passed through unchanged.

Parameters:

Name Type Description Default
value str | bool | None

The value to convert.

required

Returns:

Type Description
bool | None

bool | None: The boolean value or None.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def parse_sap_flag(value: str | bool | None) -> bool | None:
    """Convert an SAP flag ("X" = true, "" = false) into a boolean.

    Booleans (e.g. OData V4 Edm.Boolean values) and None are passed through unchanged.

    Args:
        value (str | bool | None):
            The value to convert.

    Returns:
        bool | None:
            The boolean value or None.

    """

    if isinstance(value, str):
        return value.strip().upper() == "X"

    return value

serialize_sap_flag

serialize_sap_flag(value: bool | None) -> str | None

Serialize a boolean as SAP flag ("X" = true, "" = false).

Parameters:

Name Type Description Default
value bool | None

The value to serialize.

required

Returns:

Type Description
str | None

str | None: "X", "" or None.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def serialize_sap_flag(value: bool | None) -> str | None:
    """Serialize a boolean as SAP flag ("X" = true, "" = false).

    Args:
        value (bool | None):
            The value to serialize.

    Returns:
        str | None:
            "X", "" or None.

    """

    return None if value is None else ("X" if value else "")

unwrap_odata_navigation

unwrap_odata_navigation(
    value: dict | list | None,
) -> list | None

Unwrap the OData V2 representation of a to-many navigation property.

Used as a pydantic "before" validator. SAP returns {"__deferred": {"uri": ...}} if the navigation property was not expanded and {"results": [...]} if it was expanded with $expand. OData V4 returns plain lists (or omits the property if not expanded), which are passed through.

Parameters:

Name Type Description Default
value dict | list | None

The raw value of the navigation property.

required

Returns:

Type Description
list | None

list | None: The list of child entities or None if they have not been expanded.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def unwrap_odata_navigation(value: dict | list | None) -> list | None:
    """Unwrap the OData V2 representation of a to-many navigation property.

    Used as a pydantic "before" validator. SAP returns {"__deferred": {"uri": ...}}
    if the navigation property was not expanded and {"results": [...]} if it was
    expanded with $expand. OData V4 returns plain lists (or omits the property if
    not expanded), which are passed through.

    Args:
        value (dict | list | None):
            The raw value of the navigation property.

    Returns:
        list | None:
            The list of child entities or None if they have not been expanded.

    """

    if isinstance(value, dict):
        if "__deferred" in value:
            return None
        return value.get("results", [])

    return value

unwrap_odata_single_navigation

unwrap_odata_single_navigation(
    value: dict | None,
) -> dict | None

Unwrap the OData V2 representation of a to-one navigation property.

Used as a pydantic "before" validator. SAP returns {"__deferred": {"uri": ...}} if the navigation property was not expanded, the entity if it was expanded with $expand and null if there is no related entity.

Parameters:

Name Type Description Default
value dict | None

The raw value of the navigation property.

required

Returns:

Type Description
dict | None

dict | None: The related entity or None if there is none or it has not been expanded.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def unwrap_odata_single_navigation(value: dict | None) -> dict | None:
    """Unwrap the OData V2 representation of a to-one navigation property.

    Used as a pydantic "before" validator. SAP returns {"__deferred": {"uri": ...}}
    if the navigation property was not expanded, the entity if it was expanded with
    $expand and null if there is no related entity.

    Args:
        value (dict | None):
            The raw value of the navigation property.

    Returns:
        dict | None:
            The related entity or None if there is none or it has not been expanded.

    """

    if isinstance(value, dict) and "__deferred" in value:
        return None

    return value

pad_number

pad_number(value: str | int, length: int) -> str

Normalize an SAP item / sequence number (NUMC) to its fixed length (e.g. 10 -> '00010').

Parameters:

Name Type Description Default
value str | int

The number, e.g. 10 or "10".

required
length int

The fixed length of the SAP field, e.g. 5 for purchase order items.

required

Returns:

Name Type Description
str str

The number padded with leading zeros.

Raises:

Type Description
ValueError

If the value is not numeric or too long.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def pad_number(value: str | int, length: int) -> str:
    """Normalize an SAP item / sequence number (NUMC) to its fixed length (e.g. 10 -> '00010').

    Args:
        value (str | int):
            The number, e.g. 10 or "10".
        length (int):
            The fixed length of the SAP field, e.g. 5 for purchase order items.

    Returns:
        str:
            The number padded with leading zeros.

    Raises:
        ValueError:
            If the value is not numeric or too long.

    """

    value = str(value).strip()
    if not value.isdigit() or len(value) > length:
        message = "Must be numeric with up to {} digits, got -> '{}'".format(length, value)
        raise ValueError(message)

    return value.zfill(length)

is_empty

is_empty(value: list) -> bool

Return True if a list of child entities is empty (used with Field(exclude_if=...)).

Empty child lists are excluded from create payloads - SAP would otherwise try to deep insert nothing.

Parameters:

Name Type Description Default
value list

The list of child entities.

required

Returns:

Name Type Description
bool bool

True if the list is empty.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def is_empty(value: list) -> bool:
    """Return True if a list of child entities is empty (used with Field(exclude_if=...)).

    Empty child lists are excluded from create payloads - SAP would otherwise try
    to deep insert nothing.

    Args:
        value (list):
            The list of child entities.

    Returns:
        bool:
            True if the list is empty.

    """

    return not value

unique_numbers

unique_numbers(attribute: str) -> AfterValidator

Return a validator that checks that the given (item) number is unique within a list of child entities.

Parameters:

Name Type Description Default
attribute str

The name of the number attribute of the child entities, e.g. "item".

required

Returns:

Name Type Description
AfterValidator AfterValidator

A pydantic validator to be used in an Annotated list type, e.g. Annotated[list[SAPSalesOrderItemModel], unique_numbers("item")].

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def unique_numbers(attribute: str) -> AfterValidator:
    """Return a validator that checks that the given (item) number is unique within a list of child entities.

    Args:
        attribute (str):
            The name of the number attribute of the child entities, e.g. "item".

    Returns:
        AfterValidator:
            A pydantic validator to be used in an Annotated list type, e.g.
            Annotated[list[SAPSalesOrderItemModel], unique_numbers("item")].

    """

    def check(children: list | None) -> list | None:
        if not children:
            return children

        # Children without a number (None, e.g. numbers that SAP assigns) are not compared:
        duplicates = sorted(
            number
            for number, count in Counter(getattr(child, attribute) for child in children).items()
            if count > 1 and number is not None
        )
        if duplicates:
            message = "Numbers must be unique, duplicates -> {}".format(duplicates)
            raise ValueError(message)
        return children

    return AfterValidator(check)

unit_iso_code

unit_iso_code(unit: str | None) -> str | None

Return the ISO code of an SAP unit code, e.g. 'PC' -> 'PCE' (see SAP_UNIT_ISO_CODES).

Parameters:

Name Type Description Default
unit str | None

The English (commercial) unit code, e.g. "PC".

required

Returns:

Type Description
str | None

str | None: The ISO code or None if the unit is not in SAP_UNIT_ISO_CODES.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def unit_iso_code(unit: str | None) -> str | None:
    """Return the ISO code of an SAP unit code, e.g. 'PC' -> 'PCE' (see SAP_UNIT_ISO_CODES).

    Args:
        unit (str | None):
            The English (commercial) unit code, e.g. "PC".

    Returns:
        str | None:
            The ISO code or None if the unit is not in SAP_UNIT_ISO_CODES.

    """

    return SAP_UNIT_ISO_CODES.get((unit or "").strip().upper())

send_purchase_requisition_units_as_iso

send_purchase_requisition_units_as_iso(item: dict) -> dict

Remove BaseUnit from the payload of a purchase requisition item and its account assignments.

API_PURCHASEREQUISITION_2 expects SAP's internal unit code in BaseUnit (e.g. 'ST' for 'PC') and rejects a BaseUnit that doesn't match BaseUnitISOCode - with the ISO code alone, SAP determines the unit itself.

Parameters:

Name Type Description Default
item dict

The OData payload of the item (changed in place).

required

Returns:

Name Type Description
dict dict

The payload.

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def send_purchase_requisition_units_as_iso(item: dict) -> dict:
    """Remove BaseUnit from the payload of a purchase requisition item and its account assignments.

    API_PURCHASEREQUISITION_2 expects SAP's internal unit code in BaseUnit (e.g. 'ST' for 'PC') and
    rejects a BaseUnit that doesn't match BaseUnitISOCode - with the ISO code alone, SAP determines
    the unit itself.

    Args:
        item (dict):
            The OData payload of the item (changed in place).

    Returns:
        dict:
            The payload.

    """

    for entity in [item, *item.get("_PurchaseReqnAcctAssgmt", [])]:
        if entity.get("BaseUnitISOCode"):
            entity.pop("BaseUnit", None)

    return item

odata_literal

odata_literal(
    value: str | bool | float | Decimal | date | datetime,
    odata_version: int = 2,
    kind: Literal["timestamp", "flag"] | None = None,
) -> str

Format a value as OData URI literal (for $filter conditions and function import parameters).

Parameters:

Name Type Description Default
value str | bool | float | Decimal | date | datetime

The Python value.

required
odata_version int

The OData version of the service (2 or 4). Defaults to 2.

2
kind Literal['timestamp', 'flag'] | None

"timestamp" for Edm.DateTimeOffset properties (dates are taken as midnight UTC), "flag" for SAP flags in OData V2 services ("X" = true, "" = false). Defaults to None.

None

Returns:

Name Type Description
str str

The literal, e.g. 'ABC' (quotes doubled), true, 'X', datetime'2026-10-10T00:00:00' / 2026-10-10 (V2 / V4 dates) or datetimeoffset'2026-10-10T08:00:00Z' / 2026-10-10T08:00:00Z (V2 / V4 timestamps).

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def odata_literal(
    value: str | bool | float | Decimal | date | datetime,
    odata_version: int = 2,
    kind: Literal["timestamp", "flag"] | None = None,
) -> str:
    """Format a value as OData URI literal (for $filter conditions and function import parameters).

    Args:
        value (str | bool | float | Decimal | date | datetime):
            The Python value.
        odata_version (int, optional):
            The OData version of the service (2 or 4). Defaults to 2.
        kind (Literal["timestamp", "flag"] | None, optional):
            "timestamp" for Edm.DateTimeOffset properties (dates are taken as midnight UTC),
            "flag" for SAP flags in OData V2 services ("X" = true, "" = false). Defaults to None.

    Returns:
        str:
            The literal, e.g. 'ABC' (quotes doubled), true, 'X', datetime'2026-10-10T00:00:00' /
            2026-10-10 (V2 / V4 dates) or datetimeoffset'2026-10-10T08:00:00Z' / 2026-10-10T08:00:00Z
            (V2 / V4 timestamps).

    """

    if isinstance(value, bool):
        if kind == "flag" and odata_version == 2:
            return "'X'" if value else "''"
        return "true" if value else "false"
    if isinstance(value, date) and not isinstance(value, datetime) and kind == "timestamp":
        value = datetime(value.year, value.month, value.day, tzinfo=UTC)
    if isinstance(value, datetime):
        if value.tzinfo is None and odata_version == 2:
            return "datetime'{}'".format(value.strftime("%Y-%m-%dT%H:%M:%S"))
        timestamp = (
            (value if value.tzinfo else value.replace(tzinfo=UTC)).astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
        )
        return "datetimeoffset'{}'".format(timestamp) if odata_version == 2 else timestamp
    if isinstance(value, date):
        return "datetime'{}T00:00:00'".format(value.isoformat()) if odata_version == 2 else value.isoformat()
    if isinstance(value, int | float | Decimal):
        return str(value)

    return "'{}'".format(str(value).replace("'", "''"))

text_search_variants

text_search_variants(term: str) -> list[str]

Get the spellings of a search term for a case-insensitive text search.

The SAP OData V2 services search texts case-sensitively and do not support tolower(), so the term is searched as typed, in lower case, capitalized, in title case and in upper case.

Parameters:

Name Type Description Default
term str

The search term, e.g. "seal kit".

required

Returns:

Type Description
list[str]

list[str]: The distinct spellings, e.g. ["seal kit", "Seal kit", "Seal Kit", "SEAL KIT"].

Source code in packages/pyxecm/src/pyxecm_customizer/sap_models.py
def text_search_variants(term: str) -> list[str]:
    """Get the spellings of a search term for a case-insensitive text search.

    The SAP OData V2 services search texts case-sensitively and do not support tolower(), so the
    term is searched as typed, in lower case, capitalized, in title case and in upper case.

    Args:
        term (str):
            The search term, e.g. "seal kit".

    Returns:
        list[str]:
            The distinct spellings, e.g. ["seal kit", "Seal kit", "Seal Kit", "SEAL KIT"].

    """

    term = term.strip()

    return list(dict.fromkeys([term, term.lower(), term.capitalize(), term.title(), term.upper()]))