Developer forum

Forum » Development » Creating Order programmatically

Creating Order programmatically

Marco Santos
Reply

Hello.

I am trying to create an order programatically. The reason for this is the two products that I will be placing in the order are actually dummy products to reference other orders in two other systems.

I am first creating a cart and order lines and that works fine, but once I try to run cart.UpdateCartToOrder() I get the exception "The UPDATE statement conflicted with the REFERENCE constraint "EcomOrderLines$EcomOrdersEcomOrderLines".

Question 1: What could be causing this?

Question 2: Is there a way to create the order directly, without going through a cart? All of it is done programmatically, we are not using the cart process at all.

Question 3: Can I get payment information on there as well? This would probably involve creating a dummy payment method.

Thanks.

Marco


Replies

 
Nicolai Høeg Pedersen
Reply

Hi Marco

You can call the ordline builder in Ecommerce:

Dynamicweb.eCommerce.Frontend.Cart.CartCatch.OrderLineBuilder(Dynamicweb.eCommerce.Common.Context.Cart, ...)

And here is the code inside that method. It has a lot of things you do not need, but you can see how it should be done.

 Dim QuantityOrderLine As Double = Quantity
            If QuantityCheck Then
                If QuantityOrderLine <= 0 Then
                    Return Nothing
                End If
            Else
                If QuantityOrderLine <= 0 Then
                    QuantityOrderLine = 1
                End If
            End If

            Dim ol As New OrderLine
            ol.ID = ""
            ol.OrderID = EcomCart.ID
            ol.ProductID = ProductID
            ol.ProductVariantID = VariantID
            ol.Quantity = QuantityOrderLine
            ol.Modified = Now

            ol.ProductVariantText = VariantText
            ol.UnitID = UnitID
            ol.Type = Type
            ol.ListID = listId
            'TFC - Removed for security reasons
            'If Base.Request("UnitPrice") <> "" Then
            '    ol.SetUnitPrice(Base.DoubleFromString(Base.Request("UnitPrice")))
            'End If

            If Base.Request("DontSaveReference") = "" And Not RefUrl Is Nothing Then
                If RefUrl.Length > 0 Then
                    If RefUrl.Length <= 255 Then
                        ol.Reference = RefUrl
                    Else
                        ol.Reference = RefUrl.Substring(0, 255)
                    End If
                End If
            End If

            ol.PageID = pageId

            EcomCart.IsCart = True

            ol.Order = EcomCart

            '### BOM being added to order, this is tricky, don't mess it up please.
            'Dim ProductToPutInCart As New Product(OrderLine.ProductID, OrderLine.ProductVariantID)
            Dim ProductToPutInCart As Product = Product.GetProductByID(ol.ProductID, ol.ProductVariantID)
            If ProductToPutInCart Is Nothing Then
                ProductToPutInCart = New Product()
            End If

            If ol.HasType(OrderLine.OrderLineType.PointProduct) AndAlso (ProductToPutInCart.DefaultPoints <= 0 OrElse (Not IsNothing(Modules.UserManagement.User.Current(Modules.UserManagement.PagePermissionLevels.Frontend)) AndAlso (ProductToPutInCart.DefaultPoints * Quantity + Base.ChkDouble(EcomCart.TotalPoints)) > Dynamicweb.Modules.UserManagement.User.Current(Modules.UserManagement.PagePermissionLevels.Frontend).PointBalance)) Then
                Return Nothing
            End If
            ' Check stock and reserve
            If ProductReserve.Enabled AndAlso ProductToPutInCart.Type <> ProductType.Service AndAlso ol.HasType({OrderLine.OrderLineType.Product, OrderLine.OrderLineType.PointProduct}) Then

                Dim cartStock As Double = ProductReserve.GetReservedAmount(ol.ProductID, ol.ProductVariantID) + QuantityOrderLine
                If ProductReserve.GetReserveMode = ProductReserve.ReserveMode.modeCheckout Then
                    ' When products is reserved only in checkout step we should take into account is there such product exist in cart
                    cartStock += EcomCart.OrderLines.Where(Function(cartLine) cartLine.ProductID = ProductID AndAlso cartLine.ProductVariantID = VariantID).Select(Function(cartLine) cartLine.Quantity).FirstOrDefault()
                End If

                If ProductToPutInCart.UnitStock < cartStock Then
                    Return Nothing
                End If
            End If

            If ProductToPutInCart.VariantID = "" AndAlso ol.ProductVariantID <> "" Then
                ProductToPutInCart.VirtualVariantID = ol.ProductVariantID
            End If

            '#################
            'Resolve VariantText
            '#################
            If ol.ProductVariantID <> "" And ol.ProductVariantText = "" Then
                'TFC - 17/04-2007
                ol.ProductVariantText = eCommerce.Variants.VariantNumber.VariantName(ol.ProductVariantID, Context.LanguageID)
            End If

            '#################################
            'Resolve Product information
            '---------------------------------
            'ProductName
            'ProductNumber
            '#################################
            If ProductToPutInCart.ID <> "" Then
                If ProductName = "" Then
                    ol.ProductName = ProductToPutInCart.Name
                Else
                    ol.ProductName = ProductName
                End If

                If ProductNumber = "" Then
                    ol.ProductNumber = ProductToPutInCart.Number
                Else
                    ol.ProductNumber = ProductNumber
                End If
            End If

            'OrderLineFieldValues
            If orderLineFieldValues Is Nothing Then
                orderLineFieldValues = New OrderLineFieldValueCollection()
            End If
            ol.OrderLineFieldValues = orderLineFieldValues


            If ProductToPutInCart.Type = ProductType.BOM Then
                For Each Item As ProductItem In ProductToPutInCart.Items

                    Dim bomProduct As Product
                    Dim bomQuantity As Double
                    Dim bomItemID As String = Nothing

                    If Item.BomGroupID <> String.Empty Then
                        bomItemID = Item.ID
                        bomQuantity = 1
                        If Base.Request(Item.ID) <> "" Then
                            If Base.Request(Item.ID).Contains(",") Then
                                For Each bomID As String In Base.Request(Item.ID).Split(","c)
                                    bomProduct = Item.Products.getProductById(bomID)
                                    ol.BOMOrderLines.Add(BomOrderlineBuilder(bomProduct, EcomCart, bomQuantity, ol.ID, RefUrl, bomItemID), False) '***NEW
                                Next
                            Else
                                bomProduct = Item.Products.getProductById(Base.Request(Item.ID))
                                ol.BOMOrderLines.Add(BomOrderlineBuilder(bomProduct, EcomCart, bomQuantity, ol.ID, RefUrl, bomItemID), False) '***NEW
                            End If
                        Else
                            bomProduct = Item.Products.getProductById(Item.DefaultProductID)
                            ol.BOMOrderLines.Add(BomOrderlineBuilder(bomProduct, EcomCart, bomQuantity, ol.ID, RefUrl, bomItemID), False) '***NEW
                        End If
                    Else
                        bomProduct = Item.Products.getProductById(Item.DefaultProductID)
                        bomQuantity = Item.Quantity
                        ol.BOMOrderLines.Add(BomOrderlineBuilder(bomProduct, EcomCart, bomQuantity, ol.ID, RefUrl, bomItemID), False) '***NEW
                    End If

                Next
            End If
            ol.Product = ProductToPutInCart
            If AddToCart Then
                EcomCart.OrderLines.Add(ol, True)
            End If
            Return ol
 
Marco Santos
Reply

Hello.

Does this mean that I need to go through the process of creating a cart first and then UpdateCartToOrder() ?

Marco

 
Nicolai Høeg Pedersen
Reply

Yes

Context.SetCart(New Order() With {.IsCart = True, .LanguageID = Common.Context.LanguageID})
Context.Cart.Save()
 
Marco Santos
Reply

Good morning.

I still get the same error when I try to create the cart from the order:

"The UPDATE statement conflicted with the REFERENCE constraint "EcomOrderLines$EcomOrdersEcomOrderLines". The conflict occurred in database "dynamicweb_agenthotels", table "dbo.EcomOrderLines", column 'OrderLineOrderID'

Here are the relevant bits of code:

        Private Sub SetCartValues(paymentResponse As RegistrationResponse, itineraryCost As HolidayCost)
            Context.SetCart(New Order() With {.IsCart = True, .LanguageID = Context.LanguageID})
 
            With Context.Cart
 
                .CurrencyCode = Context.Currency.Code
                .CurrencyName = Context.Currency.Name
 
                .CustomerAddress = _oPassengerDetailsLead.AddressFieldOne
                .CustomerAddress2 = _oPassengerDetailsLead.AddressFieldTwo
                .CustomerCell = _oPassengerDetailsLead.MobilePhone
                .CustomerCity = _oPassengerDetailsLead.City
                .CustomerCountry = _oPassengerDetailsLead.Country
                .CustomerEmail = _oPassengerDetailsLead.UserEmail
                .CustomerName = _oPassengerDetailsLead.Firstname & " " & _oPassengerDetailsLead.Lastname
                .CustomerPhone = _oPassengerDetailsLead.Telephone
                .CustomerRegion = _oPassengerDetailsLead.County
                .CustomerZip = _oPassengerDetailsLead.Postcode
 
                .CustomerComment = _oPassengerDetailsLead.Comments
 
                .Referrer = Request.ServerVariables("http_referer")
                .IP = Request.ServerVariables("REMOTE_ADDR")
 
                .TransactionStatus = paymentResponse.Status
                .TransactionAmount = itineraryCost.TotalCost
                .TransactionNumber = paymentResponse.TxAuthNo
 
                .StateID = Config.GTWOrderStateID 'Payed
 
            End With
 
            Context.Cart.Save()
        End Sub
        Private Sub CreateOrderLine(ByVal productNumber As StringByVal description As StringByVal total As Double)
            Dim lineProduct As Dynamicweb.eCommerce.Products.Product = Dynamicweb.eCommerce.Products.Product.GetProductByNumber(productNumber)
 
            Dim ol As OrderLine = CartCatch.OrderLineBuilder(Context.Cart, 1, False, lineProduct.ID, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, 0, description, lineProduct.Number, True)
 
            ol.ProductName = description
            ol.SetUnitPrice(total)
 
        End Sub

 

In the function where both these are called I then have:

Context.Cart.Save()
Context.Cart.UpdateCartToOrder()

Can you spot if anything is missing?

Marco

 
Marco Santos
Reply

Hello.

Any ideias on this? I'm kind of stuck at the minute.

Regards,

Marco

 
Nicolai Høeg Pedersen
Reply

I've asked a dev to take a look at your code.

 
Alexander
Reply

Hello Marco ,

I created simple page using yours methods but added few changes:
1) 
=============
    Private Sub SetCartValues(paymentResponse As RegistrationResponse, itineraryCost As HolidayCost)
....
            .StateID = "OS1" 'New' 'Config.GTWOrderStateID 'Payed
....
    End Sub
=============
2) 
=============
    Private Sub CreateOrderLine(ByVal productNumber As String, ByVal description As String, ByVal total As Double)
...
        ol.SetUnitPrice(total)
       ol.Save()
    End Sub
=============

I used the Page_Load to check the scenario:
=============
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetCartValues(Nothing, Nothing)
        CreateOrderLine("PRODUKT1", "", 1)
        CreateOrderLine("PRODUKT2", "", 2)
        Dynamicweb.eCommerce.Common.Context.Cart.UpdateCartToOrder()
    End Sub
=============

So, it works fine with my enviroment(I used Dynamicweb 8.4.1).

Check my attached source and may be it help you!

 

You must be logged in to post in the forum