narsil/Tanshu.Accounts.Repository/VoucherSettlementBI.cs
2014-11-20 13:42:20 +05:30

72 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using Tanshu.Accounts.Entities;
using Tanshu.Accounts.Entities.Auth;
using NHibernate;
using System.Linq;
using Tanshu.Common.Helpers;
namespace Tanshu.Accounts.Repository
{
public partial class VoucherBI : UnitOfWork<Voucher>
{
private IDictionary<SettleOption, decimal> GetSettlementOptions(Voucher voucher)
{
IDictionary<SettleOption, decimal> options = new Dictionary<SettleOption, decimal>();
foreach (var item in voucher.Settlements)
{
if (item.Settled == SettleOption.Amount || item.Settled == SettleOption.RoundOff || item.Settled == SettleOption.Unsettled)
continue;
if (options.ContainsKey(item.Settled))
options[item.Settled] += item.Amount;
else
options.Add(item.Settled, item.Amount);
}
return options;
}
public void UpdateSettlements(Voucher voucher, IDictionary<SettleOption, decimal> values)
{
var amount = Math.Round(-1 * voucher.Kots.Sum(x => x.Inventories.Sum(y => y.Amount)), 5);
values.Add(SettleOption.Amount, Math.Round(amount, 5));
var roundoff = Math.Round(amount) - amount;
if (roundoff != 0)
values.Add(SettleOption.RoundOff, roundoff);
var unsettled = values.Sum(x => x.Value) * -1;
if (unsettled != 0)
values.Add(SettleOption.Unsettled, unsettled);
for (var i = voucher.Settlements.Count - 1; i >= 0; i--)
{
var item = voucher.Settlements[i];
if (!values.ContainsKey(item.Settled) || (values[item.Settled] == 0 && item.Settled != SettleOption.Amount))
{
voucher.Settlements.Remove(item);
_session.Delete(item);
}
else
{
item.Amount = values[item.Settled];
_session.Update(item);
values.Remove(item.Settled);
}
}
foreach (var item in values)
{
var set = new VoucherSettlement { Settled = item.Key, Amount = item.Value, Voucher = voucher };
voucher.Settlements.Add(set);
_session.Save(set);
}
}
public void SettleVoucher(User user, Guid voucherID, IDictionary<SettleOption, decimal> values)
{
var voucher = _session.Get<Voucher>(voucherID);
UpdateSettlements(voucher, values);
voucher.User = user;
_session.Update(voucher);
}
}
}