Print new custom receipt in end transaction - Microsoft Dynamics 365 Vietnam

Microsoft Dynamics 365 Vietnam

Song Nghia - Microsoft Dynamics 365 Vietnam

Breaking

Thursday, March 19, 2020

Print new custom receipt in end transaction

Print new custom receipt in end transaction
Song Nghia - Technical Consultant

Step 1. Add extension in PostEndTransactionTrigger and return CustomReceipt6.

return this.context.runtime.executeAsync(new Device_1.GetHardwareProfileClientRequest())

.then(function (response) {

var hardwareProfile = response.data.result;

var salesOrderId = options.receipts[0].TransactionId;

var receiptRetrievalCriteria = {

 IsCopy: false,

 IsRemoteTransaction: false,

 IsPreview: false,

 QueryBySalesId: true,

 ReceiptTypeValue: Entities_1.ProxyEntities.ReceiptType.CustomReceipt6,

 HardwareProfileId: hardwareProfile.ProfileId

};

Step 2. In CRT create new SingleRequestHandler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LAW
{
    namespace Runtime.Extensions.PrintBillEndTranssaction
    {
        using System.Collections.Generic;
        using System.Collections.ObjectModel;
        using Microsoft.Dynamics.Commerce.Runtime;
        using Microsoft.Dynamics.Commerce.Runtime.DataModel;
        using Microsoft.Dynamics.Commerce.Runtime.Messages;
        using Microsoft.Dynamics.Commerce.Runtime.Services.Messages;
        using Microsoft.Dynamics.Commerce.Runtime.Workflow;
        using Microsoft.Dynamics.Commerce.Runtime.DataServices.Messages;
        using Microsoft.Dynamics.Commerce.Runtime.Data;
        /// 
        /// The request handler for GetCustomReceiptsRequestHandler class.
        /// 
        public class GetCustomReceiptsRequestHandler : SingleRequestHandler
        {

            /// 
            /// Processes the GetCustomReceiptsRequest to return the set of receipts. The request should not be null.
            /// 

            /// The request parameter.

            /// The GetReceiptResponse.

            protected override GetReceiptResponse Process(GetCustomReceiptsRequest request)
            {
                decimal PRINT2SALESINV = 0;
                ThrowIf.Null(request, "request");
                ThrowIf.Null(request.ReceiptRetrievalCriteria, "request.ReceiptRetrievalCriteria");

                // The sales order that we are printing receipts for is retrieved.
                SalesOrder salesOrder = this.GetSalesOrderForTransactionWithId(request.RequestContext, request.TransactionId);

                // Custom receipts are printed.
                Collection result = new Collection();
                switch (request.ReceiptRetrievalCriteria.ReceiptType)
                {
                    // An example of getting custom receipts.
                    case ReceiptType.CustomReceipt6:
                        {
                            var queryEXTCustTable = new SqlPagedQuery(QueryResultSettings.SingleRecord)
                            {
                                DatabaseSchema = "ext",
                                Select = new ColumnSet(new string[] { "LAW_BUSSTYLE", "LAW_PRINT2SALESINVOICE", "ACCOUNTNUM" }),
                                From = "LAW_CUSTTABLE",
                                Where = "ACCOUNTNUM = @ACCOUNTNUM AND DATAAREAID = @DATAAREAID"
                            };

                            queryEXTCustTable.Parameters["@ACCOUNTNUM"] = salesOrder.CustomerId;
                            queryEXTCustTable.Parameters["@DATAAREAID"] = request.RequestContext.GetChannelConfiguration().InventLocationDataAreaId;


                            //Step 2. Select in 2 table

                            using (DatabaseContext databaseContext = new DatabaseContext(request.RequestContext))
                            {
                                ExtensionsEntity extensions = databaseContext.ReadEntity(queryEXTCustTable).FirstOrDefault();

                                if (extensions != null)
                                {
                                    var print2Invoice = extensions != null ? extensions.GetProperty("LAW_PRINT2SALESINVOICE") : 0;
                                    PRINT2SALESINV = Convert.ToDecimal(print2Invoice);
                                }
                            }

                            if (PRINT2SALESINV == 1)
                            {
                                IEnumerable customReceipts = this.GetCustomReceipts(salesOrder, request.ReceiptRetrievalCriteria);
                                result.AddRange(customReceipts);
                            }
                        }
                        break;
                    case ReceiptType.CustomReceipt20:
                        {
                            Receipt tempReceipt = new Receipt();
                            Collection tempReceiptCollection = new Collection();

                            tempReceipt.Printers = this.GetPrinterForHardcodeReceipt(request.RequestContext, request.ReceiptRetrievalCriteria.HardwareProfileId, ReceiptType.SalesReceipt);
                            tempReceiptCollection.Add(tempReceipt);

                            IEnumerable customReceipts = tempReceiptCollection;

                            result.AddRange(customReceipts);
                        }

                        break;
                    default:
                        break;
                }
                return new GetReceiptResponse(new ReadOnlyCollection(result));
            }

            /// 
            /// Gets a sales order for the transaction with the given identifier.
            ///             private SalesOrder GetSalesOrderForTransactionWithId(RequestContext requestContext, string transactionId)
            {
                SalesOrder salesOrder = new SalesOrder();

                var getCartRequest = new GetSalesOrderDetailsByTransactionIdServiceRequest(transactionId, SearchLocation.Local);

                var getCartResponse = requestContext.Execute(getCartRequest);
                salesOrder = getCartResponse.SalesOrder;

                return salesOrder;
            }

            private Collection GetCustomReceipts(SalesOrder salesOrder, ReceiptRetrievalCriteria criteria)
            {
                Collection result = new Collection();
                var getReceiptServiceRequest = new GetReceiptServiceRequest(
                    salesOrder,
                    new Collection { criteria.ReceiptType },
                    salesOrder.TenderLines,
                    criteria.IsCopy,
                    criteria.IsPreview,
                    criteria.HardwareProfileId);
                ReadOnlyCollection customReceipts = this.Context.Execute(getReceiptServiceRequest).Receipts;
                result.AddRange(customReceipts);
                return result;
            }

            private ReadOnlyCollection GetPrinters(RequestContext context, string hardwareProfileId, ReceiptType receiptType)
            {
                Terminal terminal = context.GetTerminal();
                if (string.IsNullOrEmpty(hardwareProfileId))
                {
                    hardwareProfileId = terminal.HardwareProfile;
                }

                GetPrintersDataRequest getPrintersByReceiptTypeDataRequest = new GetPrintersDataRequest(terminal.TerminalId, receiptType, QueryResultSettings.AllRecords, hardwareProfileId);
                IEnumerable printers = context.Execute>(getPrintersByReceiptTypeDataRequest).PagedEntityCollection.Results;
                Printer printer = printers.FirstOrDefault(p => p.PrinterType == (int)DeviceType.WindowsPrinter);

                return new List() { printer }.AsReadOnly();
            }

            private ReadOnlyCollection GetPrinterForHardcodeReceipt(RequestContext context, string hardwareProfileId, ReceiptType receiptType)
            {
                Terminal terminal = context.GetTerminal();
                if (string.IsNullOrEmpty(hardwareProfileId))
                    hardwareProfileId = terminal.HardwareProfile;
                GetHardwareProfileDataRequest profileDataRequest = new GetHardwareProfileDataRequest(hardwareProfileId, QueryResultSettings.SingleRecord);
                HardwareProfile entity = context.Runtime.Execute>((Request)profileDataRequest, context).Entity;
                if (entity != null && entity.Printers != null && entity.Printers.Any())
                {
                    HardwareProfilePrinter hardwareProfilePrinter = entity.Printers.FirstOrDefault((Func)(printer => (uint)printer.DeviceType > 0U));
                    if (hardwareProfilePrinter != null)
                        return new List()
                {
                    new Printer()
                    {
                      ReceiptType = receiptType,
                      PrintBehavior = PrintBehavior.Always,
                      Terminal = terminal == null ? 0L : terminal.RecordId,
                      HardwareProfileId = hardwareProfileId,
                      Name = hardwareProfilePrinter.DeviceName,
                      PrinterType = (int) hardwareProfilePrinter.DeviceType
                    }
                }.AsReadOnly();
                }
                return new List().AsReadOnly();
            }
        }
    }
}

Solution:  from my Technical Architect  in company.