Example #1
0
        public CashEntity GetCashByRefdateAndReftype(CashEntity obCashEntity)
        {
            const string procedures = @"uspGet_Cash_ForSalary";

            object[] parms = { "@RefTypeID", obCashEntity.RefTypeId, "@PostedDate", obCashEntity.PostedDate, "@RefNo", obCashEntity.RefNo };
            return(Db.Read(procedures, true, Make, parms));
        }
Example #2
0
        /// <summary>
        /// Deletes the cash entity.
        /// </summary>
        /// <param name="cash">The cash.</param>
        /// <returns></returns>
        public string DeleteCash(CashEntity cash)
        {
            const string procedures = @"uspDelete_Cash";

            object[] parms = { "@RefID", cash.RefId };
            return(Db.Delete(procedures, true, parms));
        }
Example #3
0
 /// <summary>
 /// Takes the specified take.
 /// </summary>
 /// <param name="take">The take.</param>
 /// <returns></returns>
 private object[] Take(CashEntity take)
 {
     return(new object[]
     {
         "@RefID", take.RefId,
         "@RefTypeID", take.RefTypeId,
         "@RefNo", take.RefNo,
         "@RefDate", take.RefDate,
         "@PostedDate", take.PostedDate,
         "@AccountingObjectID", take.AccountingObjectId,
         "@CustomerID", take.CustomerId,
         "@VendorID", take.VendorId,
         "@EmployeeID", take.EmployeeId,
         "@Trader", take.Trader,
         "@CurrencyCode", take.CurrencyCode,
         "@AccountNumber", take.AccountNumber,
         "@TotalAmount", take.TotalAmount,
         "@ExchangeRate", take.ExchangeRate,
         "@TotalAmountExchange", take.TotalAmountExchange,
         "@JournalMemo", take.JournalMemo,
         "@DocumentInclude", take.DocumentInclude,
         "@AccountingObjectType", take.AccountingObjectType,
         "@BankID", take.BankId,
         "@IsIncludeCharge", take.IsIncludeCharge
     });
 }
Example #4
0
        public SalaryVoucherResponse SetSalaryVouchers(SalaryVoucherRequest request)
        {
            var     response     = new SalaryVoucherResponse();
            string  currencyCode = "";
            decimal exchangeRate = 1;


            #region Ghi sổ

            if (request.LoadOptions.Contains("SaveSalaryVoucher"))
            {
                // Lấy voucherType là thực chi
                var voucherType = VoucherTypeDao.GetVoucherTypeByCode("SalaryVoucher") ?? new VoucherTypeEntity();
                // Lấy tất cả các loại khoản lương nhân viên
                List <EmployeeEntity> employees = EmployeeDao.GetEmployeesForSalaryInMonthAndRefNo(request.PostedDate, request.RefNo);

                var obj = SalaryVoucherDao.GetSalaryVoucherMonthDate(request.PostedDate).FirstOrDefault();
                if (obj != null)
                {
                    currencyCode = obj.CurrencyCode;
                    exchangeRate = obj.ExchangeRate;
                }

                //string[] words = request.PostedDate.Split('/');//Chuyển lại ngày tháng cho hợp lý trên C# # SQL
                DateTime postedDate = Convert.ToDateTime(request.PostedDate);

                var depositEntity = new DepositEntity()
                {
                    RefId                = 0,
                    RefTypeId            = request.ReftypeId, //
                    RefDate              = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    RefNo                = request.RefNo,
                    PostedDate           = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    AccountingObjectType = 1,
                    AccountingObjectId   = null,
                    Trader               = "",
                    CustomerId           = null,
                    VendorId             = null,
                    EmployeeId           = null, // mapper.EmployeeId,
                    BankAccountCode      = "112",
                    CurrencyCode         = currencyCode,
                    ExchangeRate         = exchangeRate,
                    TotalAmountOc        = 0, // employeePayItem.Amount,
                    TotalAmountExchange  = 0, // employeePayItem.Amount,
                    JournalMemo          =
                        "Chứng từ lương tháng " + postedDate.Month + "/" + postedDate.Year,
                };
                depositEntity.DepositDetails = new List <DepositDetailEntity>();
                var cashEntity = new CashEntity
                {
                    RefId               = 0,
                    RefTypeId           = request.ReftypeId, //
                    RefNo               = request.RefNo,
                    RefDate             = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    PostedDate          = postedDate,        //DateTime.Parse(words[1] + "/" + words[0] + "/" + words[2]),
                    AccountingObjectId  = null,
                    CustomerId          = null,
                    VendorId            = null,
                    Trader              = "",
                    CurrencyCode        = currencyCode,
                    ExchangeRate        = exchangeRate,
                    TotalAmount         = 0,
                    TotalAmountExchange = 0,
                    AccountNumber       = "",
                    JournalMemo         =
                        "Chứng từ lương tháng " + postedDate.Month + "/" + postedDate.Year,
                    DocumentInclude      = "",
                    AccountingObjectType = 1,
                    EmployeeId           = null,
                };
                cashEntity.CashDetails = new List <CashDetailEntity>();

                foreach (var employee in employees)
                {
                    //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                    IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeeForViewtEmployeePayItem(employee.EmployeeId, postedDate, exchangeRate);
                    foreach (var employeePayItemEntity in listPayItems)
                    {
                        var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                        //Chi
                        if (payItems != null && (payItems.CreditAccountCode ?? "").StartsWith("111"))
                        {
                            // khởi tạo phieu chi chi tiết
                            CashDetailEntity cashDetailEntity = new CashDetailEntity()
                            {
                                RefDetailId   = 0,
                                RefId         = 0,
                                AccountNumber = payItems.DebitAccountCode,
                                CorrespondingAccountNumber = payItems.CreditAccountCode,
                                Description        = payItems.PayItemName + " tháng " + postedDate.Month + "/" + postedDate.Year,
                                AmountOc           = employeePayItemEntity.Amount,
                                AmountExchange     = employeePayItemEntity.AmountExchange,
                                VoucherTypeId      = null, //voucherType.VoucherTypeId,
                                BudgetSourceCode   = payItems.BudgetSourceCode,
                                BudgetItemCode     = payItems.BudgetItemCode,
                                AccountingObjectId = null,
                                // dùng tạm MergerFundId để lưu payitemid
                                MergerFundId = payItems.PayItemId
                            };
                            bool flag = false;
                            for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                            {
                                if (cashEntity.CashDetails[i].MergerFundId == cashDetailEntity.MergerFundId && cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber && cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber && cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode && cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                {
                                    cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                    cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                    flag = true;
                                }
                            }
                            if (flag == false)
                            {
                                if (cashDetailEntity.AmountOc > 0)
                                {
                                    cashEntity.CashDetails.Add(cashDetailEntity);
                                }
                            }
                            //Tính lại TotalAmountOc - TotalAmountExchange
                            cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                            cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                            //Get Bank Acount
                            cashEntity.AccountNumber = payItems.CreditAccountCode;
                        }
                        //Nợ
                        if (payItems != null && (payItems.CreditAccountCode ?? "").StartsWith("112"))
                        {
                            DepositDetailEntity depositDetailEntity = new DepositDetailEntity()
                            {
                                RefDetailId = request.ReftypeId,
                                RefId       = 0,
                                Description = payItems.PayItemName + " tháng " + postedDate.Month + "/" + postedDate.Year,

                                AccountNumber = payItems.DebitAccountCode,
                                CorrespondingAccountNumber = payItems.CreditAccountCode,
                                AmountOc           = employeePayItemEntity.Amount,
                                AmountExchange     = employeePayItemEntity.AmountExchange,
                                VoucherTypeId      = null, //voucherType.VoucherTypeId,
                                BudgetSourceCode   = payItems.BudgetSourceCode,
                                AccountingObjectId = null,
                                BudgetItemCode     = payItems.BudgetItemCode,
                                // dùng tạm MergerFundId để lưu payitemid
                                MergerFundId = payItems.PayItemId
                            };
                            bool flag = false;
                            for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                            {
                                // old
                                //if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                //{
                                //    depositEntity.DepositDetails[i].AmountOc = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                //    depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                //    flag = true;
                                //}

                                if (depositEntity.DepositDetails[i].MergerFundId == depositDetailEntity.MergerFundId && depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                {
                                    depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                    depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                    flag = true;
                                }
                            }
                            if (flag == false)
                            {
                                if (depositDetailEntity.AmountOc > 0)
                                {
                                    depositEntity.DepositDetails.Add(depositDetailEntity);
                                }
                            }
                            //Tính lại TotalAmountOc - TotalAmountExchange
                            depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                            depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange + depositDetailEntity.AmountExchange;
                            //Get bank Acount
                            depositEntity.BankAccountCode = payItems.CreditAccountCode;
                        }
                    }
                }

                // xóa MergerFundId đi không thì lưu nó lỗi á
                cashEntity.CashDetails.Select(c => { c.MergerFundId = null; return(c); }).ToList();
                depositEntity.DepositDetails.Select(c => { c.MergerFundId = null; return(c); }).ToList();

                long?cashId    = null;
                long?depositId = null;
                //Insert chứng từ phiếu chi
                var cashRequest = new CashRequest();
                var oCashFacade = new CashFacade();
                cashRequest.Action     = PersistType.Insert;
                cashRequest.CashEntity = cashEntity;
                // sinh định khoản đồng thời
                cashRequest.isAutoGenerateParallel = true;
                if (cashRequest.CashEntity.TotalAmount > 0)
                {
                    var cashResponse = oCashFacade.SetCashes(cashRequest);
                    cashId = cashResponse.RefId;
                }

                //Insert chứng từ giấy báo nợ
                var depositRequest = new DepositRequest();
                var oDepositFacade = new DepositFacade();
                depositRequest.Action  = PersistType.Insert;
                depositRequest.Deposit = depositEntity;
                if (depositRequest.Deposit.TotalAmountOc > 0)
                {
                    var depositRespone = oDepositFacade.SetDeposits(depositRequest, true);
                    depositId = depositRespone.RefId;
                }

                // update id phiếu chi, thu tiền gửi vào bảng
                string updateEmployeePayroll = SalaryVoucherDao.Update_EmployeePayroll_Voucher(request.RefNo, cashId, depositId);
            }


            #endregion

            #region Hủy tính ghi sổ + tính lương

            if (request.LoadOptions.Contains("CancelSalaryVoucher"))
            {
                var obj = SalaryVoucherDao.GetSalaryVoucherMonthDateIsPostedDate(request.PostedDate).FirstOrDefault();
                if (obj != null)
                {
                    currencyCode = obj.CurrencyCode;
                }



                var cashRequest = new CashRequest();
                var oCashFacade = new CashFacade();
                cashRequest.Action     = PersistType.Delete;
                cashRequest.CashEntity = CashDao.GetCash(SalaryVoucherDao.GetEmployeePayroll_VoucherID(request.RefNo, 201)); //CashDao.GetCashBySalary(request.ReftypeId, request.PostedDate, request.RefNo, currencyCode);

                var depositRequest = new DepositRequest();
                var oDepositFacade = new DepositFacade();
                depositRequest.Action  = PersistType.Delete;
                depositRequest.Deposit = DepositDao.GetDeposit(SalaryVoucherDao.GetEmployeePayroll_VoucherID(request.RefNo, 301)); //DepositDao.GetDepositsBySalary(request.ReftypeId, request.PostedDate, request.RefNo, currencyCode);

                //Xóa chứng từ lương ở phiểu chi
                if (cashRequest.CashEntity != null)
                {
                    cashRequest.RefId = cashRequest.CashEntity.RefId;
                    cashRequest.CashEntity.CashDetails = CashDetailDao.GetCashDetailsByCash(cashRequest.CashEntity.RefId);
                    if (cashRequest.CashEntity.CashDetails != null)
                    {
                        oCashFacade.SetCashes(cashRequest);
                        response.Message = CashDao.DeleteEmployeePayroll(cashRequest.CashEntity.RefNo,
                                                                         cashRequest.CashEntity.PostedDate.Month + "/" + cashRequest.CashEntity.PostedDate.Day + "/" + cashRequest.CashEntity.PostedDate.Year);
                    }
                }

                //Xóa chứng từ lương ở giấy báo nợ
                if (depositRequest.Deposit != null)
                {
                    depositRequest.RefId = depositRequest.Deposit.RefId;
                    depositRequest.Deposit.DepositDetails = DepositDetailDao.GetDepositDetailsByDeposit(depositRequest.Deposit.RefId);
                    if (depositRequest.Deposit.DepositDetails != null)
                    {
                        oDepositFacade.SetDeposits(depositRequest);
                        response.Message = DepositDao.DeleteEmployeePayroll(depositRequest.Deposit.RefNo,
                                                                            depositRequest.Deposit.PostedDate.Value.Month + "/" + depositRequest.Deposit.PostedDate.Value.Day + "/" + depositRequest.Deposit.PostedDate.Value.Year);
                    }
                }
            }

            #endregion

            #region  Hủy tính lương

            if (request.LoadOptions.Contains("CancelCalc"))
            {
                response.Message = SalaryVoucherDao.CanclCalc(request.PostedDate, request.RefNo);
            }

            #endregion

            return(response);
        }
Example #5
0
        /// <summary>
        /// Updates the cash entity.
        /// </summary>
        /// <param name="cash">The cash.</param>
        /// <returns></returns>
        public string UpdateCash(CashEntity cash)
        {
            const string procedures = @"uspUpdate_Cash";

            return(Db.Update(procedures, true, Take(cash)));
        }
Example #6
0
        /// <summary>
        /// Inserts the cash.
        /// </summary>
        /// <param name="cash">The cash.</param>
        /// <returns></returns>
        public int InsertCash(CashEntity cash)
        {
            const string procedures = @"uspInsert_Cash";

            return(Db.Insert(procedures, true, Take(cash)));
        }
Example #7
0
 public static void entityUpdate(Entity entity, CashEntity cashEntity)
 {
     var _esc = new EntityServiceClient();
     _esc.SaveEntity2(entity, cashEntity);
 }
Example #8
0
 public static void entityInsert(Entity entity, CashEntity cashEntity)
 {
     var _esc = new EntityServiceClient();
     _esc.NewEntity2(entity, cashEntity);
 }
        /// <summary>
        /// Set the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>SalaryResponse.</returns>
        public SalaryResponse SetSalaries(SalaryRequest request)
        {
            var response           = new SalaryResponse();
            var obJourentryAccount = new JournalEntryAccountEntity();
            IList <JournalEntryAccountEntity> listJournalEntryAccountEntity = new List <JournalEntryAccountEntity>();
            IList <AccountBalanceEntity>      listAccountBalanceEntity      = new List <AccountBalanceEntity>();
            var mapper = request.Salary;

            if (request.Action != PersistType.Delete)
            {
                if (!mapper.Validate())
                {
                    foreach (string error in mapper.ValidationErrors)
                    {
                        response.Message += error + Environment.NewLine;
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
            }
            try
            {
                if (request.LoadOptions.Contains("CalSalary"))
                {
                    var lstDeposit = SalaryDao.GetSalaryByRefNo(mapper.RefNo);
                    if (lstDeposit.Count > 0)
                    {
                        response.Message     = "Đã tồn tại số chứng từ " + mapper.RefNo + " !";
                        response.Acknowledge = AcknowledgeType.Failure;
                        return(response);
                    }
                    foreach (var employees in mapper.Employees)
                    {
                        mapper.EmployeeId = employees.EmployeeId;
                        response.SalaryId = SalaryDao.CalSalary(mapper);
                    }
                    var autoNumber = AutoNumberDao.GetAutoNumberByRefType(600);
                    //------------------------------------------------------------------
                    //LinhMC 29/11/2014
                    //Lưu giá trị số tự động tăng theo loại tiền
                    //---------------------------------------------------------------
                    if (request.Salary.CurrencyCode == "USD")
                    {
                        autoNumber.Value += 1;
                    }
                    else
                    {
                        autoNumber.ValueLocalCurency += 1;
                    }


                    response.Message = AutoNumberDao.UpdateAutoNumber(autoNumber);
                }

                if (request.LoadOptions.Contains("SavePostedSalary"))
                {
                    /* Danh sách các khoản lương
                     * Nhân viên liên kết Danh sách các khoản lương
                     * Lưu Chứng từ lương:  Nhân viên lấy từ lấy các khoản lương theo nhân viên==> tổng số tiền lương
                     * ==> Đồng thời lưu vào chứng từ Phiếu chi hoặc Giấy báo Nợ đặt mặc định RefType=600 vs Số chứng từ (RefNo) và ngày chứng từ lương
                     * ==> Khi lưu chứng từ Phiếu Chi hoặc Giấy báo Có được lưu dựa trên cách lưu của Phiếu Chi hoặc Giấy Báo Có
                     * ==> Để xác định chứng từ là Phiếu Chi hay Giấy báo Nợ phải dựa báo TK có trên Danh mục khoản lương
                     */
                    var depositEntity = new DepositEntity()
                    {
                        RefId                = 0,
                        RefTypeId            = mapper.RefTypeId,//
                        RefDate              = mapper.RefDate,
                        RefNo                = mapper.RefNo,
                        PostedDate           = mapper.PostedDate,
                        AccountingObjectType = 0,
                        AccountingObjectId   = null,
                        Trader               = "",
                        CustomerId           = null,
                        VendorId             = null,
                        EmployeeId           = null,// mapper.EmployeeId,
                        BankAccountCode      = "112",
                        CurrencyCode         = mapper.CurrencyCode,
                        ExchangeRate         = mapper.ExchangeRate,
                        TotalAmountOc        = 0, // employeePayItem.Amount,
                        TotalAmountExchange  = 0, // employeePayItem.Amount,
                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                    };
                    depositEntity.DepositDetails = new List <DepositDetailEntity>();
                    var cashEntity = new CashEntity
                    {
                        RefId              = 0,
                        RefTypeId          = mapper.RefTypeId,//
                        RefNo              = mapper.RefNo,
                        RefDate            = mapper.RefDate,
                        PostedDate         = mapper.PostedDate,
                        AccountingObjectId = null,
                        CustomerId         = null,
                        VendorId           = null,
                        Trader             = "",
                        CurrencyCode       = mapper.CurrencyCode,
                        ExchangeRate       = mapper.ExchangeRate,

                        TotalAmount         = 0,
                        TotalAmountExchange = 0,
                        AccountNumber       = "",

                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                        DocumentInclude      = "",
                        AccountingObjectType = 2,
                        //     CashDetails = cashDetails;
                        EmployeeId = null,
                    };
                    cashEntity.CashDetails = new List <CashDetailEntity>();

                    // var lstDeposit = SalaryDao.GetSalaryByRefNo(mapper.RefNo);
                    //if (lstDeposit.Count > 0)
                    //{
                    //    response.Message = "Đã tồn tại số chứng từ " + mapper.RefNo + " !";
                    //    response.Acknowledge = AcknowledgeType.Failure;
                    //    return response;
                    //}
                    //  var Cash
                    mapper.Employees = EmployeeDao.GetEmployeesForSalary(mapper.RefDate, mapper.RefNo);
                    foreach (var employee in mapper.Employees)
                    {
                        //Tính lại lương cho nhân viên trước khi ghi sổ
                        mapper.EmployeeId = employee.EmployeeId;
                        response.SalaryId = SalaryDao.CalSalary(mapper);

                        //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                        IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeeForViewtEmployeePayItem(employee.EmployeeId, mapper.RefDate, mapper.ExchangeRate);
                        // mapper.EmployeePayItemId = EmployeePayItemDao.GetEmployeePayItemsByEmployeeId(employee.EmployeeId);
                        foreach (var employeePayItemEntity in listPayItems)
                        {
                            mapper.EmployeePayItemId = employeePayItemEntity.EmployeePayItemId;
                            var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                            //Chi
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("111"))
                            {
                                // khởi tạo phieu chi chi tiết
                                CashDetailEntity cashDetailEntity = new CashDetailEntity()
                                {
                                    RefDetailId   = 0,
                                    RefId         = 0,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    Description        = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AmountOc           = employeePayItemEntity.Amount * mapper.ExchangeRate,
                                    AmountExchange     = employeePayItemEntity.Amount,
                                    VoucherTypeId      = null,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    AccountingObjectId = null,
                                    MergerFundId       = null
                                };
                                bool flag = false;
                                for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                                {
                                    if (cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber && cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber && cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode && cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                    {
                                        cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                        cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                        flag = true;
                                    }
                                }
                                if (flag == false)
                                {
                                    if (cashDetailEntity.AmountOc > 0)
                                    {
                                        cashEntity.CashDetails.Add(cashDetailEntity);
                                    }
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                                cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                                //Get Bank Acount
                                cashEntity.AccountNumber = payItems.CreditAccountCode;
                            }
                            //Nợ
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("112") == true)
                            {
                                DepositDetailEntity depositDetailEntity = new DepositDetailEntity()
                                {
                                    RefDetailId   = mapper.RefTypeId,
                                    RefId         = 0,
                                    Description   = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    AmountOc           = employeePayItemEntity.Amount * mapper.ExchangeRate,
                                    AmountExchange     = employeePayItemEntity.Amount,
                                    VoucherTypeId      = 1,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    AccountingObjectId = null,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    //DepartmentId = mapper.DepartmentId,
                                    MergerFundId = null
                                };
                                bool flag = false;
                                for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                                {
                                    if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber && depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode && depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                    {
                                        depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                        depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                        flag = true;
                                    }
                                }
                                if (flag == false)
                                {
                                    if (depositDetailEntity.AmountOc > 0)
                                    {
                                        depositEntity.DepositDetails.Add(depositDetailEntity);
                                    }
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                                depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange + depositDetailEntity.AmountExchange;
                                //Get bank Acount
                                depositEntity.BankAccountCode = payItems.CreditAccountCode;
                            }
                        }
                    }
                    var autoNumber = AutoNumberDao.GetAutoNumberByRefType(600);
                    //------------------------------------------------------------------
                    //LinhMC 29/11/2014
                    //Lưu giá trị số tự động tăng theo loại tiền
                    //---------------------------------------------------------------
                    if (request.Salary.CurrencyCode == "USD")
                    {
                        autoNumber.Value += 1;
                    }
                    else
                    {
                        autoNumber.ValueLocalCurency += 1;
                    }

                    response.Message = AutoNumberDao.UpdateAutoNumber(autoNumber);
                    // insert or update giấy báo nợ

                    {
                        var checkDepositEntity = DepositDao.GetDepositByRefdateAndReftype(depositEntity);
                        if (checkDepositEntity == null)
                        {
                            if (depositEntity.DepositDetails.Count > 0)
                            {
                                var depositRequest = new DepositRequest();
                                var oDepositFacade = new DepositFacade();
                                depositRequest.Action  = PersistType.Insert;
                                depositRequest.Deposit = depositEntity;
                                oDepositFacade.SetDeposits(depositRequest);
                            }
                        }
                        //Sẽ không còn trường hợp này nữa
                        //else
                        //{
                        //    //Update CheckDepositEntity with amuont depositEntity,..
                        //    checkDepositEntity.DepositDetails = new List<DepositDetailEntity>();
                        //    checkDepositEntity.RefDate = depositEntity.RefDate;
                        //    checkDepositEntity.RefNo = depositEntity.RefNo;
                        //    checkDepositEntity.ExchangeRate = depositEntity.ExchangeRate;
                        //    checkDepositEntity.CurrencyCode = depositEntity.CurrencyCode;
                        //    checkDepositEntity.ExchangeRate = depositEntity.ExchangeRate;
                        //    checkDepositEntity.TotalAmountOc = depositEntity.TotalAmountOc;
                        //    checkDepositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange;
                        //    checkDepositEntity.BankAccountCode = depositEntity.BankAccountCode;
                        //    //Thêm các details mới+
                        //    foreach (var depositDetail in depositEntity.DepositDetails)
                        //    {
                        //        if (!depositDetail.Validate())
                        //        {
                        //            foreach (string error in depositDetail.ValidationErrors)
                        //                response.Message += error + Environment.NewLine;
                        //            response.Acknowledge = AcknowledgeType.Failure;
                        //            return response;
                        //        }
                        //        depositDetail.RefId = checkDepositEntity.RefId;
                        //        checkDepositEntity.DepositDetails.Add(depositDetail);
                        //    }
                        //    var depositRequest = new DepositRequest();
                        //    var oDepositFacade = new DepositFacade();
                        //    depositRequest.Action = PersistType.Update;
                        //    depositRequest.Deposit = checkDepositEntity;
                        //    oDepositFacade.SetDeposits(depositRequest);
                        //}
                    }
                    // Insert phieu chi
                    //if (cashEntity.CashDetails.Count > 0)
                    //{
                    var checkCashEntity = CashDao.GetCashByRefdateAndReftype(cashEntity);
                    if (checkCashEntity == null)
                    {
                        if (cashEntity.CashDetails.Count > 0)
                        {
                            var cashRequest = new CashRequest();
                            var oCashFacade = new CashFacade();
                            cashRequest.Action     = PersistType.Insert;
                            cashRequest.CashEntity = cashEntity;
                            oCashFacade.SetCashes(cashRequest);
                        }
                    }
                    //Sẽ không có trường hợp này nữa
                    //else
                    //{
                    //    //Update
                    //    checkCashEntity.CashDetails = new List<CashDetailEntity>();
                    //    checkCashEntity.RefDate = cashEntity.RefDate;
                    //    checkCashEntity.RefNo = cashEntity.RefNo;
                    //    checkCashEntity.ExchangeRate = cashEntity.ExchangeRate;
                    //    checkCashEntity.CurrencyCode = cashEntity.CurrencyCode;
                    //    checkCashEntity.ExchangeRate = cashEntity.ExchangeRate;
                    //    checkCashEntity.TotalAmount = cashEntity.TotalAmount;
                    //    checkCashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange;
                    //    checkCashEntity.AccountNumber = cashEntity.AccountNumber;
                    //    //Thêm các details mới+
                    //    foreach (var cashDetail in cashEntity.CashDetails)
                    //    {
                    //        if (!cashDetail.Validate())
                    //        {
                    //            foreach (string error in cashDetail.ValidationErrors)
                    //                response.Message += error + Environment.NewLine;
                    //            response.Acknowledge = AcknowledgeType.Failure;
                    //            return response;
                    //        }
                    //        cashDetail.RefId = checkCashEntity.RefId;
                    //        checkCashEntity.CashDetails.Add(cashDetail);
                    //    }
                    //    var cashRequest = new CashRequest();
                    //    var oCashFacade = new CashFacade();
                    //    cashRequest.Action = PersistType.Update;
                    //    cashRequest.CashEntity = checkCashEntity;
                    //    oCashFacade.SetCashes(cashRequest);
                    //}
                }

                if (request.LoadOptions.Contains("CheckCalSalaryState"))
                {
                    var salaries = SalaryDao.GetSalaryByRefDateAndEmployId(mapper.RefDate, mapper.EmployeeId);
                    if (salaries.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Success;
                        response.Message     = @"Nhân viên đã được tính lương !";
                        response.Salary      = salaries[0];
                        return(response);
                    }
                    response.Message = null;
                }

                if (request.LoadOptions.Contains("CheckCalSalaryPostedState"))
                {
                    var salaries = SalaryDao.GetSalaryPostedByRefDateAndEmployId(mapper.RefDate, mapper.EmployeeId);
                    if (salaries.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Success;
                        response.Message     = @"Nhân viên đã được tính lương !";
                        response.Salary      = salaries[0];
                        return(response);
                    }
                    response.Message = null;
                }

                if (request.LoadOptions.Contains("DeleteCalSalary"))
                {
                    //foreach (var employee in mapper.Employees)
                    //{
                    //    mapper.EmployeeId = employee.EmployeeId;
                    //    response.SalaryId = SalaryDao.DeleteCalSalary(mapper);
                    //}

                    var depositEntity = new DepositEntity()
                    {
                        RefId                = 0,
                        RefTypeId            = mapper.RefTypeId,//
                        RefDate              = mapper.RefDate,
                        RefNo                = mapper.RefNo,
                        PostedDate           = mapper.PostedDate,
                        AccountingObjectType = 0,
                        AccountingObjectId   = null,
                        Trader               = "",
                        CustomerId           = null,
                        VendorId             = null,
                        EmployeeId           = null,// mapper.EmployeeId,
                        BankAccountCode      = "112",
                        CurrencyCode         = mapper.CurrencyCode,
                        ExchangeRate         = mapper.ExchangeRate,
                        TotalAmountOc        = 0, // employeePayItem.Amount,
                        TotalAmountExchange  = 0, // employeePayItem.Amount,
                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                    };
                    depositEntity.DepositDetails = new List <DepositDetailEntity>();
                    var cashEntity = new CashEntity()
                    {
                        RefId              = 0,
                        RefTypeId          = mapper.RefTypeId,//
                        RefNo              = mapper.RefNo,
                        RefDate            = mapper.RefDate,
                        PostedDate         = mapper.PostedDate,
                        AccountingObjectId = null,
                        CustomerId         = null,
                        VendorId           = null,
                        Trader             = "",
                        CurrencyCode       = mapper.CurrencyCode,
                        ExchangeRate       = mapper.ExchangeRate,

                        TotalAmount         = 0,
                        TotalAmountExchange = 0,
                        AccountNumber       = "",

                        JournalMemo          = "Chứng từ lương tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                        DocumentInclude      = "",
                        AccountingObjectType = 2,
                        //     CashDetails = cashDetails;
                        EmployeeId = null,
                    };
                    cashEntity.CashDetails = new List <CashDetailEntity>();

                    //  var Cash
                    foreach (var employee in mapper.Employees)
                    {
                        //Xóa EmployeePayroll
                        mapper.EmployeeId = employee.EmployeeId;
                        response.SalaryId = SalaryDao.DeleteCalSalary(mapper);
                        //End Xóa EmployeePayroll
                        //Từng nhân viên - từng khoảng lương - tiền tương ứng.
                        IList <EmployeePayItemEntity> listPayItems = EmployeePayItemDao.GetEmployeePayItemsByEmployeeId(employee.EmployeeId);
                        foreach (var employeePayItemEntity in listPayItems)
                        {
                            mapper.EmployeePayItemId = employeePayItemEntity.EmployeePayItemId;
                            var payItems = PayItemDao.GetPayItem(employeePayItemEntity.PayItemId);
                            //Chi
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("111"))
                            {
                                // khởi tạo phieu chi chi tiết
                                var cashDetailEntity = new CashDetailEntity()
                                {
                                    RefDetailId   = 0,
                                    RefId         = 0,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    Description        = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AmountOc           = employeePayItemEntity.Amount,
                                    AmountExchange     = employeePayItemEntity.Amount / mapper.ExchangeRate,
                                    VoucherTypeId      = null,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    AccountingObjectId = null,
                                    MergerFundId       = null
                                };
                                bool flag = false;
                                for (int i = 0; i < cashEntity.CashDetails.Count; i++)
                                {
                                    if (cashEntity.CashDetails[i].CorrespondingAccountNumber == cashDetailEntity.CorrespondingAccountNumber &&
                                        cashEntity.CashDetails[i].AccountNumber == cashDetailEntity.AccountNumber &&
                                        cashEntity.CashDetails[i].BudgetItemCode == cashDetailEntity.BudgetItemCode &&
                                        cashEntity.CashDetails[i].BudgetSourceCode == cashDetailEntity.BudgetSourceCode)
                                    {
                                        cashEntity.CashDetails[i].AmountOc       = cashEntity.CashDetails[i].AmountOc + cashDetailEntity.AmountOc;
                                        cashEntity.CashDetails[i].AmountExchange = cashEntity.CashDetails[i].AmountExchange + cashDetailEntity.AmountExchange;
                                        flag = true;
                                        //   break;
                                    }
                                }

                                if (flag == false)
                                {
                                    cashEntity.CashDetails.Add(cashDetailEntity);
                                }

                                //Tính lại TotalAmountOc - TotalAmountExchange
                                cashEntity.TotalAmount         = cashEntity.TotalAmount + cashDetailEntity.AmountOc;
                                cashEntity.TotalAmountExchange = cashEntity.TotalAmountExchange + cashDetailEntity.AmountExchange;
                                //Get Bank Acount
                                cashEntity.AccountNumber = payItems.CreditAccountCode;
                            }
                            //Nợ
                            if (payItems.CreditAccountCode.Substring(0, 3).Contains("112"))
                            {
                                var depositDetailEntity = new DepositDetailEntity()
                                {
                                    RefDetailId   = mapper.RefTypeId,
                                    RefId         = 0,
                                    Description   = payItems.PayItemName + " tháng " + mapper.RefDate.Month + "/" + mapper.RefDate.Year,
                                    AccountNumber = payItems.DebitAccountCode,
                                    CorrespondingAccountNumber = payItems.CreditAccountCode,
                                    AmountOc           = employeePayItemEntity.Amount,
                                    AmountExchange     = employeePayItemEntity.Amount / mapper.ExchangeRate,
                                    VoucherTypeId      = 1,
                                    BudgetSourceCode   = payItems.BudgetSourceCode,
                                    AccountingObjectId = null,
                                    BudgetItemCode     = payItems.BudgetItemCode,
                                    //    DepartmentId = mapper.DepartmentId,
                                    MergerFundId = null
                                };
                                bool flag = false;
                                for (int i = 0; i < depositEntity.DepositDetails.Count; i++)
                                {
                                    if (depositEntity.DepositDetails[i].CorrespondingAccountNumber == depositDetailEntity.CorrespondingAccountNumber &&
                                        depositEntity.DepositDetails[i].BudgetItemCode == depositDetailEntity.BudgetItemCode &&
                                        depositEntity.DepositDetails[i].BudgetSourceCode == depositDetailEntity.BudgetSourceCode)
                                    {
                                        depositEntity.DepositDetails[i].AmountOc       = depositEntity.DepositDetails[i].AmountOc + depositDetailEntity.AmountOc;
                                        depositEntity.DepositDetails[i].AmountExchange = depositEntity.DepositDetails[i].AmountExchange + depositDetailEntity.AmountExchange;
                                        flag = true;
                                        //  break;
                                    }
                                }

                                if (flag == false)
                                {
                                    depositEntity.DepositDetails.Add(depositDetailEntity);
                                }
                                //Tính lại TotalAmountOc - TotalAmountExchange
                                depositEntity.TotalAmountOc       = depositEntity.TotalAmountOc + depositDetailEntity.AmountOc;
                                depositEntity.TotalAmountExchange = depositEntity.TotalAmountExchange +
                                                                    depositDetailEntity.AmountExchange;
                                //Get bank Acount
                                depositEntity.BankAccountCode = payItems.CreditAccountCode;
                            }
                        }
                    }
                    var cashRequest = new CashRequest();
                    var oCashFacade = new CashFacade();
                    cashRequest.Action = PersistType.Delete;
                    var cashForDelete = CashDao.GetCashByRefdateAndReftype(cashEntity);
                    if (cashForDelete != null)
                    {
                        cashRequest.RefId     = cashForDelete.RefId;
                        cashRequest.RefTypeId = cashForDelete.RefTypeId;
                        //    cashRequest.CashEntity = cashEntity;
                        oCashFacade.SetCashes(cashRequest);
                    }

                    var depositRequest = new DepositRequest();
                    var oDepositFacade = new DepositFacade();
                    depositRequest.Action = PersistType.Delete;
                    var depositForDelete = DepositDao.GetDepositByRefdateAndReftype(depositEntity);
                    if (depositForDelete != null)
                    {
                        depositRequest.RefId   = depositForDelete.RefId;
                        depositRequest.RefType = depositForDelete.RefTypeId;
                        //    depositRequest.Deposit = depositEntity;
                        oDepositFacade.SetDeposits(depositRequest);
                    }
                }
            }
            catch (Exception ex)
            {
                response.Acknowledge = AcknowledgeType.Failure;
                response.Message     = ex.Message;
                return(response);
            }
            response.Acknowledge = response.Message != null ? AcknowledgeType.Failure : AcknowledgeType.Success;
            return(response);
        }
        public CashEntityCollection QueryCashEntity()
        {
            //TODO
            CashEntityCollection collection = new CashEntityCollection();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {

                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText = "SP_SEL_Table";
                SqlParameter _param = command.Parameters.Add("@value1", System.Data.SqlDbType.VarChar);
                _param.Value = "Entity_Cash";
                SqlParameter _param2 = command.Parameters.Add("@value2", System.Data.SqlDbType.VarChar);
                _param2.Value = "";
                SqlParameter _param3 = command.Parameters.Add("@value3", System.Data.SqlDbType.VarChar);
                _param3.Value = "";
                SqlParameter _param4 = command.Parameters.Add("@order_by1", System.Data.SqlDbType.VarChar);
                _param4.Value = "1";
                SqlParameter _param5 = command.Parameters.Add("@order_by2", System.Data.SqlDbType.TinyInt);
                _param5.Value = 0;
                command.CommandType = System.Data.CommandType.StoredProcedure;
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        CashEntity _entity = new CashEntity();
                        _entity.EntityID = Convert.ToInt32(reader["Entity_ID"]);
                        _entity.ContractNumber = reader["Contract_Number"].ToString();
                        _entity.TallyName = reader["Tally_Name"].ToString();
                        _entity.TallyNumber = reader["Tally_Number"].ToString();
                        _entity.SettlementName = reader["Settlement_Name"].ToString();
                        _entity.SettlementNumber= reader["Settlement_Number"].ToString();
                        _entity.RecommendedBy = reader["Recommended_By"].ToString();
                        _entity.Skype = reader["Skype"].ToString();
                        _entity.QQ = reader["QQ"].ToString();
                        _entity.Email = reader["Email"].ToString();
                        _entity.CreditLimit = Convert.ToDecimal(reader["Credit_Limit"]);
                        collection.Add(_entity);
                    }
                }
                reader.Close();
                return collection;
            }
        }
 /// <summary>
 /// New Cash Entity
 /// </summary>     
 public void Insert(Entity entity, CashEntity cashEntity)
 {
     //OK
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         SqlCommand command = new SqlCommand();
         command.Connection = connection;
         command.CommandText = "SP_INS_Entity_Cash";
         SqlParameter _param1 = command.Parameters.Add("@ParentID", System.Data.SqlDbType.Int);
         _param1.Value = entity.ParentID;
         SqlParameter _param2 = command.Parameters.Add("@Entity_Name", System.Data.SqlDbType.VarChar);
         _param2.Value = entity.EntityName;
         SqlParameter _param3 = command.Parameters.Add("@SumType", System.Data.SqlDbType.Int);
         _param3.Value = (int)entity.SumType;
         SqlParameter _param4 = command.Parameters.Add("@Entity_Type", System.Data.SqlDbType.Int);
         _param4.Value = (int)entity.EntityType;
         SqlParameter _param5 = command.Parameters.Add("@Currency", System.Data.SqlDbType.VarChar);
         _param5.Value = entity.Currency.CurrencyID;
         SqlParameter _param6 = command.Parameters.Add("@Exchange_Rate", System.Data.SqlDbType.Decimal);
         _param6.Value = entity.ExchangeRate;
         SqlParameter _param7 = command.Parameters.Add("@IsAccount", System.Data.SqlDbType.TinyInt);
         _param7.Value = entity.IsAccount;
         //SqlParameter _param8 = command.Parameters.Add("@Enable", System.Data.SqlDbType.TinyInt);
         //_param8.Value = entity.Enable;
         SqlParameter _param9 = command.Parameters.Add("@IsLastLevel", System.Data.SqlDbType.TinyInt);
         _param9.Value = entity.IsLastLevel;
         //Cash Entity Attribute
         SqlParameter _cashparam1 = command.Parameters.Add("@Contract_Number", System.Data.SqlDbType.VarChar);
         _cashparam1.Value = cashEntity.ContractNumber;
         SqlParameter _cashparam2 = command.Parameters.Add("@Tally_Name", System.Data.SqlDbType.VarChar);
         _cashparam2.Value = cashEntity.TallyName;
         SqlParameter _cashparam3 = command.Parameters.Add("@Tally_Number", System.Data.SqlDbType.VarChar);
         _cashparam3.Value = cashEntity.TallyNumber;
         SqlParameter _cashparam4 = command.Parameters.Add("@Settlement_Name", System.Data.SqlDbType.VarChar);
         _cashparam4.Value = cashEntity.SettlementName;
         SqlParameter _cashparam5 = command.Parameters.Add("@Settlement_Number", System.Data.SqlDbType.VarChar);
         _cashparam5.Value = cashEntity.SettlementNumber;
         SqlParameter _cashparam6 = command.Parameters.Add("@Recommended_By", System.Data.SqlDbType.VarChar);
         _cashparam6.Value = cashEntity.RecommendedBy;
         SqlParameter _cashparam7 = command.Parameters.Add("@Skype", System.Data.SqlDbType.VarChar);
         _cashparam7.Value = cashEntity.Skype;
         SqlParameter _cashparam8 = command.Parameters.Add("@QQ", System.Data.SqlDbType.VarChar);
         _cashparam8.Value = cashEntity.QQ;
         SqlParameter _cashparam9 = command.Parameters.Add("@Email", System.Data.SqlDbType.VarChar);
         _cashparam9.Value = cashEntity.Email;
         SqlParameter _cashparam10 = command.Parameters.Add("@Credit_Limit", System.Data.SqlDbType.Decimal);
         _cashparam10.Value = cashEntity.CreditLimit;
         command.CommandType = System.Data.CommandType.StoredProcedure;
         connection.Open();
         command.ExecuteNonQuery();
     }
 }