narsil/Tanshu.Accounts.Repository/BusinessLayer/VoucherSettlementBI.cs
unknown 59909a5ee7 Updated NH, Code Refactoring, made all DB transactions atomic.
Must use the Repositories with Using or else bad things will happen.
2011-06-30 01:57:07 +05:30

81 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using Tanshu.Accounts.Entities;
using Tanshu.Accounts.Entities.Auth;
using NHibernate;
using System.Linq;
namespace Tanshu.Accounts.Repository
{
public class VoucherSettlementBI : FluentBasicBase
{
public VoucherSettlementBI()
: base()
{ }
public VoucherSettlementBI(bool beginTransaction)
: base(beginTransaction)
{ }
public VoucherSettlementBI(ISession session)
: base(session)
{ }
public VoucherSettlementBI(ISession session, bool beginTransaction)
: base(session, beginTransaction)
{ }
public static void UpdateSettlements(IList<VoucherSettlement> list, decimal amount)
{
amount = Math.Round(amount, 5);
if (list.Count(x => x.Settled == SettleOption.Amount) == 0)
list.Add(new VoucherSettlement() { Amount = amount, Settled = SettleOption.Amount });
else
list.Single(x => x.Settled == SettleOption.Amount).Amount = amount;
var roundoff = Math.Round(amount) - amount;
if (list.Count(x => x.Settled == SettleOption.RoundOff) == 0)
list.Add(new VoucherSettlement() { Amount = roundoff, Settled = SettleOption.RoundOff });
else
list.Single(x => x.Settled == SettleOption.RoundOff).Amount = roundoff;
var balance = list.Where(x => x.Settled != SettleOption.Unsettled).Sum(x => x.Amount) * -1;
if (list.Count(x => x.Settled == SettleOption.Unsettled) == 0)
{
if (balance != 0)
list.Add(new VoucherSettlement() { Amount = balance, Settled = SettleOption.Unsettled });
}
else if (balance == 0)
list.Remove(list.Single(x => x.Settled == SettleOption.Unsettled));
else
list.Single(x => x.Settled == SettleOption.Unsettled).Amount = balance;
}
public void SettleVoucher(User user, int voucherID, IDictionary<SettleOption, decimal> values)
{
var voucher = Session.Get<Voucher>(voucherID);
for (var i = voucher.Settlements.Count - 1; i >= 0; i--)
{
var item = voucher.Settlements[i];
if (item.Settled == SettleOption.Amount || item.Settled == SettleOption.RoundOff || item.Settled == SettleOption.Unsettled)
continue;
if (!values.ContainsKey(item.Settled))
voucher.Settlements.Remove(item);
else
item.Amount = values[item.Settled];
}
foreach (var item in values)
{
if (voucher.Settlements.Count(x => x.Settled == item.Key) == 0)
voucher.Settlements.Add(new VoucherSettlement { Settled = item.Key, Amount = item.Value });
}
var amount = -1 * voucher.Kots.Sum(x => x.Inventories.Sum(y => y.Amount));
UpdateSettlements(voucher.Settlements, amount);
voucher.User = user;
voucher.LastEditDate = DbValues.Date;
Session.Update(voucher);
using (var ft = new FoodTableBI(Session, false))
ft.TableSettled(voucher);
}
}
}