Wednesday, August 14, 2019

How to create a duplicate copy of Invoice in Dynamic CRM

I have created a custom Plugin for creating a duplicate invoice in the system.
Triggering point for a plugin is a custom action, which gets called from JavaScript.



Below is a Plugin Code:

public class PluginBase : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
    //Extract the tracing service for use in debugging sandboxed plug-ins.
    ITracingService tracingService =
        (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    // Obtain the execution context from the service provider.
    IPluginExecutionContext context = (IPluginExecutionContext)
        serviceProvider.GetService(typeof(IPluginExecutionContext));
           
    var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    var serviceProxy = serviceFactory.CreateOrganizationService(context.UserId);           

    // The InputParameters collection contains all the data passed in the message request.
    if (context.InputParameters.Contains("Target") && context.MessageName == "new_copyinvoicecustomaction")
    {              

        Helper helper = new Helper();

        var originalInvoice = helper.GetInvoice(serviceProxy, ((Microsoft.Xrm.Sdk.EntityReference)(context.InputParameters["Target"])).Id);

        // Verify that the target entity represents an account.
        // If not, this plug-in was not registered correctly.
        if (originalInvoice == null)
            return;

        try
        {
        #region Fields Mapping

        Entity copiedInvoice = new Entity("invoice");

        //if (originalInvoice.Attributes.Contains("invoicenumber"))
        //    copiedInvoice["invoicenumber"] = originalInvoice["invoicenumber"];

        //if (originalInvoice.Attributes.Contains("new_invoicedate"))
        //    copiedInvoice["new_invoicedate"] = originalInvoice["new_invoicedate"];

        if (originalInvoice.Attributes.Contains("name"))
            copiedInvoice["name"] = "Copy Created " + DateTime.Now.ToString("dd/MM/yyyy") + " " + originalInvoice["name"].ToString();

        if (originalInvoice.Attributes.Contains("transactioncurrencyid"))
            copiedInvoice["transactioncurrencyid"] = new EntityReference("transactioncurrency", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["transactioncurrencyid"])).Id);

        if (originalInvoice.Attributes.Contains("pricelevelid"))
            copiedInvoice["pricelevelid"] = new EntityReference("pricelevel", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["pricelevelid"])).Id);

        if (originalInvoice.Attributes.Contains("ispricelocked"))
            copiedInvoice["ispricelocked"] = originalInvoice.Attributes["ispricelocked"];

        if (originalInvoice.Attributes.Contains("new_discount"))
            copiedInvoice["new_discount"] = new OptionSetValue(((Microsoft.Xrm.Sdk.OptionSetValue)(originalInvoice.Attributes["new_discount"])).Value);

        if (originalInvoice.Attributes.Contains("new_renewal"))
            copiedInvoice["new_renewal"] = originalInvoice.Attributes["new_renewal"];

        if (originalInvoice.Attributes.Contains("new_paymenttermcodedays"))
            copiedInvoice["new_paymenttermcodedays"] = originalInvoice["new_paymenttermcodedays"];

        if (originalInvoice.Attributes.Contains("new_paymentduedays"))
            copiedInvoice["new_paymentduedays"] = originalInvoice["new_paymentduedays"];

        if (originalInvoice.Attributes.Contains("paymenttermscode"))
            copiedInvoice["paymenttermscode"] = new OptionSetValue(((Microsoft.Xrm.Sdk.OptionSetValue)(originalInvoice.Attributes["paymenttermscode"])).Value);

        if (originalInvoice.Attributes.Contains("new_licensekey"))
            copiedInvoice["new_licensekey"] = originalInvoice["new_licensekey"].ToString();                   

        if (originalInvoice.Attributes.Contains("shippingmethodcode"))
            copiedInvoice["shippingmethodcode"] = new OptionSetValue(((Microsoft.Xrm.Sdk.OptionSetValue)(originalInvoice.Attributes["shippingmethodcode"])).Value);

        if (originalInvoice.Attributes.Contains("new_originalinvoicenumber"))
            copiedInvoice["new_originalinvoicenumber"] = originalInvoice["new_originalinvoicenumber"].ToString();

        if (originalInvoice.Attributes.Contains("new_originalpono"))
            copiedInvoice["new_originalpono"] = originalInvoice["new_originalpono"];

        if (originalInvoice.Attributes.Contains("new_originalquoteno"))
            copiedInvoice["new_originalquoteno"] = originalInvoice["new_originalquoteno"];

        if (originalInvoice.Attributes.Contains("new_billtocountry"))
            copiedInvoice["new_billtocountry"] = new OptionSetValue(((Microsoft.Xrm.Sdk.OptionSetValue)(originalInvoice.Attributes["new_billtocountry"])).Value);

        if (originalInvoice.Attributes.Contains("billto_city"))
            copiedInvoice["billto_city"] = originalInvoice["billto_city"].ToString();
        if (originalInvoice.Attributes.Contains("billto_country"))
            copiedInvoice["billto_country"] = originalInvoice["billto_country"].ToString();
        if (originalInvoice.Attributes.Contains("billto_stateorprovince"))
            copiedInvoice["billto_stateorprovince"] = originalInvoice["billto_stateorprovince"].ToString();
        if (originalInvoice.Attributes.Contains("billto_line1"))
            copiedInvoice["billto_line1"] = originalInvoice["billto_line1"].ToString();
        if (originalInvoice.Attributes.Contains("billto_line2"))
            copiedInvoice["billto_line2"] = originalInvoice["billto_line2"].ToString();
        if (originalInvoice.Attributes.Contains("billto_line3"))
            copiedInvoice["billto_line3"] = originalInvoice["billto_line3"].ToString();
        if (originalInvoice.Attributes.Contains("billto_postalcode"))
            copiedInvoice["billto_postalcode"] = originalInvoice["billto_postalcode"].ToString();

        if (originalInvoice.Attributes.Contains("willcall"))
            copiedInvoice["willcall"] = originalInvoice["willcall"];

        if (originalInvoice.Attributes.Contains("shipto_composite"))
            copiedInvoice["shipto_composite"] = originalInvoice["shipto_composite"].ToString();

        if (originalInvoice.Attributes.Contains("totallineitemamount"))
            copiedInvoice["totallineitemamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["totallineitemamount"])).Value)));

        if (originalInvoice.Attributes.Contains("discountpercentage"))
            copiedInvoice["discountpercentage"] = originalInvoice["discountpercentage"];

        if (originalInvoice.Attributes.Contains("discountamount"))
            copiedInvoice["discountamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["discountamount"])).Value)));
                       
        if (originalInvoice.Attributes.Contains("totalamountlessfreight"))
            copiedInvoice["totalamountlessfreight"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["totalamountlessfreight"])).Value)));

        if (originalInvoice.Attributes.Contains("freightamount"))
            copiedInvoice["freightamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["freightamount"])).Value)));

        if (originalInvoice.Attributes.Contains("totaltax"))
            copiedInvoice["totaltax"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["totaltax"])).Value)));

        if (originalInvoice.Attributes.Contains("totalamount"))
            copiedInvoice["totalamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["totalamount"])).Value)));

        if (originalInvoice.Attributes.Contains("new_endusercustomerpo"))
            copiedInvoice["new_endusercustomerpo"] = originalInvoice["new_endusercustomerpo"];//Text
        ///
        if (originalInvoice.Attributes.Contains("new_quotation"))
            copiedInvoice["new_quotation"] = new EntityReference("quote", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["new_quotation"])).Id);

        if (originalInvoice.Attributes.Contains("customerid"))
            copiedInvoice["customerid"] = new EntityReference("account", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["customerid"])).Id);

        if (originalInvoice.Attributes.Contains("new_primarycontact"))
            copiedInvoice["new_primarycontact"] = new EntityReference("contact", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["new_primarycontact"])).Id);

        if (originalInvoice.Attributes.Contains("new_deliverto"))
            copiedInvoice["new_deliverto"] = new EntityReference("contact", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["new_deliverto"])).Id);

        if (originalInvoice.Attributes.Contains("opportunityid"))
            copiedInvoice["opportunityid"] = new EntityReference("opportunity", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["opportunityid"])).Id);

        if (originalInvoice.Attributes.Contains("salesorderid"))
            copiedInvoice["salesorderid"] = new EntityReference("salesorder", ((Microsoft.Xrm.Sdk.EntityReference)(originalInvoice.Attributes["salesorderid"])).Id);

        if (originalInvoice.Attributes.Contains("description"))
            copiedInvoice["description"] = originalInvoice["description"];

        if (originalInvoice.Attributes.Contains("statecode"))
            copiedInvoice["statecode"] = new OptionSetValue(0);

        if (originalInvoice.Attributes.Contains("duedate"))
            copiedInvoice["duedate"] = originalInvoice["duedate"];

        if (originalInvoice.Attributes.Contains("datedelivered"))
            copiedInvoice["datedelivered"] = originalInvoice["datedelivered"];

        if (originalInvoice.Attributes.Contains("new_maintenanceend"))
            copiedInvoice["new_maintenanceend"] = Convert.ToDateTime(originalInvoice.Attributes["new_maintenanceend"].ToString()).AddYears(1);

        if (originalInvoice.Attributes.Contains("new_maintenancestart"))
            copiedInvoice["new_maintenancestart"] = Convert.ToDateTime(originalInvoice.Attributes["new_maintenancestart"].ToString()).AddYears(1);

        #endregion

            var res = serviceProxy.Create(copiedInvoice);

            var result = helper.GetInvoiceProduct(serviceProxy, originalInvoice.Id);

            if (result != null)
            {
                double totalAmount = 0.0;

                foreach (var product in result.Entities)
                {                    
                    totalAmount = totalAmount + Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["priceperunit"])).Value.ToString()) * Convert.ToDouble(product.Attributes["quantity"].ToString());

                    #region Prodcut Operations

                    if (Convert.ToBoolean(product.Attributes["isproductoverridden"]) == false)//existing
                    {
                        var invoiceProduct = new Entity("invoicedetail");

                        var amountFetchXML = @"
                                               
                                               
                                               
                                                   
                                                   
                                                    
                                                

                                               

                                           
";
                        var amount = serviceProxy.RetrieveMultiple(new FetchExpression(amountFetchXML));

                        if (amount != null && amount.Entities.Count > 0)
                        {
                            invoiceProduct["baseamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(amount.Entities[0].Attributes["amount"])).Value)));// currency
                        }
                        else
                        {
                            if (product.Attributes.Contains("baseamount"))
                                invoiceProduct["baseamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["baseamount"])).Value)));// currency
                        }

                        invoiceProduct["isproductoverridden"] = false;// 2 option
                        if (product.Attributes.Contains("ispriceoverridden"))
                            invoiceProduct["ispriceoverridden"] = product["ispriceoverridden"];// 2
                        if (product.Attributes.Contains("priceperunit"))
                            invoiceProduct["priceperunit"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["priceperunit"])).Value)));// currency
                        if (product.Attributes.Contains("volumediscountamount"))
                            invoiceProduct["volumediscountamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["volumediscountamount"])).Value))); // currency
                        if (product.Attributes.Contains("quantity"))
                            invoiceProduct["quantity"] = product["quantity"];// decimal
                                   
                        if (product.Attributes.Contains("manualdiscountamount"))
                            invoiceProduct["manualdiscountamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["manualdiscountamount"])).Value)));// currency
                        if (product.Attributes.Contains("tax"))
                            invoiceProduct["tax"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["tax"])).Value)));// currency
                        if (product.Attributes.Contains("extendedamount"))
                            invoiceProduct["extendedamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["extendedamount"])).Value)));// currency     
                        if (product.Attributes.Contains("productid"))
                            invoiceProduct["productid"] = new EntityReference("product", ((Microsoft.Xrm.Sdk.EntityReference)(product.Attributes["productid"])).Id);
                        if (product.Attributes.Contains("invoiceid"))
                            invoiceProduct["invoiceid"] = new EntityReference("invoice", res);
                        if (product.Attributes.Contains("uomid"))
                            invoiceProduct["uomid"] = new EntityReference("uom", ((Microsoft.Xrm.Sdk.EntityReference)(product.Attributes["uomid"])).Id); 

                        var ip = serviceProxy.Create(invoiceProduct);
                    }
                    else
                    {
                        var invoiceProduct = new Entity("invoicedetail");

                        invoiceProduct["isproductoverridden"] = true;// 2 option
                        if (product.Attributes.Contains("productdescription"))
                            invoiceProduct["productdescription"] = product["productdescription"];
                        if (product.Attributes.Contains("new_writeinsitecollection"))
                            invoiceProduct["new_writeinsitecollection"] =  new EntityReference("uom", ((Microsoft.Xrm.Sdk.EntityReference)(product.Attributes["new_writeinsitecollection"])).Id); 
                        if (product.Attributes.Contains("new_writeinnumberofusers"))
                            invoiceProduct["new_writeinnumberofusers"] = new OptionSetValue(((Microsoft.Xrm.Sdk.OptionSetValue)(product.Attributes["new_writeinnumberofusers"])).Value);//optionset
                        if (product.Attributes.Contains("ispriceoverridden"))
                            invoiceProduct["ispriceoverridden"] = product["ispriceoverridden"];// 2
                        if (product.Attributes.Contains("priceperunit"))
                            invoiceProduct["priceperunit"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["priceperunit"])).Value)));// currency
                        if (product.Attributes.Contains("volumediscountamount"))
                            invoiceProduct["volumediscountamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["volumediscountamount"])).Value))); // currency
                        if (product.Attributes.Contains("quantity"))
                            invoiceProduct["quantity"] = product["quantity"];// decimal
                        if (product.Attributes.Contains("baseamount"))
                            invoiceProduct["baseamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["baseamount"])).Value)));// currency
                        if (product.Attributes.Contains("manualdiscountamount"))
                            invoiceProduct["manualdiscountamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["manualdiscountamount"])).Value)));// currency
                        if (product.Attributes.Contains("tax"))
                            invoiceProduct["tax"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["tax"])).Value)));// currency
                        if (product.Attributes.Contains("extendedamount"))
                            invoiceProduct["extendedamount"] = new Money(new Decimal(Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(product.Attributes["extendedamount"])).Value)));// currency
                        if (product.Attributes.Contains("new_writeinproductdescription"))
                            invoiceProduct["new_writeinproductdescription"] = product["new_writeinproductdescription"];
                        if (product.Attributes.Contains("invoiceid"))
                            invoiceProduct["invoiceid"] = new EntityReference("invoice",res);

                        var ip = serviceProxy.Create(invoiceProduct);
                    }
                    #endregion
                }

                Entity updateInvoice = new Entity("invoice");
                updateInvoice.Id = res;

                #region Total Amount Calculations

                updateInvoice["totallineitemamount"] = new Money(new Decimal(totalAmount));

                double preFeightAmount = 0.0;

                if (originalInvoice.Attributes.Contains("discountpercentage") && originalInvoice.Attributes.Contains("discountamount"))
                    preFeightAmount = helper.GetPreFreightAmount(totalAmount, Convert.ToDouble((originalInvoice.Attributes["discountpercentage"]).ToString()), Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["discountamount"])).Value.ToString()));
                else if (originalInvoice.Attributes.Contains("discountpercentage"))
                    preFeightAmount = (totalAmount * Convert.ToDouble((originalInvoice.Attributes["discountpercentage"]).ToString())) / 100;
                else if (originalInvoice.Attributes.Contains("discountamount"))
                    preFeightAmount = totalAmount - Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["discountamount"])).Value.ToString());

                updateInvoice["totalamountlessfreight"] = new Money(new Decimal(preFeightAmount));
                if ((originalInvoice.Attributes.Contains("freightamount")))
                    preFeightAmount = Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["freightamount"])).Value.ToString());
                if (originalInvoice.Attributes.Contains("totaltax"))
                    preFeightAmount = preFeightAmount + Convert.ToDouble(((Microsoft.Xrm.Sdk.Money)(originalInvoice.Attributes["totaltax"])).Value.ToString());

                updateInvoice["totalamount"] = new Money(new Decimal(preFeightAmount));

                serviceProxy.Update(updateInvoice);

                #endregion                        
            }
            context.OutputParameters["Result"] = true;
            context.OutputParameters["DuplicateInvoiceId"] = res;

        }
        catch (Exception ex)
        {
            context.OutputParameters["Result"] = ex.Message;
        }             
    }
}

}

No comments: