web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Supply chain | Supply Chain Management, Commerce
Unanswered

Add item to the cart using AddItemToCartOperationRequest and AddItemToCartOperationResponse

(1) ShareShare
ReportReport
Posted on by 440
Hi All,
 
 I'm trying to add an item to the cart onprepayment Trigger, the dialogue will open to get confirmation and the required qty ,  I'm calling GetProductsByIdsClientRequest to get the product details and then calling AddItemToCartOperationRequest.
 
GetProductsByIdsClientRequest itself is not executing and is throwing a commerce error below is my code, am I doing it correctly? can any one share some example code to add item to the cart ?
 
import { IPrePaymentTriggerOptions, PrePaymentTrigger } from "PosApi/Extend/Triggers/PaymentTriggers";
import { IMessageDialogOptions, ShowMessageDialogClientRequest, ShowMessageDialogClientResponse } from "PosApi/Consume/Dialogs";
import { ClientEntities } from "PosApi/Entities";
import { GetProductsByIdsClientRequest, GetProductsByIdsClientResponse } from "PosApi/Consume/Products";
import {
    ShowNumericInputDialogClientRequest, ShowNumericInputDialogClientResponse,
    INumericInputDialogOptions
} from "PosApi/Consume/Dialogs";
import { AddItemToCartOperationRequest, AddItemToCartOperationResponse } from "PosApi/Consume/Cart";
 
export default class AddShoppingBagTrigger extends PrePaymentTrigger {
 
    public static dialogMessage: string = "Would you like to add shopping bag?";
    public static yesButtonLabel: string = 'Yes';
    public static noButtonLabel: string = 'No';
   
 
    public execute(options: IPrePaymentTriggerOptions): Promise<ClientEntities.ICancelable> {
        this.context.logger.logInformational("Executing AddShoppingBagTrigger with options " + JSON.stringify(options) + ".");
 
        let dialogOptions: IMessageDialogOptions = {
            message: AddShoppingBagTrigger.dialogMessage,
            showCloseX: false,
            button1: {
                id: 'yesButton',
                label: AddShoppingBagTrigger.yesButtonLabel,
                result: AddShoppingBagTrigger.yesButtonLabel,
                isPrimary: true
            },
            button2: {
                id: 'noButton',
                label: AddShoppingBagTrigger.noButtonLabel,
                result: AddShoppingBagTrigger.noButtonLabel,
                isPrimary: false
            },
        };
 
        let showMessageDialogClientRequest: ShowMessageDialogClientRequest<ShowMessageDialogClientResponse> =
            new ShowMessageDialogClientRequest(dialogOptions);
 
        return this.context.runtime.executeAsync(showMessageDialogClientRequest).then((value) => {
            if (!value.canceled && value.data.result.dialogResult === AddShoppingBagTrigger.yesButtonLabel) {
                // Proceed to get numeric input for quantity
                let numericInputDialogOptions: INumericInputDialogOptions = {
                    title: "Quantity",
                    subTitle: "Quantity",
                    numPadLabel: "Please enter Quantity:"
                   
                };
 
                let showNumericInputDialogClientRequest: ShowNumericInputDialogClientRequest<ShowNumericInputDialogClientResponse> =
                    new ShowNumericInputDialogClientRequest(numericInputDialogOptions);
 
                return this.context.runtime.executeAsync(showNumericInputDialogClientRequest)
                    .then((result: ClientEntities.ICancelableDataResult<ShowNumericInputDialogClientResponse>) => {
                        if (!result.canceled) {
                            let quantity = parseInt(result.data.result.value, 10) || 0;
                            this.context.logger.logInformational("NumericInputDialog result: " + quantity);
                       
                            let simplProduct: GetProductsByIdsClientRequest<GetProductsByIdsClientResponse> =
                                new GetProductsByIdsClientRequest([68719492153], "101");
                            alert("Before get product");
                            return this.context.runtime.executeAsync(simplProduct).then((response) => {
                                if (response.data.products && response.data.products.length > 0) {
                                    let simpleProductDetails = response[0];
                                     alert(response.data.products[0].ProductNumber);  
                                    // Initialize extProp and extPropValue before use
                                    let extProp: Commerce.Proxy.Entities.CommerceProperty = new Commerce.Proxy.Entities.CommercePropertyClass;
                                    let extPropValue: Commerce.Proxy.Entities.CommercePropertyValue = new Commerce.Proxy.Entities.CommercePropertyValueClass;
                                    extPropValue.StringValue = "Item Inserted";
                                    extProp.Key = "InsertItem";
                                    extProp.Value = extPropValue;                            
 
                                    let productSaleDetails: Commerce.Client.Entities.IProductSaleReturnDetails = {
                                        product: simpleProductDetails,
                                        productId: 68719492153,
                                        quantity: quantity,  // Using the numeric input quantity
                                        unitOfMeasureSymbol: simpleProductDetails.DefaultUnitOfMeasure,
                                        barcode: {},
                                        trackingId: "",
                                        catalogId: 20,
                                        preSelectedDimensions: simpleProductDetails.Dimensions,
                                        entryType: Commerce.Proxy.Entities.BarcodeEntryMethodType.ManuallyEntered,
                                        extensionProperties: [extProp]
                                    };
 
                                    let addItemToCartOperationRequest: AddItemToCartOperationRequest<AddItemToCartOperationResponse> =
                                        new AddItemToCartOperationRequest([productSaleDetails], "100000");
 
                                    return this.context.runtime.executeAsync(addItemToCartOperationRequest)
                                        .then(() => {
                                            this.context.logger.logInformational("Item added to cart successfully.");
                                            return { canceled: false, options: options };
                                        })
                                        .catch((error) => {
                                            this.context.logger.logError("Error adding item to cart: " + error);
                                            return { canceled: true, options: options };
                                        });
                                } else {
                                    this.context.logger.logError("No product found in response.");
                                    return { canceled: true, options: options };
                                }
                            }).catch((error) => {
                                this.context.logger.logError("Error fetching product: " + error);
                                alert(error);
                                return { canceled: true, options: options };
                            });
                        } else {
                            this.context.logger.logError("Numeric input canceled or invalid.");
                            return { canceled: true, options: options };
                        }
                    }).catch((error) => {
                        this.context.logger.logError("Error in numeric input dialog: " + error);
                        return { canceled: true, options: options };
                    });
            } else {
                // If user clicked 'No', we cancel the flow.
                return { canceled: true, options: options };
            }
        }).catch((reason: any) => {
            this.context.logger.logError("Error in message dialog: " + reason);
            return { canceled: false, options: options };
        });
    }
}
 
Categories:
I have the same question (0)
  • S Gopi Krishna Profile Picture
    633 on at
    If the requirement is just to add an infocode prompt after clicking any payment method then it is possible to do it in the standard application itself and need not to customize.
     
    You may add an infocode to the required payment methods in HQ so when the payment method was choosen the infocode will be prompted for input and the infocode can be configured to add an SKU when a certain input or button was clicked in this case when 'YES' button is clicked.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Supply chain | Supply Chain Management, Commerce

#1
Laurens vd Tang Profile Picture

Laurens vd Tang 301 Super User 2025 Season 2

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 118 Super User 2025 Season 2

#3
Siv Sagar Profile Picture

Siv Sagar 105 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans