/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePreValidateSalesOrderDelete(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; var SalesOrderTargetEntity = (EntityReference)context.InputParameters["Target"]; string message = context.MessageName; string error = ""; try { SalesOrderHandler SalesOrderHandler = new SalesOrderHandler(service, trace); EntityCollection SalesOrderCollection = CommonHandler.RetrieveRecordsByOneValue(SalesOrderTargetEntity.LogicalName, "salesorderid", SalesOrderTargetEntity.Id, service, null, OrderType.Ascending, new[] { "salesorderid", "gsc_statuscopy", "quoteid" }); if (SalesOrderCollection.Entities.Count > 0) { if (SalesOrderHandler.ValidateDelete(SalesOrderCollection.Entities[0]) == false) { throw new InvalidPluginExecutionException("Sales order record(s) cannot be deleted."); } } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePreOrderCreate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; Entity salesOrder = (Entity)context.InputParameters["Target"]; string message = context.MessageName; string error = ""; try { SalesOrderHandler salesOrderHandler = new SalesOrderHandler(service, trace); salesOrderHandler.CheckifCustomerHasTax(salesOrder); salesOrderHandler.CheckifVehicleHasTax(salesOrder); salesOrderHandler.ReplicateQuoteInfo(salesOrder); salesOrderHandler.ReplicateVehicleDetails(salesOrder, message); salesOrderHandler.SetVehicleColorAmount(salesOrder, message); //salesOrderHandler.SetChattelFeeAmount(salesOrder, message); salesOrderHandler.SetNetPriceAmount(salesOrder, message); salesOrderHandler.SetTotalCashOutlayAmount(salesOrder, message); salesOrderHandler.SetDates(salesOrder); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error)); } }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostOrderCreate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; Entity salesOrderEntity = (Entity)context.InputParameters["Target"]; string message = context.MessageName; string error = ""; try { SalesOrderHandler salesOrderHandler = new SalesOrderHandler(service, trace); salesOrderHandler.ReplicateQuoteVehicleAccessories(salesOrderEntity); salesOrderHandler.ReplicateQuoteDiscount(salesOrderEntity); //salesOrderHandler.ReplicateDiscountFields(salesOrder); salesOrderHandler.ReplicateQuoteCharges(salesOrderEntity); //salesOrderHandler.CreateCoverageAvailable(salesOrder, message); salesOrderHandler.CreateRequirementChecklist(salesOrderEntity, message); salesOrderHandler.DeleteExistingMonthlyAmortizationRecords(salesOrderEntity); salesOrderHandler.GetSelectedMonthlyAmortization(salesOrderEntity); salesOrderHandler.GenerateAccessoriesforVehicleModel(salesOrderEntity); salesOrderHandler.ReplicateDiscountFields(salesOrderEntity); salesOrderHandler.ReplicateQuoteCabChassis(salesOrderEntity); } catch (Exception ex) { //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error)); throw new InvalidPluginExecutionException(ex.Message); } }
public void SetCCAddOnAmount(Entity orderCabChassis, String message) { _tracingService.Trace("Started SetCCAddOnAmount Method..."); var orderId = orderCabChassis.Contains("gsc_orderid") ? orderCabChassis.GetAttributeValue <EntityReference>("gsc_orderid").Id : Guid.Empty; Decimal ccAddOns = 0; EntityCollection orderCollection = CommonHandler.RetrieveRecordsByOneValue("salesorder", "salesorderid", orderId, _organizationService, null, OrderType.Ascending, new[] { "gsc_discount", "gsc_ccaddons", "gsc_netprice", "gsc_unitprice", "gsc_colorprice", "gsc_freightandhandling", "gsc_paymentmode", "gsc_branchid", "gsc_vatablesales", "gsc_vatexemptsales", "gsc_zeroratedsales", "gsc_totalsales", "gsc_vatamount", "gsc_totalamountdue", "gsc_insurance", "gsc_othercharges", "customerid" , "gsc_accessories", "gsc_productid", "gsc_downpaymentamount", "gsc_discountamountfinanced" }); if (orderCollection.Entities.Count > 0) { Entity orderEntity = orderCollection.Entities[0]; Decimal paymentMode = orderEntity.Contains("gsc_paymentmode") ? orderEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value : 0; //Retrieve all order cab chassis related to quote EntityCollection orderCabChassisCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_ordercabchassis", "gsc_orderid", orderId, _organizationService, null, OrderType.Ascending, new[] { "gsc_amount", "gsc_financing" }); if (orderCabChassisCollection.Entities.Count > 0) { //Get total cc add on price that are for financing... foreach (Entity quoteCabChassisEntity in orderCabChassisCollection.Entities) { if (quoteCabChassisEntity.Contains("gsc_amount")) { ccAddOns += quoteCabChassisEntity.GetAttributeValue <Money>("gsc_amount").Value; _tracingService.Trace("CC Add Ons Amount: " + ccAddOns); } } //Subtract sellprice of deleted. if (orderCabChassis.Contains("gsc_amount") && message.Equals("Delete")) { _tracingService.Trace("Message is Delete..."); ccAddOns = ccAddOns - (Decimal)orderCabChassis.GetAttributeValue <Money>("gsc_amount").Value; } orderEntity["gsc_ccaddons"] = new Money(ccAddOns); #region Recalculate net price SalesOrderHandler orderHandler = new SalesOrderHandler(_organizationService, _tracingService); orderEntity["gsc_netprice"] = new Money(orderHandler.ComputeNetPrice(orderEntity)); orderEntity = orderHandler.ComputeVAT(orderEntity); var paymentmode = orderEntity.Contains("gsc_paymentmode") ? orderEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value : Decimal.Zero; var amountfinanced = Decimal.Zero; //Financing if (paymentmode == 100000001 || (paymentmode == 100000002 && orderHandler.CheckifOrderHasDownPayment(orderEntity) == true)) { amountfinanced = orderHandler.ComputeAmountFinanced(orderEntity); orderEntity["gsc_amountfinanced"] = new Money(amountfinanced); orderEntity["gsc_totalamountfinanced"] = new Money(amountfinanced); } #endregion if (ccAddOns >= 0) { _organizationService.Update(orderEntity); } else { _tracingService.Trace("CC add on is negative..."); } } } _tracingService.Trace("ending SetCCAddOnAmount Entity"); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostOrderUpdate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; Entity salesOrder = (Entity)context.InputParameters["Target"]; if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)) { return; } if (salesOrder.LogicalName != "salesorder") { return; } if (context.Mode == 0) //Synchronous Plug-in { string message = context.MessageName; try { #region Pre-images var preImageCustomerId = preImageEntity.GetAttributeValue <EntityReference>("customerid") != null ? preImageEntity.GetAttributeValue <EntityReference>("customerid").Id : Guid.Empty; var preImageProductId = preImageEntity.GetAttributeValue <EntityReference>("gsc_productid") != null ? preImageEntity.GetAttributeValue <EntityReference>("gsc_productid").Id : Guid.Empty; var preImageBankId = preImageEntity.GetAttributeValue <EntityReference>("gsc_bankid") != null ? preImageEntity.GetAttributeValue <EntityReference>("gsc_bankid").Id : Guid.Empty; var preImageUnitPrice = preImageEntity.GetAttributeValue <Money>("gsc_unitprice") != null ? preImageEntity.GetAttributeValue <Money>("gsc_unitprice").Value : Decimal.Zero; var preImageDpAmount = preImageEntity.GetAttributeValue <Money>("gsc_applytodpamount") != null ? preImageEntity.GetAttributeValue <Money>("gsc_applytodpamount").Value : Decimal.Zero; var preImageAfAmount = preImageEntity.GetAttributeValue <Money>("gsc_applytoafamount") != null ? preImageEntity.GetAttributeValue <Money>("gsc_applytoafamount").Value : Decimal.Zero; var preImageUpAmount = preImageEntity.GetAttributeValue <Money>("gsc_applytoupamount") != null ? preImageEntity.GetAttributeValue <Money>("gsc_applytoupamount").Value : Decimal.Zero; var preImagePreferredColor1 = preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid1") != null ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid1").Id : Guid.Empty; var preImagePreferredColor2 = preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid2") != null ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid2").Id : Guid.Empty; var preImagePreferredColor3 = preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid3") != null ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid3").Id : Guid.Empty; var preImageFreeChattelFee = preImageEntity.GetAttributeValue <Boolean>("gsc_freechattelfee"); var preImageTotalInsurance = preImageEntity.GetAttributeValue <Money>("gsc_totalinsurancecharges") != null ? preImageEntity.GetAttributeValue <Money>("gsc_totalinsurancecharges").Value : Decimal.Zero; var preImageFinancingScheme = preImageEntity.GetAttributeValue <EntityReference>("gsc_financingschemeid") != null ? preImageEntity.GetAttributeValue <EntityReference>("gsc_financingschemeid").Id : Guid.Empty; var preImageNetDownPayment = preImageEntity.GetAttributeValue <Money>("gsc_netdownpayment") != null ? preImageEntity.GetAttributeValue <Money>("gsc_netdownpayment").Value : Decimal.Zero; var preImageIsRequestForAllocation = preImageEntity.GetAttributeValue <Boolean>("gsc_isrequestforallocation"); var preImageInventoryIdforAllocation = preImageEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") != null ? preImageEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") : String.Empty; var preImageChattelFeeEditable = preImageEntity.GetAttributeValue <Money>("gsc_chattelfeeeditable") != null ? preImageEntity.GetAttributeValue <Money>("gsc_chattelfeeeditable").Value : Decimal.Zero; var preImagePaymentMode = preImageEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode") != null ? preImageEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value : 0; var preImageChattelFee = preImageEntity.GetAttributeValue <Money>("gsc_chattelfee") != null ? preImageEntity.GetAttributeValue <Money>("gsc_chattelfee").Value : Decimal.Zero; var preImageInsurance = preImageEntity.GetAttributeValue <Money>("gsc_insurance") != null ? preImageEntity.GetAttributeValue <Money>("gsc_insurance").Value : Decimal.Zero; var preImageOtherCharges = preImageEntity.GetAttributeValue <Money>("gsc_othercharges") != null ? preImageEntity.GetAttributeValue <Money>("gsc_othercharges").Value : Decimal.Zero; var preImageDownPaymentAmount = preImageEntity.GetAttributeValue <Money>("gsc_downpaymentamount") != null ? preImageEntity.GetAttributeValue <Money>("gsc_downpaymentamount").Value : Decimal.Zero; var preImageStatus = preImageEntity.Contains("gsc_status") ? preImageEntity.GetAttributeValue <OptionSetValue>("gsc_status").Value : Decimal.Zero; var preImageReservation = preImageEntity.GetAttributeValue <Money>("gsc_reservationfee") != null ? preImageEntity.GetAttributeValue <Money>("gsc_reservationfee").Value : Decimal.Zero; var preImageAllocatedItemstoDelete = preImageEntity.Contains("gsc_allocateditemstodelete") ? preImageEntity.GetAttributeValue <String>("gsc_allocateditemstodelete") : String.Empty; var preImageIsReadyPDI = preImageEntity.GetAttributeValue <Boolean>("gsc_isreadyforpdi"); var preImageIsTransferforInvoice = preImageEntity.GetAttributeValue <Boolean>("gsc_istransferforinvoicing"); #endregion #region Post-images var postImageCustomerId = postImageEntity.GetAttributeValue <EntityReference>("customerid") != null ? postImageEntity.GetAttributeValue <EntityReference>("customerid").Id : Guid.Empty; var postImageProductId = postImageEntity.GetAttributeValue <EntityReference>("gsc_productid") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_productid").Id : Guid.Empty; var postImageBankId = postImageEntity.GetAttributeValue <EntityReference>("gsc_bankid") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_bankid").Id : Guid.Empty; var postImageUnitPrice = postImageEntity.GetAttributeValue <Money>("gsc_unitprice") != null ? postImageEntity.GetAttributeValue <Money>("gsc_unitprice").Value : Decimal.Zero; var postImageDpAmount = postImageEntity.GetAttributeValue <Money>("gsc_applytodpamount") != null ? postImageEntity.GetAttributeValue <Money>("gsc_applytodpamount").Value : Decimal.Zero; var postImageAfAmount = postImageEntity.GetAttributeValue <Money>("gsc_applytoafamount") != null ? postImageEntity.GetAttributeValue <Money>("gsc_applytoafamount").Value : Decimal.Zero; var postImageUpAmount = postImageEntity.GetAttributeValue <Money>("gsc_applytoupamount") != null ? postImageEntity.GetAttributeValue <Money>("gsc_applytoupamount").Value : Decimal.Zero; var postImagePreferredColor1 = postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid1") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid1").Id : Guid.Empty; var postImagePreferredColor2 = postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid2") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid2").Id : Guid.Empty; var postImagePreferredColor3 = postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid3") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid3").Id : Guid.Empty; var postImageFreeChattelFee = postImageEntity.GetAttributeValue <Boolean>("gsc_freechattelfee"); var postImageTotalInsurance = postImageEntity.GetAttributeValue <Money>("gsc_totalinsurancecharges") != null ? postImageEntity.GetAttributeValue <Money>("gsc_totalinsurancecharges").Value : Decimal.Zero; var postImageFinancingScheme = postImageEntity.GetAttributeValue <EntityReference>("gsc_financingschemeid") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_financingschemeid").Id : Guid.Empty; var postImageNetDownPayment = postImageEntity.GetAttributeValue <Money>("gsc_netdownpayment") != null ? postImageEntity.GetAttributeValue <Money>("gsc_netdownpayment").Value : Decimal.Zero; var postImageIsRequestForAllocation = postImageEntity.GetAttributeValue <Boolean>("gsc_isrequestforallocation"); var postImageInventoryIdforAllocation = postImageEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") != null ? postImageEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") : String.Empty; var postImageChattelFeeEditable = postImageEntity.GetAttributeValue <Money>("gsc_chattelfeeeditable") != null ? postImageEntity.GetAttributeValue <Money>("gsc_chattelfeeeditable").Value : Decimal.Zero; var postImagePaymentMode = postImageEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode") != null ? postImageEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value : 0; var postImageChattelFee = postImageEntity.GetAttributeValue <Money>("gsc_chattelfee") != null ? postImageEntity.GetAttributeValue <Money>("gsc_chattelfee").Value : Decimal.Zero; var postImageInsurance = postImageEntity.GetAttributeValue <Money>("gsc_insurance") != null ? postImageEntity.GetAttributeValue <Money>("gsc_insurance").Value : Decimal.Zero; var postImageOtherCharges = postImageEntity.GetAttributeValue <Money>("gsc_othercharges") != null ? postImageEntity.GetAttributeValue <Money>("gsc_othercharges").Value : Decimal.Zero; var postImageDownPaymentAmount = postImageEntity.GetAttributeValue <Money>("gsc_downpaymentamount") != null ? postImageEntity.GetAttributeValue <Money>("gsc_downpaymentamount").Value : Decimal.Zero; var postImageStatus = postImageEntity.GetAttributeValue <OptionSetValue>("gsc_status") != null ? postImageEntity.GetAttributeValue <OptionSetValue>("gsc_status").Value : Decimal.Zero; var postImageReservation = postImageEntity.GetAttributeValue <Money>("gsc_reservationfee") != null ? postImageEntity.GetAttributeValue <Money>("gsc_reservationfee").Value : Decimal.Zero; var postImageAllocatedItemstoDelete = postImageEntity.Contains("gsc_allocateditemstodelete") ? postImageEntity.GetAttributeValue <String>("gsc_allocateditemstodelete") : String.Empty; var postImageIsTransferforInvoice = postImageEntity.GetAttributeValue <Boolean>("gsc_istransferforinvoicing"); var postImageIsReadyPDI = postImageEntity.GetAttributeValue <Boolean>("gsc_isreadyforpdi"); #endregion SalesOrderHandler salesOrderHandler = new SalesOrderHandler(service, trace); if (preImageCustomerId != postImageCustomerId) { salesOrderHandler.PopulateCustomerInfo(postImageEntity); } //Function triggered on Payment Mode change if (preImagePaymentMode != postImagePaymentMode) { salesOrderHandler.SetNetPriceAmount(postImageEntity, message); salesOrderHandler.SetChattelFeeAmount(postImageEntity, message); } //Functions triggered on Product change if (preImageProductId != postImageProductId) { salesOrderHandler.ReplicateVehicleDetails(postImageEntity, message); salesOrderHandler.DeleteExistingVehicleFreebies(postImageEntity); salesOrderHandler.DeleteOrderCabChassis(postImageEntity); salesOrderHandler.SetNetPriceAmount(postImageEntity, message); } //Functions triggered on Unit Price, Bank, or Free Chattel Fee change if (preImageBankId != postImageBankId || preImageUnitPrice != postImageUnitPrice || preImageFreeChattelFee != postImageFreeChattelFee) { salesOrderHandler.SetChattelFeeAmount(postImageEntity, message); } //Functions triggered on Chattel Fee (gsc_chattelfeeeditable) change if (preImageChattelFeeEditable != postImageChattelFeeEditable) { salesOrderHandler.ReplicateEditableChattelFee(postImageEntity); } //Functions triggered on Apply Amount fields if (preImageDpAmount != postImageDpAmount || preImageAfAmount != postImageAfAmount || preImageUpAmount != postImageUpAmount || preImageDownPaymentAmount != postImageDownPaymentAmount) { salesOrderHandler.SetLessDiscountValues(postImageEntity, message); } if (preImageTotalInsurance != postImageTotalInsurance) { salesOrderHandler.UpdateInsurance(postImageEntity); } //Function triggered Preferred Color change if (preImagePreferredColor1 != postImagePreferredColor1) { salesOrderHandler.SetVehicleColorAmount(postImageEntity, message); } if (preImageFinancingScheme != postImageFinancingScheme) { salesOrderHandler.DeleteExistingMonthlyAmortizationRecords(postImageEntity); } //Functions triggered on Net Down Payment or Total Premium change if (preImageNetDownPayment != postImageNetDownPayment) { salesOrderHandler.SetNetPriceAmount(postImageEntity, message); } if (preImageBankId != postImageBankId) { salesOrderHandler.DeleteExistingRequirementChecklist(preImageEntity); salesOrderHandler.CreateRequirementChecklist(postImageEntity, message); } //Functions triggered on IsRequestForAllocation change if (preImageIsRequestForAllocation != postImageIsRequestForAllocation) { if (salesOrderHandler.CheckifHasVehicleAllocator(postImageEntity) == false) { throw new InvalidPluginExecutionException("There is no setup for vehicle allocator."); } else { salesOrderHandler.SetRequestAllocationDate(postImageEntity); } } //Functions triggered on InventoryIdforAllocation change if (preImageInventoryIdforAllocation != postImageInventoryIdforAllocation) { salesOrderHandler.AllocateVehicle(postImageEntity); } //Functions triggered on Net Down Payment, Chattel Fee, Insurance Charges, and Other Charges field on Summary section if (preImageNetDownPayment != postImageNetDownPayment || preImageChattelFee != postImageChattelFee || preImageInsurance != postImageInsurance || preImageOtherCharges != postImageOtherCharges) { salesOrderHandler.SetTotalCashOutlayAmount(postImageEntity, message); } //Function triggered on change of status if (preImageStatus != postImageStatus) { salesOrderHandler.UpdateStatus(postImageEntity); salesOrderHandler.UnAllocateVehicle(postImageEntity); } //Function triggered on Update gsc_allocateditemstodelete if (preImageAllocatedItemstoDelete != postImageAllocatedItemstoDelete) { salesOrderHandler.DeleteVehicleAllocatedItems(postImageEntity); } //Function trigger on Update gsc_istransferforinvoicing if (preImageIsTransferforInvoice != postImageIsTransferforInvoice) { salesOrderHandler.SetTransferInvoiceDate(postImageEntity); } if (preImageReservation != postImageReservation) { salesOrderHandler.UpdateReservation(postImageEntity); } //Recompute Unit Price when Markup % Changed - Leslie Baliguat 05/08/17 var preMarkup = preImageEntity.Contains("gsc_markup") ? preImageEntity.GetAttributeValue <Decimal>("gsc_markup") : 0; var postMarkup = postImageEntity.Contains("gsc_markup") ? postImageEntity.GetAttributeValue <Decimal>("gsc_markup") : 0; if (preMarkup != postMarkup) { salesOrderHandler.UpdateGovernmentTax(postImageEntity, message); } if (preImageIsReadyPDI != postImageIsReadyPDI) { salesOrderHandler.UpdatePDIStatus(postImageEntity); } } catch (Exception ex) { //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error)); throw new InvalidPluginExecutionException(ex.Message); } } }
//Created By : Jerome Anthony Gerero, Created On : 3/11/2016 public Entity SetOrderTotalChargesAmount(Entity salesOrderChargeEntity, String message) { _tracingService.Trace("Started SetOrderTotalChargesAmount method.."); var orderId = salesOrderChargeEntity.GetAttributeValue <EntityReference>("gsc_orderid") != null ? salesOrderChargeEntity.GetAttributeValue <EntityReference>("gsc_orderid").Id : Guid.Empty; var chargetype = salesOrderChargeEntity.Contains("gsc_chargetype") ? salesOrderChargeEntity.GetAttributeValue <OptionSetValue>("gsc_chargetype").Value : 0; Decimal totalOtherCharges = 0; Decimal totalFreight = 0; //Retrieve Applied Charges records with the same Sales Order EntityCollection salesOrderChargeRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_cmn_ordercharge", "gsc_orderid", orderId, _organizationService, null, OrderType.Ascending, new[] { "gsc_actualcost", "gsc_free", "gsc_chargetype" }); //Retrieve Sales Order record from Sales Order field value EntityCollection salesOrderRecords = CommonHandler.RetrieveRecordsByOneValue("salesorder", "salesorderid", orderId, _organizationService, null, OrderType.Ascending, new[] { "gsc_totalchargesamount", "statecode", "gsc_othercharges", "gsc_totalcashoutlay", "gsc_downpayment", "gsc_chattelfee", "gsc_netdownpayment", "gsc_insurance", "gsc_freightandhandling", "gsc_discount", "gsc_unitprice", "gsc_colorprice", "gsc_netprice", "gsc_reservation", "gsc_paymentmode", "gsc_vatablesales", "gsc_vatexemptsales", "gsc_zeroratedsales", "gsc_totalsales", "gsc_vatamount", "gsc_totalamountdue", "customerid", "gsc_productid", "gsc_totalchargesamount", "gsc_totalpremium", "gsc_amountfinanced", "gsc_downpaymentamount", "gsc_totalamountfinanced" }); if (salesOrderChargeRecords != null && salesOrderChargeRecords.Entities.Count > 0) { foreach (var salesOrderCharge in salesOrderChargeRecords.Entities) { chargetype = salesOrderCharge.Contains("gsc_chargetype") ? salesOrderCharge.GetAttributeValue <OptionSetValue>("gsc_chargetype").Value : 0; if (salesOrderCharge.Contains("gsc_actualcost")) { if (chargetype == 100000000) //freight { _tracingService.Trace("Add Freight."); totalFreight += salesOrderCharge.GetAttributeValue <Boolean>("gsc_free") ? Decimal.Zero : salesOrderCharge.GetAttributeValue <Money>("gsc_actualcost").Value; _tracingService.Trace(totalFreight.ToString()); } else { _tracingService.Trace("Add Other Charges."); totalOtherCharges += salesOrderCharge.GetAttributeValue <Boolean>("gsc_free") ? Decimal.Zero : salesOrderCharge.GetAttributeValue <Money>("gsc_actualcost").Value; _tracingService.Trace(totalOtherCharges.ToString()); } } } if (salesOrderChargeEntity.Contains("gsc_actualcost") && message.Equals("Delete")) { if (chargetype == 100000000) //freight { _tracingService.Trace("Delete Freight."); totalFreight = totalFreight - (Decimal)salesOrderChargeEntity.GetAttributeValue <Money>("gsc_actualcost").Value; _tracingService.Trace(totalFreight.ToString()); } else { _tracingService.Trace("Delete Other Charges."); totalOtherCharges = totalOtherCharges - (Decimal)salesOrderChargeEntity.GetAttributeValue <Money>("gsc_actualcost").Value; _tracingService.Trace(totalOtherCharges.ToString()); } } } if (salesOrderRecords != null && salesOrderRecords.Entities.Count > 0 && salesOrderRecords.Entities[0].GetAttributeValue <OptionSetValue>("statecode").Value == 0) { SalesOrderHandler SOHandler = new SalesOrderHandler(_organizationService, _tracingService); Entity salesOrder = salesOrderRecords.Entities[0]; salesOrder["gsc_freightandhandling"] = new Money(totalFreight); salesOrder["gsc_othercharges"] = new Money(totalOtherCharges); salesOrder["gsc_totalchargesamount"] = new Money(totalFreight + totalOtherCharges); var netprice = SOHandler.ComputeNetPrice(salesOrder); salesOrder["gsc_netprice"] = new Money(netprice); //Compute VAT salesOrder = SOHandler.ComputeVAT(salesOrder); var paymentmode = salesOrder.Contains("gsc_paymentmode") ? salesOrder.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value : Decimal.Zero; //Financing if (paymentmode == 100000001 || paymentmode == 100000002) { var amountfinanced = SOHandler.ComputeAmountFinanced(salesOrder); salesOrder["gsc_amountfinanced"] = new Money(amountfinanced); salesOrder["gsc_totalamountfinanced"] = new Money(amountfinanced); if (paymentmode == 100000001) { salesOrder = SOHandler.SetTotalCashOutlayAmount(salesOrder, "Create"); } } _organizationService.Update(salesOrder); return(salesOrder); } _tracingService.Trace("Ended SetOrderTotalChargesAmount method.."); return(salesOrderChargeEntity); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostOrderChargeUpdate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)) { return; } Entity salesOrderChargeEntity = (Entity)context.InputParameters["Target"]; if (salesOrderChargeEntity.LogicalName != "gsc_cmn_ordercharge") { return; } if (context.Mode == 0) //Synchronous Plugin { try { #region Pre-images var preImageSalesOrderId = preImageEntity.Contains("gsc_orderid") ? preImageEntity.GetAttributeValue <EntityReference>("gsc_orderid").Id : Guid.Empty; var preImageSalesOrderChargeAmount = preImageEntity.Contains("gsc_actualcost") ? preImageEntity.GetAttributeValue <Money>("gsc_actualcost").Value : Decimal.Zero; var preImageChargesCode = preImageEntity.Contains("gsc_chargesid") ? preImageEntity.GetAttributeValue <EntityReference>("gsc_chargesid").Id : Guid.Empty; var preImageFree = preImageEntity.GetAttributeValue <Boolean>("gsc_free"); #endregion #region Post-images var postImageSalesOrderId = postImageEntity.Contains("gsc_orderid") ? postImageEntity.GetAttributeValue <EntityReference>("gsc_orderid").Id : Guid.Empty; var postImageSalesOrderChargeAmount = postImageEntity.Contains("gsc_actualcost") ? postImageEntity.GetAttributeValue <Money>("gsc_actualcost").Value : Decimal.Zero; var postImageChargesCode = postImageEntity.Contains("gsc_chargesid") ? postImageEntity.GetAttributeValue <EntityReference>("gsc_chargesid").Id : Guid.Empty; var postImageFree = postImageEntity.GetAttributeValue <Boolean>("gsc_free"); #endregion //Modified By : Jerome Anthony Gerero, Modified On : 9/21/2016 //Purpose : Call SetTotalCashOutlayAmount method from SalesOrderHandler on Total Charges Amount change string message = context.MessageName; SalesOrderChargeHandler salesOrderChargeHandler = new SalesOrderChargeHandler(service, trace); SalesOrderHandler salesOrderHandler = new SalesOrderHandler(service, trace); Guid salesOrderId = postImageEntity.GetAttributeValue <EntityReference>("gsc_orderid") != null ? postImageEntity.GetAttributeValue <EntityReference>("gsc_orderid").Id : Guid.Empty; Entity salesOrder = service.Retrieve("salesorder", salesOrderId, new ColumnSet(true)); //Call functions on Charge Code change if (preImageChargesCode != postImageChargesCode) { salesOrderChargeHandler.SetChargeDetails(postImageEntity, message); } //Call functions on Order ID, Charge Amount change if (preImageSalesOrderId != postImageSalesOrderId || preImageSalesOrderChargeAmount != postImageSalesOrderChargeAmount || preImageFree != postImageFree) { salesOrderChargeHandler.SetOrderTotalChargesAmount(postImageEntity, message); //salesOrderHandler.SetTotalCashOutlayAmount(salesOrder, message); } if (preImageFree != postImageFree) { salesOrderChargeHandler.FreeCharges(postImageEntity); } } catch (Exception ex) { //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error)); throw new InvalidPluginExecutionException(ex.Message); } } }
public void checkForCompleteRequirements() { #region 1. Setup / Arrange var orgServiceMock = new Mock <IOrganizationService>(); var orgService = orgServiceMock.Object; var orgTracingMock = new Mock <ITracingService>(); var orgTracing = orgTracingMock.Object; #region Sales Order Entity Collection var SalesOrderCollection = new EntityCollection() { EntityName = "salesorder", Entities = { new Entity { Id = Guid.NewGuid(), LogicalName = "salesorder", Attributes = { { "gsc_status", new OptionSetValue(1) } }, FormattedValues = { { "gsc_status", "Test" }, } }, new Entity { Id = Guid.NewGuid(), LogicalName = "salesorder", Attributes = { { "gsc_status", new OptionSetValue(1) } }, FormattedValues = { { "gsc_status", "Test" }, } } } }; #endregion #region Requirement Checklist Entity Collection var RequirementChecklistCollection = new EntityCollection() { EntityName = "gsc_sls_requirementchecklist", Entities = { new Entity { Id = Guid.NewGuid(), LogicalName = "gsc_sls_requirementchecklist", Attributes = { { "gsc_submitted", (bool)true }, { "gsc_orderid", new EntityReference("salesorder", SalesOrderCollection.Entities[0].Id)} } }, new Entity { Id = Guid.NewGuid(), LogicalName = "gsc_sls_requirementchecklist", Attributes = { { "gsc_submitted", (bool)true }, { "gsc_orderid", new EntityReference("salesorder", SalesOrderCollection.Entities[1].Id)} } }, new Entity { Id = Guid.NewGuid(), LogicalName = "gsc_sls_requirementchecklist", Attributes = { { "gsc_submitted", (bool)true }, { "gsc_orderid", new EntityReference("salesorder", SalesOrderCollection.Entities[0].Id)} } } } }; #endregion orgServiceMock.Setup((service => service.RetrieveMultiple( It.Is <QueryExpression>(expression => expression.EntityName == RequirementChecklistCollection.EntityName) ))).Returns(RequirementChecklistCollection); orgServiceMock.Setup(service => service.Retrieve( It.IsAny <string>(), It.IsAny <Guid>(), It.IsAny <ColumnSet>())).Returns(SalesOrderCollection.Entities[0]); #endregion #region 2. Call/Action //RequirementsChecklistHandler handler = new RequirementsChecklistHandler(orgService, orgTracing); SalesOrderHandler soHandler = new SalesOrderHandler(orgService, orgTracing); //bool res = handler.checkForCompleteRequirements(RequirementChecklistCollection.Entities[0]); //if (res) // soHandler.SetStatus(RequirementChecklistCollection.Entities[0].GetAttributeValue<EntityReference>("gsc_orderid").Id); #endregion #region 3. Verify //Assert.AreEqual(true,res); Assert.AreEqual(new OptionSetValue(100000002), SalesOrderCollection.Entities[0].GetAttributeValue <OptionSetValue>("gsc_status")); #endregion }