Search code examples
c#moryx

How to create products in MORYX when importing orders from external systems?


I'm fetching order data from an external MES system and try to create orders in MORYX accordingly.

This is, roughly, what creating the order looks like:

var orderContext = new OrderCreationContext
{
    Number = externalOrder.Number,
};


var operationContext = new OperationCreationContext
{
    Order = orderContext,
    TotalAmount = externalOrder.Amount,
    Number = externalOrder.OperationNumber,
    ProductIdentifier = externalOrder.ProductNumber,
};
orderContext.Operations.Add(operationContext);

_orderManagement.AddOperation(operationContext);

It successfully creates an order, but if the provided product doesn't exist yet in MORYX, it comes with an error:

It was not possible to assign the product!

In this case, I'd like to create the product on the fly, but my first guess, the ProductManager, doesn't seem to provide a method to do this.

If it is, how is it possible to import yet unknown products into MORYX?


Solution

  • The error message already hints you towards the solution. By default MORYX uses the given identifier and tries to fetch a digitial twin from IProductManagement. But you can customize that behavior by implementing and configuring your own IProductAssignment

    An example could look like the code below:

    public class AutoCreateProductAssignment : ProductAssignmentBase<ProductAssignmentConfig>
    {
        /// <inheritdoc />
        public override Task<IProductType> SelectProduct(Operation operation, IOperationLogger operationLogger)
        {
            var productIdentity = (ProductIdentity)operation.Product.Identity;
            var selectedType = ProductManagement.LoadType(productIdentity);
            if (selectedType == null)
            {
                selectedType = new MyProductType()
                {
                    Name = operation.CreationContext.ProductName,
                    Identity = new ProductIdentity(productIdentity.Identifier, productIdentity.Revision),
                    // Assign any additional attributes you can derive from context
                };
                ProductManagement.SaveType(selectedType);
            }
    
            return Task.FromResult(selectedType);
        }
    }