我正在创建一个将平均分配折扣的插件。我想平均分配所有产品的折扣金额。因此,如果一个产品的价格为2000,而另一个产品的价格为1000,则我想给予折扣300,因此应将其除以金额200应分配为2000,crm为100至100。 / p>
public class DivideEqualDiscount : IPlugin
{
static IOrganizationService _service;
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
Entity target = (Entity)context.InputParameters["Target"];
if (target.Attributes.Contains("new_amount"))
{
target["new_amount"] = "52";
}
if (target.Attributes.Contains("new_discount"))
{
target["new_discount"] = "52";
}
string fetchData = @"
<entity name='opportunityproduct' >
<attribute name='manualdiscountamount' />
<attribute name='priceperunit' />
<attribute name='volumediscountamount' />
<attribute name='quantity' />
<attribute name='extendedamount' />
</entity>
</fetch>";
EntityCollection ec = ExecuteFetch(fetchData);
foreach (var item in ec.Entities)
{
if (item.Attributes.Contains("msdyn_costpriceperunit"))
{
target["new_discountamount"] = "";
target["new_discountpercentage"] = "";
}
if (item.Attributes.Contains("quantity"))
{
}
if (item.Attributes.Contains("extendedamount"))
{
}
}
}
}
public static EntityCollection ExecuteFetch(string fetchXmlString)
{
return _service.RetrieveMultiple(new FetchExpression(fetchXmlString));
}
}
}
答案 0 :(得分:1)
一种方法是计算折扣与商机总额的百分比,然后将该折扣百分比应用于每行。
例如:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
public override void Run()
{
var totalDiscount = 200000;
using (var ctx = new OrganizationServiceContext(svc))
{
var q = from l in ctx.CreateQuery("opportunityproduct")
where l.GetAttributeValue<EntityReference>("opportunityid").Id.Equals(new Guid("D80E0283-5BF2-E311-945F-6C3BE5A8DD64"))
select l;
var lines = q.ToList();
var total = lines.Sum(l => getLineTotal(l));
var discountPercent = totalDiscount / total;
lines.ForEach(l =>
{
var discount = discountPercent * getLineTotal(l);
l["manualdiscountamount"] = new Money(discount);
ctx.UpdateObject(l);
});
ctx.SaveChanges();
}
}
private decimal getLineTotal(Entity line) =>
line.GetAttributeValue<Money>("priceperunit").Value * line.GetAttributeValue<decimal>("quantity");