示例#1
0
        public IHttpActionResult PostExpense(Expenses expense)
        {
            //using (AccountingEntities entities = new AccountingEntities())
            //{
            entities.Expenses.Add(expense);
            entities.SaveChanges();
            return(CreatedAtRoute("DefaultApi", new { id = expense.ID }, expense));

            //}
        }
        public static string AddEditArDepBalance(int?shipperId, int?consigneeId,
                                                 int currId, decimal amountToAdd, AccountingEntities db)
        {
            string isSaved = "true";

            //AccountingEntities db = new AccountingEntities();

            var arDepBalance = GetBalanceObj(shipperId, consigneeId, currId, db);

            //New balance case
            if (arDepBalance.BalanceAmount == 0)
            {
                arDepBalance.BalanceAmount = amountToAdd;
                arDepBalance.ConsigneeId   = consigneeId;
                arDepBalance.ShipperId     = shipperId;
                arDepBalance.CurrencyId    = currId;
                db.ArCashDepositBalances.Add(arDepBalance);
            }
            else
            {
                db.ArCashDepositBalances.Attach(arDepBalance);
                arDepBalance.BalanceAmount = arDepBalance.BalanceAmount + amountToAdd;
            }

            db.SaveChanges();

            return(isSaved);
        }
示例#3
0
        /// <summary>
        /// Delete accounting transaction the transaction table
        /// </summary>
        /// <param name="transID"></param>
        /// <returns></returns>
        public static bool DeleteTransaction(int transID)
        {
            bool isDeleted        = false;
            AccountingEntities db = new AccountingEntities();

            AccTransaction transDb = new AccTransaction();
            List <AccTransactionDetail> transDetailDb = new List <AccTransactionDetail>();

            transDb = db.AccTransactions.Where(x => x.TransId == transID).FirstOrDefault();
            if (transDb != null)
            {
                transDetailDb = db.AccTransactionDetails.Where(x => x.TransId == transID).ToList();
                try
                {
                    db.AccTransactions.Remove(transDb);
                    foreach (var item in transDetailDb)
                    {
                        db.AccTransactionDetails.Remove(item);
                    }
                    db.SaveChanges();
                    isDeleted = true;
                }
                catch
                {
                    isDeleted = false;
                }
            }
            return(isDeleted);
        }
示例#4
0
 public void Setup()
 {
     using (var dbContext = new AccountingEntities())
     {
         dbContext.Budgets.RemoveRange(dbContext.Budgets);
         dbContext.SaveChanges();
     }
 }
示例#5
0
        internal static void ChangeAgNoteStatus(int agNoteId, InvStatusEnum invStatusEnum)
        {
            byte invStatusId      = (byte)invStatusEnum;
            AccountingEntities db = new AccountingEntities();
            var invDb             = db.AgentNotes.Where(x => x.AgentNoteId == agNoteId).FirstOrDefault();

            invDb.InvStatusId = invStatusId;

            db.SaveChanges();
        }
示例#6
0
        internal static string Delete(int invId, string deleteReason)
        {
            string isSaved = "false";

            if (invId == 0)
            {
                return(isSaved);
            }

            AccountingEntities db = new AccountingEntities();

            InvoiceAP invDb = new InvoiceAP();

            invDb = db.InvoiceAPs
                    .Where(x => x.InvoiceId == invId).FirstOrDefault();

            int?transID = null;

            if (invDb.TransId != null)
            {
                transID = invDb.TransId.Value;
            }

            if (invDb.InvStatusId == 1 || invDb.InvStatusId == 2)
            {
                invDb.IsDeleted    = true;
                invDb.DeleteReason = deleteReason;
                invDb.DeletedBy    = EasyFreight.DAL.AdminHelper.GetCurrentUserId();
                invDb.TransId      = null;

                // invoice total
                var invTotal = db.InvoiceTotalAPs.Where(x => x.InvoiceId == invId).FirstOrDefault();

                try
                {
                    db.SaveChanges();

                    db.InvoiceTotalAPs.Remove(invTotal);

                    if (transID.HasValue)
                    {
                        AccountingHelper.DeleteTransaction(transID.Value);
                    }


                    isSaved = "true";
                }
                catch
                {
                    isSaved = "false";
                }
            }

            return(isSaved);
        }
示例#7
0
        public static string AddEditBank(BankVm bankVm)
        {
            int                bankId  = bankVm.BankId;
            string             isSaved = "true";
            AccountingEntities db      = new AccountingEntities();
            Bank               bankDb;
            List <BankAccount> dbContactList = new List <BankAccount>();

            if (bankId == 0) //Add new case
            {
                bankDb = new Bank();
            }
            else
            {
                bankDb = db.Banks.Include("BankAccounts").Where(x => x.BankId == bankId).FirstOrDefault();
                //delete any removed contact on the screen
                dbContactList = bankDb.BankAccounts.ToList();

                //Get contact Ids sent from the screen
                List <int> contactVmIds = bankVm.BankAccounts.Select(x => x.BankAccId).ToList();
                var        contactDel   = dbContactList.Where(x => !contactVmIds.Contains(x.BankAccId)).ToList();

                foreach (var item in contactDel)
                {
                    db.BankAccounts.Remove(item);
                }
            }

            Mapper.CreateMap <BankVm, Bank>().IgnoreAllNonExisting();
            Mapper.CreateMap <BankAccountVm, BankAccount>().IgnoreAllNonExisting();
            Mapper.Map(bankVm, bankDb);



            if (bankId == 0)
            {
                db.Banks.Add(bankDb);
            }


            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                isSaved = "false " + e.Message;
            }
            catch (Exception e)
            {
                isSaved = "false " + e.Message;
            }

            return(isSaved);
        }
示例#8
0
        public static string AddEditExpense(int expenseId, string expenseNameEn, string expenseNameAr)
        {
            string             isSaved = "";
            AccountingEntities db      = new AccountingEntities();
            ExpenseLib         expenseLibDb;

            if (expenseId != 0)
            {
                expenseLibDb = db.ExpenseLibs.Where(x => x.ExpenseId == expenseId).FirstOrDefault();
            }
            else
            {
                expenseLibDb = new ExpenseLib();
            }

            expenseLibDb.ExpenseNameEn = expenseNameEn;
            expenseLibDb.ExpenseNameAr = expenseNameAr;

            if (expenseId == 0)
            {
                db.ExpenseLibs.Add(expenseLibDb);
            }

            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    db.SaveChanges();
                    if (expenseId == 0)
                    {
                        expenseId = expenseLibDb.ExpenseId;
                        string parentAccountId = ((int)AccountingChartEnum.GeneralAndAdministrativeExpenses).ToString();
                        string accountId       = AccountingChartHelper.AddAccountToChart(expenseNameEn, expenseNameAr, parentAccountId);
                        AccountingChartHelper.AddAccountIdToObj(accountId, "ExpenseLib", expenseId, "ExpenseId");

                        isSaved = expenseId.ToString();
                    }

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                }
            }

            return(isSaved);
        }
示例#9
0
        public static string AddArCashDeposit(CashInVm cashInVm)
        {
            string             isSaved       = "true";
            AccountingEntities db            = new AccountingEntities();
            ArCashDeposit      arCashDeposit = new ArCashDeposit();

            Mapper.CreateMap <CashInVm, ArCashDeposit>()
            .IgnoreAllNonExisting();
            Mapper.Map(cashInVm, arCashDeposit);

            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    arCashDeposit.ReceiptCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.CashIn, true);
                    db.ArCashDeposits.Add(arCashDeposit);

                    db.SaveChanges();



                    cashInVm.ReceiptId   = arCashDeposit.ReceiptId;
                    cashInVm.ReceiptCode = arCashDeposit.ReceiptCode;

                    string creditAccountId = ((int)AccountingChartEnum.DepositRevenues).ToString();

                    //Add invoice to accounting transactions table
                    CashHelper.AddReceiptToTransTable(creditAccountId, cashInVm, "ArCashDeposit");

                    //Add or update deposit balance for this client
                    CashDepositBalanceHelper.AddEditArDepBalance(cashInVm.ShipperId, cashInVm.ConsigneeId,
                                                                 cashInVm.CurrencyId, cashInVm.ReceiptAmount.Value, db);

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                }
            }


            return(isSaved);
        }
示例#10
0
        public static string AddAccountToChart(string accountNameEn, string accountNameAr, string parentAccountId)
        {
            AccountingEntities db = new AccountingEntities();
            // string accountRecCode = ((int) AccountingChartEnum.AccountsRecievable).ToString();
            // int addOne = db.AccountingCharts.Where(x => x.ParentAccountId == parentAccountId).Count() + 1;
            var    addOne       = db.AccountingCharts.Where(x => x.ParentAccountId == parentAccountId).ToList();
            string newAccountId = "";

            if (addOne.Count() > 0)
            {
                var accNumberAddOne = long.Parse(addOne.Max(x => long.Parse(x.AccountId)).ToString()
                                                 .Replace(parentAccountId, "")) + 1;
                newAccountId = parentAccountId + accNumberAddOne;
            }

            else
            {
                newAccountId = parentAccountId + "1";
            }

            AccountingChart accChart = new AccountingChart()
            {
                AccountId       = newAccountId,
                AccountNameAr   = accountNameAr,
                AccountNameEn   = accountNameEn,
                CreateDate      = DateTime.Now,
                ParentAccountId = parentAccountId
            };

            db.AccountingCharts.Add(accChart);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                newAccountId = "false " + e.Message;
                throw;
            }
            catch (Exception e)
            {
                newAccountId = "false " + e.InnerException;
                throw;
            }

            return(newAccountId);
        }
示例#11
0
        public static string DeleteBank(int id)
        {
            string             isDeleted = "true";
            AccountingEntities db        = new AccountingEntities();
            Bank bankDbObj = db.Banks.Include("BankAccounts")
                             .Where(x => x.BankId == id).FirstOrDefault();

            db.Banks.Remove(bankDbObj);

            int bankFound = 0;

            AgentNote agNoteDb;

            agNoteDb  = db.AgentNotes.Where(x => x.BankId == id && (x.InvStatusId != 1)).FirstOrDefault();
            bankFound = agNoteDb != null ? bankFound + 1 : bankFound;

            CashInReceipt cashInReceiptDb;

            cashInReceiptDb = db.CashInReceipts.Where(x => x.BankId == id && (x.IsDeleted != true)).FirstOrDefault();
            bankFound       = cashInReceiptDb != null ? bankFound + 1 : bankFound;

            CashOutReceipt cashOutReceiptDb;

            cashOutReceiptDb = db.CashOutReceipts.Where(x => x.BankId == id && (x.IsDeleted != true)).FirstOrDefault();
            bankFound        = cashOutReceiptDb != null ? bankFound + 1 : bankFound;

            if (bankFound > 0)
            {
                isDeleted = "Cannot Delete this bank there are some related transactions ! ";
                return(isDeleted);
            }


            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                isDeleted = "false " + ex.Message;
            }

            return(isDeleted);
        }
示例#12
0
        internal static void ChangeInvStatus(int invId, InvStatusEnum invStatusEnum, bool isOut = false)
        {
            byte invStatusId      = (byte)invStatusEnum;
            AccountingEntities db = new AccountingEntities();

            if (isOut)
            {
                var invDb = db.InvoiceAPs.Where(x => x.InvoiceId == invId).FirstOrDefault();
                invDb.InvStatusId = invStatusId;
            }
            else
            {
                var invDb = db.Invoices.Where(x => x.InvoiceId == invId).FirstOrDefault();
                invDb.InvStatusId = invStatusId;
            }


            db.SaveChanges();
        }
示例#13
0
        /// <summary>
        /// Will use it tho delete an account from the chart .. most of time when account is generated and the
        /// main object insertion falied
        /// </summary>
        /// <param name="accountId"></param>
        public static void DeleteAccount(string accountId)
        {
            AccountingEntities db = new AccountingEntities();
            var accountObj        = db.AccountingCharts.Where(x => x.AccountId == accountId).FirstOrDefault();

            db.AccountingCharts.Remove(accountObj);
            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#14
0
        internal static string PayCheck(int receiptId)
        {
            string             isCollected = "true";
            AccountingEntities db          = new AccountingEntities();
            var receiptData = db.CashOutReceipts.Where(x => x.ReceiptId == receiptId)
                              .Select(x => new { x.ReceiptAmount, x.CurrencyId, x.ReceiptCode, x.BankAccId })
                              .FirstOrDefault();
            var receiptCheck = db.CashOutReceiptChecks.Where(x => x.ReceiptId == receiptId).FirstOrDefault();

            receiptCheck.IsCollected = true;
            receiptCheck.CollectDate = DateTime.Now;
            receiptCheck.CollectBy   = AdminHelper.GetCurrentUserId();

            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    db.SaveChanges();

                    //Add Transactions
                    string creditAccId = AccountingChartHelper.GetAccountIdByPkAndTbName(receiptData.BankAccId.Value, "BankAccount", "BankAccId");
                    string debitAccId  = ((int)AccountingChartEnum.NotesPayable).ToString();
                    string comment     = "Pay check number " + receiptCheck.CheckNumber + " received by cash receipt code " + receiptData.ReceiptCode;
                    string commentAr   = "دفع الشيك رقم " + receiptCheck.CheckNumber + " المستلم بموجب ايصال استلام رقم " + receiptData.ReceiptCode;
                    AddCheckActionToTransTable(debitAccId, creditAccId, receiptData.ReceiptAmount,
                                               receiptData.CurrencyId.Value, comment, commentAr, receiptId, "CashOutReceiptCheck");

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isCollected = "false " + e.Message;
                }
                catch (Exception e)
                {
                    isCollected = "false " + e.Message;
                }


                return(isCollected);
            }
        }
示例#15
0
        public void add_data_and_query_data()
        {
            using (var dbContext = new AccountingEntities())
            {
                var amount = new Random(DateTime.Now.Millisecond).Next(0, 100);
                dbContext.Budgets.Add(new Budget()
                {
                    Amount = amount, YearMonth = "20200206"
                });
                dbContext.SaveChanges();

                var expected = new Budget()
                {
                    Amount = amount, YearMonth = "20200206"
                };
                var actual = dbContext.Budgets.First();

                expected.ToExpectedObject().ShouldMatch(actual);
            }
        }
示例#16
0
        /// <summary>
        /// Add accounting transaction the transaction table
        /// </summary>
        /// <param name="transVm">AccTransactionVm</param>
        /// <returns>The Id for the added trans</returns>
        public static int AddTransaction(AccTransactionVm transVm)
        {
            int transId           = 0;
            AccountingEntities db = new AccountingEntities();

            AccTransaction transDb = new AccTransaction();

            Mapper.CreateMap <AccTransactionVm, AccTransaction>().IgnoreAllNonExisting();
            Mapper.CreateMap <AccTransactionDetailVm, AccTransactionDetail>().IgnoreAllNonExisting();
            Mapper.Map(transVm, transDb);

            db.AccTransactions.Add(transDb);

            try
            {
                db.SaveChanges();
                transId = transDb.TransId;
            }
            catch
            {
                throw;
            }
            return(transId);
        }
示例#17
0
        public static string DeleteExpense(int expenseId)
        {
            string             isDeleted = "true";
            AccountingEntities db        = new AccountingEntities();
            string             accountId = db.ExpenseLibs.Where(x => x.ExpenseId == expenseId).FirstOrDefault().AccountId;
            bool expIsUsed = db.AccTransactionDetails.Any(x => x.AccountId == accountId);

            if (expIsUsed)
            {
                isDeleted = "Can't delete this expense as it has accounting transactions";
            }
            else
            {
                var expenseObj      = db.ExpenseLibs.Where(x => x.ExpenseId == expenseId).FirstOrDefault();
                var accountChartObj = db.AccountingCharts.Where(x => x.AccountId == accountId).FirstOrDefault();

                db.AccountingCharts.Remove(accountChartObj);
                db.ExpenseLibs.Remove(expenseObj);

                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    isDeleted = "false " + e.Message;
                }
                catch (Exception e)
                {
                    isDeleted = "false " + e.Message;
                }
            }


            return(isDeleted);
        }
示例#18
0
        /*
         * internal static string DeleteCashOutReceipt(int receiptId, int invID, string deleteReason)
         * {
         *
         *  string isSaved = "false";
         *
         *  if (receiptId == 0)
         *      return isSaved;
         *
         *  AccountingEntities db = new AccountingEntities();
         *
         *  CashOutReceipt cashOutDb = new CashOutReceipt();
         *  cashOutDb = db.CashOutReceipts
         *          .Where(x => x.ReceiptId == receiptId).FirstOrDefault();
         *
         *  CashOutReceiptCheck cashOutCheckDb = new CashOutReceiptCheck();
         *  cashOutCheckDb = db.CashOutReceiptChecks
         *          .Where(x => x.ReceiptId == receiptId).FirstOrDefault();
         *
         *  CashOutReceiptInv cashOutInvkDb = new CashOutReceiptInv();
         *  cashOutInvkDb = db.CashOutReceiptInvs
         *          .Where(x => x.ReceiptId == receiptId).FirstOrDefault();
         *
         *
         *
         *  int? transID = null;
         *  if (cashOutDb.TransId != null)
         *      transID = cashOutDb.TransId.Value;
         *  cashOutDb.IsDeleted = true;
         *  cashOutDb.DeleteReason = deleteReason;
         *  cashOutDb.DeletedBy = EasyFreight.DAL.AdminHelper.GetCurrentUserId();
         *  cashOutDb.TransId = null;
         *
         *
         *  if (cashOutCheckDb != null)
         *      db.CashOutReceiptChecks.Remove(cashOutCheckDb);
         *
         *  if (cashOutInvkDb != null)
         *      db.CashOutReceiptInvs.Remove(cashOutInvkDb);
         *
         *  try
         *  {
         *      db.SaveChanges();
         *
         *      if (transID.HasValue)
         *          AccountingHelper.DeleteTransaction(transID.Value);
         *
         *      List<CashInInvoiceVm> cashOutVmObj = GetCashInvList(invID);
         *
         *      if (invID != 0)
         *      {
         *          if (cashOutVmObj.Count == 0)
         *              InvoiceHelper.ChangeInvStatus(invID, InvStatusEnum.Approved, true);
         *          else
         *          {
         *
         *              InvoiceAP invDb = db.InvoiceAPs.Where(x => x.InvoiceId == invID).FirstOrDefault();
         *
         *              decimal InvoiceTotals = invDb.InvoiceTotalAPs.Sum(s => s.TotalAmount);
         *
         *              decimal? totalPaidAmount = cashOutVmObj.Sum(s => s.PaidAmount);
         *
         *              if (totalPaidAmount == null)
         *                  InvoiceHelper.ChangeInvStatus(invID, InvStatusEnum.Approved, true);
         *              else
         *              {
         *                  if (totalPaidAmount == InvoiceTotals)
         *                      InvoiceHelper.ChangeInvStatus(invID, InvStatusEnum.Paid, true);
         *                  if (totalPaidAmount < InvoiceTotals)
         *                      InvoiceHelper.ChangeInvStatus(invID, InvStatusEnum.PartiallyPaid, true);
         *              }
         *          }
         *      }
         *
         *      isSaved = "true";
         *  }
         *  catch
         *  {
         *      isSaved = "false";
         *  }
         *
         *
         *
         *  return isSaved;
         *
         * }
         */

        internal static string AddEditOpenCashReceipt(CashInVm cashInVmObj, out int savedReceiptId, bool addToTrans = true)
        {
            string isSaved = "true";

            AccountingEntities db = new AccountingEntities();



            int receiptId = cashInVmObj.ReceiptId;

            savedReceiptId = receiptId;



            CashOutReceipt cashDbObj;

            if (receiptId == 0)
            {
                cashDbObj = new CashOutReceipt();
            }
            else
            {
                cashDbObj = db.CashOutReceipts.Include("CashOutReceiptChecks")
                            .Include("CashOutReceiptInvs")
                            .Where(x => x.ReceiptId == receiptId).FirstOrDefault();

                //Delete invoice list .. will insert it again
                var invList = cashDbObj.CashOutReceiptInvs.ToList();
                foreach (var item in invList)
                {
                    cashDbObj.CashOutReceiptInvs.Remove(item);
                }

                //Delete check list .. will insert it again
                var checkList = cashDbObj.CashOutReceiptChecks.ToList();
                foreach (var item in checkList)
                {
                    cashDbObj.CashOutReceiptChecks.Remove(item);
                }
            }

            Mapper.CreateMap <CashInVm, CashOutReceipt>()
            .ForMember(x => x.CashOutReceiptInvs, y => y.Ignore())
            .ForMember(x => x.CashOutReceiptChecks, y => y.Ignore())
            .IgnoreAllNonExisting();
            Mapper.Map(cashInVmObj, cashDbObj);

            CashOutReceiptCheck cashCheckDb;

            foreach (var item in cashInVmObj.CashInReceiptChecks)
            {
                if (!string.IsNullOrEmpty(item.CheckNumber))
                {
                    cashCheckDb = new CashOutReceiptCheck();
                    Mapper.CreateMap <CashInCheckVm, CashOutReceiptCheck>().IgnoreAllNonExisting();
                    Mapper.Map(item, cashCheckDb);

                    cashDbObj.CashOutReceiptChecks.Add(cashCheckDb);
                }
            }

            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    if (receiptId == 0)
                    {
                        cashDbObj.ReceiptCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.CashOut, true);
                        db.CashOutReceipts.Add(cashDbObj);
                    }

                    db.SaveChanges();

                    cashInVmObj.ReceiptId   = cashDbObj.ReceiptId;
                    cashInVmObj.ReceiptCode = cashDbObj.ReceiptCode;

                    savedReceiptId = cashInVmObj.ReceiptId;

                    #region Add To Transaction Table
                    if (addToTrans)
                    {
                        string creditAccountId = "";

                        if (cashInVmObj.ShipperId != null)
                        {
                            creditAccountId = AccountingChartHelper.GetAccountIdByPkAndTbName(cashInVmObj.ShipperId.Value, "Shipper", "ShipperId");
                        }
                        if (cashInVmObj.CarrierId != null)
                        {
                            creditAccountId = AccountingChartHelper.GetAccountIdByPkAndTbName(cashInVmObj.CarrierId.Value, "Carrier", "CarrierId");
                        }
                        if (cashInVmObj.ContractorId != null)
                        {
                            creditAccountId = AccountingChartHelper.GetAccountIdByPkAndTbName(cashInVmObj.ContractorId.Value, "Contractor", "ContractorId");
                        }
                        if (cashInVmObj.AgentId != null)
                        {
                            creditAccountId = AccountingChartHelper.GetAccountIdByPkAndTbName(cashInVmObj.AgentId.Value, "Agent", "AgentId");
                        }
                        if (cashInVmObj.ConsigneeId != null)
                        {
                            creditAccountId = AccountingChartHelper.GetAccountIdByPkAndTbName(cashInVmObj.ConsigneeId.Value, "Consignee", "ConsigneeId");
                        }

                        //AccTransaction accTran = new AccTransaction()
                        //{
                        //    CreateBy = AdminHelper.GetCurrentUserId(),
                        //    CreateDate = DateTime.Now,
                        //    TransactionName = "pay open balance"
                        //};

                        //AccTransactionDetail accTranDetail = new AccTransactionDetail();

                        //accTranDetail.AccountId = creditAccountId;
                        //accTranDetail.DebitAmount = cashInVmObj.ReceiptAmount.Value;
                        //accTranDetail.CurrencyId = cashInVmObj.CurrencyId;

                        //accTran.AccTransactionDetails.Add(accTranDetail);

                        //db.AccTransactions.Add(accTran);

                        //db.SaveChanges();

                        AddReceiptToTransTable(creditAccountId, cashInVmObj, true);
                    }

                    #endregion

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;

                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
            }

            return(isSaved);
        }
示例#19
0
        internal static string AddEditAgentNote(AgentNoteVm agentNoteVm)
        {
            string             isSaved = "true";
            AccountingEntities db      = new AccountingEntities();
            AgentNote          agNoteDb;
            int agNoteId = agentNoteVm.AgentNoteId;

            if (agNoteId == 0)
            {
                agNoteDb = new AgentNote();
            }
            else
            {
                agNoteDb = db.AgentNotes.Where(x => x.AgentNoteId == agNoteId).FirstOrDefault();
            }

            Mapper.CreateMap <AgentNoteVm, AgentNote>()
            .ForMember(x => x.AgentNoteDetails, y => y.Ignore())
            .IgnoreAllNonExisting();

            Mapper.Map(agentNoteVm, agNoteDb);

            AgentNoteDetail agNoteDetail;

            Mapper.CreateMap <AgentNoteDetailVm, AgentNoteDetail>().IgnoreAllNonExisting();

            foreach (var item in agentNoteVm.AgentNoteDetails)
            {
                if (item.IsSelected)
                {
                    agNoteDetail = new AgentNoteDetail();
                    Mapper.Map(item, agNoteDetail);
                    agNoteDb.AgentNoteDetails.Add(agNoteDetail);
                }
            }

            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    string agentAccId = AccountingChartHelper.GetAccountIdByPkAndTbName(agNoteDb.AgentId, "Agent", "AgentId");
                    if (string.IsNullOrEmpty(agentAccId))
                    {
                        agentAccId = AccountingChartHelper.AddAgentToChart(agNoteDb.AgentId, agNoteDb.AgentNoteType);
                    }


                    if (agNoteId == 0)
                    {
                        agNoteDb.AgentNoteCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.AgentNote, true);
                        db.AgentNotes.Add(agNoteDb);
                    }

                    db.SaveChanges();

                    if (agNoteId == 0)
                    {
                        agentNoteVm.AgentId       = agNoteDb.AgentId;
                        agentNoteVm.AgentNoteCode = agNoteDb.AgentNoteCode;
                        //Add invoice to accounting transactions table
                        AddAgentToTransTable(agentAccId, agentNoteVm);


                        OperationHelper.ChangeOperationStatus(agentNoteVm.OperationId, (byte)StatusEnum.InvoiceIssued);
                    }
                    isSaved = "true" + agNoteDb.AgentNoteId;
                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;
                    AdminHelper.LastIdRemoveOne(PrefixForEnum.AgentNote);
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                    AdminHelper.LastIdRemoveOne(PrefixForEnum.AgentNote);
                }
            }


            return(isSaved);
        }
示例#20
0
        internal static string Delete(int invId, string deleteReason)
        {
            string isSaved = "false";

            if (invId == 0)
            {
                return(isSaved);
            }

            AccountingEntities db = new AccountingEntities();

            Invoice invDb = new Invoice();

            invDb = db.Invoices
                    .Where(x => x.InvoiceId == invId).FirstOrDefault();

            int?transID = null;

            if (invDb.TransId != null)
            {
                transID = invDb.TransId.Value;
            }

            if (invDb.InvStatusId == 1 || invDb.InvStatusId == 2)
            {
                invDb.IsDeleted    = true;
                invDb.DeleteReason = deleteReason;
                invDb.DeletedBy    = EasyFreight.DAL.AdminHelper.GetCurrentUserId();
                invDb.TransId      = null;

                // invoice total
                var invTotal = db.InvoiceTotals.Where(x => x.InvoiceId == invId).FirstOrDefault();

                try
                {
                    db.SaveChanges();

                    db.InvoiceTotals.Remove(invTotal);

                    if (transID.HasValue)
                    {
                        AccountingHelper.DeleteTransaction(transID.Value);
                    }

                    #region Update Operation Status...
                    try
                    {
                        var provInvs = db.Invoices
                                       .Where(x => x.OperationId == invDb.OperationId && x.IsDeleted == null && x.InvoiceId != invDb.InvoiceId).ToList();
                        if (provInvs.Count == 0)
                        {
                            OperationsEntities opdb = new OperationsEntities();
                            var operation           = opdb.Operations.Where(z => z.OperationId == invDb.OperationId).FirstOrDefault();
                            operation.StatusId = 3;
                            opdb.SaveChanges();
                        }
                    }
                    catch { }
                    #endregion

                    isSaved = "true";
                }
                catch
                {
                    isSaved = "false";
                }
            }

            return(isSaved);
        }
示例#21
0
        internal static string AddEditInvoice(InvoiceVm invoiceVm)
        {
            string isSaved = "true";

            AccountingEntities db = new AccountingEntities();
            int  invoiceId        = invoiceVm.InvoiceId;
            byte invoiceType      = invoiceVm.InvoiceType;
            // int hbId = invoiceVm.HouseBillId;

            Invoice invDb;

            if (invoiceId == 0)
            {
                invDb = new Invoice();
            }
            else
            {
                invDb = db.Invoices.Include("InvoiceDetails").Include("InvoiceTotals")
                        .Where(x => x.InvoiceId == invoiceId).FirstOrDefault();
                //Delete Invoice details and totals .. will insert it again
                var invDbTotals  = invDb.InvoiceTotals;
                var invDbDetails = invDb.InvoiceDetails;
                foreach (var item in invDbDetails)
                {
                    invDb.InvoiceDetails.Remove(item);
                }
                foreach (var item in invDbTotals)
                {
                    invDb.InvoiceTotals.Remove(item);
                }
            }


            Mapper.CreateMap <InvoiceVm, Invoice>()
            .ForMember(x => x.InvoiceTotals, y => y.Ignore())
            .ForMember(x => x.InvoiceDetails, y => y.Ignore())
            .IgnoreAllNonExisting();
            Mapper.Map(invoiceVm, invDb);

            InvoiceDetail invDetail;

            Mapper.CreateMap <InvoiceDetailVm, InvoiceDetail>().IgnoreAllNonExisting();
            foreach (var item in invoiceVm.InvoiceDetails)
            {
                if (item.IsSelected == true)
                {
                    invDetail = new InvoiceDetail();
                    Mapper.Map(item, invDetail);
                    invDb.InvoiceDetails.Add(invDetail);
                }
            }

            InvoiceTotal invTotalDb;

            foreach (var item in invoiceVm.InvoiceTotals)
            {
                invTotalDb = new InvoiceTotal()
                {
                    CurrencyId       = item.CurrencyId,
                    TotalAmount      = item.TotalAmount,
                    CurrencySign     = item.CurrencySign,
                    TaxDepositAmount = item.TaxDepositAmount,
                    TotalBeforeTax   = item.TotalBeforeTax,
                    VatTaxAmount     = item.VatTaxAmount
                };

                invDb.InvoiceTotals.Add(invTotalDb);
            }



            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    //Add shipper or consignee to accounting chart
                    string accountId = GetAccountId(invoiceVm.OrderFrom, invoiceVm.ShipperId, invoiceVm.ConsigneeId);

                    if (invoiceId == 0)
                    {
                        invDb.InvoiceCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.AccountingInvoice, true);
                        db.Invoices.Add(invDb);
                    }

                    db.SaveChanges();

                    invoiceVm.InvoiceId   = invDb.InvoiceId;
                    invoiceVm.InvoiceCode = invDb.InvoiceCode;


                    //Change HB status
                    if (invoiceId == 0)
                    {
                        //Add invoice to accounting transactions table
                        AddInvToTransTable(accountId, invoiceVm);

                        HouseBillHelper.ChangeHBStatus(invDb.HouseBillId, (byte)StatusEnum.InvoiceIssued);
                        OperationHelper.ChangeOperationStatus(invDb.OperationId, (byte)StatusEnum.InvoiceIssued);
                    }

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;

                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
            }

            return(isSaved);
        }
示例#22
0
        //public static OpenBalanceVm GetOpenBalanceForCash()
        //{
        //    OpenBalanceVm balanceVm = new OpenBalanceVm();
        //    balanceVm.TbName = "Currency";
        //    balanceVm.LibItemId = 0;
        //    balanceVm.CreateDate = DateTime.Now;
        //    balanceVm.IsCreditAgent = false;

        //    AccountingEntities db = new AccountingEntities();

        //    //Get Currency List
        //    var currList = db.CurrencyAccs.ToList();
        //    OpenBalanceDetailVm openBalanceDet;

        //    foreach (var item in currList)
        //    {
        //        string accountId = AccountingChartHelper.GetAccountIdByPkAndTbName(item.CurrencyId, "Currency", "CurrencyId");
        //        //Get Transaction details for open balance
        //        var accTanDet = db.AccTransactionDetails.Include("AccTransaction")
        //            .Where(x => x.AccountId == accountId && x.AccTransaction.TransactionName == "open balance").ToList();
        //        openBalanceDet = new OpenBalanceDetailVm();
        //        openBalanceDet.CurrencyId = item.CurrencyId;
        //        openBalanceDet.CurrencySign = item.CurrencySign;
        //        openBalanceDet.CurrencyAccountId = item.AccountId;
        //        //check if has open balance for this currency
        //        var openAccTran = accTanDet.Where(x => x.CurrencyId == item.CurrencyId).FirstOrDefault();
        //        if (openAccTran != null)
        //        {
        //            openBalanceDet.TransDetailId = openAccTran.TransDetailId;
        //            openBalanceDet.CreditAmount = openAccTran.CreditAmount;
        //            openBalanceDet.DebitAmount = openAccTran.DebitAmount;
        //        }

        //        balanceVm.OpenBalanceDetails.Add(openBalanceDet);
        //    }



        //    return balanceVm;
        //}

        public static string AddEditOpenBalance(OpenBalanceVm openBalanceVm)
        {
            string isSaved = "true";

            string accountId = "";
            string tbName, pkName; int libId; bool isCreditAgent = false;

            libId  = openBalanceVm.LibItemId;
            tbName = openBalanceVm.TbName;
            pkName = openBalanceVm.PkName;
            if (openBalanceVm.IsCreditAgent != null)
            {
                isCreditAgent = openBalanceVm.IsCreditAgent.Value;
            }

            //Get AccountId
            accountId = AccountingChartHelper.GetAccountIdByPkAndTbName(libId, tbName, pkName);
            if (string.IsNullOrEmpty(accountId))
            {
                switch (tbName)
                {
                case "Agent":
                    byte agentType;
                    if (isCreditAgent == false)
                    {
                        agentType = 1;     //debit note A/R
                    }
                    else
                    {
                        agentType = 2;     //Credit note A/P
                    }
                    accountId = AccountingChartHelper.AddAgentToChart(libId, agentType);
                    break;

                case "Carrier":
                    accountId = AccountingChartHelper.AddCarrierToChart(libId);
                    break;

                case "Contractor":
                    accountId = AccountingChartHelper.AddContractorToChart(libId);
                    break;

                case "Shipper":
                    accountId = AccountingChartHelper.AddShipperToChart(libId);
                    break;

                case "Consignee":
                    accountId = AccountingChartHelper.AddConsigneeToChart(libId);
                    break;

                case "Currency":
                    accountId = AccountingChartHelper.AddCashToChart(libId);
                    break;

                case "BankAccount":
                    accountId = AccountingChartHelper.AddBankAccountToChart(0, libId);
                    break;

                case "AccountingChart":
                    accountId = AccountingChartHelper.AddBankAccountToChart(0, libId);
                    break;
                }

                AccountingChartHelper.AddAccountIdToObj(accountId, tbName, libId, pkName);
            }

            openBalanceVm.AccountId = accountId;

            int            transId = openBalanceVm.TransId;
            AccTransaction accTran;

            AccountingEntities db = new AccountingEntities();

            if (transId != 0)
            {
                accTran = db.AccTransactions.Include("AccTransactionDetails").Where(x => x.TransId == transId).FirstOrDefault();
                //delete all tran details and add it later
                foreach (var item in accTran.AccTransactionDetails.ToList())
                {
                    db.AccTransactionDetails.Remove(item);
                }
            }
            else
            {
                accTran =
                    new AccTransaction()
                {
                    CreateBy        = AdminHelper.GetCurrentUserId(),
                    CreateDate      = DateTime.Now,
                    TransactionName = "open balance"
                };
            }

            Mapper.CreateMap <OpenBalanceDetailVm, AccTransactionDetail>();
            AccTransactionDetail accTranDetail;

            foreach (var item in openBalanceVm.OpenBalanceDetails.Where(x => x.DebitAmount != null || x.CreditAmount != null))
            {
                accTranDetail = new AccTransactionDetail();

                item.AccountId = accountId;
                Mapper.Map(item, accTranDetail);
                accTran.AccTransactionDetails.Add(accTranDetail);
            }

            if (transId == 0)
            {
                db.AccTransactions.Add(accTran);
            }

            try
            {
                db.SaveChanges();
            }

            catch (DbEntityValidationException e)
            {
                isSaved = "false " + e.Message;
            }
            catch (Exception e)
            {
                isSaved = "false " + e.Message;
            }
            return(isSaved);
        }
示例#23
0
        internal static string AddEditCashReceipt(CashInVm cashInVmObj, out int savedReceiptId, bool addToTrans = true)
        {
            string isSaved = "true";

            AccountingEntities db = new AccountingEntities();
            int receiptId         = cashInVmObj.ReceiptId;

            savedReceiptId = receiptId;
            CashOutReceipt cashDbObj;

            if (receiptId == 0)
            {
                cashDbObj = new CashOutReceipt();
            }
            else
            {
                cashDbObj = db.CashOutReceipts.Include("CashOutReceiptChecks")
                            .Include("CashOutReceiptInvs")
                            .Where(x => x.ReceiptId == receiptId).FirstOrDefault();

                //Delete invoice list .. will insert it again
                var invList = cashDbObj.CashOutReceiptInvs.ToList();
                foreach (var item in invList)
                {
                    cashDbObj.CashOutReceiptInvs.Remove(item);
                }

                //Delete check list .. will insert it again
                var checkList = cashDbObj.CashOutReceiptChecks.ToList();
                foreach (var item in checkList)
                {
                    cashDbObj.CashOutReceiptChecks.Remove(item);
                }
            }

            Mapper.CreateMap <CashInVm, CashOutReceipt>()
            .ForMember(x => x.CashOutReceiptInvs, y => y.Ignore())
            .ForMember(x => x.CashOutReceiptChecks, y => y.Ignore())
            .IgnoreAllNonExisting();
            Mapper.Map(cashInVmObj, cashDbObj);

            CashOutReceiptCheck cashCheckDb;

            foreach (var item in cashInVmObj.CashInReceiptChecks)
            {
                if (!string.IsNullOrEmpty(item.CheckNumber))
                {
                    cashCheckDb = new CashOutReceiptCheck();
                    Mapper.CreateMap <CashInCheckVm, CashOutReceiptCheck>().IgnoreAllNonExisting();
                    Mapper.Map(item, cashCheckDb);

                    cashDbObj.CashOutReceiptChecks.Add(cashCheckDb);
                }
            }

            if (cashInVmObj.OperationId != null) //CC Cash Deposit
            {
                CashOutCCCashDeposit cashDeposit = new CashOutCCCashDeposit();
                cashDeposit.OperationId = cashInVmObj.OperationId.Value;
                cashDeposit.ReceiptId   = cashInVmObj.ReceiptId;
                cashDbObj.CashOutCCCashDeposits.Add(cashDeposit);
            }

            else if (cashInVmObj.AgentId == null) //Cash Receipt for invoice
            {
                //Add Receipt invoices
                CashOutReceiptInv cashInvDb;
                foreach (var item in cashInVmObj.CashInReceiptInvs)
                {
                    if (item.IsSelected)
                    {
                        cashInvDb = new CashOutReceiptInv();
                        Mapper.CreateMap <CashInInvoiceVm, CashOutReceiptInv>().IgnoreAllNonExisting();
                        item.CashInReceipt = null;
                        Mapper.Map(item, cashInvDb);

                        cashDbObj.CashOutReceiptInvs.Add(cashInvDb);
                    }
                }
            }
            else //Cash Receipt for Agent Note
            {
                //Add Receipt Agent Notes
                CashOutReceiptAgNote cashAgNoteDb;
                foreach (var item in cashInVmObj.CashInReceiptInvs)
                {
                    if (item.IsSelected)
                    {
                        cashAgNoteDb = new CashOutReceiptAgNote();
                        Mapper.CreateMap <CashInInvoiceVm, CashOutReceiptAgNote>().IgnoreAllNonExisting();
                        item.CashInReceipt = null;
                        Mapper.Map(item, cashAgNoteDb);

                        cashDbObj.CashOutReceiptAgNotes.Add(cashAgNoteDb);
                    }
                }
            }


            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    if (receiptId == 0)
                    {
                        cashDbObj.ReceiptCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.CashOut, true);
                        db.CashOutReceipts.Add(cashDbObj);
                    }

                    db.SaveChanges();

                    cashInVmObj.ReceiptId   = cashDbObj.ReceiptId;
                    cashInVmObj.ReceiptCode = cashDbObj.ReceiptCode;

                    savedReceiptId = cashInVmObj.ReceiptId;

                    #region Add To Transaction Table
                    if (addToTrans)
                    {
                        //Add shipper or consignee to accounting chart
                        string debitAccountId = "";
                        if (cashInVmObj.OperationId != null) //CC Cash Deposit
                        {
                            debitAccountId = AccountingChartHelper.GetCCCashDepAccountId(cashInVmObj.OperationId.Value);
                            if (string.IsNullOrEmpty(debitAccountId))
                            {
                                debitAccountId = AccountingChartHelper.AddCCCashDepositToChart(cashInVmObj.OperationId.Value);
                            }
                        }
                        else if (!string.IsNullOrEmpty(cashInVmObj.PartnerAccountId)) //Partner Drawing
                        {
                            debitAccountId = cashInVmObj.PartnerAccountId;
                        }
                        else if (cashInVmObj.AgentId == null) //Cash Receipt for invoice
                        {
                            if (cashInVmObj.InvoiceType == 1) //carrier
                            {
                                debitAccountId = AccountingChartHelper
                                                 .GetAccountIdByPkAndTbName(cashInVmObj.CarrierId.Value, "Carrier", "CarrierId");
                                if (string.IsNullOrEmpty(debitAccountId))
                                {
                                    debitAccountId = AccountingChartHelper.AddCarrierToChart(cashInVmObj.CarrierId.Value);
                                }
                            }
                            else if (cashInVmObj.InvoiceType == 2) //contractor
                            {
                                debitAccountId = AccountingChartHelper
                                                 .GetAccountIdByPkAndTbName(cashInVmObj.ContractorId.Value, "Contractor", "ContractorId");
                                if (string.IsNullOrEmpty(debitAccountId))
                                {
                                    debitAccountId = AccountingChartHelper.AddContractorToChart(cashInVmObj.ContractorId.Value);
                                }
                            }
                            else if (cashInVmObj.InvoiceType == 3) //custom clearance .. 22/11/2016
                            {
                                debitAccountId = ((int)AccountingChartEnum.CustomClearanceSupplier).ToString();
                            }
                        }
                        else //Cash Receipt for Agent Note
                        {
                            debitAccountId = AccountingChartHelper.GetAccountIdByPkAndTbName(cashInVmObj.AgentId.Value, "Agent", "AgentId");
                            if (string.IsNullOrEmpty(debitAccountId))
                            {
                                debitAccountId = AccountingChartHelper.AddAgentToChart(cashInVmObj.AgentId.Value, 2); //AgentNoteType = 2 .. Credit Agent
                            }
                        }

                        if (receiptId == 0)
                        {
                            //Add invoice to accounting transactions table

                            AddReceiptToTransTable(debitAccountId, cashInVmObj);

                            foreach (var item in cashInVmObj.CashInReceiptInvs)
                            {
                                if (item.IsSelected)
                                {
                                    if (item.InvoiceId != 0) //Cash Receipt for invoice
                                    {
                                        //Change Invoice status
                                        if (item.AmountDue == 0)
                                        {
                                            InvoiceHelper.ChangeInvStatus(item.InvoiceId, InvStatusEnum.Paid, true);
                                        }
                                        else if (item.CollectedAmount != 0 && item.AmountDue != 0)
                                        {
                                            InvoiceHelper.ChangeInvStatus(item.InvoiceId, InvStatusEnum.PartiallyPaid, true);
                                        }
                                    }
                                    else //Cash Receipt for Agent Note
                                    {
                                        //Change Agent Note status
                                        if (item.AmountDue == 0)
                                        {
                                            AgentNoteHelper.ChangeAgNoteStatus(item.AgentNoteId, InvStatusEnum.Paid);
                                        }
                                        else if (item.CollectedAmount != 0 && item.AmountDue != 0)
                                        {
                                            AgentNoteHelper.ChangeAgNoteStatus(item.AgentNoteId, InvStatusEnum.PartiallyPaid);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    #endregion

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;

                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
            }

            return(isSaved);
        }
示例#24
0
        internal static string AddEditExpenseCashReceipt(CashInVm cashInVmObj)
        {
            string isSaved = "true";

            AccountingEntities db    = new AccountingEntities();
            int            receiptId = cashInVmObj.ReceiptId;
            CashOutReceipt cashDbObj;

            if (receiptId == 0)
            {
                cashDbObj = new CashOutReceipt();
            }
            else
            {
                cashDbObj = db.CashOutReceipts.Include("CashOutReceiptExpenses")
                            .Where(x => x.ReceiptId == receiptId).FirstOrDefault();

                //Delete expenses list .. will insert it again
                var invList = cashDbObj.CashOutReceiptExpenses.ToList();
                foreach (var item in invList)
                {
                    cashDbObj.CashOutReceiptExpenses.Remove(item);
                }
            }

            Mapper.CreateMap <CashInVm, CashOutReceipt>()
            .ForMember(x => x.CashOutReceiptInvs, y => y.Ignore())
            .ForMember(x => x.CashOutReceiptChecks, y => y.Ignore());

            Mapper.CreateMap <CashOutExpense, CashOutReceiptExpense>();
            Mapper.Map(cashInVmObj, cashDbObj);

            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    if (receiptId == 0)
                    {
                        cashDbObj.ReceiptCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.CashOut, true);
                        db.CashOutReceipts.Add(cashDbObj);
                    }

                    db.SaveChanges();

                    cashInVmObj.ReceiptId   = cashDbObj.ReceiptId;
                    cashInVmObj.ReceiptCode = cashDbObj.ReceiptCode;

                    AddExpenseReceiptToTrans(cashInVmObj);

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;

                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
            }

            return(isSaved);
        }
示例#25
0
        internal static string AddEditInvoice(InvoiceVm invoiceVm)
        {
            string isSaved = "true";

            AccountingEntities db = new AccountingEntities();
            int  invoiceId        = invoiceVm.InvoiceId;
            byte invFor           = invoiceVm.InvoiceType;
            //  int hbId = invoiceVm.HouseBillId;

            InvoiceAP invDb;

            if (invoiceId == 0)
            {
                invDb = new InvoiceAP();
            }
            else
            {
                invDb = db.InvoiceAPs.Include("InvoiceDetailAPs").Include("InvoiceTotalAPs")
                        .Where(x => x.InvoiceId == invoiceId).FirstOrDefault();
                //Delete Invoice details and totals .. will insert it again
                var invDbTotals  = invDb.InvoiceTotalAPs;
                var invDbDetails = invDb.InvoiceDetailAPs;
                foreach (var item in invDbDetails)
                {
                    invDb.InvoiceDetailAPs.Remove(item);
                }
                foreach (var item in invDbTotals)
                {
                    invDb.InvoiceTotalAPs.Remove(item);
                }
            }


            Mapper.CreateMap <InvoiceVm, InvoiceAP>()
            .ForMember(x => x.InvoiceTotalAPs, y => y.Ignore())
            .ForMember(x => x.InvoiceDetailAPs, y => y.Ignore())
            .IgnoreAllNonExisting();
            Mapper.Map(invoiceVm, invDb);

            InvoiceDetailAP invDetail;

            Mapper.CreateMap <InvoiceDetailVm, InvoiceDetailAP>().IgnoreAllNonExisting();
            foreach (var item in invoiceVm.InvoiceDetails)
            {
                if (item.IsSelected == true)
                {
                    invDetail = new InvoiceDetailAP();
                    Mapper.Map(item, invDetail);
                    invDb.InvoiceDetailAPs.Add(invDetail);
                }
            }

            InvoiceTotalAP invTotalDb;

            foreach (var item in invoiceVm.InvoiceTotals)
            {
                invTotalDb = new InvoiceTotalAP()
                {
                    CurrencyId   = item.CurrencyId,
                    TotalAmount  = item.TotalAmount,
                    CurrencySign = item.CurrencySign
                };

                invDb.InvoiceTotalAPs.Add(invTotalDb);
            }



            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    //Add shipper or consignee to accounting chart
                    string creditAccountId = "";
                    if (invFor == 1) //carrier
                    {
                        creditAccountId = AccountingChartHelper
                                          .GetAccountIdByPkAndTbName(invoiceVm.CarrierId.Value, "Carrier", "CarrierId");
                        if (string.IsNullOrEmpty(creditAccountId))
                        {
                            creditAccountId = AccountingChartHelper.AddCarrierToChart(invoiceVm.CarrierId.Value);
                        }
                    }
                    else if (invFor == 2) //Contractor
                    {
                        creditAccountId = AccountingChartHelper
                                          .GetAccountIdByPkAndTbName(invoiceVm.ContractorId.Value, "Contractor", "ContractorId");
                        if (string.IsNullOrEmpty(creditAccountId))
                        {
                            creditAccountId = AccountingChartHelper.AddContractorToChart(invoiceVm.ContractorId.Value);
                        }
                    }
                    else if (invFor == 3) //Custom Clearance
                    {
                        creditAccountId = AccountingChartHelper.GetCCCashDepAccountId(invoiceVm.OperationId);

                        if (!string.IsNullOrEmpty(creditAccountId))
                        {
                            invDb.InvStatusId = 4; //paid with cash deposit
                        }
                        else // In this case there was no cash deposit paid .. I added an account to sotre
                             //any credit amount for custom clearance
                        {
                            creditAccountId = ((int)AccountingChartEnum.CustomClearanceSupplier).ToString();
                        }
                    }

                    if (invoiceId == 0)
                    {
                        invDb.InvoiceCode = AdminHelper.GeneratePrefixCode(PrefixForEnum.APInvoice, true);
                        db.InvoiceAPs.Add(invDb);
                    }

                    db.SaveChanges();

                    invoiceVm.InvoiceId   = invDb.InvoiceId;
                    invoiceVm.InvoiceCode = invDb.InvoiceCode;

                    //Change HB status
                    if (invoiceId == 0)
                    {
                        //Add invoice to accounting transactions table
                        if (!string.IsNullOrEmpty(creditAccountId))
                        {
                            AddAPInvToTransTable(creditAccountId, invoiceVm);
                        }

                        //if (invFor == 3) //Custom Clearance
                        if (invFor == 3) //will link the cash out receipts with same currency to this invoice as it is paid
                        {
                            int     operId     = invoiceVm.OperationId;
                            int     savedInvId = invoiceVm.InvoiceId;
                            int     currId     = invoiceVm.InvCurrencyId;
                            decimal invAmount  = invoiceVm.InvoiceTotals.FirstOrDefault().TotalAmount;
                            //Get cashout receiptIds
                            var cashoutReceiptIds = db.CashOutReceipts.Include("CashOutReceiptInvs")
                                                    .Where(x => x.OperationId == operId && x.CurrencyId == currId)
                                                    .ToList();

                            CashOutReceiptInv cashOutReceiptInv;
                            decimal           prevPaidFromReceipt, receiptAmount, amountToPay = 0;

                            foreach (var item in cashoutReceiptIds)
                            {
                                receiptAmount = item.ReceiptAmount;

                                //Get what paid before by this receipt
                                prevPaidFromReceipt = item.CashOutReceiptInvs.Sum(x => x.PaidAmount);
                                amountToPay         = receiptAmount - prevPaidFromReceipt;
                                if (amountToPay <= 0) //This receipt total amount is used by another invoices
                                {
                                    continue;
                                }

                                if (invAmount <= 0) //This Invoice is total paid
                                {
                                    break;
                                }

                                if (amountToPay > invAmount)
                                {
                                    amountToPay = invAmount;
                                }

                                //Add cash out receipt invoice
                                cashOutReceiptInv            = new CashOutReceiptInv();
                                cashOutReceiptInv.ReceiptId  = item.ReceiptId;
                                cashOutReceiptInv.InvoiceId  = savedInvId;
                                cashOutReceiptInv.PaidAmount = amountToPay;

                                db.CashOutReceiptInvs.Add(cashOutReceiptInv);

                                invAmount = invAmount - amountToPay;
                            }

                            db.SaveChanges();
                        }
                        // HouseBillHelper.ChangeHBStatus(invDb.HouseBillId, (byte)StatusEnum.InvoiceIssued);
                        OperationHelper.ChangeOperationStatus(invDb.OperationId, (byte)StatusEnum.InvoiceIssued);
                    }

                    transaction.Complete();
                }
                catch (DbEntityValidationException e)
                {
                    isSaved = "false " + e.Message;

                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
                catch (Exception e)
                {
                    isSaved = "false " + e.Message;
                    //AdminHelper.LastIdRemoveOne(PrefixForEnum.AccountingInvoice);
                }
            }

            return(isSaved);
        }