using Ease.Core.DataAccess; using Ease.Core.Model; using Ease.Core.Utility; using System; using System.Collections.Generic; using System.Linq; using HRM.BO; using System.Data; using Microsoft.AspNetCore.Http; using System.Configuration; using ZstdSharp; using System.Diagnostics; using K4os.Compression.LZ4.Internal; using NPOI.SS.Formula.Functions; using Microsoft.AspNetCore.JsonPatch.Internal; using HRM.DA.Fund; using System.Diagnostics.CodeAnalysis; namespace HRM.DA { #region GLTran Service public class GLTranService : ServiceTemplate, IGLTranService { public GLTranService() { } private void MapObject(GLTran gLTran, DataReader readerNH) { this.SetObjectID(gLTran, readerNH.GetInt32("GLTranID").Value); gLTran.EntryMethod = (EnumEntryMethod)readerNH.GetInt32("EntryMethod"); gLTran.VoucherDate = readerNH.GetDateTime("VoucherDate").Value; gLTran.VoucherNo = readerNH.GetString("VoucherNo"); gLTran.FundTypeID = readerNH.GetInt32("FundTypeID") ?? 0; gLTran.Description = readerNH.GetString("Description"); gLTran.ChequeDate = readerNH.GetDateTime("ChequeDate").HasValue ? readerNH.GetDateTime("ChequeDate").Value : DateTime.MinValue; gLTran.ChequeNo = readerNH.GetString("ChequeNo")??""; gLTran.DebitAmount = readerNH.GetDouble("DebitAmount").Value; gLTran.CreditAmount = readerNH.GetDouble("CreditAmount").Value; gLTran.GLTranType = (EnumGLTranType)readerNH.GetInt32("GLTranType"); gLTran.GLTranID = readerNH.GetInt32("GLTRANID").Value; gLTran.ReconciledState = (EnumReconciledState)readerNH.GetInt32("ReconciledStatus"); gLTran.CreatedBy = readerNH.GetInt32("CreatedBy").Value; gLTran.CreatedDate = readerNH.GetDateTime("CreateDate").Value; gLTran.ModifiedBy = readerNH.GetInt32("Modifiedby"); gLTran.ModifiedDate = readerNH.GetDateTime("ModifiedDate"); this.SetObjectState(gLTran, Ease.Core.ObjectState.Saved); } protected override T CreateObject(DataReader oReader) { GLTran oGL = new GLTran(); MapObject(oGL, oReader); return oGL as T; } protected GLTran CreateObject(DataReader oReader) { GLTran oGL = new GLTran(); MapObject(oGL, oReader); return oGL; } private void OpenMapObject(GLTran gLTran, DataReader readerNH) { this.SetObjectID(gLTran, readerNH.GetInt32("OpenGLTranID").Value); gLTran.EntryMethod = (EnumEntryMethod)readerNH.GetInt32("EntryMethod"); gLTran.VoucherDate = readerNH.GetDateTime("VoucherDate").Value; gLTran.VoucherNo = readerNH.GetString("VoucherNo"); gLTran.FundTypeID = readerNH.GetInt32("FundTypeID").Value; gLTran.Description = readerNH.GetString("Description"); gLTran.ChequeDate = readerNH.GetDateTime("ChequeDate").Value; gLTran.ChequeNo = readerNH.GetString("ChequeNo"); gLTran.DebitAmount = readerNH.GetDouble("DebitAmount").Value; gLTran.CreditAmount = readerNH.GetDouble("CreditAmount").Value; gLTran.GLTranType = (EnumGLTranType)readerNH.GetInt32("OpenGLTranType"); gLTran.ReconciledState = (EnumReconciledState)readerNH.GetInt16("ReconciledStatus"); gLTran.CreatedBy = readerNH.GetInt32("CreatedBy").Value; gLTran.CreatedDate = readerNH.GetDateTime("CreateDate").Value; gLTran.ModifiedBy = readerNH.GetInt32("Modifiedby"); gLTran.ModifiedDate = readerNH.GetDateTime("ModifiedDate"); this.SetObjectState(gLTran, Ease.Core.ObjectState.Saved); } private GLTran OpenCreateObject(DataReader oReader) { GLTran oGLTran = new GLTran(); MapObject(oGLTran, oReader); return oGLTran; } public void DistributeProfit(int userId, int fundtypeid, double distributableAmount, double distributePercentOnBal, int plvoucherid) { List _membersTransactionDetailsColl = new List(); FundType oFundType = new FundTypeService().Get(fundtypeid); DateTime fiscalYearStart; if (oFundType.ProfitDistributionDuration == EnumProfitDistributionDuration.Monthly) { fiscalYearStart = GlobalExtensions.FirstDateOfMonth(oFundType.LastProfitDistributionMonth); } else if (oFundType.ProfitDistributionDuration == EnumProfitDistributionDuration.Half_Yearly) { fiscalYearStart = GlobalExtensions.FirstDateOfMonth(oFundType.LastProfitDistributionMonth.AddMonths(-5)); } else fiscalYearStart = GlobalExtensions.FirstDateOfMonth(oFundType.LastProfitDistributionMonth.AddMonths(-11)); DateTime fiscalYearEnd = oFundType.LastProfitDistributionMonth; if (this.VoucherExist(EnumGLTranType.DividendDistribution, fiscalYearStart, fiscalYearEnd, fundtypeid) == true) { throw new Exception("Devident are already distributed this year."); } GLTran plVoucher = new GLTranService().Get(plvoucherid); List omembers = new MemberService().GetMembersJoinTransaction(fiscalYearStart, fiscalYearEnd, fundtypeid); try { List ouserRecords = new UserRecordService().Get(GlobalFunctions.Fund_UserObject_Member, oFundType.ID); int calculationType = 1; // closing balance, 2 MonthlyProduct Balance DataTable allMemberBalance; if (calculationType == 1) allMemberBalance = new MembersTransactionDetailsService() .GetOpeningBalanceAllMember(fundtypeid, fiscalYearEnd); else allMemberBalance = new MembersTransactionDetailsService() .GetOpeningBalanceAllMember(fundtypeid, fiscalYearStart); if (distributePercentOnBal == 0) { if (calculationType == 1) { double closingBalance = 0; foreach (DataRow newrow in allMemberBalance.Rows) { var mem = omembers.FirstOrDefault(x => x.MemberID == Convert.ToInt32(newrow["memberid"].ToString())); if (mem != null) { closingBalance = closingBalance + Convert.ToDouble(newrow["balance"].ToString()); } } int count = 0; foreach (Member omember in omembers) { count = count + 1; DataRow[] foundRows = allMemberBalance.Select("memberid=" + omember.ID); DataRow temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.EPF); double bal = Convert.ToDouble(temprows["balance"]); bal = bal / closingBalance * distributableAmount; bal = Math.Round(bal, 2); MembersTransactionDetail epfTran = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.EPF_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.EPF); epfTran.Member = omember; _membersTransactionDetailsColl.Add(epfTran); temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.Voluntary); if (temprows != null) { bal = Convert.ToDouble(temprows["balance"]); bal = bal / closingBalance * distributableAmount; bal = Math.Round(bal, 2); MembersTransactionDetail epfvol = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.Voluntary_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.Voluntary); epfvol.Member = omember; _membersTransactionDetailsColl.Add(epfvol); } temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.CPF); bal = Convert.ToDouble(temprows["balance"]); bal = bal / closingBalance * distributableAmount; bal = Math.Round(bal, 2); MembersTransactionDetail cpfTran = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.CPF_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.CPF); cpfTran.Member = omember; _membersTransactionDetailsColl.Add(cpfTran); } double temptotal = Math.Round(_membersTransactionDetailsColl.Sum(x => x.Amount), 2); _membersTransactionDetailsColl[0].Amount = _membersTransactionDetailsColl[0].Amount + distributableAmount - temptotal; } else { List memtrans = new MembersTransactionDetailsService().GetbyFundType( fundtypeid, fiscalYearStart, fiscalYearEnd); DateTime dStart = fiscalYearStart; double monthlyDistributeAmount = distributableAmount / 12; while (dStart != fiscalYearEnd) { double closingBalance = 0; foreach (DataRow newrow in allMemberBalance.Rows) { var mem = omembers.FirstOrDefault(x => x.MemberID == Convert.ToInt32(newrow["memberid"].ToString())); if (mem != null) { closingBalance = closingBalance + Convert.ToDouble(newrow["balance"].ToString()); double? monthBal = memtrans.Where(x => x.MemberID == mem.MemberID && x.TranDate <= dStart).Sum(x => x.Amount); if (monthBal != null) closingBalance = closingBalance + Convert.ToDouble(monthBal); } } double totaldistribute = 0; foreach (Member omember in omembers) { DataRow[] foundRows = allMemberBalance.Select("memberid=" + omember.ID); DataRow temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.EPF); double bal = Convert.ToDouble(temprows["balance"]); double? monthBal = memtrans.Where(x => x.MemberID == omember.ID && x.TranDate == dStart && x.fundCategory == EnumFundCategory.EPF).Sum(x => x.Amount); if (monthBal != null) bal = bal + Convert.ToDouble(monthBal); bal = Math.Round((bal / closingBalance * distributableAmount), 2); totaldistribute = totaldistribute + bal; var epfItem = _membersTransactionDetailsColl.FirstOrDefault(x => x.MemberID == omember.ID && x.TranTypeID == EnumMemberTranType.EPF_Interest); if (epfItem == null) { MembersTransactionDetail epfTran = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.EPF_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.EPF); epfTran.Member = omember; _membersTransactionDetailsColl.Add(epfTran); } else epfItem.Amount = epfItem.Amount + bal; monthBal = memtrans.Where(x => x.MemberID == omember.ID && x.TranDate == dStart && x.fundCategory == EnumFundCategory.Voluntary).Sum(x => x.Amount); if (monthBal != null) { foundRows = allMemberBalance.Select("memberid=" + omember.ID); temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.Voluntary); bal = Convert.ToDouble(temprows["balance"]); if (monthBal != null) bal = bal + Convert.ToDouble(monthBal); bal = Math.Round((bal / closingBalance * distributableAmount), 2); totaldistribute = totaldistribute + bal; MembersTransactionDetail volunItem = _membersTransactionDetailsColl.FirstOrDefault(x => x.MemberID == omember.ID && x.TranTypeID == EnumMemberTranType.Voluntary_Interest); if (volunItem == null) { MembersTransactionDetail volunTran = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.Voluntary_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.Voluntary); volunTran.Member = omember; _membersTransactionDetailsColl.Add(volunTran); } else volunItem.Amount = volunItem.Amount + bal; } foundRows = allMemberBalance.Select("memberid=" + omember.ID); temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.CPF); bal = Convert.ToDouble(temprows["balance"]); if (monthBal != null) bal = bal + Convert.ToDouble(monthBal); bal = Math.Round((bal / closingBalance * distributableAmount), 2); totaldistribute = totaldistribute + bal; var cpfItem = _membersTransactionDetailsColl.FirstOrDefault(x => x.MemberID == omember.ID && x.TranTypeID == EnumMemberTranType.CPF_Interest); if (cpfItem == null) { MembersTransactionDetail ocpfItem = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.CPF_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.CPF); ocpfItem.Member = omember; _membersTransactionDetailsColl.Add(ocpfItem); } else cpfItem.Amount = cpfItem.Amount + bal; } dStart = GlobalFunctions.LastDateOfMonth(dStart.AddMonths(1)); } } } else { #region distribute on yearly Balance int count = 0; foreach (Member omember in omembers) { count = count + 1; DataRow[] foundRows = allMemberBalance.Select("memberid=" + omember.ID); DataRow temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.EPF); double bal = Convert.ToDouble(temprows["balance"]); bal = bal * distributePercentOnBal / 100; distributableAmount = distributableAmount + bal; MembersTransactionDetail epfTran = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.EPF_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.EPF); epfTran.Member = omember; _membersTransactionDetailsColl.Add(epfTran); temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.Voluntary); if (temprows != null) { bal = Convert.ToDouble(temprows["balance"]); bal = bal * distributePercentOnBal / 100; distributableAmount = distributableAmount + bal; MembersTransactionDetail voluntary = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.Voluntary_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.Voluntary); voluntary.Member = omember; _membersTransactionDetailsColl.Add(voluntary); } temprows = foundRows.FirstOrDefault(row => (EnumFundCategory) Convert.ToInt32(row["fundCategory"]) == EnumFundCategory.CPF); bal = Convert.ToDouble(temprows["balance"]); bal = bal * distributePercentOnBal / 100; MembersTransactionDetail cpfTran = new MembersTransactionDetail(omember.ID, fundtypeid, EnumMemberTranType.CPF_Interest, bal, oFundType.LastProfitDistributionMonth, EnumFundCategory.CPF); cpfTran.Member = omember; _membersTransactionDetailsColl.Add(cpfTran); distributableAmount = distributableAmount + bal; } #endregion } #region Prepare Voucher #region Year-End member Voucher GLTran otranReducePL = new GLTran(); otranReducePL.VoucherDate = oFundType.LastProfitDistributionMonth; otranReducePL.GLTranType = EnumGLTranType.DividendDistribution; otranReducePL.Description = "Distribute Interest to Member :" + oFundType.LastProfitDistributionMonth.ToString("dd MMM yyyy"); otranReducePL.FundTypeID = oFundType.ID; List vsetups = new ActivityVoucherSetupService().GetByProcessType(fundtypeid, EnumFundProcessType.Monthly_Dividend_Distribution); ActivityVoucherSetup interestGL = vsetups.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.PL_Profit); if (interestGL == null) throw new Exception("Profit GL not found in " + " profit distribution voucher setup"); GLTranDetail odetailReducePL = new GLTranDetail(); odetailReducePL.GLID = interestGL.GLID; odetailReducePL.Amount = (double)Math.Round(distributableAmount, 2); odetailReducePL.Transide = interestGL.GLSide; odetailReducePL.Description = "Distribute Interest to Member"; otranReducePL.GlTranDetails = new List(); otranReducePL.GlTranDetails.Add(odetailReducePL); ActivityVoucherSetup epfSetup = vsetups.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.EPF_Interest); GLTranDetail odetailEPF = new GLTranDetail(); odetailEPF.Description = "Distribute EPF Interest to Member"; odetailEPF.GLID = epfSetup.GLID; odetailEPF.Amount = (double)Math.Round(_membersTransactionDetailsColl.Where(x => x.fundCategory == EnumFundCategory.EPF).Sum(x => x.Amount), 2); odetailEPF.Transide = epfSetup.GLSide; odetailEPF.GLTranUserRecords = new List(); otranReducePL.GlTranDetails.Add(odetailEPF); ActivityVoucherSetup voluntarySetup = vsetups.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.Voluntary_EPF_Interest); GLTranDetail odetailvoluntary = null; if (voluntarySetup != null) { odetailvoluntary = new GLTranDetail(); odetailvoluntary.Description = "Distribute voluntary Interest to Member"; odetailvoluntary.GLID = voluntarySetup.GLID; odetailvoluntary.Amount = (double)Math.Round(_membersTransactionDetailsColl.Where(x => x.fundCategory == EnumFundCategory.Voluntary).Sum(x => x.Amount), 2); odetailvoluntary.Transide = voluntarySetup.GLSide; odetailvoluntary.GLTranUserRecords = new List(); otranReducePL.GlTranDetails.Add(odetailvoluntary); } ActivityVoucherSetup cpfSetup = vsetups.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.CPF_Interest); GLTranDetail odetailCPF = new GLTranDetail(); odetailCPF.GLID = cpfSetup.GLID; odetailCPF.Description = "Distribute CPF Interest to Member"; odetailCPF.Amount = (double)Math.Round(_membersTransactionDetailsColl.Where(x => x.fundCategory == EnumFundCategory.CPF).Sum(x => x.Amount), 2); odetailCPF.Transide = cpfSetup.GLSide; odetailCPF.GLTranUserRecords = new List(); otranReducePL.GlTranDetails.Add(odetailCPF); foreach (MembersTransactionDetail item in _membersTransactionDetailsColl) { var uRecord = ouserRecords.FirstOrDefault(x => x.Field1 == item.Member.EmpCode); if (item.TranTypeID == EnumMemberTranType.EPF_Interest) { GLTranUserRecord orecord = new GLTranUserRecord(epfSetup.GLID, 0, 0, GlobalFunctions.Fund_UserObject_Member, uRecord.ID, item.Amount); odetailCPF.GLTranUserRecords.Add(orecord); } else if (item.TranTypeID == EnumMemberTranType.Voluntary_Interest) { GLTranUserRecord volorecord = new GLTranUserRecord(voluntarySetup.GLID, 0, 0, GlobalFunctions.Fund_UserObject_Member, uRecord.ID, item.Amount); odetailvoluntary.GLTranUserRecords.Add(volorecord); } else { GLTranUserRecord cpforecord = new GLTranUserRecord(cpfSetup.GLID, 0, 0, GlobalFunctions.Fund_UserObject_Member, uRecord.ID, item.Amount); odetailEPF.GLTranUserRecords.Add(cpforecord); } } #endregion Prepare Voucher odetailEPF.Amount = Math.Round(Convert.ToDouble( odetailEPF.GLTranUserRecords.Sum(x => x.Amount)), 2); odetailCPF.Amount = Math.Round(Convert.ToDouble( odetailCPF.GLTranUserRecords.Sum(x => x.Amount)), 2); if (odetailvoluntary != null) odetailvoluntary.Amount = Math.Round(Convert.ToDouble( odetailCPF.GLTranUserRecords.Sum(x => x.Amount)), 2); otranReducePL.DebitAmount = Math.Round(otranReducePL.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount), 2); otranReducePL.CreditAmount = Math.Round(otranReducePL.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount), 2); if ((otranReducePL.DebitAmount - otranReducePL.CreditAmount) != 0) { double aAmount = otranReducePL.DebitAmount - otranReducePL.CreditAmount; otranReducePL.GlTranDetails[1].GLTranUserRecords[0].Amount = otranReducePL.GlTranDetails[1].GLTranUserRecords[0].Amount + aAmount; odetailEPF.Amount = Math.Round(Convert.ToDouble( odetailEPF.GLTranUserRecords.Sum(x => x.Amount)), 2); odetailCPF.Amount = Math.Round(Convert.ToDouble( odetailCPF.GLTranUserRecords.Sum(x => x.Amount)), 2); if (odetailvoluntary != null) odetailvoluntary.Amount = Math.Round(Convert.ToDouble( odetailCPF.GLTranUserRecords.Sum(x => x.Amount)), 2); otranReducePL.CreditAmount = Math.Round(otranReducePL.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount), 2); } new YearEndService().DoDistributeDivident(oFundType, otranReducePL, _membersTransactionDetailsColl); #endregion } catch (Exception ex) { throw new Exception(ex.Message); } } public double CalcualteProfitLoss(int userId, int fundtypeid) { FundType ftype = new FundTypeService().Get(fundtypeid); DateTime Startdate = ftype.LastProfitDistributionMonth.AddDays(1); DateTime EndDate = ftype.NextProfitDistributionMonth; if (GlobalFunctions.LastDateOfMonth(ftype.CurrentMonth) != GlobalFunctions.LastDateOfMonth(ftype.NextProfitDistributionMonth)) { throw new Exception("Process Month and Profit Distibution month is not same."); } if(this.VoucherExist(EnumGLTranType.YearEndVoucher, Startdate, EndDate, fundtypeid) ==true) { throw new Exception("Profit/Loss calculation is already done for this year."); } DateTime DistributedMonth = ftype.NextProfitDistributionMonth; double pl = 0, incomeAmount = 0, expenditureAmount = 0; double glTranDebitAmount = 0, glTranCreditAmount = 0; List glTranDetails = new List(); GLTranDetail glTranDetailsForCr = new GLTranDetail(); List incomeGLs = new GLService().Get(EnumGLType.Income, 4, fundtypeid); // new GL().Get(Ease.Core.Framework.ID.FromInteger(3)); foreach (GL glPosting in incomeGLs) { double CrBalance = new GLTranService().GetTranSideBalance(glPosting.ID, EnumTranSide.Credit, Startdate, EndDate); double DrBalance = new GLTranService().GetTranSideBalance(glPosting.ID, EnumTranSide.Debit, Startdate, EndDate); if (Math.Abs(CrBalance) + Math.Abs(DrBalance) > 0) { if (CrBalance != DrBalance) { incomeAmount += (CrBalance - DrBalance); GLTranDetail glTranDetail = new GLTranDetail(); glTranDetail.GLID = glPosting.ID; glTranDetail.Description = "Monthly Profit Distribution auto generate voucher"; if (CrBalance > DrBalance) { glTranDetail.Amount = (CrBalance - DrBalance); glTranDetail.Transide = EnumTranSide.Debit; glTranDebitAmount += CrBalance - DrBalance; glTranDetails.Add(glTranDetail); } else if (CrBalance < DrBalance) { glTranDetail.Amount = (DrBalance - CrBalance); glTranDetail.Transide = EnumTranSide.Credit; glTranCreditAmount += DrBalance - CrBalance; glTranDetails.Add(glTranDetail); } } } } List expenditureGLs = new GLService().Get(EnumGLType.Expenditure, 4, fundtypeid);// new GL().Get(Ease.Core.Framework.ID.FromInteger(4)); foreach (GL glPosting in expenditureGLs) { double CrBalance = new GLTranService().GetTranSideBalance( glPosting.ID, EnumTranSide.Credit, Startdate, EndDate); double DrBalance = new GLTranService().GetTranSideBalance(glPosting.ID, EnumTranSide.Debit, Startdate, EndDate); if (Math.Abs(CrBalance) + Math.Abs(DrBalance) > 0) { if (CrBalance != DrBalance) { expenditureAmount += ( DrBalance - CrBalance); GLTranDetail glTranDetail = new GLTranDetail(); glTranDetail.GLID = glPosting.ID; glTranDetail.Description = "Monthly Profit Distribution auto generate voucher"; if (CrBalance > DrBalance) { glTranDetail.Amount = (CrBalance - DrBalance); glTranDetail.Transide = EnumTranSide.Debit; glTranDebitAmount += CrBalance - DrBalance; glTranDetails.Add(glTranDetail); } else if (CrBalance < DrBalance) { glTranDetail.Amount = (DrBalance - CrBalance); glTranDetail.Transide = EnumTranSide.Credit; glTranCreditAmount += DrBalance - CrBalance; glTranDetails.Add(glTranDetail); } } } } double fixedGLDrAmount = 0, fixedGLCrAmount = 0; pl = (incomeAmount - expenditureAmount); pl = pl - (fixedGLDrAmount - fixedGLCrAmount); GLTran _glTran = new GLTran(); _glTran.GlTranDetails = glTranDetails; _glTran.GLTranType = EnumGLTranType.YearEndVoucher; _glTran.Description = "Monthly Profit Distribution auto voucher, Year : " + ftype.NextProfitDistributionMonth.ToString("dd MMM yyyy"); _glTran.VoucherDate = ftype.NextProfitDistributionMonth; // _glTran.ChequeDate = ftype.NextProfitDistributionMonth; _glTran.CreatedDate = DateTime.Now; _glTran.CreatedBy = userId; _glTran.FundTypeID = fundtypeid; List vsetups = new ActivityVoucherSetupService().GetByProcessType(fundtypeid, EnumFundProcessType.Profit_Loss); if (pl < 0) pl = pl * -1; if (pl >0) { ActivityVoucherSetup profit = vsetups.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.PL_Profit); if (profit == null) throw new Exception("There is no profit-Gl in the voucher setup."); GLTranDetail oProfiltDetail = new GLTranDetail(profit.GLID, profit.GLSide,(double) pl, "Profit/Loss"); _glTran.GlTranDetails.Add(oProfiltDetail); } else { ActivityVoucherSetup loss = vsetups.FirstOrDefault(x => x.VouhcerSetupItemType == EnumVouhcerSetupItemType.PL_Loss); if (loss == null) throw new Exception("There is no loss-Gl in the voucher setup."); GLTranDetail olossDetail = new GLTranDetail(loss.GLID, loss.GLSide, (double)pl, "Profit/Loss "); _glTran.GlTranDetails.Add(olossDetail); } // need to adjust PL amount during uat _glTran.DebitAmount = _glTran.GlTranDetails.Where(x=>x.Transide == EnumTranSide.Debit).Sum(x=>x.Amount); _glTran.CreditAmount = _glTran.GlTranDetails.Where(x => x.Transide == EnumTranSide.Credit).Sum(x => x.Amount); // new GLTranService().Save(_glTran); new YearEndService().DoYearEnd(ftype, _glTran); return (double)pl; } private List OpenCreateObjects(DataReader oReader) { List oGLTrans = new List(); while (oReader.Read()) { GLTran oItem = OpenCreateObject(oReader); oGLTrans.Add(oItem); } return oGLTrans; } #endregion #region Service implementation public GLTran Get(int id) { GLTran gLTran = new GLTran(); GLTranDetailService gLTranDetailService = new GLTranDetailService(); GLTranUserRecordService gLTranUserRecordService = new GLTranUserRecordService(); TransactionContext tc = null; try { tc = TransactionContext.Begin(true); DataReader oreader = new DataReader(GLTranDA.Get(tc, id)); if (oreader.Read()) { gLTran = CreateObject(oreader); } oreader.Close(); gLTran.GlTranDetails = gLTranDetailService.GetByGLTranID(tc, gLTran.ID); foreach (GLTranDetail gLTranDetail in gLTran.GlTranDetails) { gLTranDetail.GLTranUserRecords = gLTranUserRecordService.GetByGLTranDetailID(tc, gLTranDetail.ID); } gLTran.GLTranUserRecords = gLTranUserRecordService.GetByGLTranID(tc, gLTran.ID); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to get GLTran", e); #endregion } return gLTran; } public GLTran Get(TransactionContext tc, int id) { GLTran gLTran = new GLTran(); GLTranDetailService gLTranDetailService = new GLTranDetailService(); GLTranUserRecordService gLTranUserRecordService = new GLTranUserRecordService(); try { DataReader oreader = new DataReader(GLTranDA.Get(tc, id)); if (oreader.Read()) { gLTran = CreateObject(oreader); } oreader.Close(); gLTran.GlTranDetails = gLTranDetailService.GetByGLTranID(tc, gLTran.ID); foreach (GLTranDetail gLTranDetail in gLTran.GlTranDetails) { gLTranDetail.GLTranUserRecords = gLTranUserRecordService.GetByGLTranDetailID(tc, gLTranDetail.ID); } gLTran.GLTranUserRecords = gLTranUserRecordService.GetByGLTranID(tc, gLTran.ID); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to get GLTran", e); #endregion } return gLTran; } public List GetGLTransOrderByDate(DateTime startDate, DateTime endDate, GL gL) { List gLTrans = new List(); GLTranDetailService gLTranDetailService = new GLTranDetailService(); GLTranUserRecordService gLTranUserRecordService = new GLTranUserRecordService(); TransactionContext tc = null; try { tc = TransactionContext.Begin(true); DataReader oReader = new DataReader(GLTranDA.GetGLTransOrderByDate(tc, startDate, endDate, gL)); gLTrans = CreateObjects(oReader); oReader.Close(); tc.End(); if (gLTrans.Count > 0) { List gLTranDetails = new GLTranDetailService().Get(startDate, endDate, gL.ID); foreach (GLTran oItem in gLTrans) { oItem.GlTranDetails = new List(); var gld = gLTranDetails.FindAll(x => x.GLTranID == oItem.GLTranID); if (gld != null) oItem.GlTranDetails = gld; } } } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to Get GLTran", e); #endregion } return gLTrans; } public double GetOpeningBalanceOnSide(int nGLID, DateTime dTranDate, EnumTranSide side) { double nCurrentBalance = 0; TransactionContext tc = null; try { tc = TransactionContext.Begin(true); nCurrentBalance = GLTranDA.GetOpeningBalance(tc, nGLID, side, dTranDate); tc.End(); } catch (Exception e) { throw new ServiceException("Failed to Get Balance :", e); } return nCurrentBalance; } private string getBottomMostChildKeys(TransactionContext tc, GL gl) { string bmcks = string.Empty; List children = new GLService().GetByOwnerID(tc, gl.ID); if (children.Count == 0) return gl.ID.ToString(); else { foreach (GL c in children) { bmcks += "," + getBottomMostChildKeys(tc, c); } bmcks = bmcks.Substring(1); return bmcks; } } public double GetTranSideBalance(int nGLID, EnumTranSide tranSide, DateTime fromTranDate, DateTime toTranDate) { double Balance = 0; TransactionContext tc = null; try { tc = TransactionContext.Begin(true); Balance = GLTranDA.GetTranSideBalanceGL(tc, nGLID, tranSide, fromTranDate, toTranDate); tc.End(); } catch (Exception e) { throw new ServiceException("Failed to Get Balance :", e); } return Balance; } public double GetBalanceForBS(int nGLID, DateTime dTranDate) { double nCurrentBalance = 0; GL gl = new GL(); GLService gLService = new GLService(); TransactionContext tc = null; try { tc = TransactionContext.Begin(true); nCurrentBalance = 0; double amount = GLTranDA.GetOpeningBalance(tc, nGLID, dTranDate); nCurrentBalance = amount; tc.End(); } catch (Exception e) { throw new ServiceException("Failed to Get Balance ALL", e); } return nCurrentBalance; } public int Save(TransactionContext tc, GLTran gLTranUI) { try { this.ValidateVoucher(gLTranUI); if (gLTranUI.IsNew) { //generate voucher no int id = tc.GenerateID("FM_GLTRAN", "GLTRANID"); base.SetObjectID(gLTranUI, id); gLTranUI.VoucherNo=gLTranUI.ID.ToString("000000"); GLTranDA.Insert(tc, gLTranUI); } else { GLTranDA.Update(tc, gLTranUI); } new GLTranUserRecordService().DeleteByGLTranID(tc, gLTranUI.ID); new GLTranDetailService().DeleteByGLTranID(tc, gLTranUI.ID); foreach (GLTranDetail glTranDetailUI in gLTranUI.GlTranDetails) { glTranDetailUI.GLTranID = gLTranUI.ID; new GLTranDetailService().Save(tc, glTranDetailUI); if (glTranDetailUI.GLTranUserRecords != null) { foreach (GLTranUserRecord glTranUserRecordUI in glTranDetailUI.GLTranUserRecords) { glTranUserRecordUI.GLTranID = gLTranUI.ID; glTranUserRecordUI.GLTranDetailID = glTranDetailUI.ID; //new GLTranUserRecordService().Save(tc, glTranUserRecordUI); } new GLTranUserRecordService().SaveBulk(tc, glTranDetailUI.GLTranUserRecords); } } } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message); #endregion } return gLTranUI.ID; } private void ValidateVoucher(GLTran otran) { if (otran.GlTranDetails.Count <=1) { throw new ServiceException("Invalid voucher, GL head missing"); } if (otran.DebitAmount != otran.CreditAmount) { throw new ServiceException("Debit and Credit amount must be same!"); } double? tempAmount = Math.Round(otran.GlTranDetails.Sum(x=>x.Amount),2); if(Math.Round(Convert.ToDouble(tempAmount), 2) != Math.Round( (otran.DebitAmount + otran.CreditAmount),2)) { throw new ServiceException("Voucher amount is not equal to detial GL wise amount"); } tempAmount = Math.Round(otran.GlTranDetails.Where(x=>x.Transide == EnumTranSide.Credit).Sum(x => x.Amount),2); if (Convert.ToDouble(tempAmount) != otran.CreditAmount) { throw new ServiceException("Total Credit Amount is not equal of GL wise Credit amount"); } tempAmount = Math.Round(otran.GlTranDetails.Where(x => x.Transide == EnumTranSide.Debit).Sum(x => x.Amount),2); if (Convert.ToDouble(tempAmount) != otran.DebitAmount) { throw new ServiceException("Total Debit Amount is not equal of GL wise Debit amount"); } foreach(GLTranDetail item in otran.GlTranDetails) { if(item.GLTranUserRecords !=null && item.GLTranUserRecords.Count >0) { if(item.Amount != Math.Round(Convert.ToDouble( item.GLTranUserRecords.Sum(x=>x.Amount)),2)) { throw new ServiceException("GL amount is not equal to sum of subsidiaries amount."); } } } } public int Save(GLTran gLTranUI) { TransactionContext tc = null; try { tc = TransactionContext.Begin(true); this.Save(tc, gLTranUI); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message); #endregion } return gLTranUI.ID; } public double GetOpeningBalance(int nGLID, DateTime dTranDate) { double opbal = 0; TransactionContext tc = null; try { tc = TransactionContext.Begin(true); //nCurrentBalance = 0; //string glids = ""; //if (gl.TierNo == 1) //{ // glids = SQLParser.MakeSQL(@"select glid from Gl where ownerid=%n // union // select glid from Gl where ownerid in ( select glid from Gl where ownerid=%n) // union // select glid from Gl where ownerid in( select glid from Gl where ownerid in ( // select glid from Gl where ownerid=%n))", nGLID, nGLID, nGLID); //} //else if (gl.TierNo == 2) //{ // glids = SQLParser.MakeSQL(@"select glid from Gl where ownerid=%n // union // select glid from Gl where ownerid in ( select glid from Gl where ownerid=%n) ", nGLID, nGLID); //} //else if (gl.TierNo == 3) //{ // glids = SQLParser.MakeSQL(@"select glid from Gl where ownerid=%n ", nGLID); //} //else //{ // glids = nGLID.ToString(); //} opbal = GLTranDA.GetOpeningBalance(tc, nGLID, dTranDate); tc.End(); } catch (Exception e) { throw new ServiceException("Failed to Get Balance; reason:" + e.Message, e); } return opbal; } public List GetGlTransForSearch( DateTime startDate, DateTime endDate, int glID, int fundTypeID) { List gLTrans = new List(); GLTranDetailService gLTranDetailService = new GLTranDetailService(); GLTranUserRecordService gLTranUserRecordService = new GLTranUserRecordService(); TransactionContext tc = null; try { tc = TransactionContext.Begin(true); string whereClause = string.Empty; whereClause = whereClause + SQLParser.MakeSQL(" AND FundTypeID =%n ", fundTypeID); if (glID > 0) { whereClause = whereClause + SQLParser.MakeSQL(" AND GLTranID IN(SELECT GLTranID FROM FM_GLTranDetail WHERE GLID=%n)", glID); } string sql = string.Empty; sql = SQLParser.MakeSQL("SELECT * FROM FM_GLTran WHERE VoucherDate>=%d AND VoucherDate<=%d %q" + " ORDER BY VoucherDate DESC ", startDate, endDate, whereClause); DataReader reader =new DataReader(GLTranDA.GetGlTransForSearch(tc, sql)); gLTrans = CreateObjects(reader); reader.Close(); //foreach (GLTran glTran in gLTrans) //{ // glTran.GlTranDetails = gLTranDetailService.GetByGLTranID(tc, glTran.ID); // foreach (GLTranDetail gLTranDetail in glTran.GlTranDetails) // { // gLTranDetail.GLTranUserRecords = gLTranUserRecordService.GetByGLTranDetailID(tc, gLTranDetail.ID); // } // glTran.GLTranUserRecords = gLTranUserRecordService.GetByGLTranID(tc, glTran.ID); //} tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to Get Transactions.\nBecause " + e.Message, e); #endregion } return gLTrans; } public List GetYearEndGlTrans(int fundTypeID) { List gLTrans = new List(); GLTranDetailService gLTranDetailService = new GLTranDetailService(); GLTranUserRecordService gLTranUserRecordService = new GLTranUserRecordService(); TransactionContext tc = null; try { tc = TransactionContext.Begin(true); string whereClause = string.Empty; DataReader reader = new DataReader(GLTranDA.GetYearEndGlTrans(tc,fundTypeID)); gLTrans = CreateObjects(reader); reader.Close(); foreach (GLTran glTran in gLTrans) { glTran.GlTranDetails = gLTranDetailService.GetByGLTranID(tc, glTran.ID); foreach (GLTranDetail gLTranDetail in glTran.GlTranDetails) { gLTranDetail.GLTranUserRecords = gLTranUserRecordService.GetByGLTranDetailID(tc, gLTranDetail.ID); } glTran.GLTranUserRecords = gLTranUserRecordService.GetByGLTranID(tc, glTran.ID); } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to Get Transactions.\nBecause " + e.Message, e); #endregion } return gLTrans; } public bool VoucherExist(EnumGLTranType glTranType, DateTime fromDate, DateTime ToDate, int fundTypeID) { TransactionContext tc = null; try { tc = TransactionContext.Begin(true); bool result = true; result = GLTranDA.VoucherExist(tc, glTranType, fromDate, ToDate, fundTypeID); tc.End(); return result; } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to get transaction", e); #endregion } } public void Delete(TransactionContext tc, int id) { try { GLTranDA.Delete(tc, id); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to delete GL Transaction", e); #endregion } } public void DeleteWithReference(int id) { TransactionContext tc = null; GLTran otran = this.Get(id); try { tc = TransactionContext.Begin(true); switch (otran.GLTranType) { #region no reference case EnumGLTranType.None: case EnumGLTranType.BankPayment: case EnumGLTranType.BankReceipt: case EnumGLTranType.BankToBank: case EnumGLTranType.BankToCash: case EnumGLTranType.CashToBank: case EnumGLTranType.CashToCash: case EnumGLTranType.CashPayment: case EnumGLTranType.CashReceipt: case EnumGLTranType.JournalVoucher: case EnumGLTranType.ReverseVoucher: break; #endregion case EnumGLTranType.OpeningMemberBalance: case EnumGLTranType.OpeningVoucher: MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.EFP_Opening,(int) otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.CPF_Opening, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.EPF_Interest_Opening, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.CPF_Interest_Opening, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.Voluntary_EFP_Opening, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.Voluntary_Interest_Opening, (int)otran.FundTypeID); break; case EnumGLTranType.YearEndVoucher: MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.EPF_Interest, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.CPF_Interest, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.Voluntary_Interest, (int)otran.FundTypeID); break; case EnumGLTranType.MonthlyContributionEPF: case EnumGLTranType.MonthlyContribution: case EnumGLTranType.MonthlyContributionCPF: MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.EPF, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.CPF, (int)otran.FundTypeID); MembersTransactionDetailsDA.DeleteFromVoucher(tc, otran.VoucherDate, EnumMemberTranType.Voluntary_EFP, (int)otran.FundTypeID); break; case EnumGLTranType.InvestmentPurchase: InvestmentInfo info = new InvestmentService().GetbyGLTranId(tc,otran.ID); if(info.TotalProAccruedAmount > 0) { throw new Exception("You are not allowed to delete an investment purchase that has profit or interest accrual information. " + "Please delete the profit or interest accrual voucher first."); } InvestmentDA.DeleteInvestment(tc, info.ID); break; case EnumGLTranType.MonthlyInvestmentAccrual: throw new Exception("Delete from Investment accrual History "); break; case EnumGLTranType.InvestmentLiquidation: break; case EnumGLTranType.InvestmentEncashment: break; case EnumGLTranType.InvestmentRenewal: break; case EnumGLTranType.ReducingAccrualInterest: break; case EnumGLTranType.LoanIssue: throw new Exception("Delete from Loan Issue page "); break; case EnumGLTranType.DividendDistribution: break; case EnumGLTranType.LoanPrincipalReliazation: case EnumGLTranType.LoanInterestReliazation: LoanScheduleDA.DeleteFromVoucher(tc, otran.ID, otran.VoucherDate, (int)otran.FundTypeID); break; case EnumGLTranType.LoanEarlySettlement: break; case EnumGLTranType.WidthdrawalPFBalance: break; case EnumGLTranType.FinalSettlement: break; case EnumGLTranType.LoanOpeningIssue: break; case EnumGLTranType.LoanOpeningPrincipalReliazation: break; case EnumGLTranType.GratuitySettlement: break; case EnumGLTranType.WPPFFundDistribution: break; default: break; } GLTranDA.Delete(tc, id); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException("Failed to delete GL Transaction", e); #endregion } } public decimal GetOpen(int gLID, int userObjectID, int userRecordID, DateTime tranDate) { decimal currentBalance = 0; TransactionContext tc = null; try { tc = TransactionContext.Begin(true); currentBalance = GLTranDA.GetOpen(tc, gLID, userObjectID, userRecordID, tranDate); tc.End(); } catch (Exception e) { throw new ServiceException("Failed to Get Balance :" + e.Message, e); } return currentBalance; } public bool GetProcessMonthForInterfaceWithPayroll(int fundTypeID, DateTime month, bool loanDeduction, bool contribution) { bool isMonthProcessed; TransactionContext tc = null; string sSearch = string.Empty; try { if (fundTypeID > 0) { sSearch += SQLParser.MakeSQL("Where fundTypeID = %n ", fundTypeID); } if (loanDeduction) { sSearch += SQLParser.MakeSQL(" And GLTRANTYPE IN (%n, %n) ", EnumGLTranType.LoanPrincipalReliazation, EnumGLTranType.LoanInterestReliazation); } if (contribution) { sSearch += SQLParser.MakeSQL(" And GLTRANTYPE = %n", EnumGLTranType.MonthlyContribution); } if (month > DateTime.MinValue) { sSearch += SQLParser.MakeSQL(" And VoucherDate = %d", GlobalFunctions.LastDateOfMonth(month)); } tc = TransactionContext.Begin(true); isMonthProcessed = GLTranDA.GetProcessMonthForInterfaceWithPayroll(tc, sSearch); tc.End(); } catch (Exception e) { throw new ServiceException("Failed to Get Balance :" + e.Message, e); } return isMonthProcessed; } #endregion } }